Collection of utility functions for data processing, URL handling, CSV operations, label processing, object manipulation, and various data manipulation tasks commonly needed in data visualization applications.
Functions for converting and processing data values.
/**
* Converts any value to a number with fallback handling
* @param value - Value to convert (string, number, boolean, etc.)
* @returns Numeric representation or NaN if cannot convert
*/
function anyToNumber(value: any): number;
/**
* Rounds number to specified decimal places
* @param val - Number to round
* @param decimals - Number of decimal places
* @returns Rounded number
*/
function roundDecimals(val: number, decimals: number): number;
/**
* Guesses appropriate number of decimal places for a number
* @param num - Number to analyze
* @returns Recommended decimal places
*/
function guessDecimals(num: number): number;Usage Examples:
import { anyToNumber, roundDecimals, guessDecimals } from "@grafana/data";
// Convert various types to numbers
console.log(anyToNumber("42")); // 42
console.log(anyToNumber("42.5")); // 42.5
console.log(anyToNumber(true)); // 1
console.log(anyToNumber("abc")); // NaN
// Round numbers
console.log(roundDecimals(3.14159, 2)); // 3.14
console.log(roundDecimals(42.999, 0)); // 43
// Guess decimal places
console.log(guessDecimals(3.14)); // 2
console.log(guessDecimals(42)); // 0
console.log(guessDecimals(0.001)); // 3Functions for URL manipulation and browser location handling.
/**
* Location utility functions
*/
const locationUtil: {
/** Update browser URL without page reload */
update(update: LocationUpdate): void;
/** Get current URL parameters */
getSearchObject(): UrlQueryMap;
/** Get search parameter by key */
getSearch(key: string): UrlQueryValue;
/** Navigate to URL */
assign(url: string): void;
/** Reload current page */
reload(): void;
/** Replace current URL */
replace(url: string): void;
};
/**
* URL utility functions
*/
const urlUtil: {
/** Parse URL query string */
parseKeyValue(query: string): UrlQueryMap;
/** Convert object to query string */
toUrlParams(obj: UrlQueryMap): string;
/** Render URL with parameters */
renderUrl(path: string, query?: UrlQueryMap): string;
/** Update URL parameters */
updateUrlParams(url: string, params: UrlQueryMap): string;
/** Strip base URL from path */
stripBaseFromUrl(url: string): string;
/** Check if URL is absolute */
isAbsoluteUrl(url: string): boolean;
};
/**
* Serializes state object to URL parameter
* @param urlState - State to serialize
* @param defaultUrlState - Default state for comparison
* @returns URL parameter string
*/
function serializeStateToUrlParam(urlState: any, defaultUrlState?: any): string;
/**
* Converts time range to URL format
* @param range - Time range to convert
* @returns URL-safe time range representation
*/
function toURLRange(range: TimeRange): URLRange;Functions for reading and writing CSV data with DataFrame integration.
/**
* Reads CSV text and converts to DataFrames
* @param text - CSV text content
* @param options - CSV parsing options
* @returns Array of DataFrames
*/
function readCSV(text: string, options?: CSVOptions): DataFrame[];
/**
* CSV reader class for streaming CSV processing
*/
class CSVReader {
constructor(options?: CSVOptions);
/** Read CSV from string */
readCSV(text: string): DataFrame[];
/** Read CSV from file */
readFile(file: File): Promise<DataFrame[]>;
}
/**
* Converts DataFrames to CSV format
* @param dataFrames - DataFrames to convert
* @param options - CSV output options
* @returns CSV text
*/
function toCSV(dataFrames: DataFrame[], options?: CSVConfig): string;Usage Examples:
import { readCSV, toCSV, CSVHeaderStyle } from "@grafana/data";
// Read CSV data
const csvText = `name,age,city
Alice,25,New York
Bob,30,Los Angeles`;
const frames = readCSV(csvText, {
headerStyle: CSVHeaderStyle.name
});
// Convert DataFrames back to CSV
const csvOutput = toCSV(frames, {
headerStyle: CSVHeaderStyle.name
});Functions for parsing and manipulating label data.
/**
* Parses label string into Labels object
* @param labels - Label string (e.g., "key1=value1,key2=value2")
* @returns Parsed labels object
*/
function parseLabels(labels: string): Labels;
/**
* Finds common labels across multiple datasets
* @param datasets - Array of data with labels
* @returns Common labels object
*/
function findCommonLabels(datasets: Array<{ labels?: Labels }>): Labels;
/**
* Finds unique labels across datasets
* @param datasets - Array of data with labels
* @returns Unique labels object
*/
function findUniqueLabels(datasets: Array<{ labels?: Labels }>): Labels;
/**
* Matches all labels against matchers
* @param labels - Labels to match
* @param matchers - Array of label matchers
* @returns True if all matchers match
*/
function matchAllLabels(labels: Labels, matchers: any[]): boolean;
/**
* Formats labels for display
* @param labels - Labels to format
* @param defaultLabel - Default label if none provided
* @returns Formatted label string
*/
function formatLabels(labels?: Labels, defaultLabel?: string): string;Functions for object and array manipulation.
/**
* Removes undefined properties from object
* @param obj - Object to clean
* @returns Object without undefined properties
*/
function objRemoveUndefined<T>(obj: T): T;
/**
* Checks if object is empty
* @param obj - Object to check
* @returns True if object has no enumerable properties
*/
function isEmptyObject(obj: any): boolean;
/**
* Array utility functions namespace
*/
namespace arrayUtils {
/** Remove duplicates from array */
export function uniq<T>(array: T[]): T[];
/** Move array element to new position */
export function move<T>(array: T[], from: number, to: number): T[];
/** Insert element at specific position */
export function insert<T>(array: T[], index: number, item: T): T[];
/** Remove element at specific position */
export function remove<T>(array: T[], index: number): T[];
/** Chunk array into smaller arrays */
export function chunk<T>(array: T[], size: number): T[][];
/** Flatten nested arrays */
export function flatten<T>(arrays: T[][]): T[];
/** Find last element matching predicate */
export function findLast<T>(array: T[], predicate: (item: T) => boolean): T | undefined;
}Functions for data source configuration and management.
/**
* Creates data source reference
* @param ds - Data source or reference
* @returns Normalized data source reference
*/
function getDataSourceRef(ds: DataSourceApi | DataSourceRef | string | null | undefined): DataSourceRef | undefined;
/**
* Type guard for data source references
* @param ref - Value to check
* @returns True if value is DataSourceRef
*/
function isDataSourceRef(ref: any): ref is DataSourceRef;
/**
* Extracts UID from data source reference
* @param ref - Data source reference
* @returns Data source UID
*/
function getDataSourceUID(ref: DataSourceRef): string;
/**
* Updates data source option
* @param option - Current option value
* @param key - Option key
* @returns Update function
*/
function onUpdateDatasourceOption(option: any, key: string): (event: any) => void;
/**
* Updates data source JSON data option
* @param option - Current option value
* @param key - Option key
* @returns Update function
*/
function onUpdateDatasourceJsonDataOption(option: any, key: string): (event: any) => void;
/**
* Updates data source secure JSON data option
* @param option - Current option value
* @param key - Option key
* @returns Update function
*/
function onUpdateDatasourceSecureJsonDataOption(option: any, key: string): (event: any) => void;
/**
* Resets data source option
* @param option - Current option value
* @param key - Option key
* @returns Reset function
*/
function onUpdateDatasourceResetOption(option: any, key: string): () => void;Functions for building UI configuration interfaces.
/**
* Panel options editor builder
*/
class PanelOptionsEditorBuilder<T> {
/** Add text input field */
addTextInput(config: TextInputConfig): this;
/** Add number input field */
addNumberInput(config: NumberInputConfig): this;
/** Add boolean switch */
addBooleanSwitch(config: BooleanSwitchConfig): this;
/** Add radio group */
addRadio(config: RadioConfig): this;
/** Add select dropdown */
addSelect(config: SelectConfig): this;
/** Add multi-select */
addMultiSelect(config: MultiSelectConfig): this;
/** Add slider input */
addSliderInput(config: SliderInputConfig): this;
/** Add color picker */
addColorPicker(config: ColorPickerConfig): this;
/** Add custom editor */
addCustomEditor(config: CustomEditorConfig): this;
}
/**
* Field config editor builder
*/
class FieldConfigEditorBuilder<T> {
/** Add unit picker */
addUnitPicker(config: UnitPickerConfig): this;
/** Add min/max inputs */
addMinMax(config: MinMaxConfig): this;
/** Add decimals input */
addDecimals(config: DecimalsConfig): this;
/** Add display name input */
addDisplayName(config: DisplayNameConfig): this;
/** Add thresholds editor */
addThresholds(config: ThresholdsConfig): this;
/** Add value mappings editor */
addValueMappings(config: ValueMappingsConfig): this;
/** Add color scheme picker */
addColorScheme(config: ColorSchemeConfig): this;
/** Add data links editor */
addDataLinks(config: DataLinksConfig): this;
}Functions for string manipulation and validation.
/**
* Escapes string for use in regular expressions
* @param value - String to escape
* @returns Escaped string
*/
function escapeStringForRegex(value: string): string;
/**
* Unescapes string from regular expression
* @param value - String to unescape
* @returns Unescaped string
*/
function unEscapeStringFromRegex(value: string): string;
/**
* Checks if string starts as regular expression
* @param str - String to check
* @returns True if string is regex pattern
*/
function stringStartsAsRegEx(str: string): boolean;
/**
* Converts string to JavaScript RegExp
* @param str - String to convert
* @returns RegExp object
*/
function stringToJsRegex(str: string): RegExp;
/**
* Converts string to milliseconds
* @param str - Time string (e.g., "5m", "1h", "30s")
* @returns Milliseconds value
*/
function stringToMs(str: string): number;
/**
* Converts value to number string
* @param value - Value to convert
* @returns Number as string
*/
function toNumberString(value: any): string;
/**
* Converts value to integer or undefined
* @param value - Value to convert
* @returns Integer or undefined if invalid
*/
function toIntegerOrUndefined(value: any): number | undefined;
/**
* Converts value to float or undefined
* @param value - Value to convert
* @returns Float or undefined if invalid
*/
function toFloatOrUndefined(value: any): number | undefined;
/**
* Converts string to PascalCase
* @param str - String to convert
* @returns PascalCase string
*/
function toPascalCase(str: string): string;
/**
* Escapes regex special characters
* @param value - String to escape
* @returns Escaped string
*/
function escapeRegex(value: string): string;
/**
* Finds highlighted chunks in text for highlighting search terms
* @param options - Search configuration with words and text
* @returns Array of text matches with positions
*/
function findHighlightChunksInText(options: {
searchWords: Array<string | RegExp>;
textToHighlight: string;
}): TextMatch[];
/**
* Finds all matches of a search term in text
* @param haystack - Text to search in
* @param needle - Search term
* @returns Array of matches with positions
*/
function findMatchesInText(haystack: string, needle: string): TextMatch[];
/**
* Parses regex flags from search string
* @param text - Text containing flags
* @returns Cleaned text and extracted flags
*/
function parseFlags(text: string): { cleaned: string; flags: string };Various helper functions for common tasks.
/**
* Storage utility object
*/
const store: {
/** Get item from localStorage */
get(key: string): any;
/** Set item in localStorage */
set(key: string, value: any): void;
/** Remove item from localStorage */
delete(key: string): void;
/** Check if key exists */
exists(key: string): boolean;
};
/**
* Storage class for typed storage operations
*/
class Store<T> {
constructor(key: string);
/** Get stored value */
get(): T | undefined;
/** Set stored value */
set(value: T): void;
/** Delete stored value */
delete(): void;
/** Check if value exists */
exists(): boolean;
}
/**
* Local storage value provider
*/
class LocalStorageValueProvider<T> {
constructor(key: string, defaultValue: T);
/** Get current value */
get(): T;
/** Set new value */
set(value: T): void;
/** Subscribe to changes */
subscribe(callback: (value: T) => void): () => void;
}
/**
* Makes ES5 compatible class
* @param clazz - Class to make compatible
* @returns ES5 compatible class
*/
function makeClassES5Compatible<T>(clazz: new (...args: any[]) => T): new (...args: any[]) => T;
/**
* Higher-order component for loading indicators
* @param options - Loading indicator options
* @returns HOC function
*/
function withLoadingIndicator<T>(options: WithLoadingIndicatorOptions<T>): (Component: ComponentType<T>) => ComponentType<T>;
/**
* Shows deprecation warning
* @param file - File where deprecated feature is used
* @param oldName - Old feature name
* @param newName - New feature name
*/
function deprecationWarning(file: string, oldName: string, newName: string): void;
/**
* Matches plugin ID patterns
* @param id - Plugin ID to match
* @returns True if ID matches pattern
*/
function matchPluginId(id: string): boolean;
/**
* Renders legend format with variables
* @param aliasPattern - Alias pattern
* @param aliasData - Data for variable replacement
* @returns Rendered legend text
*/
function renderLegendFormat(aliasPattern: string, aliasData: any): string;
/**
* Classic color palette
*/
const classicColors: string[];
/**
* Converts value to selectable option
* @param value - Value to convert
* @param label - Optional label
* @returns Selectable value option
*/
function toOption<T = any>(value: T, label?: string): SelectableValue<T>;
/**
* Fuzzy search implementation
* @param haystack - Array to search in
* @param needle - Search term
* @returns Array of matching results
*/
function fuzzySearch<T>(haystack: T[], needle: string): T[];
/**
* Throws error if Angular is detected
*/
function throwIfAngular(): void;
/**
* Checks if user has specific permission
* @param action - Permission action to check
* @param user - Current user
* @returns True if user has permission
*/
function userHasPermission(action: string, user: CurrentUser): boolean;
/**
* Checks if user has permission in metadata object
* @param action - Permission action to check
* @param object - Object with access control metadata
* @returns True if user has permission
*/
function userHasPermissionInMetadata(action: string, object: WithAccessControlMetadata): boolean;
/**
* Checks if user has all specified permissions
* @param actions - Array of permission actions
* @param user - Current user
* @returns True if user has all permissions
*/
function userHasAllPermissions(actions: string[], user: CurrentUser): boolean;
/**
* Checks if user has any of the specified permissions
* @param actions - Array of permission actions
* @param user - Current user
* @returns True if user has any permission
*/
function userHasAnyPermission(actions: string[], user: CurrentUser): boolean;/**
* Text search match result
*/
interface TextMatch {
text: string;
start: number;
length: number;
end: number;
}
/**
* URL query types
*/
type UrlQueryValue = string | number | boolean | string[] | number[] | boolean[] | undefined | null;
type UrlQueryMap = Record<string, UrlQueryValue>;
/**
* CSV configuration
*/
interface CSVConfig {
headerStyle?: CSVHeaderStyle;
delimiter?: string;
newline?: string;
quoteChar?: string;
encoding?: string;
}
interface CSVOptions extends CSVConfig {
skipFirstNRows?: number;
skipLinesWithError?: boolean;
}
interface CSVParseCallbacks {
/** Callback for each parsed row */
onRow?: (row: any[], rowIndex: number) => void;
/** Callback for parsing errors */
onError?: (error: Error, rowIndex: number) => void;
/** Callback when parsing completes */
onComplete?: (results: DataFrame[]) => void;
}
enum CSVHeaderStyle {
none = 'none',
name = 'name',
guess = 'guess'
}
/**
* Labels type
*/
interface Labels {
[key: string]: string;
}
/**
* Loading indicator options
*/
interface WithLoadingIndicatorOptions<T> {
/** Loading predicate */
isLoading: (props: T) => boolean;
/** Loading component */
LoadingComponent?: ComponentType<any>;
}
/**
* Registry system
*/
interface RegistryItem {
/** Item ID */
id: string;
/** Item name */
name: string;
/** Description */
description?: string;
}
interface RegistryItemWithOptions<T> extends RegistryItem {
/** Item options */
options?: T;
}
class Registry<T extends RegistryItem> {
/** Register item */
register(item: T): void;
/** Get item by ID */
get(id: string): T | undefined;
/** Get all items */
list(): T[];
/** Check if item exists */
exists(id: string): boolean;
/** Remove item */
remove(id: string): void;
}
/**
* Documentation IDs
*/
enum DocsId {
Transformations = 'transformations',
FieldOptions = 'field-options',
FieldOverrides = 'field-overrides',
StandardOptions = 'standard-options'
}
/**
* Node graph field names
*/
enum NodeGraphDataFrameFieldNames {
id = 'id',
title = 'title',
subTitle = 'subtitle',
mainStat = 'mainstat',
secondaryStat = 'secondarystat',
source = 'source',
target = 'target'
}
/**
* Binary operation types
*/
enum BinaryOperationID {
Add = 'add',
Subtract = 'subtract',
Multiply = 'multiply',
Divide = 'divide',
Power = 'power',
Modulo = 'modulo'
}
interface BinaryOperation {
id: BinaryOperationID;
name: string;
operation: (left: number, right: number) => number;
}
const binaryOperators: Registry<BinaryOperation>;
/**
* Unary operation types
*/
enum UnaryOperationID {
Abs = 'abs',
Log = 'log',
Inf = 'inf',
Nan = 'nan',
Null = 'null',
Round = 'round',
Ceil = 'ceil',
Floor = 'floor'
}
interface UnaryOperation {
id: UnaryOperationID;
name: string;
operation: (value: number) => number;
}
const unaryOperators: Registry<UnaryOperation>;