@grafana/scenes 5.25.1--canary.858.11930656504.0 → 5.26.0--canary.974.11969404553.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (47) hide show
  1. package/CHANGELOG.md +22 -6
  2. package/dist/esm/behaviors/SceneQueryController.js +5 -60
  3. package/dist/esm/behaviors/SceneQueryController.js.map +1 -1
  4. package/dist/esm/components/SceneRefreshPicker.js +1 -6
  5. package/dist/esm/components/SceneRefreshPicker.js.map +1 -1
  6. package/dist/esm/components/VizPanel/VizPanel.js +6 -9
  7. package/dist/esm/components/VizPanel/VizPanel.js.map +1 -1
  8. package/dist/esm/core/SceneTimeRange.js +0 -3
  9. package/dist/esm/core/SceneTimeRange.js.map +1 -1
  10. package/dist/esm/core/sceneGraph/index.js +3 -3
  11. package/dist/esm/core/sceneGraph/index.js.map +1 -1
  12. package/dist/esm/core/sceneGraph/sceneGraph.js +26 -1
  13. package/dist/esm/core/sceneGraph/sceneGraph.js.map +1 -1
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/esm/querying/SceneQueryRunner.js +3 -1
  16. package/dist/esm/querying/SceneQueryRunner.js.map +1 -1
  17. package/dist/esm/querying/layers/annotations/filterAnnotations.js +3 -2
  18. package/dist/esm/querying/layers/annotations/filterAnnotations.js.map +1 -1
  19. package/dist/esm/querying/registerQueryWithController.js +2 -18
  20. package/dist/esm/querying/registerQueryWithController.js.map +1 -1
  21. package/dist/esm/utils/getDataSource.js +1 -17
  22. package/dist/esm/utils/getDataSource.js.map +1 -1
  23. package/dist/esm/variables/adhoc/AdHocFilterRenderer.js +8 -12
  24. package/dist/esm/variables/adhoc/AdHocFilterRenderer.js.map +1 -1
  25. package/dist/esm/variables/adhoc/AdHocFiltersCombobox/utils.js +9 -48
  26. package/dist/esm/variables/adhoc/AdHocFiltersCombobox/utils.js.map +1 -1
  27. package/dist/esm/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.js +4 -1
  28. package/dist/esm/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.js.map +1 -1
  29. package/dist/esm/variables/adhoc/getAdhocOptionSearcher.js +6 -38
  30. package/dist/esm/variables/adhoc/getAdhocOptionSearcher.js.map +1 -1
  31. package/dist/esm/variables/components/VariableValueSelect.js +0 -5
  32. package/dist/esm/variables/components/VariableValueSelect.js.map +1 -1
  33. package/dist/esm/variables/components/getOptionSearcher.js +5 -39
  34. package/dist/esm/variables/components/getOptionSearcher.js.map +1 -1
  35. package/dist/esm/variables/groupby/GroupByVariable.js +2 -2
  36. package/dist/esm/variables/groupby/GroupByVariable.js.map +1 -1
  37. package/dist/esm/variables/utils.js +23 -1
  38. package/dist/esm/variables/utils.js.map +1 -1
  39. package/dist/esm/variables/variants/TestVariable.js.map +1 -1
  40. package/dist/index.d.ts +32 -44
  41. package/dist/index.js +289 -622
  42. package/dist/index.js.map +1 -1
  43. package/package.json +3 -3
  44. package/dist/esm/behaviors/SceneRenderProfiler.js +0 -169
  45. package/dist/esm/behaviors/SceneRenderProfiler.js.map +0 -1
  46. package/dist/esm/core/sceneGraph/getQueryController.js +0 -19
  47. package/dist/esm/core/sceneGraph/getQueryController.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"GroupByVariable.js","sources":["../../../../src/variables/groupby/GroupByVariable.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useState } from 'react';\n// @ts-expect-error Remove when 11.1.x is released\nimport { AdHocVariableFilter, DataSourceApi, GetTagResponse, MetricFindValue, SelectableValue } from '@grafana/data';\nimport { allActiveGroupByVariables } from './findActiveGroupByVariablesByUid';\nimport { DataSourceRef, VariableType } from '@grafana/schema';\nimport { SceneComponentProps, ControlsLayout, SceneObjectUrlSyncHandler } from '../../core/types';\nimport { sceneGraph } from '../../core/sceneGraph';\nimport { ValidateAndUpdateResult, VariableValueOption, VariableValueSingle } from '../types';\nimport { MultiValueVariable, MultiValueVariableState, VariableGetOptionsArgs } from '../variants/MultiValueVariable';\nimport { from, lastValueFrom, map, mergeMap, Observable, of, take, tap } from 'rxjs';\nimport { getDataSource } from '../../utils/getDataSource';\nimport { InputActionMeta, MultiSelect } from '@grafana/ui';\nimport { isArray } from 'lodash';\nimport { dataFromResponse, getQueriesForVariables, handleOptionGroups, responseHasError } from '../utils';\nimport { OptionWithCheckbox } from '../components/VariableValueSelect';\nimport { GroupByVariableUrlSyncHandler } from './GroupByVariableUrlSyncHandler';\nimport { getOptionSearcher } from '../components/getOptionSearcher';\nimport { getEnrichedFiltersRequest } from '../getEnrichedFiltersRequest';\nimport { wrapInSafeSerializableSceneObject } from '../../utils/wrapInSafeSerializableSceneObject';\n\nexport interface GroupByVariableState extends MultiValueVariableState {\n /** Defaults to \"Group\" */\n name: string;\n /** The visible keys to group on */\n // TODO review this type and name (naming is hard)\n defaultOptions?: MetricFindValue[];\n /** Base filters to always apply when looking up keys */\n baseFilters?: AdHocVariableFilter[];\n /** Datasource to use for getTagKeys and also controls which scene queries the group by should apply to */\n datasource: DataSourceRef | null;\n /** Controls if the group by can be changed */\n readOnly?: boolean;\n /**\n * @experimental\n * Controls the layout and design of the label.\n * Vertical layout does not yet support operator selector.\n */\n layout?: ControlsLayout;\n /**\n * Defaults to same-datasource which means group by will automatically be applied to all queries with the same data source as this GroupBySet.\n * In manual mode no queries are re-run on changes, and you have to manually apply the filter to whatever queries you want.\n */\n applyMode?: 'auto' | 'manual';\n /**\n * Filter out the keys that do not match the regex.\n */\n tagKeyRegexFilter?: RegExp;\n /**\n * Extension hook for customizing the key lookup.\n * Return replace: true if you want to override the default lookup\n * Return replace: false if you want to combine the results with the default lookup\n */\n getTagKeysProvider?: getTagKeysProvider;\n}\n\nexport type getTagKeysProvider = (\n set: GroupByVariable,\n currentKey: string | null\n) => Promise<{ replace?: boolean; values: MetricFindValue[] | GetTagResponse }>;\n\nexport class GroupByVariable extends MultiValueVariable<GroupByVariableState> {\n static Component = GroupByVariableRenderer;\n isLazy = true;\n\n protected _urlSync: SceneObjectUrlSyncHandler = new GroupByVariableUrlSyncHandler(this);\n\n public validateAndUpdate(): Observable<ValidateAndUpdateResult> {\n return this.getValueOptions({}).pipe(\n map((options) => {\n this._updateValueGivenNewOptions(options);\n return {};\n })\n );\n }\n\n private _updateValueGivenNewOptions(options: VariableValueOption[]) {\n const { value: currentValue, text: currentText } = this.state;\n\n const stateUpdate: Partial<MultiValueVariableState> = {\n options,\n loading: false,\n value: currentValue ?? [],\n text: currentText ?? [],\n };\n\n this.setState(stateUpdate);\n }\n\n public getValueOptions(args: VariableGetOptionsArgs): Observable<VariableValueOption[]> {\n // When default dimensions are provided, return the static list\n if (this.state.defaultOptions) {\n return of(\n this.state.defaultOptions.map((o) => ({\n label: o.text,\n value: String(o.value),\n // @ts-expect-error Remove when we update to @grafana/data > 11.1.0\n group: o.group,\n }))\n );\n }\n\n this.setState({ loading: true, error: null });\n\n return from(\n getDataSource(this.state.datasource, {\n __sceneObject: wrapInSafeSerializableSceneObject(this),\n })\n ).pipe(\n mergeMap((ds) => {\n return from(this._getKeys(ds)).pipe(\n tap((response) => {\n if (responseHasError(response)) {\n this.setState({ error: response.error.message });\n }\n }),\n map((response) => dataFromResponse(response)),\n take(1),\n mergeMap((data) => {\n // @ts-expect-error Remove when 11.1.x is released\n const a: VariableValueOption[] = data.map((i) => {\n return {\n label: i.text,\n value: i.value ? String(i.value) : i.text,\n group: i.group,\n };\n });\n return of(a);\n })\n );\n })\n );\n }\n\n public constructor(initialState: Partial<GroupByVariableState>) {\n super({\n isMulti: true,\n name: '',\n value: [],\n text: [],\n options: [],\n datasource: null,\n baseFilters: [],\n applyMode: 'auto',\n layout: 'horizontal',\n type: 'groupby' as VariableType,\n ...initialState,\n noValueOnClear: true,\n });\n\n this.addActivationHandler(() => {\n allActiveGroupByVariables.add(this);\n\n return () => allActiveGroupByVariables.delete(this);\n });\n }\n\n /**\n * Get possible keys given current filters. Do not call from plugins directly\n */\n public _getKeys = async (ds: DataSourceApi) => {\n // TODO: provide current dimensions?\n const override = await this.state.getTagKeysProvider?.(this, null);\n\n if (override && override.replace) {\n return override.values;\n }\n\n if (this.state.defaultOptions) {\n return this.state.defaultOptions.concat(dataFromResponse(override?.values ?? []));\n }\n\n if (!ds.getTagKeys) {\n return [];\n }\n\n const queries = getQueriesForVariables(this);\n\n const otherFilters = this.state.baseFilters || [];\n const timeRange = sceneGraph.getTimeRange(this).state.value;\n const response = await ds.getTagKeys({\n filters: otherFilters,\n queries,\n timeRange,\n ...getEnrichedFiltersRequest(this),\n });\n if (responseHasError(response)) {\n // @ts-expect-error Remove when 11.1.x is released\n this.setState({ error: response.error.message });\n }\n\n let keys = dataFromResponse(response);\n if (override) {\n keys = keys.concat(dataFromResponse(override.values));\n }\n\n const tagKeyRegexFilter = this.state.tagKeyRegexFilter;\n if (tagKeyRegexFilter) {\n // @ts-expect-error Remove when 11.1.x is released\n keys = keys.filter((f) => f.text.match(tagKeyRegexFilter));\n }\n\n return keys;\n };\n\n /**\n * Allows clearing the value of the variable to an empty value. Overrides default behavior of a MultiValueVariable\n */\n public getDefaultMultiState(options: VariableValueOption[]): { value: VariableValueSingle[]; text: string[] } {\n return { value: [], text: [] };\n }\n}\nexport function GroupByVariableRenderer({ model }: SceneComponentProps<MultiValueVariable>) {\n const { value, text, key, maxVisibleValues, noValueOnClear, options, includeAll } = model.useState();\n\n const values = useMemo<Array<SelectableValue<VariableValueSingle>>>(() => {\n const arrayValue = isArray(value) ? value : [value];\n const arrayText = isArray(text) ? text : [text];\n\n return arrayValue.map((value, idx) => ({\n value,\n label: String(arrayText[idx] ?? value),\n }));\n }, [value, text]);\n\n const [isFetchingOptions, setIsFetchingOptions] = useState(false);\n const [isOptionsOpen, setIsOptionsOpen] = useState(false);\n const [inputValue, setInputValue] = useState('');\n\n // To not trigger queries on every selection we store this state locally here and only update the variable onBlur\n const [uncommittedValue, setUncommittedValue] = useState(values);\n\n const optionSearcher = useMemo(() => getOptionSearcher(options, includeAll), [options, includeAll]);\n\n // Detect value changes outside\n useEffect(() => {\n setUncommittedValue(values);\n }, [values]);\n\n const onInputChange = (value: string, { action }: InputActionMeta) => {\n if (action === 'input-change') {\n setInputValue(value);\n if (model.onSearchChange) {\n model.onSearchChange!(value);\n }\n return value;\n }\n\n if (action === 'input-blur') {\n setInputValue('');\n return '';\n }\n\n return inputValue;\n };\n\n const filteredOptions = useMemo(\n () => handleOptionGroups(optionSearcher(inputValue).map(toSelectableValue)),\n [optionSearcher, inputValue]\n );\n\n return (\n <MultiSelect<VariableValueSingle>\n data-testid={`GroupBySelect-${key}`}\n id={key}\n placeholder={'Select value'}\n width=\"auto\"\n allowCustomValue={true}\n inputValue={inputValue}\n value={uncommittedValue}\n noMultiValueWrap={true}\n maxVisibleValues={maxVisibleValues ?? 5}\n tabSelectsValue={false}\n virtualized\n options={filteredOptions}\n filterOption={filterNoOp}\n closeMenuOnSelect={false}\n isOpen={isOptionsOpen}\n isClearable={true}\n hideSelectedOptions={false}\n isLoading={isFetchingOptions}\n components={{ Option: OptionWithCheckbox }}\n onInputChange={onInputChange}\n onBlur={() => {\n model.changeValueTo(\n uncommittedValue.map((x) => x.value!),\n uncommittedValue.map((x) => x.label!)\n );\n }}\n onChange={(newValue, action) => {\n if (action.action === 'clear' && noValueOnClear) {\n model.changeValueTo([]);\n }\n setUncommittedValue(newValue);\n }}\n onOpenMenu={async () => {\n setIsFetchingOptions(true);\n await lastValueFrom(model.validateAndUpdate());\n setIsFetchingOptions(false);\n setIsOptionsOpen(true);\n }}\n onCloseMenu={() => {\n setIsOptionsOpen(false);\n }}\n />\n );\n}\n\nconst filterNoOp = () => true;\n\nfunction toSelectableValue(input: VariableValueOption): SelectableValue<VariableValueSingle> {\n const { label, value, group } = input;\n const result: SelectableValue<VariableValueSingle> = {\n label,\n value,\n };\n\n if (group) {\n result.group = group;\n }\n\n return result;\n}\n"],"names":["value"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DO,MAAM,wBAAwB,kBAAyC,CAAA;AAAA,EAyErE,YAAY,YAA6C,EAAA;AAC9D,IAAM,KAAA,CAAA,aAAA,CAAA,cAAA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CAAO,KAAQ,GAAA,KAAA,CAAA;AAAA,GACjB;AAEA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"GroupByVariable.js","sources":["../../../../src/variables/groupby/GroupByVariable.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useState } from 'react';\n// @ts-expect-error Remove when 11.1.x is released\nimport { AdHocVariableFilter, DataSourceApi, GetTagResponse, MetricFindValue, SelectableValue } from '@grafana/data';\nimport { allActiveGroupByVariables } from './findActiveGroupByVariablesByUid';\nimport { DataSourceRef, VariableType } from '@grafana/schema';\nimport { SceneComponentProps, ControlsLayout, SceneObjectUrlSyncHandler } from '../../core/types';\nimport { sceneGraph } from '../../core/sceneGraph';\nimport { ValidateAndUpdateResult, VariableValueOption, VariableValueSingle } from '../types';\nimport { MultiValueVariable, MultiValueVariableState, VariableGetOptionsArgs } from '../variants/MultiValueVariable';\nimport { from, lastValueFrom, map, mergeMap, Observable, of, take, tap } from 'rxjs';\nimport { getDataSource } from '../../utils/getDataSource';\nimport { InputActionMeta, MultiSelect } from '@grafana/ui';\nimport { isArray } from 'lodash';\nimport { dataFromResponse, getQueriesForVariables, handleOptionGroups, responseHasError } from '../utils';\nimport { OptionWithCheckbox } from '../components/VariableValueSelect';\nimport { GroupByVariableUrlSyncHandler } from './GroupByVariableUrlSyncHandler';\nimport { getOptionSearcher } from '../components/getOptionSearcher';\nimport { getEnrichedFiltersRequest } from '../getEnrichedFiltersRequest';\nimport { wrapInSafeSerializableSceneObject } from '../../utils/wrapInSafeSerializableSceneObject';\n\nexport interface GroupByVariableState extends MultiValueVariableState {\n /** Defaults to \"Group\" */\n name: string;\n /** The visible keys to group on */\n // TODO review this type and name (naming is hard)\n defaultOptions?: MetricFindValue[];\n /** Base filters to always apply when looking up keys */\n baseFilters?: AdHocVariableFilter[];\n /** Datasource to use for getTagKeys and also controls which scene queries the group by should apply to */\n datasource: DataSourceRef | null;\n /** Controls if the group by can be changed */\n readOnly?: boolean;\n /**\n * @experimental\n * Controls the layout and design of the label.\n * Vertical layout does not yet support operator selector.\n */\n layout?: ControlsLayout;\n /**\n * Defaults to same-datasource which means group by will automatically be applied to all queries with the same data source as this GroupBySet.\n * In manual mode no queries are re-run on changes, and you have to manually apply the filter to whatever queries you want.\n */\n applyMode?: 'auto' | 'manual';\n /**\n * Filter out the keys that do not match the regex.\n */\n tagKeyRegexFilter?: RegExp;\n /**\n * Extension hook for customizing the key lookup.\n * Return replace: true if you want to override the default lookup\n * Return replace: false if you want to combine the results with the default lookup\n */\n getTagKeysProvider?: getTagKeysProvider;\n}\n\nexport type getTagKeysProvider = (\n set: GroupByVariable,\n currentKey: string | null\n) => Promise<{ replace?: boolean; values: MetricFindValue[] | GetTagResponse }>;\n\nexport class GroupByVariable extends MultiValueVariable<GroupByVariableState> {\n static Component = GroupByVariableRenderer;\n isLazy = true;\n\n protected _urlSync: SceneObjectUrlSyncHandler = new GroupByVariableUrlSyncHandler(this);\n\n public validateAndUpdate(): Observable<ValidateAndUpdateResult> {\n return this.getValueOptions({}).pipe(\n map((options) => {\n this._updateValueGivenNewOptions(options);\n return {};\n })\n );\n }\n\n private _updateValueGivenNewOptions(options: VariableValueOption[]) {\n const { value: currentValue, text: currentText } = this.state;\n\n const stateUpdate: Partial<MultiValueVariableState> = {\n options,\n loading: false,\n value: currentValue ?? [],\n text: currentText ?? [],\n };\n\n this.setState(stateUpdate);\n }\n\n public getValueOptions(args: VariableGetOptionsArgs): Observable<VariableValueOption[]> {\n // When default dimensions are provided, return the static list\n if (this.state.defaultOptions) {\n return of(\n this.state.defaultOptions.map((o) => ({\n label: o.text,\n value: String(o.value),\n // @ts-expect-error Remove when we update to @grafana/data > 11.1.0\n group: o.group,\n }))\n );\n }\n\n this.setState({ loading: true, error: null });\n\n return from(\n getDataSource(this.state.datasource, {\n __sceneObject: wrapInSafeSerializableSceneObject(this),\n })\n ).pipe(\n mergeMap((ds) => {\n return from(this._getKeys(ds)).pipe(\n tap((response) => {\n if (responseHasError(response)) {\n this.setState({ error: response.error.message });\n }\n }),\n map((response) => dataFromResponse(response)),\n take(1),\n mergeMap((data) => {\n // @ts-expect-error Remove when 11.1.x is released\n const a: VariableValueOption[] = data.map((i) => {\n return {\n label: i.text,\n value: i.value ? String(i.value) : i.text,\n group: i.group,\n };\n });\n return of(a);\n })\n );\n })\n );\n }\n\n public constructor(initialState: Partial<GroupByVariableState>) {\n super({\n isMulti: true,\n name: '',\n value: [],\n text: [],\n options: [],\n datasource: null,\n baseFilters: [],\n applyMode: 'auto',\n layout: 'horizontal',\n type: 'groupby' as VariableType,\n ...initialState,\n noValueOnClear: true,\n });\n\n this.addActivationHandler(() => {\n allActiveGroupByVariables.add(this);\n\n return () => allActiveGroupByVariables.delete(this);\n });\n }\n\n /**\n * Get possible keys given current filters. Do not call from plugins directly\n */\n public _getKeys = async (ds: DataSourceApi) => {\n // TODO: provide current dimensions?\n const override = await this.state.getTagKeysProvider?.(this, null);\n\n if (override && override.replace) {\n return override.values;\n }\n\n if (this.state.defaultOptions) {\n return this.state.defaultOptions.concat(dataFromResponse(override?.values ?? []));\n }\n\n if (!ds.getTagKeys) {\n return [];\n }\n\n const queries = getQueriesForVariables(this);\n\n const otherFilters = this.state.baseFilters || [];\n const timeRange = sceneGraph.getTimeRange(this).state.value;\n const response = await ds.getTagKeys({\n filters: otherFilters,\n queries,\n timeRange,\n ...getEnrichedFiltersRequest(this),\n });\n if (responseHasError(response)) {\n // @ts-expect-error Remove when 11.1.x is released\n this.setState({ error: response.error.message });\n }\n\n let keys = dataFromResponse(response);\n if (override) {\n keys = keys.concat(dataFromResponse(override.values));\n }\n\n const tagKeyRegexFilter = this.state.tagKeyRegexFilter;\n if (tagKeyRegexFilter) {\n // @ts-expect-error Remove when 11.1.x is released\n keys = keys.filter((f) => f.text.match(tagKeyRegexFilter));\n }\n\n return keys;\n };\n\n /**\n * Allows clearing the value of the variable to an empty value. Overrides default behavior of a MultiValueVariable\n */\n public getDefaultMultiState(options: VariableValueOption[]): { value: VariableValueSingle[]; text: string[] } {\n return { value: [], text: [] };\n }\n}\nexport function GroupByVariableRenderer({ model }: SceneComponentProps<MultiValueVariable>) {\n const { value, text, key, maxVisibleValues, noValueOnClear, options, includeAll, allowCustomValue } =\n model.useState();\n\n const values = useMemo<Array<SelectableValue<VariableValueSingle>>>(() => {\n const arrayValue = isArray(value) ? value : [value];\n const arrayText = isArray(text) ? text : [text];\n\n return arrayValue.map((value, idx) => ({\n value,\n label: String(arrayText[idx] ?? value),\n }));\n }, [value, text]);\n\n const [isFetchingOptions, setIsFetchingOptions] = useState(false);\n const [isOptionsOpen, setIsOptionsOpen] = useState(false);\n const [inputValue, setInputValue] = useState('');\n\n // To not trigger queries on every selection we store this state locally here and only update the variable onBlur\n const [uncommittedValue, setUncommittedValue] = useState(values);\n\n const optionSearcher = useMemo(() => getOptionSearcher(options, includeAll), [options, includeAll]);\n\n // Detect value changes outside\n useEffect(() => {\n setUncommittedValue(values);\n }, [values]);\n\n const onInputChange = (value: string, { action }: InputActionMeta) => {\n if (action === 'input-change') {\n setInputValue(value);\n if (model.onSearchChange) {\n model.onSearchChange!(value);\n }\n return value;\n }\n\n if (action === 'input-blur') {\n setInputValue('');\n return '';\n }\n\n return inputValue;\n };\n\n const filteredOptions = useMemo(\n () => handleOptionGroups(optionSearcher(inputValue).map(toSelectableValue)),\n [optionSearcher, inputValue]\n );\n\n return (\n <MultiSelect<VariableValueSingle>\n data-testid={`GroupBySelect-${key}`}\n id={key}\n placeholder={'Select value'}\n width=\"auto\"\n allowCustomValue={allowCustomValue ?? true}\n inputValue={inputValue}\n value={uncommittedValue}\n noMultiValueWrap={true}\n maxVisibleValues={maxVisibleValues ?? 5}\n tabSelectsValue={false}\n virtualized\n options={filteredOptions}\n filterOption={filterNoOp}\n closeMenuOnSelect={false}\n isOpen={isOptionsOpen}\n isClearable={true}\n hideSelectedOptions={false}\n isLoading={isFetchingOptions}\n components={{ Option: OptionWithCheckbox }}\n onInputChange={onInputChange}\n onBlur={() => {\n model.changeValueTo(\n uncommittedValue.map((x) => x.value!),\n uncommittedValue.map((x) => x.label!)\n );\n }}\n onChange={(newValue, action) => {\n if (action.action === 'clear' && noValueOnClear) {\n model.changeValueTo([]);\n }\n setUncommittedValue(newValue);\n }}\n onOpenMenu={async () => {\n setIsFetchingOptions(true);\n await lastValueFrom(model.validateAndUpdate());\n setIsFetchingOptions(false);\n setIsOptionsOpen(true);\n }}\n onCloseMenu={() => {\n setIsOptionsOpen(false);\n }}\n />\n );\n}\n\nconst filterNoOp = () => true;\n\nfunction toSelectableValue(input: VariableValueOption): SelectableValue<VariableValueSingle> {\n const { label, value, group } = input;\n const result: SelectableValue<VariableValueSingle> = {\n label,\n value,\n };\n\n if (group) {\n result.group = group;\n }\n\n return result;\n}\n"],"names":["value"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DO,MAAM,wBAAwB,kBAAyC,CAAA;AAAA,EAyErE,YAAY,YAA6C,EAAA;AAC9D,IAAM,KAAA,CAAA,aAAA,CAAA,cAAA,CAAA;AAAA,MACJ,OAAS,EAAA,IAAA;AAAA,MACT,IAAM,EAAA,EAAA;AAAA,MACN,OAAO,EAAC;AAAA,MACR,MAAM,EAAC;AAAA,MACP,SAAS,EAAC;AAAA,MACV,UAAY,EAAA,IAAA;AAAA,MACZ,aAAa,EAAC;AAAA,MACd,SAAW,EAAA,MAAA;AAAA,MACX,MAAQ,EAAA,YAAA;AAAA,MACR,IAAM,EAAA,SAAA;AAAA,KAAA,EACH,YAXC,CAAA,EAAA;AAAA,MAYJ,cAAgB,EAAA,IAAA;AAAA,KACjB,CAAA,CAAA,CAAA;AArFH,IAAS,IAAA,CAAA,MAAA,GAAA,IAAA,CAAA;AAET,IAAU,IAAA,CAAA,QAAA,GAAsC,IAAI,6BAAA,CAA8B,IAAI,CAAA,CAAA;AA+FtF,IAAO,IAAA,CAAA,QAAA,GAAW,OAAO,EAAsB,KAAA;AA/JjD,MAAA,IAAA,EAAA,EAAA,EA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xB;AACA,MAAA,mBAAA,CAAoB,QAAQ,CAAA,CAAA;AAAA,KAC9B;AAAA,IACA,YAAY,YAAY;AACtB,MAAA,oBAAA,CAAqB,IAAI,CAAA,CAAA;AACzB,MAAM,MAAA,aAAA,CAAc,KAAM,CAAA,iBAAA,EAAmB,CAAA,CAAA;AAC7C,MAAA,oBAAA,CAAqB,KAAK,CAAA,CAAA;AAC1B,MAAA,gBAAA,CAAiB,IAAI,CAAA,CAAA;AAAA,KACvB;AAAA,IACA,aAAa,MAAM;AACjB,MAAA,gBAAA,CAAiB,KAAK,CAAA,CAAA;AAAA,KACxB;AAAA,GACF,CAAA,CAAA;AAEJ,CAAA;AAEA,MAAM,aAAa,MAAM,IAAA,CAAA;AAEzB,SAAS,kBAAkB,KAAkE,EAAA;AAC3F,EAAA,MAAM,EAAE,KAAA,EAAO,KAAO,EAAA,KAAA,EAAU,GAAA,KAAA,CAAA;AAChC,EAAA,MAAM,MAA+C,GAAA;AAAA,IACnD,KAAA;AAAA,IACA,KAAA;AAAA,GACF,CAAA;AAEA,EAAA,IAAI,KAAO,EAAA;AACT,IAAA,MAAA,CAAO,KAAQ,GAAA,KAAA,CAAA;AAAA,GACjB;AAEA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
@@ -1,6 +1,7 @@
1
1
  import { isEqual } from 'lodash';
2
2
  import { sceneGraph } from '../core/sceneGraph/index.js';
3
3
  import { SceneQueryRunner } from '../querying/SceneQueryRunner.js';
4
+ import uFuzzy from '@leeoniya/ufuzzy';
4
5
 
5
6
  function isVariableValueEqual(a, b) {
6
7
  if (a === b) {
@@ -145,6 +146,27 @@ function handleOptionGroups(values) {
145
146
  }
146
147
  return result;
147
148
  }
149
+ function getFuzzySearcher(haystack, limit = 1e4) {
150
+ const ufuzzy = new uFuzzy();
151
+ const FIRST = Array.from({ length: Math.min(limit, haystack.length) }, (_, i) => i);
152
+ return (search) => {
153
+ if (search === "") {
154
+ return FIRST;
155
+ }
156
+ const [idxs, info, order] = ufuzzy.search(haystack, search);
157
+ if (idxs) {
158
+ if (info && order) {
159
+ const outIdxs = Array(Math.min(order.length, limit));
160
+ for (let i = 0; i < outIdxs.length; i++) {
161
+ outIdxs[i] = info.idx[order[i]];
162
+ }
163
+ return outIdxs;
164
+ }
165
+ return idxs.slice(0, limit);
166
+ }
167
+ return [];
168
+ };
169
+ }
148
170
 
149
- export { dataFromResponse, escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector, escapeUrlCommaDelimiters, escapeUrlPipeDelimiters, getQueriesForVariables, handleOptionGroups, isVariableValueEqual, renderPrometheusLabelFilters, responseHasError, safeStringifyValue, toUrlCommaDelimitedString, unescapeUrlDelimiters };
171
+ export { dataFromResponse, escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector, escapeUrlCommaDelimiters, escapeUrlPipeDelimiters, getFuzzySearcher, getQueriesForVariables, handleOptionGroups, isVariableValueEqual, renderPrometheusLabelFilters, responseHasError, safeStringifyValue, toUrlCommaDelimitedString, unescapeUrlDelimiters };
150
172
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../src/variables/utils.ts"],"sourcesContent":["import { isEqual } from 'lodash';\nimport { VariableValue } from './types';\n// @ts-expect-error Remove when 11.1.x is released\nimport { AdHocVariableFilter, DataQueryError, GetTagResponse, MetricFindValue, SelectableValue } from '@grafana/data';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { SceneDataQuery, SceneObject, SceneObjectState } from '../core/types';\nimport { SceneQueryRunner } from '../querying/SceneQueryRunner';\nimport { DataSourceRef } from '@grafana/schema';\n\nexport function isVariableValueEqual(a: VariableValue | null | undefined, b: VariableValue | null | undefined) {\n if (a === b) {\n return true;\n }\n\n return isEqual(a, b);\n}\n\nexport function safeStringifyValue(value: unknown) {\n // Avoid circular references ignoring those references\n const getCircularReplacer = () => {\n const seen = new WeakSet();\n return (_: string, value: object | null) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n }\n return value;\n };\n };\n\n try {\n return JSON.stringify(value, getCircularReplacer());\n } catch (error) {\n console.error(error);\n }\n\n return '';\n}\n\nexport function renderPrometheusLabelFilters(filters: AdHocVariableFilter[]) {\n return filters.map((filter) => renderFilter(filter)).join(',');\n}\n\nfunction renderFilter(filter: AdHocVariableFilter) {\n let value = '';\n let operator = filter.operator;\n\n // map \"one of\" operator to regex\n if (operator === '=|') {\n operator = '=~';\n // TODO remove when we're on the latest version of @grafana/data\n // @ts-expect-error\n value = filter.values?.map(escapeLabelValueInRegexSelector).join('|');\n } else if (operator === '!=|') {\n operator = '!~';\n // TODO remove when we're on the latest version of @grafana/data\n // @ts-expect-error\n value = filter.values?.map(escapeLabelValueInRegexSelector).join('|');\n } else if (operator === '=~' || operator === '!~') {\n value = escapeLabelValueInRegexSelector(filter.value);\n } else {\n value = escapeLabelValueInExactSelector(filter.value);\n }\n\n return `${filter.key}${operator}\"${value}\"`;\n}\n\n// based on the openmetrics-documentation, the 3 symbols we have to handle are:\n// - \\n ... the newline character\n// - \\ ... the backslash character\n// - \" ... the double-quote character\nexport function escapeLabelValueInExactSelector(labelValue: string): string {\n return labelValue.replace(/\\\\/g, '\\\\\\\\').replace(/\\n/g, '\\\\n').replace(/\"/g, '\\\\\"');\n}\n\nexport function escapeLabelValueInRegexSelector(labelValue: string): string {\n return escapeLabelValueInExactSelector(escapeLokiRegexp(labelValue));\n}\n\nexport function isRegexSelector(selector?: string) {\n if (selector && (selector.includes('=~') || selector.includes('!~'))) {\n return true;\n }\n return false;\n}\n\n// Loki regular-expressions use the RE2 syntax (https://github.com/google/re2/wiki/Syntax),\n// so every character that matches something in that list has to be escaped.\n// the list of meta characters is: *+?()|\\.[]{}^$\n// we make a javascript regular expression that matches those characters:\nconst RE2_METACHARACTERS = /[*+?()|\\\\.\\[\\]{}^$]/g;\nfunction escapeLokiRegexp(value: string): string {\n return value.replace(RE2_METACHARACTERS, '\\\\$&');\n}\n\n/**\n * Get all queries in the scene that have the same datasource as provided source object\n */\nexport function getQueriesForVariables(\n sourceObject: SceneObject<SceneObjectState & { datasource: DataSourceRef | null }>\n) {\n const runners = sceneGraph.findAllObjects(\n sourceObject.getRoot(),\n (o) => o instanceof SceneQueryRunner\n ) as SceneQueryRunner[];\n\n const applicableRunners = filterOutInactiveRunnerDuplicates(runners).filter((r) => {\n return r.state.datasource?.uid === sourceObject.state.datasource?.uid;\n });\n\n if (applicableRunners.length === 0) {\n return [];\n }\n\n const result: SceneDataQuery[] = [];\n applicableRunners.forEach((r) => {\n result.push(...r.state.queries);\n });\n\n return result;\n}\n\n// Filters out inactive runner duplicates, keeping only the ones that are currently active.\n// This is needed for scnearios whan a query runner is cloned and the original is not removed but de-activated.\n// Can happen i.e. when editing a panel in Grafana Core dashboards.\nfunction filterOutInactiveRunnerDuplicates(runners: SceneQueryRunner[]) {\n // Group items by key\n const groupedItems: { [key: string]: SceneQueryRunner[] } = {};\n\n for (const item of runners) {\n if (item.state.key) {\n if (!(item.state.key in groupedItems)) {\n groupedItems[item.state.key] = [];\n }\n groupedItems[item.state.key].push(item);\n }\n }\n\n // Filter out inactive items and concatenate active items\n return Object.values(groupedItems).flatMap((group) => {\n const activeItems = group.filter((item) => item.isActive);\n // Keep inactive items if there's only one item with the key\n if (activeItems.length === 0 && group.length === 1) {\n return group;\n }\n return activeItems;\n });\n}\n\nexport function escapeUrlPipeDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Replace the pipe due to using it as a filter separator\n return (value = /\\|/g[Symbol.replace](value, '__gfp__'));\n}\n\nexport function escapeUrlCommaDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Replace the comma due to using it as a value/label separator\n return /,/g[Symbol.replace](value, '__gfc__');\n}\n\nexport function unescapeUrlDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n value = /__gfp__/g[Symbol.replace](value, '|');\n value = /__gfc__/g[Symbol.replace](value, ',');\n\n return value;\n}\n\nexport function toUrlCommaDelimitedString(key: string, label?: string): string {\n // Omit for identical key/label or when label is not set at all\n if (!label || key === label) {\n return escapeUrlCommaDelimiters(key);\n }\n\n return [key, label].map(escapeUrlCommaDelimiters).join(',');\n}\n\nexport function dataFromResponse(response: GetTagResponse | MetricFindValue[]) {\n return Array.isArray(response) ? response : response.data;\n}\n\nexport function responseHasError(\n response: GetTagResponse | MetricFindValue[]\n): response is GetTagResponse & { error: DataQueryError } {\n return !Array.isArray(response) && Boolean(response.error);\n}\n\n// Collect a flat list of SelectableValues with a `group` property into a hierarchical list with groups\nexport function handleOptionGroups(values: SelectableValue[]): Array<SelectableValue<string>> {\n const result: Array<SelectableValue<string>> = [];\n const groupedResults = new Map<string, Array<SelectableValue<string>>>();\n\n for (const value of values) {\n const groupLabel = value.group;\n if (groupLabel) {\n let group = groupedResults.get(groupLabel);\n\n if (!group) {\n group = [];\n groupedResults.set(groupLabel, group);\n result.push({ label: groupLabel, options: group });\n }\n\n group.push(value);\n } else {\n result.push(value);\n }\n }\n\n return result;\n}\n"],"names":["value"],"mappings":";;;;AASgB,SAAA,oBAAA,CAAqB,GAAqC,CAAqC,EAAA;AAC7G,EAAA,IAAI,MAAM,CAAG,EAAA;AACX,IAAO,OAAA,IAAA,CAAA;AAAA,GACT;AAEA,EAAO,OAAA,OAAA,CAAQ,GAAG,CAAC,CAAA,CAAA;AACrB,CAAA;AAEO,SAAS,mBAAmB,KAAgB,EAAA;AAEjD,EAAA,MAAM,sBAAsB,MAAM;AAChC,IAAM,MAAA,IAAA,uBAAW,OAAQ,EAAA,CAAA;AACzB,IAAO,OAAA,CAAC,GAAWA,MAAyB,KAAA;AAC1C,MAAA,IAAI,OAAOA,MAAAA,KAAU,QAAYA,IAAAA,MAAAA,KAAU,IAAM,EAAA;AAC/C,QAAI,IAAA,IAAA,CAAK,GAAIA,CAAAA,MAAK,CAAG,EAAA;AACnB,UAAA,OAAA;AAAA,SACF;AACA,QAAA,IAAA,CA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AA,CAAQ,QAAQ,CAAA,GAAI,WAAW,QAAS,CAAA,IAAA,CAAA;AACvD,CAAA;AAEO,SAAS,iBACd,QACwD,EAAA;AACxD,EAAA,OAAO,CAAC,KAAM,CAAA,OAAA,CAAQ,QAAQ,CAAK,IAAA,OAAA,CAAQ,SAAS,KAAK,CAAA,CAAA;AAC3D,CAAA;AAGO,SAAS,mBAAmB,MAA2D,EAAA;AAC5F,EAAA,MAAM,SAAyC,EAAC,CAAA;AAChD,EAAM,MAAA,cAAA,uBAAqB,GAA4C,EAAA,CAAA;AAEvE,EAAA,KAAA,MAAW,SAAS,MAAQ,EAAA;AAC1B,IAAA,MAAM,aAAa,KAAM,CAAA,KAAA,CAAA;AACzB,IAAA,IAAI,UAAY,EAAA;AACd,MAAI,IAAA,KAAA,GAAQ,cAAe,CAAA,GAAA,CAAI,UAAU,CAAA,CAAA;AAEzC,MAAA,IAAI,CAAC,KAAO,EAAA;AACV,QAAA,KAAA,GAAQ,EAAC,CAAA;AACT,QAAe,cAAA,CAAA,GAAA,CAAI,YAAY,KAAK,CAAA,CAAA;AACpC,QAAA,MAAA,CAAO,KAAK,EAAE,KAAA,EAAO,UAAY,EAAA,OAAA,EAAS,OAAO,CAAA,CAAA;AAAA,OACnD;AAEA,MAAA,KAAA,CAAM,KAAK,KAAK,CAAA,CAAA;AAAA,KACX,MAAA;AACL,MAAA,MAAA,CAAO,KAAK,KAAK,CAAA,CAAA;AAAA,KACnB;AAAA,GACF;AAEA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"utils.js","sources":["../../../src/variables/utils.ts"],"sourcesContent":["import { isEqual } from 'lodash';\nimport { VariableValue } from './types';\n// @ts-expect-error Remove when 11.1.x is released\nimport { AdHocVariableFilter, DataQueryError, GetTagResponse, MetricFindValue, SelectableValue } from '@grafana/data';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { SceneDataQuery, SceneObject, SceneObjectState } from '../core/types';\nimport { SceneQueryRunner } from '../querying/SceneQueryRunner';\nimport { DataSourceRef } from '@grafana/schema';\nimport uFuzzy from '@leeoniya/ufuzzy';\n\nexport function isVariableValueEqual(a: VariableValue | null | undefined, b: VariableValue | null | undefined) {\n if (a === b) {\n return true;\n }\n\n return isEqual(a, b);\n}\n\nexport function safeStringifyValue(value: unknown) {\n // Avoid circular references ignoring those references\n const getCircularReplacer = () => {\n const seen = new WeakSet();\n return (_: string, value: object | null) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n }\n return value;\n };\n };\n\n try {\n return JSON.stringify(value, getCircularReplacer());\n } catch (error) {\n console.error(error);\n }\n\n return '';\n}\n\nexport function renderPrometheusLabelFilters(filters: AdHocVariableFilter[]) {\n return filters.map((filter) => renderFilter(filter)).join(',');\n}\n\nfunction renderFilter(filter: AdHocVariableFilter) {\n let value = '';\n let operator = filter.operator;\n\n // map \"one of\" operator to regex\n if (operator === '=|') {\n operator = '=~';\n // TODO remove when we're on the latest version of @grafana/data\n // @ts-expect-error\n value = filter.values?.map(escapeLabelValueInRegexSelector).join('|');\n } else if (operator === '!=|') {\n operator = '!~';\n // TODO remove when we're on the latest version of @grafana/data\n // @ts-expect-error\n value = filter.values?.map(escapeLabelValueInRegexSelector).join('|');\n } else if (operator === '=~' || operator === '!~') {\n value = escapeLabelValueInRegexSelector(filter.value);\n } else {\n value = escapeLabelValueInExactSelector(filter.value);\n }\n\n return `${filter.key}${operator}\"${value}\"`;\n}\n\n// based on the openmetrics-documentation, the 3 symbols we have to handle are:\n// - \\n ... the newline character\n// - \\ ... the backslash character\n// - \" ... the double-quote character\nexport function escapeLabelValueInExactSelector(labelValue: string): string {\n return labelValue.replace(/\\\\/g, '\\\\\\\\').replace(/\\n/g, '\\\\n').replace(/\"/g, '\\\\\"');\n}\n\nexport function escapeLabelValueInRegexSelector(labelValue: string): string {\n return escapeLabelValueInExactSelector(escapeLokiRegexp(labelValue));\n}\n\nexport function isRegexSelector(selector?: string) {\n if (selector && (selector.includes('=~') || selector.includes('!~'))) {\n return true;\n }\n return false;\n}\n\n// Loki regular-expressions use the RE2 syntax (https://github.com/google/re2/wiki/Syntax),\n// so every character that matches something in that list has to be escaped.\n// the list of meta characters is: *+?()|\\.[]{}^$\n// we make a javascript regular expression that matches those characters:\nconst RE2_METACHARACTERS = /[*+?()|\\\\.\\[\\]{}^$]/g;\nfunction escapeLokiRegexp(value: string): string {\n return value.replace(RE2_METACHARACTERS, '\\\\$&');\n}\n\n/**\n * Get all queries in the scene that have the same datasource as provided source object\n */\nexport function getQueriesForVariables(\n sourceObject: SceneObject<SceneObjectState & { datasource: DataSourceRef | null }>\n) {\n const runners = sceneGraph.findAllObjects(\n sourceObject.getRoot(),\n (o) => o instanceof SceneQueryRunner\n ) as SceneQueryRunner[];\n\n const applicableRunners = filterOutInactiveRunnerDuplicates(runners).filter((r) => {\n return r.state.datasource?.uid === sourceObject.state.datasource?.uid;\n });\n\n if (applicableRunners.length === 0) {\n return [];\n }\n\n const result: SceneDataQuery[] = [];\n applicableRunners.forEach((r) => {\n result.push(...r.state.queries);\n });\n\n return result;\n}\n\n// Filters out inactive runner duplicates, keeping only the ones that are currently active.\n// This is needed for scnearios whan a query runner is cloned and the original is not removed but de-activated.\n// Can happen i.e. when editing a panel in Grafana Core dashboards.\nfunction filterOutInactiveRunnerDuplicates(runners: SceneQueryRunner[]) {\n // Group items by key\n const groupedItems: { [key: string]: SceneQueryRunner[] } = {};\n\n for (const item of runners) {\n if (item.state.key) {\n if (!(item.state.key in groupedItems)) {\n groupedItems[item.state.key] = [];\n }\n groupedItems[item.state.key].push(item);\n }\n }\n\n // Filter out inactive items and concatenate active items\n return Object.values(groupedItems).flatMap((group) => {\n const activeItems = group.filter((item) => item.isActive);\n // Keep inactive items if there's only one item with the key\n if (activeItems.length === 0 && group.length === 1) {\n return group;\n }\n return activeItems;\n });\n}\n\nexport function escapeUrlPipeDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Replace the pipe due to using it as a filter separator\n return (value = /\\|/g[Symbol.replace](value, '__gfp__'));\n}\n\nexport function escapeUrlCommaDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Replace the comma due to using it as a value/label separator\n return /,/g[Symbol.replace](value, '__gfc__');\n}\n\nexport function unescapeUrlDelimiters(value: string | undefined): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n value = /__gfp__/g[Symbol.replace](value, '|');\n value = /__gfc__/g[Symbol.replace](value, ',');\n\n return value;\n}\n\nexport function toUrlCommaDelimitedString(key: string, label?: string): string {\n // Omit for identical key/label or when label is not set at all\n if (!label || key === label) {\n return escapeUrlCommaDelimiters(key);\n }\n\n return [key, label].map(escapeUrlCommaDelimiters).join(',');\n}\n\nexport function dataFromResponse(response: GetTagResponse | MetricFindValue[]) {\n return Array.isArray(response) ? response : response.data;\n}\n\nexport function responseHasError(\n response: GetTagResponse | MetricFindValue[]\n): response is GetTagResponse & { error: DataQueryError } {\n return !Array.isArray(response) && Boolean(response.error);\n}\n\n// Collect a flat list of SelectableValues with a `group` property into a hierarchical list with groups\nexport function handleOptionGroups(values: SelectableValue[]): Array<SelectableValue<string>> {\n const result: Array<SelectableValue<string>> = [];\n const groupedResults = new Map<string, Array<SelectableValue<string>>>();\n\n for (const value of values) {\n const groupLabel = value.group;\n if (groupLabel) {\n let group = groupedResults.get(groupLabel);\n\n if (!group) {\n group = [];\n groupedResults.set(groupLabel, group);\n result.push({ label: groupLabel, options: group });\n }\n\n group.push(value);\n } else {\n result.push(value);\n }\n }\n\n return result;\n}\n\nexport function getFuzzySearcher(haystack: string[], limit = 10_000) {\n const ufuzzy = new uFuzzy();\n\n const FIRST = Array.from({ length: Math.min(limit, haystack.length) }, (_, i) => i);\n\n // returns matched indices by quality\n return (search: string): number[] => {\n if (search === '') {\n return FIRST;\n }\n\n const [idxs, info, order] = ufuzzy.search(haystack, search);\n\n if (idxs) {\n if (info && order) {\n const outIdxs = Array(Math.min(order.length, limit));\n\n for (let i = 0; i < outIdxs.length; i++) {\n outIdxs[i] = info.idx[order[i]];\n }\n\n return outIdxs;\n }\n\n return idxs.slice(0, limit);\n }\n\n return [];\n };\n}\n"],"names":["value"],"mappings":";;;;;AAUgB,SAAA,oBAAA,CAAqB,GAAqC,CAAqC,EAAA;AAC7G,EAAA,IAAI,MAAM,CAAG,EAAA;AACX,IAAO,OAAA,IAAA,CAAA;AAAA,GACT;AAEA,EAAO,OAAA,OAAA,CAAQ,GAAG,CAAC,CAAA,CAAA;AACrB,CAAA;AAEO,SAAS,mBAAmB,KAAgB,EAAA;AAEjD,EAAA,MAAM,sBAAsB,MAAM;AAChC,IAAM,MAAA,IAAA,uBAAW,OAAQ,EAAA,CAAA;AACzB,IAAO,OAAA,CAAC,GAAWA,MAAyB,KAAA;AAC1C,MAAA,IAAI,OAAOA,MAAAA,KAAU,QAAYA,IAAAA,MAAAA,KAAU,IAAM,EAAA;AAC/C,QAAI,IAAA,IAAA,CAAK,GAAIA,CAAAA,MAAK,CAAG,EAAA;AACnB,UAAA,OAAA;AAAA,SACF;AACA,QAAA,IAAA,CAAK,IAAIA,MAAK,CAAA,CAAA;AAAA,OAChB;AACA,MAAOA,OAAAA,MAAAA,CAAAA;AAAA,KACT,CAAA;AAAA,GACF,CAAA;AAEA,EAAI,IAAA;AACF,IAAA,OAAO,IAAK,CAAA,SAAA,CAAU,KAAO,EAAA,mBAAA,EAAqB,CAAA,CAAA;AAAA,WAC3C,KAAP,EAAA;AACA,IAAA,OAAA,CAAQ,MAAM,KAAK,CAAA,CAAA;AAAA,GACrB;AAEA,EAAO,OAAA,EAAA,CAAA;AACT,CAAA;AAEO,SAAS,6BAA6B,OAAgC,EAAA;AAC3E,EAAO,OAAA,OAAA,CAAQ,IAAI,CAAC,MAAA,KAAW,aAAa,MAAM,CAAC,CAAE,CAAA,IAAA,CAAK,GAAG,CAAA,CAAA;AAC/D,CAAA;AAEA,SAAS,aAAa,MAA6B,EAAA;AA9CnD,EAAA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AAA,CAAA,GAAK,IAAK,CAAA,GAAA,CAAI,KAAM,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,SAC9B;AAEA,QAAO,OAAA,OAAA,CAAA;AAAA,OACT;AAEA,MAAO,OAAA,IAAA,CAAK,KAAM,CAAA,CAAA,EAAG,KAAK,CAAA,CAAA;AAAA,KAC5B;AAEA,IAAA,OAAO,EAAC,CAAA;AAAA,GACV,CAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"TestVariable.js","sources":["../../../../src/variables/variants/TestVariable.tsx"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\n\nimport { sceneGraph } from '../../core/sceneGraph';\nimport { SceneComponentProps } from '../../core/types';\nimport { queryMetricTree } from '../../utils/metricTree';\nimport { VariableDependencyConfig } from '../VariableDependencyConfig';\nimport { renderSelectForVariable } from '../components/VariableValueSelect';\nimport { VariableValueOption } from '../types';\n\nimport { MultiValueVariable, MultiValueVariableState, VariableGetOptionsArgs } from './MultiValueVariable';\nimport { VariableRefresh } from '@grafana/data';\nimport { getClosest } from '../../core/sceneGraph/utils';\nimport { SceneVariableSet } from '../sets/SceneVariableSet';\nimport { SceneQueryControllerEntry } from '../../behaviors/types';\n\nexport interface TestVariableState extends MultiValueVariableState {\n query: string;\n delayMs?: number;\n issuedQuery?: string;\n refresh?: VariableRefresh;\n throwError?: string;\n optionsToReturn?: VariableValueOption[];\n updateOptions?: boolean;\n}\n\n/**\n * This variable is only designed for unit tests and potentially e2e tests.\n */\nexport class TestVariable extends MultiValueVariable<TestVariableState> {\n private completeUpdate = new Subject<number>();\n public isGettingValues = true;\n public getValueOptionsCount = 0;\n isLazy = false;\n\n protected _variableDependency = new VariableDependencyConfig(this, {\n statePaths: ['query'],\n });\n\n public constructor(initialState: Partial<TestVariableState>, isLazy = false) {\n super({\n type: 'custom',\n name: 'Test',\n value: 'Value',\n text: 'Text',\n query: 'Query',\n options: [],\n refresh: VariableRefresh.onDashboardLoad,\n updateOptions: true,\n ...initialState,\n });\n this.isLazy = isLazy;\n }\n\n public getValueOptions(args: VariableGetOptionsArgs): Observable<VariableValueOption[]> {\n const { delayMs } = this.state;\n\n this.getValueOptionsCount += 1;\n\n const queryController = sceneGraph.getQueryController(this);\n\n return new Observable<VariableValueOption[]>((observer) => {\n const queryEntry: SceneQueryControllerEntry = {\n type: 'variable',\n origin: this,\n cancel: () => observer.complete(),\n };\n\n if (queryController) {\n queryController.queryStarted(queryEntry);\n }\n\n this.setState({ loading: true });\n\n if (this.state.throwError) {\n throw new Error(this.state.throwError);\n }\n\n const interpolatedQuery = sceneGraph.interpolate(this, this.state.query);\n const options = this.getOptions(interpolatedQuery);\n\n const sub = this.completeUpdate.subscribe({\n next: () => {\n const newState: Partial<TestVariableState> = { issuedQuery: interpolatedQuery, loading: false };\n\n if (this.state.updateOptions) {\n newState.options = options;\n }\n\n this.setState(newState);\n observer.next(options);\n observer.complete();\n },\n });\n\n let timeout: number | undefined;\n if (delayMs) {\n timeout = window.setTimeout(() => this.signalUpdateCompleted(), delayMs);\n } else if (delayMs === 0) {\n this.signalUpdateCompleted();\n }\n\n this.isGettingValues = true;\n\n return () => {\n sub.unsubscribe();\n window.clearTimeout(timeout);\n this.isGettingValues = false;\n\n if (this.state.loading) {\n this.setState({ loading: false });\n }\n\n if (queryController) {\n queryController.queryCompleted(queryEntry);\n }\n };\n });\n }\n\n public cancel() {\n const sceneVarSet = getClosest(this, (s) => (s instanceof SceneVariableSet ? s : undefined));\n sceneVarSet?.cancel(this);\n }\n\n private getOptions(interpolatedQuery: string) {\n if (this.state.optionsToReturn) {\n return this.state.optionsToReturn;\n }\n\n return queryMetricTree(interpolatedQuery).map((x) => ({ label: x.name, value: x.name }));\n }\n\n /** Useful from tests */\n public signalUpdateCompleted() {\n this.completeUpdate.next(1);\n }\n\n public static Component = ({ model }: SceneComponentProps<MultiValueVariable>) => {\n return renderSelectForVariable(model);\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA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,EAAE,KAAA,EAAqD,KAAA;AAChF,EAAA,OAAO,wBAAwB,KAAK,CAAA,CAAA;AACtC,CAAA;;;;"}
1
+ {"version":3,"file":"TestVariable.js","sources":["../../../../src/variables/variants/TestVariable.tsx"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\n\nimport { sceneGraph } from '../../core/sceneGraph';\nimport { SceneComponentProps } from '../../core/types';\nimport { queryMetricTree } from '../../utils/metricTree';\nimport { VariableDependencyConfig } from '../VariableDependencyConfig';\nimport { renderSelectForVariable } from '../components/VariableValueSelect';\nimport { VariableValueOption } from '../types';\n\nimport { MultiValueVariable, MultiValueVariableState, VariableGetOptionsArgs } from './MultiValueVariable';\nimport { VariableRefresh } from '@grafana/data';\nimport { getClosest } from '../../core/sceneGraph/utils';\nimport { SceneVariableSet } from '../sets/SceneVariableSet';\nimport { SceneQueryControllerEntry } from '../../behaviors/SceneQueryController';\n\nexport interface TestVariableState extends MultiValueVariableState {\n query: string;\n delayMs?: number;\n issuedQuery?: string;\n refresh?: VariableRefresh;\n throwError?: string;\n optionsToReturn?: VariableValueOption[];\n updateOptions?: boolean;\n}\n\n/**\n * This variable is only designed for unit tests and potentially e2e tests.\n */\nexport class TestVariable extends MultiValueVariable<TestVariableState> {\n private completeUpdate = new Subject<number>();\n public isGettingValues = true;\n public getValueOptionsCount = 0;\n isLazy = false;\n\n protected _variableDependency = new VariableDependencyConfig(this, {\n statePaths: ['query'],\n });\n\n public constructor(initialState: Partial<TestVariableState>, isLazy = false) {\n super({\n type: 'custom',\n name: 'Test',\n value: 'Value',\n text: 'Text',\n query: 'Query',\n options: [],\n refresh: VariableRefresh.onDashboardLoad,\n updateOptions: true,\n ...initialState,\n });\n this.isLazy = isLazy;\n }\n\n public getValueOptions(args: VariableGetOptionsArgs): Observable<VariableValueOption[]> {\n const { delayMs } = this.state;\n\n this.getValueOptionsCount += 1;\n\n const queryController = sceneGraph.getQueryController(this);\n\n return new Observable<VariableValueOption[]>((observer) => {\n const queryEntry: SceneQueryControllerEntry = {\n type: 'variable',\n origin: this,\n cancel: () => observer.complete(),\n };\n\n if (queryController) {\n queryController.queryStarted(queryEntry);\n }\n\n this.setState({ loading: true });\n\n if (this.state.throwError) {\n throw new Error(this.state.throwError);\n }\n\n const interpolatedQuery = sceneGraph.interpolate(this, this.state.query);\n const options = this.getOptions(interpolatedQuery);\n\n const sub = this.completeUpdate.subscribe({\n next: () => {\n const newState: Partial<TestVariableState> = { issuedQuery: interpolatedQuery, loading: false };\n\n if (this.state.updateOptions) {\n newState.options = options;\n }\n\n this.setState(newState);\n observer.next(options);\n observer.complete();\n },\n });\n\n let timeout: number | undefined;\n if (delayMs) {\n timeout = window.setTimeout(() => this.signalUpdateCompleted(), delayMs);\n } else if (delayMs === 0) {\n this.signalUpdateCompleted();\n }\n\n this.isGettingValues = true;\n\n return () => {\n sub.unsubscribe();\n window.clearTimeout(timeout);\n this.isGettingValues = false;\n\n if (this.state.loading) {\n this.setState({ loading: false });\n }\n\n if (queryController) {\n queryController.queryCompleted(queryEntry);\n }\n };\n });\n }\n\n public cancel() {\n const sceneVarSet = getClosest(this, (s) => (s instanceof SceneVariableSet ? s : undefined));\n sceneVarSet?.cancel(this);\n }\n\n private getOptions(interpolatedQuery: string) {\n if (this.state.optionsToReturn) {\n return this.state.optionsToReturn;\n }\n\n return queryMetricTree(interpolatedQuery).map((x) => ({ label: x.name, value: x.name }));\n }\n\n /** Useful from tests */\n public signalUpdateCompleted() {\n this.completeUpdate.next(1);\n }\n\n public static Component = ({ model }: SceneComponentProps<MultiValueVariable>) => {\n return renderSelectForVariable(model);\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,MAAM,qBAAqB,kBAAsC,CAAA;AAAA,EAU/D,WAAA,CAAY,YAA0C,EAAA,MAAA,GAAS,KAAO,EAAA;AAC3E,IAAM,KAAA,CAAA,cAAA,CAAA;AAAA,MACJ,IAAM,EAAA,QAAA;AAAA,MACN,IAAM,EAAA,MAAA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K,eAAkB,GAAA,KAAA,CAAA;AAEvB,QAAI,IAAA,IAAA,CAAK,MAAM,OAAS,EAAA;AACtB,UAAA,IAAA,CAAK,QAAS,CAAA,EAAE,OAAS,EAAA,KAAA,EAAO,CAAA,CAAA;AAAA,SAClC;AAEA,QAAA,IAAI,eAAiB,EAAA;AACnB,UAAA,eAAA,CAAgB,eAAe,UAAU,CAAA,CAAA;AAAA,SAC3C;AAAA,OACF,CAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AAAA,EAEO,MAAS,GAAA;AACd,IAAM,MAAA,WAAA,GAAc,WAAW,IAAM,EAAA,CAAC,MAAO,CAAa,YAAA,gBAAA,GAAmB,IAAI,KAAU,CAAA,CAAA,CAAA;AAC3F,IAAA,WAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,WAAA,CAAa,MAAO,CAAA,IAAA,CAAA,CAAA;AAAA,GACtB;AAAA,EAEQ,WAAW,iBAA2B,EAAA;AAC5C,IAAI,IAAA,IAAA,CAAK,MAAM,eAAiB,EAAA;AAC9B,MAAA,OAAO,KAAK,KAAM,CAAA,eAAA,CAAA;AAAA,KACpB;AAEA,IAAA,OAAO,eAAgB,CAAA,iBAAiB,CAAE,CAAA,GAAA,CAAI,CAAC,CAAA,MAAO,EAAE,KAAA,EAAO,CAAE,CAAA,IAAA,EAAM,KAAO,EAAA,CAAA,CAAE,MAAO,CAAA,CAAA,CAAA;AAAA,GACzF;AAAA,EAGO,qBAAwB,GAAA;AAC7B,IAAK,IAAA,CAAA,cAAA,CAAe,KAAK,CAAC,CAAA,CAAA;AAAA,GAC5B;AAKF,CAAA;AAhHa,YAAA,CA6GG,SAAY,GAAA,CAAC,EAAE,KAAA,EAAqD,KAAA;AAChF,EAAA,OAAO,wBAAwB,KAAK,CAAA,CAAA;AACtC,CAAA;;;;"}
package/dist/index.d.ts CHANGED
@@ -963,6 +963,20 @@ declare class UserActionEvent extends BusEventWithPayload<UserActionEventPayload
963
963
  */
964
964
  declare function lookupVariable(name: string, sceneObject: SceneObject): SceneVariable | null;
965
965
 
966
+ /**
967
+ * Will walk up the scene object graph to the closest $timeRange scene object
968
+ */
969
+ declare function getTimeRange(sceneObject: SceneObject): SceneTimeRangeLike;
970
+
971
+ interface SceneQueryStateControllerState extends SceneObjectState {
972
+ isRunning: boolean;
973
+ }
974
+ interface SceneQueryControllerLike extends SceneObject<SceneQueryStateControllerState> {
975
+ isQueryController: true;
976
+ cancelAll(): void;
977
+ queryStarted(entry: SceneQueryControllerEntry): void;
978
+ queryCompleted(entry: SceneQueryControllerEntry): void;
979
+ }
966
980
  interface QueryResultWithState {
967
981
  state: LoadingState;
968
982
  }
@@ -972,40 +986,17 @@ interface SceneQueryControllerEntry {
972
986
  origin: SceneObject;
973
987
  cancel?: () => void;
974
988
  }
975
- type SceneQueryControllerEntryType = 'data' | 'annotations' | 'variable' | 'alerts' | 'plugin';
976
- interface SceneInteractionProfileEvent {
977
- origin: string;
978
- duration: number;
979
- networkDuration: number;
980
- jsHeapSizeLimit: number;
981
- usedJSHeapSize: number;
982
- totalJSHeapSize: number;
983
- crumbs: string[];
984
- }
985
- interface SceneQueryStateControllerState extends SceneObjectState {
986
- isRunning: boolean;
987
- enableProfiling?: boolean;
988
- onProfileComplete?(event: SceneInteractionProfileEvent): void;
989
- }
990
- interface SceneQueryControllerLike extends SceneObject<SceneQueryStateControllerState> {
989
+ type SceneQueryControllerEntryType = 'data' | 'annotations' | 'variable' | 'alerts';
990
+ declare class SceneQueryController extends SceneObjectBase<SceneQueryStateControllerState> implements SceneQueryControllerLike {
991
+ #private;
991
992
  isQueryController: true;
992
- cancelAll(): void;
993
+ constructor();
993
994
  queryStarted(entry: SceneQueryControllerEntry): void;
994
995
  queryCompleted(entry: SceneQueryControllerEntry): void;
995
- startProfile(source: SceneObject): void;
996
- runningQueriesCount(): number;
996
+ private changeRunningQueryCount;
997
+ cancelAll(): void;
997
998
  }
998
999
 
999
- /**
1000
- * Returns the closest query controller undefined if none found
1001
- */
1002
- declare function getQueryController(sceneObject: SceneObject): SceneQueryControllerLike | undefined;
1003
-
1004
- /**
1005
- * Will walk up the scene object graph to the closest $timeRange scene object
1006
- */
1007
- declare function getTimeRange(sceneObject: SceneObject): SceneTimeRangeLike;
1008
-
1009
1000
  interface UrlSyncManagerLike {
1010
1001
  initSync(root: SceneObject): void;
1011
1002
  cleanUp(root: SceneObject): void;
@@ -1108,6 +1099,15 @@ declare function getAncestor<ParentType>(sceneObject: SceneObject, ancestorType:
1108
1099
  * This will search down the full scene graph, looking for objects that match the provided descendentType type.
1109
1100
  */
1110
1101
  declare function findDescendents<T extends SceneObject>(scene: SceneObject, descendentType: SceneType<T>): T[];
1102
+ /**
1103
+ * Returns the closest query controller undefined if none found
1104
+ */
1105
+ declare function getQueryController(sceneObject: SceneObject): SceneQueryControllerLike | undefined;
1106
+ /**
1107
+ * Returns the closest SceneObject that has a state property with the
1108
+ * name urlSyncManager that is of type UrlSyncManager
1109
+ */
1110
+ declare function getUrlSyncManager(sceneObject: SceneObject): UrlSyncManagerLike | undefined;
1111
1111
 
1112
1112
  declare const sceneGraph: {
1113
1113
  getVariables: typeof getVariables;
@@ -1123,8 +1123,9 @@ declare const sceneGraph: {
1123
1123
  findObject: typeof findObject;
1124
1124
  findAllObjects: typeof findAllObjects;
1125
1125
  getAncestor: typeof getAncestor;
1126
- getQueryController: typeof getQueryController;
1127
1126
  findDescendents: typeof findDescendents;
1127
+ getQueryController: typeof getQueryController;
1128
+ getUrlSyncManager: typeof getUrlSyncManager;
1128
1129
  };
1129
1130
 
1130
1131
  interface ActWhenVariableChangedState extends SceneObjectState {
@@ -1170,19 +1171,6 @@ declare class PanelContextEventBus implements EventBus {
1170
1171
  newScopedBus(key: string, filter: EventFilterOptions): EventBus;
1171
1172
  }
1172
1173
 
1173
- declare class SceneQueryController extends SceneObjectBase<SceneQueryStateControllerState> implements SceneQueryControllerLike {
1174
- #private;
1175
- isQueryController: true;
1176
- private profiler;
1177
- constructor(state?: Partial<SceneQueryStateControllerState>);
1178
- runningQueriesCount: () => number;
1179
- startProfile(source: SceneObject): void;
1180
- queryStarted(entry: SceneQueryControllerEntry): void;
1181
- queryCompleted(entry: SceneQueryControllerEntry): void;
1182
- private changeRunningQueryCount;
1183
- cancelAll(): void;
1184
- }
1185
-
1186
1174
  interface LiveNowTimerState extends SceneObjectState {
1187
1175
  enabled: boolean;
1188
1176
  }
@@ -2839,4 +2827,4 @@ declare const sceneUtils: {
2839
2827
  isGroupByVariable: typeof isGroupByVariable;
2840
2828
  };
2841
2829
 
2842
- export { AdHocFiltersVariable, CancelActivationHandler, ConstantVariable, ControlsLabel, ControlsLayout, CustomFormatterVariable, CustomTransformOperator, CustomTransformerDefinition, CustomVariable, CustomVariableValue, DataLayerFilter, DataProviderProxy, DataRequestEnricher, DataSourceVariable, DeepPartial, EmbeddedScene, EmbeddedSceneState, ExtraQueryDataProcessor, ExtraQueryDescriptor, ExtraQueryProvider, FieldConfigBuilder, FieldConfigBuilders, FieldConfigOverridesBuilder, FiltersRequestEnricher, FormatVariable, GroupByVariable, InterpolationFormatParameter, IntervalVariable, LocalValueVariable, MacroVariableConstructor, MultiValueVariable, MultiValueVariableState, NestedScene, NewSceneObjectAddedEvent, PanelBuilders, PanelOptionsBuilders, QueryRunnerState, QueryVariable, RuntimeDataSource, SafeSerializableSceneObject, SceneActivationHandler, SceneApp, SceneAppDrilldownView, SceneAppPage, SceneAppPageLike, SceneAppPageState, SceneAppRoute, SceneByFrameRepeater, SceneByVariableRepeater, SceneCSSGridItem, SceneCSSGridLayout, SceneCanvasText, SceneComponent, SceneComponentProps, SceneControlsSpacer, SceneDataLayerBase, SceneDataLayerControls, SceneDataLayerProvider, SceneDataLayerProviderState, SceneDataLayerSet, SceneDataLayerSetBase, SceneDataNode, SceneDataProvider, SceneDataProviderResult, SceneDataQuery, SceneDataState, SceneDataTransformer, SceneDataTransformerState, SceneDeactivationHandler, SceneDebugger, SceneFlexItem, SceneFlexItemLike, SceneFlexItemState, SceneFlexLayout, SceneGridItem, SceneGridItemLike, SceneGridItemStateLike, SceneGridLayout, SceneGridRow, SceneInteractionProfileEvent, SceneLayout, SceneLayoutChildOptions, SceneLayoutState, SceneObject, SceneObjectBase, SceneObjectRef, SceneObjectState, SceneObjectStateChangedEvent, SceneObjectStateChangedPayload, SceneObjectUrlSyncConfig, SceneObjectUrlSyncHandler, SceneObjectUrlValue, SceneObjectUrlValues, SceneObjectWithUrlSync, SceneQueryControllerEntry, SceneQueryControllerEntryType, SceneQueryControllerLike, SceneQueryRunner, SceneReactObject, SceneRefreshPicker, SceneRefreshPickerState, SceneRouteMatch, SceneStateChangedHandler, SceneStatelessBehavior, SceneTimePicker, SceneTimeRange, SceneTimeRangeCompare, SceneTimeRangeLike, SceneTimeRangeState, SceneTimeRangeTransformerBase, SceneTimeZoneOverride, SceneToolbarButton, SceneToolbarInput, SceneUrlSyncOptions, SceneVariable, SceneVariableDependencyConfigLike, SceneVariableSet, SceneVariableSetState, SceneVariableState, SceneVariableValueChangedEvent, SceneVariables, SplitLayout, TestVariable, TextBoxVariable, UrlSyncContextProvider, UrlSyncManager, UrlSyncManagerLike, UseStateHookOptions, UserActionEvent, ValidateAndUpdateResult, VariableCustomFormatterFn, VariableDependencyConfig, VariableGetOptionsArgs, VariableValue, VariableValueControl, VariableValueOption, VariableValueSelectWrapper, VariableValueSelectors, VariableValueSingle, VizConfig, VizConfigBuilder, VizConfigBuilders, VizPanel, VizPanelBuilder, VizPanelExploreButton, VizPanelMenu, VizPanelState, index$1 as behaviors, index as dataLayers, formatRegistry, getExploreURL, isCustomVariableValue, isDataLayer, isDataRequestEnricher, isFiltersRequestEnricher, isSceneObject, registerQueryWithController, registerRuntimeDataSource, renderSelectForVariable, sceneGraph, sceneUtils, useSceneApp, useSceneObjectState, useUrlSync };
2830
+ export { AdHocFiltersVariable, CancelActivationHandler, ConstantVariable, ControlsLabel, ControlsLayout, CustomFormatterVariable, CustomTransformOperator, CustomTransformerDefinition, CustomVariable, CustomVariableValue, DataLayerFilter, DataProviderProxy, DataRequestEnricher, DataSourceVariable, DeepPartial, EmbeddedScene, EmbeddedSceneState, ExtraQueryDataProcessor, ExtraQueryDescriptor, ExtraQueryProvider, FieldConfigBuilder, FieldConfigBuilders, FieldConfigOverridesBuilder, FiltersRequestEnricher, FormatVariable, GroupByVariable, InterpolationFormatParameter, IntervalVariable, LocalValueVariable, MacroVariableConstructor, MultiValueVariable, MultiValueVariableState, NestedScene, NewSceneObjectAddedEvent, PanelBuilders, PanelOptionsBuilders, QueryRunnerState, QueryVariable, RuntimeDataSource, SafeSerializableSceneObject, SceneActivationHandler, SceneApp, SceneAppDrilldownView, SceneAppPage, SceneAppPageLike, SceneAppPageState, SceneAppRoute, SceneByFrameRepeater, SceneByVariableRepeater, SceneCSSGridItem, SceneCSSGridLayout, SceneCanvasText, SceneComponent, SceneComponentProps, SceneControlsSpacer, SceneDataLayerBase, SceneDataLayerControls, SceneDataLayerProvider, SceneDataLayerProviderState, SceneDataLayerSet, SceneDataLayerSetBase, SceneDataNode, SceneDataProvider, SceneDataProviderResult, SceneDataQuery, SceneDataState, SceneDataTransformer, SceneDataTransformerState, SceneDeactivationHandler, SceneDebugger, SceneFlexItem, SceneFlexItemLike, SceneFlexItemState, SceneFlexLayout, SceneGridItem, SceneGridItemLike, SceneGridItemStateLike, SceneGridLayout, SceneGridRow, SceneLayout, SceneLayoutChildOptions, SceneLayoutState, SceneObject, SceneObjectBase, SceneObjectRef, SceneObjectState, SceneObjectStateChangedEvent, SceneObjectStateChangedPayload, SceneObjectUrlSyncConfig, SceneObjectUrlSyncHandler, SceneObjectUrlValue, SceneObjectUrlValues, SceneObjectWithUrlSync, SceneQueryControllerEntry, SceneQueryControllerEntryType, SceneQueryControllerLike, SceneQueryRunner, SceneReactObject, SceneRefreshPicker, SceneRefreshPickerState, SceneRouteMatch, SceneStateChangedHandler, SceneStatelessBehavior, SceneTimePicker, SceneTimeRange, SceneTimeRangeCompare, SceneTimeRangeLike, SceneTimeRangeState, SceneTimeRangeTransformerBase, SceneTimeZoneOverride, SceneToolbarButton, SceneToolbarInput, SceneUrlSyncOptions, SceneVariable, SceneVariableDependencyConfigLike, SceneVariableSet, SceneVariableSetState, SceneVariableState, SceneVariableValueChangedEvent, SceneVariables, SplitLayout, TestVariable, TextBoxVariable, UrlSyncContextProvider, UrlSyncManager, UrlSyncManagerLike, UseStateHookOptions, UserActionEvent, ValidateAndUpdateResult, VariableCustomFormatterFn, VariableDependencyConfig, VariableGetOptionsArgs, VariableValue, VariableValueControl, VariableValueOption, VariableValueSelectWrapper, VariableValueSelectors, VariableValueSingle, VizConfig, VizConfigBuilder, VizConfigBuilders, VizPanel, VizPanelBuilder, VizPanelExploreButton, VizPanelMenu, VizPanelState, index$1 as behaviors, index as dataLayers, formatRegistry, getExploreURL, isCustomVariableValue, isDataLayer, isDataRequestEnricher, isFiltersRequestEnricher, isSceneObject, registerQueryWithController, registerRuntimeDataSource, renderSelectForVariable, sceneGraph, sceneUtils, useSceneApp, useSceneObjectState, useUrlSync };