@grafana/scenes 5.25.0 → 5.25.1--canary.858.11930656504.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (41) hide show
  1. package/CHANGELOG.md +6 -6
  2. package/dist/esm/behaviors/SceneQueryController.js +60 -5
  3. package/dist/esm/behaviors/SceneQueryController.js.map +1 -1
  4. package/dist/esm/behaviors/SceneRenderProfiler.js +169 -0
  5. package/dist/esm/behaviors/SceneRenderProfiler.js.map +1 -0
  6. package/dist/esm/components/SceneRefreshPicker.js +6 -1
  7. package/dist/esm/components/SceneRefreshPicker.js.map +1 -1
  8. package/dist/esm/components/VizPanel/VizPanel.js +9 -6
  9. package/dist/esm/components/VizPanel/VizPanel.js.map +1 -1
  10. package/dist/esm/components/layout/grid/SceneGridRow.js +2 -1
  11. package/dist/esm/components/layout/grid/SceneGridRow.js.map +1 -1
  12. package/dist/esm/core/SceneTimeRange.js +3 -0
  13. package/dist/esm/core/SceneTimeRange.js.map +1 -1
  14. package/dist/esm/core/sceneGraph/getQueryController.js +19 -0
  15. package/dist/esm/core/sceneGraph/getQueryController.js.map +1 -0
  16. package/dist/esm/core/sceneGraph/index.js +3 -3
  17. package/dist/esm/core/sceneGraph/index.js.map +1 -1
  18. package/dist/esm/core/sceneGraph/sceneGraph.js +1 -26
  19. package/dist/esm/core/sceneGraph/sceneGraph.js.map +1 -1
  20. package/dist/esm/index.js.map +1 -1
  21. package/dist/esm/querying/SceneQueryRunner.js +1 -3
  22. package/dist/esm/querying/SceneQueryRunner.js.map +1 -1
  23. package/dist/esm/querying/registerQueryWithController.js +18 -2
  24. package/dist/esm/querying/registerQueryWithController.js.map +1 -1
  25. package/dist/esm/utils/getDataSource.js +17 -1
  26. package/dist/esm/utils/getDataSource.js.map +1 -1
  27. package/dist/esm/variables/VariableDependencyConfig.js +29 -0
  28. package/dist/esm/variables/VariableDependencyConfig.js.map +1 -1
  29. package/dist/esm/variables/adhoc/AdHocFilterRenderer.js +12 -8
  30. package/dist/esm/variables/adhoc/AdHocFilterRenderer.js.map +1 -1
  31. package/dist/esm/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.js +1 -4
  32. package/dist/esm/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.js.map +1 -1
  33. package/dist/esm/variables/components/VariableValueSelect.js +5 -0
  34. package/dist/esm/variables/components/VariableValueSelect.js.map +1 -1
  35. package/dist/esm/variables/sets/SceneVariableSet.js.map +1 -1
  36. package/dist/esm/variables/utils.js.map +1 -1
  37. package/dist/esm/variables/variants/TestVariable.js.map +1 -1
  38. package/dist/index.d.ts +49 -32
  39. package/dist/index.js +788 -509
  40. package/dist/index.js.map +1 -1
  41. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"SceneQueryRunner.js","sources":["../../../src/querying/SceneQueryRunner.ts"],"sourcesContent":["import { cloneDeep, isEqual } from 'lodash';\nimport { forkJoin, ReplaySubject, Unsubscribable } from 'rxjs';\n\nimport { DataQuery, DataSourceRef, LoadingState } from '@grafana/schema';\n\nimport {\n AlertStateInfo,\n DataFrame,\n DataFrameView,\n DataQueryRequest,\n DataSourceApi,\n DataTopic,\n PanelData,\n preProcessPanelData,\n rangeUtil,\n} from '@grafana/data';\n\n// TODO: Remove this ignore annotation when the grafana runtime dependency has been updated\n// @ts-ignore\nimport { getRunRequest, toDataQueryError, isExpressionReference, config } from '@grafana/runtime';\n\nimport { SceneObjectBase } from '../core/SceneObjectBase';\nimport { sceneGraph } from '../core/sceneGraph';\nimport {\n DataLayerFilter,\n SceneDataProvider,\n SceneDataProviderResult,\n SceneDataQuery,\n SceneObjectState,\n SceneTimeRangeLike,\n} from '../core/types';\nimport { getDataSource } from '../utils/getDataSource';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig';\nimport { writeSceneLog } from '../utils/writeSceneLog';\nimport { VariableValueRecorder } from '../variables/VariableValueRecorder';\nimport { emptyPanelData } from '../core/SceneDataNode';\nimport { getClosest } from '../core/sceneGraph/utils';\nimport { isExtraQueryProvider, ExtraQueryDataProcessor, ExtraQueryProvider } from './ExtraQueryProvider';\nimport { passthroughProcessor, extraQueryProcessingOperator } from './extraQueryProcessingOperator';\nimport { filterAnnotations } from './layers/annotations/filterAnnotations';\nimport { getEnrichedDataRequest } from './getEnrichedDataRequest';\nimport { findActiveAdHocFilterVariableByUid } from '../variables/adhoc/patchGetAdhocFilters';\nimport { registerQueryWithController } from './registerQueryWithController';\nimport { findActiveGroupByVariablesByUid } from '../variables/groupby/findActiveGroupByVariablesByUid';\nimport { GroupByVariable } from '../variables/groupby/GroupByVariable';\nimport { AdHocFiltersVariable, isFilterComplete } from '../variables/adhoc/AdHocFiltersVariable';\nimport { SceneVariable } from '../variables/types';\nimport { DataLayersMerger } from './DataLayersMerger';\nimport { interpolate } from '../core/sceneGraph/sceneGraph';\nimport { wrapInSafeSerializableSceneObject } from '../utils/wrapInSafeSerializableSceneObject';\n\nlet counter = 100;\n\nexport function getNextRequestId() {\n return 'SQR' + counter++;\n}\n\nexport interface QueryRunnerState extends SceneObjectState {\n data?: PanelData;\n queries: SceneDataQuery[];\n datasource?: DataSourceRef;\n minInterval?: string;\n maxDataPoints?: number;\n liveStreaming?: boolean;\n maxDataPointsFromWidth?: boolean;\n cacheTimeout?: DataQueryRequest['cacheTimeout'];\n queryCachingTTL?: DataQueryRequest['queryCachingTTL'];\n /**\n * When set to auto (the default) query runner will issue queries on activate (when variable dependencies are ready) or when time range change.\n * Set to manual to have full manual control over when queries are issued. Try not to set this. This is mainly useful for unit tests, or special edge case workflows.\n */\n runQueriesMode?: 'auto' | 'manual';\n // Filters to be applied to data layer results before combining them with SQR results\n dataLayerFilter?: DataLayerFilter;\n // Private runtime state\n _hasFetchedData?: boolean;\n}\n\nexport interface DataQueryExtended extends DataQuery {\n [key: string]: any;\n\n // Opt this query out of time window comparison\n timeRangeCompare?: boolean;\n}\n\n// The requests that will be run by the query runner.\n//\n// Generally the query runner will run a single primary request.\n// If the scene graph contains implementations of\n// `ExtraQueryProvider`, the requests created by these\n// implementations will be added to the list of secondary requests,\n// and these will be executed at the same time as the primary request.\n//\n// The results of each secondary request will be passed to an associated\n// processor function (along with the results of the primary request),\n// which can transform the results as desired.\ninterface PreparedRequests {\n // The primary request to run.\n primary: DataQueryRequest;\n // A possibly empty list of secondary requests to run alongside\n // the primary request.\n secondaries: DataQueryRequest[];\n // A map from `requestId` of secondary requests to processors\n // for those requests. Provided by the `ExtraQueryProvider`.\n processors: Map<string, ExtraQueryDataProcessor>;\n}\n\nexport class SceneQueryRunner extends SceneObjectBase<QueryRunnerState> implements SceneDataProvider {\n private _querySub?: Unsubscribable;\n private _dataLayersSub?: Unsubscribable;\n private _dataLayersMerger = new DataLayersMerger();\n private _timeSub?: Unsubscribable;\n private _timeSubRange?: SceneTimeRangeLike;\n private _containerWidth?: number;\n private _variableValueRecorder = new VariableValueRecorder();\n private _results = new ReplaySubject<SceneDataProviderResult>(1);\n private _scopedVars = { __sceneObject: wrapInSafeSerializableSceneObject(this) };\n private _layerAnnotations?: DataFrame[];\n private _resultAnnotations?: DataFrame[];\n\n private _adhocFiltersVar?: AdHocFiltersVariable;\n private _groupByVar?: GroupByVariable;\n\n public getResultsStream() {\n return this._results;\n }\n\n protected _variableDependency: VariableDependencyConfig<QueryRunnerState> = new VariableDependencyConfig(this, {\n statePaths: ['queries', 'datasource'],\n onVariableUpdateCompleted: this.onVariableUpdatesCompleted.bind(this),\n onAnyVariableChanged: this.onAnyVariableChanged.bind(this),\n });\n\n public constructor(initialState: QueryRunnerState) {\n super(initialState);\n\n this.addActivationHandler(() => this._onActivate());\n }\n\n private _onActivate() {\n if (this.isQueryModeAuto()) {\n const timeRange = sceneGraph.getTimeRange(this);\n\n // Add subscriptions to any extra providers so that they rerun queries\n // when their state changes and they should rerun.\n const providers = this.getClosestExtraQueryProviders();\n for (const provider of providers) {\n this._subs.add(\n provider.subscribeToState((n, p) => {\n if (provider.shouldRerun(p, n, this.state.queries)) {\n this.runQueries();\n }\n }),\n );\n }\n\n this.subscribeToTimeRangeChanges(\n timeRange,\n );\n\n if (this.shouldRunQueriesOnActivate()) {\n this.runQueries();\n }\n }\n\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n\n return () => this._onDeactivate();\n }\n\n // This method subscribes to all SceneDataLayers up until the root, and combines the results into data provided from SceneQueryRunner\n private _handleDataLayers() {\n const dataLayers = sceneGraph.getDataLayers(this);\n\n if (dataLayers.length === 0) {\n return;\n }\n\n this._dataLayersSub = this._dataLayersMerger\n .getMergedStream(dataLayers)\n .subscribe(this._onLayersReceived.bind(this));\n }\n\n private _onLayersReceived(results: Iterable<SceneDataProviderResult>) {\n const timeRange = sceneGraph.getTimeRange(this);\n const { dataLayerFilter } = this.state;\n\n let annotations: DataFrame[] = [];\n let alertStates: DataFrame[] = [];\n let alertState: AlertStateInfo | undefined;\n\n for (const result of results) {\n for (let frame of result.data.series) {\n if (frame.meta?.dataTopic === DataTopic.Annotations) {\n annotations = annotations.concat(frame);\n }\n if (frame.meta?.dataTopic === DataTopic.AlertStates) {\n alertStates = alertStates.concat(frame);\n }\n }\n }\n\n if (dataLayerFilter?.panelId) {\n if (annotations.length > 0) {\n annotations = filterAnnotations(annotations, dataLayerFilter);\n }\n\n if (alertStates.length > 0) {\n for (const frame of alertStates) {\n const frameView = new DataFrameView<AlertStateInfo>(frame);\n\n for (const row of frameView) {\n if (row.panelId === dataLayerFilter.panelId) {\n alertState = row;\n break;\n }\n }\n }\n }\n }\n\n // Skip unnessary state updates\n if (\n allFramesEmpty(annotations) &&\n allFramesEmpty(this._layerAnnotations) &&\n isEqual(alertState, this.state.data?.alertState)\n ) {\n return;\n }\n\n this._layerAnnotations = annotations;\n\n const baseStateUpdate = this.state.data ? this.state.data : { ...emptyPanelData, timeRange: timeRange.state.value };\n\n this.setState({\n data: {\n ...baseStateUpdate,\n annotations: [...(this._resultAnnotations ?? []), ...annotations],\n alertState: alertState ?? this.state.data?.alertState,\n },\n });\n }\n\n /**\n * This tries to start a new query whenever a variable completes or is changed.\n *\n * We care about variable update completions even when the variable has not changed and even when it is not a direct dependency.\n * Example: Variables A and B (B depends on A). A update depends on time range. So when time change query runner will\n * find that variable A is loading which is a dependency on of variable B so will set _isWaitingForVariables to true and\n * not issue any query.\n *\n * When A completes it's loading (with no value change, so B never updates) it will cause a call of this function letting\n * the query runner know that A has completed, and in case _isWaitingForVariables we try to run the query. The query will\n * only run if all variables are in a non loading state so in other scenarios where a query depends on many variables this will\n * be called many times until all dependencies are in a non loading state. *\n */\n private onVariableUpdatesCompleted() {\n if(this.isQueryModeAuto()){\n this.runQueries();\n }\n }\n\n /**\n * Check if value changed is a adhoc filter o group by variable that did not exist when we issued the last query\n */\n private onAnyVariableChanged(variable: SceneVariable) {\n // If this variable has already been detected this variable as a dependency onVariableUpdatesCompleted above will handle value changes\n if (this._adhocFiltersVar === variable || this._groupByVar === variable || !this.isQueryModeAuto()) {\n return;\n }\n\n if (variable instanceof AdHocFiltersVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n\n if (variable instanceof GroupByVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n }\n\n private _isRelevantAutoVariable(variable: AdHocFiltersVariable | GroupByVariable) {\n const datasource = this.state.datasource ?? findFirstDatasource(this.state.queries);\n return variable.state.applyMode === 'auto' && datasource?.uid === variable.state.datasource?.uid;\n }\n\n private shouldRunQueriesOnActivate() {\n if (this._variableValueRecorder.hasDependenciesChanged(this)) {\n writeSceneLog(\n 'SceneQueryRunner',\n 'Variable dependency changed while inactive, shouldRunQueriesOnActivate returns true'\n );\n return true;\n }\n\n // If we don't have any data we should run queries\n if (!this.state.data) {\n return true;\n }\n\n // If time range is stale / different we should run queries\n if (this._isDataTimeRangeStale(this.state.data)) {\n return true;\n }\n\n return false;\n }\n\n private _isDataTimeRangeStale(data: PanelData) {\n const timeRange = sceneGraph.getTimeRange(this);\n\n const stateTimeRange = timeRange.state.value;\n const dataTimeRange = data.timeRange;\n\n if (\n stateTimeRange.from.unix() === dataTimeRange.from.unix() &&\n stateTimeRange.to.unix() === dataTimeRange.to.unix()\n ) {\n return false;\n }\n writeSceneLog('SceneQueryRunner', 'Data time range is stale');\n return true;\n }\n\n private _onDeactivate(): void {\n if (this._querySub) {\n this._querySub.unsubscribe();\n this._querySub = undefined;\n }\n\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = undefined;\n }\n\n this._timeSub?.unsubscribe();\n this._timeSub = undefined;\n this._timeSubRange = undefined;\n this._adhocFiltersVar = undefined;\n this._groupByVar = undefined;\n this._variableValueRecorder.recordCurrentDependencyValuesForSceneObject(this);\n }\n\n public setContainerWidth(width: number) {\n // If we don't have a width we should run queries\n if (!this._containerWidth && width > 0) {\n this._containerWidth = width;\n\n // If we don't have maxDataPoints specifically set and maxDataPointsFromWidth is true\n if (this.state.maxDataPointsFromWidth && !this.state.maxDataPoints) {\n // As this is called from render path we need to wait for next tick before running queries\n setTimeout(() => {\n if (this.isActive && !this.state._hasFetchedData) {\n this.runQueries();\n }\n }, 0);\n }\n } else {\n // if the updated container width is bigger than 0 let's remember the width until next query issue\n if (width > 0) {\n this._containerWidth = width;\n }\n }\n }\n\n public isDataReadyToDisplay() {\n return Boolean(this.state._hasFetchedData);\n }\n\n private subscribeToTimeRangeChanges(timeRange: SceneTimeRangeLike) {\n if (this._timeSubRange === timeRange) {\n // Nothing to do, already subscribed\n return;\n }\n\n if (this._timeSub) {\n this._timeSub.unsubscribe();\n }\n\n this._timeSubRange = timeRange;\n this._timeSub = timeRange.subscribeToState(() => {\n this.runWithTimeRange(timeRange);\n });\n }\n\n public runQueries() {\n const timeRange = sceneGraph.getTimeRange(this);\n if(this.isQueryModeAuto()){\n this.subscribeToTimeRangeChanges(timeRange);\n }\n\n this.runWithTimeRange(timeRange);\n }\n\n private getMaxDataPoints() {\n if (this.state.maxDataPoints) {\n return this.state.maxDataPoints;\n }\n\n return this.state.maxDataPointsFromWidth ? this._containerWidth ?? 500 : 500;\n }\n\n public cancelQuery() {\n this._querySub?.unsubscribe();\n\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = undefined;\n }\n\n this.setState({\n data: { ...this.state.data!, state: LoadingState.Done },\n });\n }\n\n private async runWithTimeRange(timeRange: SceneTimeRangeLike) {\n // If no maxDataPoints specified we might need to wait for container width to be set from the outside\n if (!this.state.maxDataPoints && this.state.maxDataPointsFromWidth && !this._containerWidth) {\n return;\n }\n\n // If data layers subscription doesn't exist, create one\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n\n // Cancel any running queries\n this._querySub?.unsubscribe();\n\n // Skip executing queries if variable dependency is in loading state\n if (this._variableDependency.hasDependencyInLoadingState()) {\n writeSceneLog('SceneQueryRunner', 'Variable dependency is in loading state, skipping query execution');\n this.setState({ data: { ...(this.state.data ?? emptyPanelData), state: LoadingState.Loading } });\n return;\n }\n\n const { queries } = this.state;\n\n // Simple path when no queries exist\n if (!queries?.length) {\n this._setNoDataState();\n return;\n }\n\n try {\n const datasource = this.state.datasource ?? findFirstDatasource(queries);\n const ds = await getDataSource(datasource, this._scopedVars);\n\n this.findAndSubscribeToAdHocFilters(datasource?.uid);\n\n const runRequest = getRunRequest();\n const { primary, secondaries, processors } = this.prepareRequests(timeRange, ds);\n\n writeSceneLog('SceneQueryRunner', 'Starting runRequest', this.state.key);\n\n let stream = runRequest(ds, primary);\n\n if (secondaries.length > 0) {\n // Submit all secondary requests in parallel.\n const secondaryStreams = secondaries.map((r) => runRequest(ds, r));\n // Create the rxjs operator which will combine the primary and secondary responses\n // by calling the correct processor functions provided by the\n // extra request providers.\n const op = extraQueryProcessingOperator(processors);\n // Combine the primary and secondary streams into a single stream, and apply the operator.\n stream = forkJoin([stream, ...secondaryStreams]).pipe(op);\n }\n\n stream = stream.pipe(\n registerQueryWithController({\n type: 'data',\n request: primary,\n origin: this,\n cancel: () => this.cancelQuery(),\n })\n );\n\n this._querySub = stream.subscribe(this.onDataReceived);\n } catch (err) {\n console.error('PanelQueryRunner Error', err);\n\n this.onDataReceived({\n ...emptyPanelData,\n ...this.state.data,\n state: LoadingState.Error,\n errors: [toDataQueryError(err)],\n });\n }\n }\n\n public clone(withState?: Partial<QueryRunnerState>) {\n const clone = super.clone(withState);\n\n if (this._resultAnnotations) {\n clone['_resultAnnotations'] = this._resultAnnotations.map((frame) => ({ ...frame }));\n }\n\n if (this._layerAnnotations) {\n clone['_layerAnnotations'] = this._layerAnnotations.map((frame) => ({ ...frame }));\n }\n\n clone['_variableValueRecorder'] = this._variableValueRecorder.cloneAndRecordCurrentValuesForSceneObject(this);\n clone['_containerWidth'] = this._containerWidth;\n clone['_results'].next({ origin: this, data: this.state.data ?? emptyPanelData });\n\n return clone;\n }\n\n private prepareRequests(timeRange: SceneTimeRangeLike, ds: DataSourceApi): PreparedRequests {\n const { minInterval, queries } = this.state;\n\n let request: DataQueryRequest<DataQueryExtended> = {\n app: 'scenes',\n requestId: getNextRequestId(),\n timezone: timeRange.getTimeZone(),\n range: timeRange.state.value,\n interval: '1s',\n intervalMs: 1000,\n targets: cloneDeep(queries),\n maxDataPoints: this.getMaxDataPoints(),\n scopedVars: this._scopedVars,\n startTime: Date.now(),\n liveStreaming: this.state.liveStreaming,\n rangeRaw: {\n from: timeRange.state.from,\n to: timeRange.state.to,\n },\n cacheTimeout: this.state.cacheTimeout,\n queryCachingTTL: this.state.queryCachingTTL,\n // This asks the scene root to provide context properties like app, panel and dashboardUID\n ...getEnrichedDataRequest(this),\n };\n\n if (this._adhocFiltersVar) {\n // only pass filters that have both key and value\n // @ts-ignore (Temporary ignore until we update @grafana/data)\n request.filters = this._adhocFiltersVar.state.filters.filter(isFilterComplete);\n }\n\n if (this._groupByVar) {\n // @ts-ignore (Temporary ignore until we update @grafana/data)\n request.groupByKeys = this._groupByVar.state.value;\n }\n\n request.targets = request.targets.map((query) => {\n if (\n !query.datasource ||\n (query.datasource.uid !== ds.uid &&\n !ds.meta?.mixed &&\n isExpressionReference /* TODO: Remove this check when isExpressionReference is properly exported from grafan runtime */ &&\n !isExpressionReference(query.datasource))\n ) {\n query.datasource = ds.getRef();\n }\n return query;\n });\n\n const lowerIntervalLimit = minInterval ? interpolate(this, minInterval) : ds.interval;\n const norm = rangeUtil.calculateInterval(timeRange.state.value, request.maxDataPoints!, lowerIntervalLimit);\n\n // make shallow copy of scoped vars,\n // and add built in variables interval and interval_ms\n request.scopedVars = Object.assign({}, request.scopedVars, {\n __interval: { text: norm.interval, value: norm.interval },\n __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs },\n });\n\n request.interval = norm.interval;\n request.intervalMs = norm.intervalMs;\n\n // If there are any extra request providers, we need to add a new request for each\n // and map the request's ID to the processor function given by the provider, to ensure that\n // the processor is called with the correct response data.\n const primaryTimeRange = timeRange.state.value;\n let secondaryRequests: DataQueryRequest[] = [];\n let secondaryProcessors = new Map();\n for (const provider of this.getClosestExtraQueryProviders() ?? []) {\n for (const { req, processor } of provider.getExtraQueries(request)) {\n const requestId = getNextRequestId();\n secondaryRequests.push({ ...req, requestId });\n secondaryProcessors.set(requestId, processor ?? passthroughProcessor);\n }\n }\n request.range = primaryTimeRange;\n return { primary: request, secondaries: secondaryRequests, processors: secondaryProcessors };\n }\n\n private onDataReceived = (data: PanelData) => {\n // Will combine annotations from SQR queries (frames with meta.dataTopic === DataTopic.Annotations)\n const preProcessedData = preProcessPanelData(data, this.state.data);\n\n // Save query annotations\n this._resultAnnotations = data.annotations;\n\n // Will combine annotations & alert state from data layer providers\n const dataWithLayersApplied = this._combineDataLayers(preProcessedData);\n\n let hasFetchedData = this.state._hasFetchedData;\n\n if (!hasFetchedData && preProcessedData.state !== LoadingState.Loading) {\n hasFetchedData = true;\n }\n\n this.setState({ data: dataWithLayersApplied, _hasFetchedData: hasFetchedData });\n this._results.next({ origin: this, data: dataWithLayersApplied });\n };\n\n private _combineDataLayers(data: PanelData) {\n if (this._layerAnnotations && this._layerAnnotations.length > 0) {\n data.annotations = (data.annotations || []).concat(this._layerAnnotations);\n }\n\n if (this.state.data && this.state.data.alertState) {\n data.alertState = this.state.data.alertState;\n }\n\n return data;\n }\n\n private _setNoDataState() {\n if (this.state.data !== emptyPanelData) {\n this.setState({ data: emptyPanelData });\n }\n }\n\n /**\n * Walk up the scene graph and find any ExtraQueryProviders.\n *\n * This will return an array of the closest provider of each type.\n */\n private getClosestExtraQueryProviders(): Array<ExtraQueryProvider<any>> {\n // Maintain a map from provider constructor to provider object. The constructor\n // is used as a unique key for each class, to ensure we have no more than one\n // type of each type of provider.\n const found = new Map();\n if (!this.parent) {\n return [];\n }\n getClosest(this.parent, (s) => {\n if (isExtraQueryProvider(s) && !found.has(s.constructor)) {\n found.set(s.constructor, s);\n }\n s.forEachChild((child) => {\n if (isExtraQueryProvider(child) && !found.has(child.constructor)) {\n found.set(child.constructor, child);\n }\n });\n // Always return null so that the search continues to the top of\n // the scene graph.\n return null;\n });\n return Array.from(found.values());\n }\n\n /**\n * Walk up scene graph and find the closest filterset with matching data source\n */\n private findAndSubscribeToAdHocFilters(uid: string | undefined) {\n const filtersVar = findActiveAdHocFilterVariableByUid(uid);\n\n if (this._adhocFiltersVar !== filtersVar) {\n this._adhocFiltersVar = filtersVar;\n this._updateExplicitVariableDependencies();\n }\n\n const groupByVar = findActiveGroupByVariablesByUid(uid);\n if (this._groupByVar !== groupByVar) {\n this._groupByVar = groupByVar;\n this._updateExplicitVariableDependencies();\n }\n }\n\n private _updateExplicitVariableDependencies() {\n const explicitDependencies: string[] = [];\n\n if (this._adhocFiltersVar) {\n explicitDependencies.push(this._adhocFiltersVar.state.name);\n }\n\n if (this._groupByVar) {\n explicitDependencies.push(this._groupByVar.state.name);\n }\n\n this._variableDependency.setVariableNames(explicitDependencies);\n }\n\n private isQueryModeAuto(): boolean {\n return (this.state.runQueriesMode ?? 'auto') === 'auto'\n }\n}\n\nexport function findFirstDatasource(targets: DataQuery[]): DataSourceRef | undefined {\n return targets.find((t) => t.datasource !== null)?.datasource ?? undefined;\n}\n\nfunction allFramesEmpty(frames?: DataFrame[]) {\n if (!frames) {\n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CAAA;AAAA,GAChE;AAAA,EAEQ,eAA2B,GAAA;AA/qBrC,IAAA,IAAA,EAAA,CAAA;AAgrBI,IAAA,OAAA,CAAA,CAAQ,EAAK,GAAA,IAAA,CAAA,KAAA,CAAM,cAAX,KAAA,IAAA,GAAA,EAAA,GAA6B,MAAY,MAAA,MAAA,CAAA;AAAA,GACnD;AACF,CAAA;AAEO,SAAS,oBAAoB,OAAiD,EAAA;AAprBrF,EAAA,IAAA,EAAA,EAAA,EAAA,CAAA;AAqrBE,EAAO,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,OAAA,CAAQ,IAAK,CAAA,CAAC,CAAM,KAAA,CAAA,CAAE,eAAe,IAAI,CAAA,KAAzC,IAA4C,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,UAAA,KAA5C,IAA0D,GAAA,EAAA,GAAA,KAAA,CAAA,CAAA;AACnE,CAAA;AAEA,SAAS,eAAe,MAAsB,EAAA;AAC5C,EAAA,IAAI,CAAC,MAAQ,EAAA;AACX,IAAO,OAAA,IAAA,CAAA;AAAA,GACT;AAEA,EAAA,KAAA,IAAS,CAAI,GAAA,CAAA,EAAG,CAAI,GAAA,MAAA,CAAO,QAAQ,CAAK,EAAA,EAAA;AACtC,IAAI,IAAA,MAAA,CAAO,CAAG,CAAA,CAAA,MAAA,GAAS,CAAG,EAAA;AACxB,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAAA,GACF;AAEA,EAAO,OAAA,IAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"SceneQueryRunner.js","sources":["../../../src/querying/SceneQueryRunner.ts"],"sourcesContent":["import { cloneDeep, isEqual } from 'lodash';\nimport { forkJoin, ReplaySubject, Unsubscribable } from 'rxjs';\n\nimport { DataQuery, DataSourceRef, LoadingState } from '@grafana/schema';\n\nimport {\n AlertStateInfo,\n DataFrame,\n DataFrameView,\n DataQueryRequest,\n DataSourceApi,\n DataTopic,\n PanelData,\n preProcessPanelData,\n rangeUtil,\n} from '@grafana/data';\n\n// TODO: Remove this ignore annotation when the grafana runtime dependency has been updated\n// @ts-ignore\nimport { getRunRequest, toDataQueryError, isExpressionReference, config } from '@grafana/runtime';\n\nimport { SceneObjectBase } from '../core/SceneObjectBase';\nimport { sceneGraph } from '../core/sceneGraph';\nimport {\n DataLayerFilter,\n SceneDataProvider,\n SceneDataProviderResult,\n SceneDataQuery,\n SceneObjectState,\n SceneTimeRangeLike,\n} from '../core/types';\nimport { getDataSource } from '../utils/getDataSource';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig';\nimport { writeSceneLog } from '../utils/writeSceneLog';\nimport { VariableValueRecorder } from '../variables/VariableValueRecorder';\nimport { emptyPanelData } from '../core/SceneDataNode';\nimport { getClosest } from '../core/sceneGraph/utils';\nimport { isExtraQueryProvider, ExtraQueryDataProcessor, ExtraQueryProvider } from './ExtraQueryProvider';\nimport { passthroughProcessor, extraQueryProcessingOperator } from './extraQueryProcessingOperator';\nimport { filterAnnotations } from './layers/annotations/filterAnnotations';\nimport { getEnrichedDataRequest } from './getEnrichedDataRequest';\nimport { findActiveAdHocFilterVariableByUid } from '../variables/adhoc/patchGetAdhocFilters';\nimport { registerQueryWithController } from './registerQueryWithController';\nimport { findActiveGroupByVariablesByUid } from '../variables/groupby/findActiveGroupByVariablesByUid';\nimport { GroupByVariable } from '../variables/groupby/GroupByVariable';\nimport { AdHocFiltersVariable, isFilterComplete } from '../variables/adhoc/AdHocFiltersVariable';\nimport { SceneVariable } from '../variables/types';\nimport { DataLayersMerger } from './DataLayersMerger';\nimport { interpolate } from '../core/sceneGraph/sceneGraph';\nimport { wrapInSafeSerializableSceneObject } from '../utils/wrapInSafeSerializableSceneObject';\n\nlet counter = 100;\n\nexport function getNextRequestId() {\n return 'SQR' + counter++;\n}\n\nexport interface QueryRunnerState extends SceneObjectState {\n data?: PanelData;\n queries: SceneDataQuery[];\n datasource?: DataSourceRef;\n minInterval?: string;\n maxDataPoints?: number;\n liveStreaming?: boolean;\n maxDataPointsFromWidth?: boolean;\n cacheTimeout?: DataQueryRequest['cacheTimeout'];\n queryCachingTTL?: DataQueryRequest['queryCachingTTL'];\n /**\n * When set to auto (the default) query runner will issue queries on activate (when variable dependencies are ready) or when time range change.\n * Set to manual to have full manual control over when queries are issued. Try not to set this. This is mainly useful for unit tests, or special edge case workflows.\n */\n runQueriesMode?: 'auto' | 'manual';\n // Filters to be applied to data layer results before combining them with SQR results\n dataLayerFilter?: DataLayerFilter;\n // Private runtime state\n _hasFetchedData?: boolean;\n}\n\nexport interface DataQueryExtended extends DataQuery {\n [key: string]: any;\n\n // Opt this query out of time window comparison\n timeRangeCompare?: boolean;\n}\n\n// The requests that will be run by the query runner.\n//\n// Generally the query runner will run a single primary request.\n// If the scene graph contains implementations of\n// `ExtraQueryProvider`, the requests created by these\n// implementations will be added to the list of secondary requests,\n// and these will be executed at the same time as the primary request.\n//\n// The results of each secondary request will be passed to an associated\n// processor function (along with the results of the primary request),\n// which can transform the results as desired.\ninterface PreparedRequests {\n // The primary request to run.\n primary: DataQueryRequest;\n // A possibly empty list of secondary requests to run alongside\n // the primary request.\n secondaries: DataQueryRequest[];\n // A map from `requestId` of secondary requests to processors\n // for those requests. Provided by the `ExtraQueryProvider`.\n processors: Map<string, ExtraQueryDataProcessor>;\n}\n\nexport class SceneQueryRunner extends SceneObjectBase<QueryRunnerState> implements SceneDataProvider {\n private _querySub?: Unsubscribable;\n private _dataLayersSub?: Unsubscribable;\n private _dataLayersMerger = new DataLayersMerger();\n private _timeSub?: Unsubscribable;\n private _timeSubRange?: SceneTimeRangeLike;\n private _containerWidth?: number;\n private _variableValueRecorder = new VariableValueRecorder();\n private _results = new ReplaySubject<SceneDataProviderResult>(1);\n private _scopedVars = { __sceneObject: wrapInSafeSerializableSceneObject(this) };\n private _layerAnnotations?: DataFrame[];\n private _resultAnnotations?: DataFrame[];\n\n private _adhocFiltersVar?: AdHocFiltersVariable;\n private _groupByVar?: GroupByVariable;\n\n public getResultsStream() {\n return this._results;\n }\n\n protected _variableDependency: VariableDependencyConfig<QueryRunnerState> = new VariableDependencyConfig(this, {\n statePaths: ['queries', 'datasource'],\n onVariableUpdateCompleted: this.onVariableUpdatesCompleted.bind(this),\n onAnyVariableChanged: this.onAnyVariableChanged.bind(this),\n });\n\n public constructor(initialState: QueryRunnerState) {\n super(initialState);\n\n this.addActivationHandler(() => this._onActivate());\n }\n\n private _onActivate() {\n if (this.isQueryModeAuto()) {\n const timeRange = sceneGraph.getTimeRange(this);\n\n // Add subscriptions to any extra providers so that they rerun queries\n // when their state changes and they should rerun.\n const providers = this.getClosestExtraQueryProviders();\n for (const provider of providers) {\n this._subs.add(\n provider.subscribeToState((n, p) => {\n if (provider.shouldRerun(p, n, this.state.queries)) {\n this.runQueries();\n }\n })\n );\n }\n\n this.subscribeToTimeRangeChanges(timeRange);\n\n if (this.shouldRunQueriesOnActivate()) {\n this.runQueries();\n }\n }\n\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n\n return () => this._onDeactivate();\n }\n\n // This method subscribes to all SceneDataLayers up until the root, and combines the results into data provided from SceneQueryRunner\n private _handleDataLayers() {\n const dataLayers = sceneGraph.getDataLayers(this);\n\n if (dataLayers.length === 0) {\n return;\n }\n\n this._dataLayersSub = this._dataLayersMerger\n .getMergedStream(dataLayers)\n .subscribe(this._onLayersReceived.bind(this));\n }\n\n private _onLayersReceived(results: Iterable<SceneDataProviderResult>) {\n const timeRange = sceneGraph.getTimeRange(this);\n const { dataLayerFilter } = this.state;\n\n let annotations: DataFrame[] = [];\n let alertStates: DataFrame[] = [];\n let alertState: AlertStateInfo | undefined;\n\n for (const result of results) {\n for (let frame of result.data.series) {\n if (frame.meta?.dataTopic === DataTopic.Annotations) {\n annotations = annotations.concat(frame);\n }\n if (frame.meta?.dataTopic === DataTopic.AlertStates) {\n alertStates = alertStates.concat(frame);\n }\n }\n }\n\n if (dataLayerFilter?.panelId) {\n if (annotations.length > 0) {\n annotations = filterAnnotations(annotations, dataLayerFilter);\n }\n\n if (alertStates.length > 0) {\n for (const frame of alertStates) {\n const frameView = new DataFrameView<AlertStateInfo>(frame);\n\n for (const row of frameView) {\n if (row.panelId === dataLayerFilter.panelId) {\n alertState = row;\n break;\n }\n }\n }\n }\n }\n\n // Skip unnessary state updates\n if (\n allFramesEmpty(annotations) &&\n allFramesEmpty(this._layerAnnotations) &&\n isEqual(alertState, this.state.data?.alertState)\n ) {\n return;\n }\n\n this._layerAnnotations = annotations;\n\n const baseStateUpdate = this.state.data ? this.state.data : { ...emptyPanelData, timeRange: timeRange.state.value };\n\n this.setState({\n data: {\n ...baseStateUpdate,\n annotations: [...(this._resultAnnotations ?? []), ...annotations],\n alertState: alertState ?? this.state.data?.alertState,\n },\n });\n }\n\n /**\n * This tries to start a new query whenever a variable completes or is changed.\n *\n * We care about variable update completions even when the variable has not changed and even when it is not a direct dependency.\n * Example: Variables A and B (B depends on A). A update depends on time range. So when time change query runner will\n * find that variable A is loading which is a dependency on of variable B so will set _isWaitingForVariables to true and\n * not issue any query.\n *\n * When A completes it's loading (with no value change, so B never updates) it will cause a call of this function letting\n * the query runner know that A has completed, and in case _isWaitingForVariables we try to run the query. The query will\n * only run if all variables are in a non loading state so in other scenarios where a query depends on many variables this will\n * be called many times until all dependencies are in a non loading state. *\n */\n private onVariableUpdatesCompleted() {\n if (this.isQueryModeAuto()) {\n this.runQueries();\n }\n }\n\n /**\n * Check if value changed is a adhoc filter o group by variable that did not exist when we issued the last query\n */\n private onAnyVariableChanged(variable: SceneVariable) {\n // If this variable has already been detected this variable as a dependency onVariableUpdatesCompleted above will handle value changes\n if (this._adhocFiltersVar === variable || this._groupByVar === variable || !this.isQueryModeAuto()) {\n return;\n }\n\n if (variable instanceof AdHocFiltersVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n\n if (variable instanceof GroupByVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n }\n\n private _isRelevantAutoVariable(variable: AdHocFiltersVariable | GroupByVariable) {\n const datasource = this.state.datasource ?? findFirstDatasource(this.state.queries);\n return variable.state.applyMode === 'auto' && datasource?.uid === variable.state.datasource?.uid;\n }\n\n private shouldRunQueriesOnActivate() {\n if (this._variableValueRecorder.hasDependenciesChanged(this)) {\n writeSceneLog(\n 'SceneQueryRunner',\n 'Variable dependency changed while inactive, shouldRunQueriesOnActivate returns true'\n );\n return true;\n }\n\n // If we don't have any data we should run queries\n if (!this.state.data) {\n return true;\n }\n\n // If time range is stale / different we should run queries\n if (this._isDataTimeRangeStale(this.state.data)) {\n return true;\n }\n\n return false;\n }\n\n private _isDataTimeRangeStale(data: PanelData) {\n const timeRange = sceneGraph.getTimeRange(this);\n\n const stateTimeRange = timeRange.state.value;\n const dataTimeRange = data.timeRange;\n\n if (\n stateTimeRange.from.unix() === dataTimeRange.from.unix() &&\n stateTimeRange.to.unix() === dataTimeRange.to.unix()\n ) {\n return false;\n }\n writeSceneLog('SceneQueryRunner', 'Data time range is stale');\n return true;\n }\n\n private _onDeactivate(): void {\n if (this._querySub) {\n this._querySub.unsubscribe();\n this._querySub = undefined;\n }\n\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = undefined;\n }\n\n this._timeSub?.unsubscribe();\n this._timeSub = undefined;\n this._timeSubRange = undefined;\n this._adhocFiltersVar = undefined;\n this._groupByVar = undefined;\n this._variableValueRecorder.recordCurrentDependencyValuesForSceneObject(this);\n }\n\n public setContainerWidth(width: number) {\n // If we don't have a width we should run queries\n if (!this._containerWidth && width > 0) {\n this._containerWidth = width;\n\n // If we don't have maxDataPoints specifically set and maxDataPointsFromWidth is true\n if (this.state.maxDataPointsFromWidth && !this.state.maxDataPoints) {\n // As this is called from render path we need to wait for next tick before running queries\n setTimeout(() => {\n if (this.isActive && !this.state._hasFetchedData) {\n this.runQueries();\n }\n }, 0);\n }\n } else {\n // if the updated container width is bigger than 0 let's remember the width until next query issue\n if (width > 0) {\n this._containerWidth = width;\n }\n }\n }\n\n public isDataReadyToDisplay() {\n return Boolean(this.state._hasFetchedData);\n }\n\n private subscribeToTimeRangeChanges(timeRange: SceneTimeRangeLike) {\n if (this._timeSubRange === timeRange) {\n // Nothing to do, already subscribed\n return;\n }\n\n if (this._timeSub) {\n this._timeSub.unsubscribe();\n }\n\n this._timeSubRange = timeRange;\n this._timeSub = timeRange.subscribeToState(() => {\n this.runWithTimeRange(timeRange);\n });\n }\n\n public runQueries() {\n const timeRange = sceneGraph.getTimeRange(this);\n if (this.isQueryModeAuto()) {\n this.subscribeToTimeRangeChanges(timeRange);\n }\n\n this.runWithTimeRange(timeRange);\n }\n\n private getMaxDataPoints() {\n if (this.state.maxDataPoints) {\n return this.state.maxDataPoints;\n }\n\n return this.state.maxDataPointsFromWidth ? this._containerWidth ?? 500 : 500;\n }\n\n public cancelQuery() {\n this._querySub?.unsubscribe();\n\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = undefined;\n }\n\n this.setState({\n data: { ...this.state.data!, state: LoadingState.Done },\n });\n }\n\n private async runWithTimeRange(timeRange: SceneTimeRangeLike) {\n // If no maxDataPoints specified we might need to wait for container width to be set from the outside\n if (!this.state.maxDataPoints && this.state.maxDataPointsFromWidth && !this._containerWidth) {\n return;\n }\n\n // If data layers subscription doesn't exist, create one\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n\n // Cancel any running queries\n this._querySub?.unsubscribe();\n\n // Skip executing queries if variable dependency is in loading state\n if (this._variableDependency.hasDependencyInLoadingState()) {\n writeSceneLog('SceneQueryRunner', 'Variable dependency is in loading state, skipping query execution');\n this.setState({ data: { ...(this.state.data ?? emptyPanelData), state: LoadingState.Loading } });\n return;\n }\n\n const { queries } = this.state;\n\n // Simple path when no queries exist\n if (!queries?.length) {\n this._setNoDataState();\n return;\n }\n\n try {\n const datasource = this.state.datasource ?? findFirstDatasource(queries);\n const ds = await getDataSource(datasource, this._scopedVars);\n\n this.findAndSubscribeToAdHocFilters(datasource?.uid);\n\n const runRequest = getRunRequest();\n const { primary, secondaries, processors } = this.prepareRequests(timeRange, ds);\n\n writeSceneLog('SceneQueryRunner', 'Starting runRequest', this.state.key);\n\n let stream = runRequest(ds, primary);\n\n if (secondaries.length > 0) {\n // Submit all secondary requests in parallel.\n const secondaryStreams = secondaries.map((r) => runRequest(ds, r));\n // Create the rxjs operator which will combine the primary and secondary responses\n // by calling the correct processor functions provided by the\n // extra request providers.\n const op = extraQueryProcessingOperator(processors);\n // Combine the primary and secondary streams into a single stream, and apply the operator.\n stream = forkJoin([stream, ...secondaryStreams]).pipe(op);\n }\n\n stream = stream.pipe(\n registerQueryWithController({\n type: 'data',\n request: primary,\n origin: this,\n cancel: () => this.cancelQuery(),\n })\n );\n\n this._querySub = stream.subscribe(this.onDataReceived);\n } catch (err) {\n console.error('PanelQueryRunner Error', err);\n\n this.onDataReceived({\n ...emptyPanelData,\n ...this.state.data,\n state: LoadingState.Error,\n errors: [toDataQueryError(err)],\n });\n }\n }\n\n public clone(withState?: Partial<QueryRunnerState>) {\n const clone = super.clone(withState);\n\n if (this._resultAnnotations) {\n clone['_resultAnnotations'] = this._resultAnnotations.map((frame) => ({ ...frame }));\n }\n\n if (this._layerAnnotations) {\n clone['_layerAnnotations'] = this._layerAnnotations.map((frame) => ({ ...frame }));\n }\n\n clone['_variableValueRecorder'] = this._variableValueRecorder.cloneAndRecordCurrentValuesForSceneObject(this);\n clone['_containerWidth'] = this._containerWidth;\n clone['_results'].next({ origin: this, data: this.state.data ?? emptyPanelData });\n\n return clone;\n }\n\n private prepareRequests(timeRange: SceneTimeRangeLike, ds: DataSourceApi): PreparedRequests {\n const { minInterval, queries } = this.state;\n\n let request: DataQueryRequest<DataQueryExtended> = {\n app: 'scenes',\n requestId: getNextRequestId(),\n timezone: timeRange.getTimeZone(),\n range: timeRange.state.value,\n interval: '1s',\n intervalMs: 1000,\n targets: cloneDeep(queries),\n maxDataPoints: this.getMaxDataPoints(),\n scopedVars: this._scopedVars,\n startTime: Date.now(),\n liveStreaming: this.state.liveStreaming,\n rangeRaw: {\n from: timeRange.state.from,\n to: timeRange.state.to,\n },\n cacheTimeout: this.state.cacheTimeout,\n queryCachingTTL: this.state.queryCachingTTL,\n // This asks the scene root to provide context properties like app, panel and dashboardUID\n ...getEnrichedDataRequest(this),\n };\n\n if (this._adhocFiltersVar) {\n // only pass filters that have both key and value\n // @ts-ignore (Temporary ignore until we update @grafana/data)\n request.filters = this._adhocFiltersVar.state.filters.filter(isFilterComplete);\n }\n\n if (this._groupByVar) {\n // @ts-ignore (Temporary ignore until we update @grafana/data)\n request.groupByKeys = this._groupByVar.state.value;\n }\n\n request.targets = request.targets.map((query) => {\n if (\n !query.datasource ||\n (query.datasource.uid !== ds.uid &&\n !ds.meta?.mixed &&\n isExpressionReference /* TODO: Remove this check when isExpressionReference is properly exported from grafan runtime */ &&\n !isExpressionReference(query.datasource))\n ) {\n query.datasource = ds.getRef();\n }\n return query;\n });\n\n const lowerIntervalLimit = minInterval ? interpolate(this, minInterval) : ds.interval;\n const norm = rangeUtil.calculateInterval(timeRange.state.value, request.maxDataPoints!, lowerIntervalLimit);\n\n // make shallow copy of scoped vars,\n // and add built in variables interval and interval_ms\n request.scopedVars = Object.assign({}, request.scopedVars, {\n __interval: { text: norm.interval, value: norm.interval },\n __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs },\n });\n\n request.interval = norm.interval;\n request.intervalMs = norm.intervalMs;\n\n // If there are any extra request providers, we need to add a new request for each\n // and map the request's ID to the processor function given by the provider, to ensure that\n // the processor is called with the correct response data.\n const primaryTimeRange = timeRange.state.value;\n let secondaryRequests: DataQueryRequest[] = [];\n let secondaryProcessors = new Map();\n for (const provider of this.getClosestExtraQueryProviders() ?? []) {\n for (const { req, processor } of provider.getExtraQueries(request)) {\n const requestId = getNextRequestId();\n secondaryRequests.push({ ...req, requestId });\n secondaryProcessors.set(requestId, processor ?? passthroughProcessor);\n }\n }\n request.range = primaryTimeRange;\n return { primary: request, secondaries: secondaryRequests, processors: secondaryProcessors };\n }\n\n private onDataReceived = (data: PanelData) => {\n // Will combine annotations from SQR queries (frames with meta.dataTopic === DataTopic.Annotations)\n const preProcessedData = preProcessPanelData(data, this.state.data);\n\n // Save query annotations\n this._resultAnnotations = data.annotations;\n\n // Will combine annotations & alert state from data layer providers\n const dataWithLayersApplied = this._combineDataLayers(preProcessedData);\n\n let hasFetchedData = this.state._hasFetchedData;\n\n if (!hasFetchedData && preProcessedData.state !== LoadingState.Loading) {\n hasFetchedData = true;\n }\n\n this.setState({ data: dataWithLayersApplied, _hasFetchedData: hasFetchedData });\n this._results.next({ origin: this, data: dataWithLayersApplied });\n };\n\n private _combineDataLayers(data: PanelData) {\n if (this._layerAnnotations && this._layerAnnotations.length > 0) {\n data.annotations = (data.annotations || []).concat(this._layerAnnotations);\n }\n\n if (this.state.data && this.state.data.alertState) {\n data.alertState = this.state.data.alertState;\n }\n\n return data;\n }\n\n private _setNoDataState() {\n if (this.state.data !== emptyPanelData) {\n this.setState({ data: emptyPanelData });\n }\n }\n\n /**\n * Walk up the scene graph and find any ExtraQueryProviders.\n *\n * This will return an array of the closest provider of each type.\n */\n private getClosestExtraQueryProviders(): Array<ExtraQueryProvider<any>> {\n // Maintain a map from provider constructor to provider object. The constructor\n // is used as a unique key for each class, to ensure we have no more than one\n // type of each type of provider.\n const found = new Map();\n if (!this.parent) {\n return [];\n }\n getClosest(this.parent, (s) => {\n if (isExtraQueryProvider(s) && !found.has(s.constructor)) {\n found.set(s.constructor, s);\n }\n s.forEachChild((child) => {\n if (isExtraQueryProvider(child) && !found.has(child.constructor)) {\n found.set(child.constructor, child);\n }\n });\n // Always return null so that the search continues to the top of\n // the scene graph.\n return null;\n });\n return Array.from(found.values());\n }\n\n /**\n * Walk up scene graph and find the closest filterset with matching data source\n */\n private findAndSubscribeToAdHocFilters(uid: string | undefined) {\n const filtersVar = findActiveAdHocFilterVariableByUid(uid);\n\n if (this._adhocFiltersVar !== filtersVar) {\n this._adhocFiltersVar = filtersVar;\n this._updateExplicitVariableDependencies();\n }\n\n const groupByVar = findActiveGroupByVariablesByUid(uid);\n if (this._groupByVar !== groupByVar) {\n this._groupByVar = groupByVar;\n this._updateExplicitVariableDependencies();\n }\n }\n\n private _updateExplicitVariableDependencies() {\n const explicitDependencies: string[] = [];\n\n if (this._adhocFiltersVar) {\n explicitDependencies.push(this._adhocFiltersVar.state.name);\n }\n\n if (this._groupByVar) {\n explicitDependencies.push(this._groupByVar.state.name);\n }\n\n this._variableDependency.setVariableNames(explicitDependencies);\n }\n\n private isQueryModeAuto(): boolean {\n return (this.state.runQueriesMode ?? 'auto') === 'auto';\n }\n}\n\nexport function findFirstDatasource(targets: DataQuery[]): DataSourceRef | undefined {\n return targets.find((t) => t.datasource !== null)?.datasource ?? undefined;\n}\n\nfunction allFramesEmpty(frames?: DataFrame[]) {\n if (!frames) {\n return true;\n }\n\n for (let i = 0; i < frames.length; i++) {\n if (frames[i].length > 0) {\n return false;\n }\n }\n\n return true;\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAI,OAAU,GAAA,GAAA,CAAA;AAEP,SAAS,gBAAmB,GAAA;AACjC,EAAA,OAAO,KAAQ,GAAA,OAAA,EAAA,CAAA;AACjB,CAAA;AAoDO,MAAM,yBAAyB,eAA+D,CAAA;AAAA,EA0B5F,YAAY,YAAgC,EAAA;AACjD,IAAA,KAAA,CAAM,YAAY,CAAA,CAAA;AAxBpB,IAAQ,IAAA,CAAA,iBAAA,GAAoB,IAAI,gBAAiB,EAAA,CAAA;AAIjD,IAAQ,IAAA,CAAA,sBAAA,GAAyB,IAAI,qBAAsB,EAAA,CAAA;AAC3D,IAAQ,IAAA,CAAA,QAAA,GAAW,IAAI,aAAA,CAAuC,CAAC,CAAA,CAAA;AAC/D,IAAA,IAAA,CAAQ,WAAc,GAAA,EAAE,aAAe,EAAA,iCAAA,CAAkC,IAAI,CAAE,EAAA,CAAA;AAW/E,IAAU,IAAA,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GAAA,MAAA,CAAO,QAAQ,CAAK,EAAA,EAAA;AACtC,IAAI,IAAA,MAAA,CAAO,CAAG,CAAA,CAAA,MAAA,GAAS,CAAG,EAAA;AACxB,MAAO,OAAA,KAAA,CAAA;AAAA,KACT;AAAA,GACF;AAEA,EAAO,OAAA,IAAA,CAAA;AACT;;;;"}
@@ -1,4 +1,4 @@
1
- import { Observable } from 'rxjs';
1
+ import { Observable, from, map, catchError } from 'rxjs';
2
2
  import { LoadingState } from '@grafana/schema';
3
3
  import { sceneGraph } from '../core/sceneGraph/index.js';
4
4
 
@@ -36,6 +36,22 @@ function registerQueryWithController(entry) {
36
36
  });
37
37
  };
38
38
  }
39
+ function wrapPromiseInStateObservable(promise) {
40
+ return new Observable((observer) => {
41
+ observer.next({ state: LoadingState.Loading });
42
+ const promiseObservable = from(promise);
43
+ promiseObservable.pipe(
44
+ map(() => ({ state: LoadingState.Done })),
45
+ catchError(() => {
46
+ observer.next({ state: LoadingState.Error });
47
+ return [];
48
+ })
49
+ ).subscribe({
50
+ next: (result) => observer.next(result),
51
+ complete: () => observer.complete()
52
+ });
53
+ });
54
+ }
39
55
 
40
- export { registerQueryWithController };
56
+ export { registerQueryWithController, wrapPromiseInStateObservable };
41
57
  //# sourceMappingURL=registerQueryWithController.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"registerQueryWithController.js","sources":["../../../src/querying/registerQueryWithController.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport { LoadingState } from '@grafana/schema';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { QueryResultWithState, SceneQueryControllerEntry } from '../behaviors/SceneQueryController';\n\n/**\n * Will look for a scene object with a behavior that is a SceneQueryController and register the query with it.\n */\nexport function registerQueryWithController<T extends QueryResultWithState>(entry: SceneQueryControllerEntry) {\n return (queryStream: Observable<T>) => {\n const queryControler = sceneGraph.getQueryController(entry.origin);\n if (!queryControler) {\n return queryStream;\n }\n\n return new Observable<T>((observer) => {\n if (!entry.cancel) {\n entry.cancel = () => observer.complete();\n }\n\n queryControler.queryStarted(entry);\n let markedAsCompleted = false;\n\n const sub = queryStream.subscribe({\n next: (v) => {\n if (!markedAsCompleted && v.state !== LoadingState.Loading) {\n markedAsCompleted = true;\n queryControler.queryCompleted(entry);\n }\n\n observer.next(v);\n },\n error: (e) => observer.error(e),\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n sub.unsubscribe();\n\n if (!markedAsCompleted) {\n queryControler.queryCompleted(entry);\n }\n };\n });\n };\n}\n"],"names":[],"mappings":";;;;AAQO,SAAS,4BAA4D,KAAkC,EAAA;AAC5G,EAAA,OAAO,CAAC,WAA+B,KAAA;AACrC,IAAA,MAAM,cAAiB,GAAA,UAAA,CAAW,kBAAmB,CAAA,KAAA,CAAM,MAAM,CAAA,CAAA;AACjE,IAAA,IAAI,CAAC,cAAgB,EAAA;AACnB,MAAO,OAAA,WAAA,CAAA;AAAA,KACT;AAEA,IAAO,OAAA,IAAI,UAAc,CAAA,CAAC,QAAa,KAAA;AACrC,MAAI,IAAA,CAAC,MAAM,MAAQ,EAAA;AACjB,QAAM,KAAA,CAAA,MAAA,GAAS,MAAM,QAAA,CAAS,QAAS,EAAA,CAAA;AAAA,OACzC;AAEA,MAAA,cAAA,CAAe,aAAa,KAAK,CAAA,CAAA;AACjC,MAAA,IAAI,iBAAoB,GAAA,KAAA,CAAA;AAExB,MAAM,MAAA,GAAA,GAAM,YAAY,SAAU,CAAA;AAAA,QAChC,IAAA,EAAM,CAAC,CAAM,KAAA;AACX,UAAA,IAAI,CAAC,iBAAA,IAAqB,CAAE,CAAA,KAAA,KAAU,aAAa,OAAS,EAAA;AAC1D,YAAoB,iBAAA,GAAA,IAAA,CAAA;AACpB,YAAA,cAAA,CAAe,eAAe,KAAK,CAAA,CAAA;AAAA,WACrC;AAEA,UAAA,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AAAA,SACjB;AAAA,QACA,KAAO,EAAA,CAAC,CAAM,KAAA,QAAA,CAAS,MAAM,CAAC,CAAA;AAAA,QAC9B,UAAU,MAAM;AACd,UAAA,QAAA,CAAS,QAAS,EAAA,CAAA;AAAA,SACpB;AAAA,OACD,CAAA,CAAA;AAED,MAAA,OAAO,MAAM;AACX,QAAA,GAAA,CAAI,WAAY,EAAA,CAAA;AAEhB,QAAA,IAAI,CAAC,iBAAmB,EAAA;AACtB,UAAA,cAAA,CAAe,eAAe,KAAK,CAAA,CAAA;AAAA,SACrC;AAAA,OACF,CAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH,CAAA;AACF;;;;"}
1
+ {"version":3,"file":"registerQueryWithController.js","sources":["../../../src/querying/registerQueryWithController.ts"],"sourcesContent":["import { Observable, catchError, from, map } from 'rxjs';\nimport { LoadingState } from '@grafana/schema';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { QueryResultWithState, SceneQueryControllerEntry } from '../behaviors/types';\n\n/**\n * Will look for a scene object with a behavior that is a SceneQueryController and register the query with it.\n */\nexport function registerQueryWithController<T extends QueryResultWithState>(entry: SceneQueryControllerEntry) {\n return (queryStream: Observable<T>) => {\n const queryControler = sceneGraph.getQueryController(entry.origin);\n if (!queryControler) {\n return queryStream;\n }\n\n return new Observable<T>((observer) => {\n if (!entry.cancel) {\n entry.cancel = () => observer.complete();\n }\n\n queryControler.queryStarted(entry);\n let markedAsCompleted = false;\n\n const sub = queryStream.subscribe({\n next: (v) => {\n if (!markedAsCompleted && v.state !== LoadingState.Loading) {\n markedAsCompleted = true;\n queryControler.queryCompleted(entry);\n }\n\n observer.next(v);\n },\n error: (e) => observer.error(e),\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n sub.unsubscribe();\n\n if (!markedAsCompleted) {\n queryControler.queryCompleted(entry);\n }\n };\n });\n };\n}\n\n// Wraps an arbitrary Promise in an observble that emits Promise state\nexport function wrapPromiseInStateObservable(promise: Promise<any>): Observable<QueryResultWithState> {\n return new Observable<QueryResultWithState>((observer) => {\n // Emit 'loading' state initially\n observer.next({ state: LoadingState.Loading });\n\n // Convert the promise to an observable\n const promiseObservable = from(promise);\n\n // Subscribe to the promise observable\n promiseObservable\n .pipe(\n map(() => ({ state: LoadingState.Done })),\n\n catchError(() => {\n observer.next({ state: LoadingState.Error });\n return [];\n })\n )\n .subscribe({\n next: (result) => observer.next(result),\n complete: () => observer.complete(),\n });\n });\n}\n"],"names":[],"mappings":";;;;AAQO,SAAS,4BAA4D,KAAkC,EAAA;AAC5G,EAAA,OAAO,CAAC,WAA+B,KAAA;AACrC,IAAA,MAAM,cAAiB,GAAA,UAAA,CAAW,kBAAmB,CAAA,KAAA,CAAM,MAAM,CAAA,CAAA;AACjE,IAAA,IAAI,CAAC,cAAgB,EAAA;AACnB,MAAO,OAAA,WAAA,CAAA;AAAA,KACT;AAEA,IAAO,OAAA,IAAI,UAAc,CAAA,CAAC,QAAa,KAAA;AACrC,MAAI,IAAA,CAAC,MAAM,MAAQ,EAAA;AACjB,QAAM,KAAA,CAAA,MAAA,GAAS,MAAM,QAAA,CAAS,QAAS,EAAA,CAAA;AAAA,OACzC;AAEA,MAAA,cAAA,CAAe,aAAa,KAAK,CAAA,CAAA;AACjC,MAAA,IAAI,iBAAoB,GAAA,KAAA,CAAA;AAExB,MAAM,MAAA,GAAA,GAAM,YAAY,SAAU,CAAA;AAAA,QAChC,IAAA,EAAM,CAAC,CAAM,KAAA;AACX,UAAA,IAAI,CAAC,iBAAA,IAAqB,CAAE,CAAA,KAAA,KAAU,aAAa,OAAS,EAAA;AAC1D,YAAoB,iBAAA,GAAA,IAAA,CAAA;AACpB,YAAA,cAAA,CAAe,eAAe,KAAK,CAAA,CAAA;AAAA,WACrC;AAEA,UAAA,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AAAA,SACjB;AAAA,QACA,KAAO,EAAA,CAAC,CAAM,KAAA,QAAA,CAAS,MAAM,CAAC,CAAA;AAAA,QAC9B,UAAU,MAAM;AACd,UAAA,QAAA,CAAS,QAAS,EAAA,CAAA;AAAA,SACpB;AAAA,OACD,CAAA,CAAA;AAED,MAAA,OAAO,MAAM;AACX,QAAA,GAAA,CAAI,WAAY,EAAA,CAAA;AAEhB,QAAA,IAAI,CAAC,iBAAmB,EAAA;AACtB,UAAA,cAAA,CAAe,eAAe,KAAK,CAAA,CAAA;AAAA,SACrC;AAAA,OACF,CAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH,CAAA;AACF,CAAA;AAGO,SAAS,6BAA6B,OAAyD,EAAA;AACpG,EAAO,OAAA,IAAI,UAAiC,CAAA,CAAC,QAAa,KAAA;AAExD,IAAA,QAAA,CAAS,IAAK,CAAA,EAAE,KAAO,EAAA,YAAA,CAAa,SAAS,CAAA,CAAA;AAG7C,IAAM,MAAA,iBAAA,GAAoB,KAAK,OAAO,CAAA,CAAA;AAGtC,IACG,iBAAA,CAAA,IAAA;AAAA,MACC,IAAI,OAAO,EAAE,KAAO,EAAA,YAAA,CAAa,MAAO,CAAA,CAAA;AAAA,MAExC,WAAW,MAAM;AACf,QAAA,QAAA,CAAS,IAAK,CAAA,EAAE,KAAO,EAAA,YAAA,CAAa,OAAO,CAAA,CAAA;AAC3C,QAAA,OAAO,EAAC,CAAA;AAAA,OACT,CAAA;AAAA,MAEF,SAAU,CAAA;AAAA,MACT,IAAM,EAAA,CAAC,MAAW,KAAA,QAAA,CAAS,KAAK,MAAM,CAAA;AAAA,MACtC,QAAA,EAAU,MAAM,QAAA,CAAS,QAAS,EAAA;AAAA,KACnC,CAAA,CAAA;AAAA,GACJ,CAAA,CAAA;AACH;;;;"}
@@ -1,5 +1,7 @@
1
1
  import { getDataSourceSrv } from '@grafana/runtime';
2
2
  import { runtimeDataSources } from '../querying/RuntimeDataSource.js';
3
+ import { wrapPromiseInStateObservable, registerQueryWithController } from '../querying/registerQueryWithController.js';
4
+ import { sceneGraph } from '../core/sceneGraph/index.js';
3
5
 
4
6
  async function getDataSource(datasource, scopedVars) {
5
7
  if (datasource == null ? void 0 : datasource.uid) {
@@ -11,7 +13,21 @@ async function getDataSource(datasource, scopedVars) {
11
13
  if (datasource && datasource.query) {
12
14
  return datasource;
13
15
  }
14
- return await getDataSourceSrv().get(datasource, scopedVars);
16
+ const dsPromise = getDataSourceSrv().get(datasource, scopedVars);
17
+ if (scopedVars.__sceneObject && scopedVars.__sceneObject.value.valueOf()) {
18
+ const queryControler = sceneGraph.getQueryController(scopedVars.__sceneObject.value.valueOf());
19
+ if (queryControler && queryControler.state.enableProfiling) {
20
+ wrapPromiseInStateObservable(dsPromise).pipe(
21
+ registerQueryWithController({
22
+ type: "plugin",
23
+ origin: scopedVars.__sceneObject.value.valueOf()
24
+ })
25
+ ).subscribe(() => {
26
+ });
27
+ }
28
+ }
29
+ const result = await dsPromise;
30
+ return result;
15
31
  }
16
32
 
17
33
  export { getDataSource };
@@ -1 +1 @@
1
- {"version":3,"file":"getDataSource.js","sources":["../../../src/utils/getDataSource.ts"],"sourcesContent":["import { DataSourceApi, ScopedVars } from '@grafana/data';\nimport { getDataSourceSrv } from '@grafana/runtime';\nimport { DataSourceRef } from '@grafana/schema';\nimport { runtimeDataSources } from '../querying/RuntimeDataSource';\n\nexport async function getDataSource(\n datasource: DataSourceRef | undefined | null,\n scopedVars: ScopedVars\n): Promise<DataSourceApi> {\n if (datasource?.uid) {\n const runtimeDataSource = runtimeDataSources.get(datasource.uid);\n if (runtimeDataSource) {\n return runtimeDataSource;\n }\n }\n\n if (datasource && (datasource as any).query) {\n return datasource as DataSourceApi;\n }\n\n return await getDataSourceSrv().get(datasource as string, scopedVars);\n}\n"],"names":[],"mappings":";;;AAKsB,eAAA,aAAA,CACpB,YACA,UACwB,EAAA;AACxB,EAAA,IAAI,yCAAY,GAAK,EAAA;AACnB,IAAA,MAAM,iBAAoB,GAAA,kBAAA,CAAmB,GAAI,CAAA,UAAA,CAAW,GAAG,CAAA,CAAA;AAC/D,IAAA,IAAI,iBAAmB,EAAA;AACrB,MAAO,OAAA,iBAAA,CAAA;AAAA,KACT;AAAA,GACF;AAEA,EAAI,IAAA,UAAA,IAAe,WAAmB,KAAO,EAAA;AAC3C,IAAO,OAAA,UAAA,CAAA;AAAA,GACT;AAEA,EAAA,OAAO,MAAM,gBAAA,EAAmB,CAAA,GAAA,CAAI,YAAsB,UAAU,CAAA,CAAA;AACtE;;;;"}
1
+ {"version":3,"file":"getDataSource.js","sources":["../../../src/utils/getDataSource.ts"],"sourcesContent":["import { DataSourceApi, ScopedVars } from '@grafana/data';\nimport { getDataSourceSrv } from '@grafana/runtime';\nimport { DataSourceRef } from '@grafana/schema';\nimport { runtimeDataSources } from '../querying/RuntimeDataSource';\nimport { registerQueryWithController, wrapPromiseInStateObservable } from '../querying/registerQueryWithController';\nimport { SceneObject } from '../core/types';\nimport { sceneGraph } from '../core/sceneGraph';\n\nexport async function getDataSource(\n datasource: DataSourceRef | undefined | null,\n scopedVars: ScopedVars\n): Promise<DataSourceApi> {\n if (datasource?.uid) {\n const runtimeDataSource = runtimeDataSources.get(datasource.uid);\n if (runtimeDataSource) {\n return runtimeDataSource;\n }\n }\n\n if (datasource && (datasource as any).query) {\n return datasource as DataSourceApi;\n }\n\n const dsPromise = getDataSourceSrv().get(datasource as string, scopedVars);\n\n if (scopedVars.__sceneObject && scopedVars.__sceneObject.value.valueOf()) {\n const queryControler = sceneGraph.getQueryController(scopedVars.__sceneObject.value.valueOf() as SceneObject);\n if (queryControler && queryControler.state.enableProfiling) {\n wrapPromiseInStateObservable(dsPromise)\n .pipe(\n registerQueryWithController({\n type: 'plugin',\n origin: scopedVars.__sceneObject.value.valueOf() as SceneObject,\n })\n )\n .subscribe(() => {});\n }\n }\n\n const result = await dsPromise;\n return result;\n}\n"],"names":[],"mappings":";;;;;AAQsB,eAAA,aAAA,CACpB,YACA,UACwB,EAAA;AACxB,EAAA,IAAI,yCAAY,GAAK,EAAA;AACnB,IAAA,MAAM,iBAAoB,GAAA,kBAAA,CAAmB,GAAI,CAAA,UAAA,CAAW,GAAG,CAAA,CAAA;AAC/D,IAAA,IAAI,iBAAmB,EAAA;AACrB,MAAO,OAAA,iBAAA,CAAA;AAAA,KACT;AAAA,GACF;AAEA,EAAI,IAAA,UAAA,IAAe,WAAmB,KAAO,EAAA;AAC3C,IAAO,OAAA,UAAA,CAAA;AAAA,GACT;AAEA,EAAA,MAAM,SAAY,GAAA,gBAAA,EAAmB,CAAA,GAAA,CAAI,YAAsB,UAAU,CAAA,CAAA;AAEzE,EAAA,IAAI,WAAW,aAAiB,IAAA,UAAA,CAAW,aAAc,CAAA,KAAA,CAAM,SAAW,EAAA;AACxE,IAAA,MAAM,iBAAiB,UAAW,CAAA,kBAAA,CAAmB,WAAW,aAAc,CAAA,KAAA,CAAM,SAAwB,CAAA,CAAA;AAC5G,IAAI,IAAA,cAAA,IAAkB,cAAe,CAAA,KAAA,CAAM,eAAiB,EAAA;AAC1D,MAAA,4BAAA,CAA6B,SAAS,CACnC,CAAA,IAAA;AAAA,QACC,2BAA4B,CAAA;AAAA,UAC1B,IAAM,EAAA,QAAA;AAAA,UACN,MAAQ,EAAA,UAAA,CAAW,aAAc,CAAA,KAAA,CAAM,OAAQ,EAAA;AAAA,SAChD,CAAA;AAAA,OACH,CACC,UAAU,MAAM;AAAA,OAAE,CAAA,CAAA;AAAA,KACvB;AAAA,GACF;AAEA,EAAA,MAAM,SAAS,MAAM,SAAA,CAAA;AACrB,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
@@ -3,6 +3,7 @@ import { sceneGraph } from '../core/sceneGraph/index.js';
3
3
  import { writeSceneLog } from '../utils/writeSceneLog.js';
4
4
  import { VARIABLE_REGEX } from './constants.js';
5
5
  import { safeStringifyValue } from './utils.js';
6
+ import { ConstantVariable } from './variants/ConstantVariable.js';
6
7
 
7
8
  class VariableDependencyConfig {
8
9
  constructor(_sceneObject, _options) {
@@ -12,6 +13,9 @@ class VariableDependencyConfig {
12
13
  this._isWaitingForVariables = false;
13
14
  this.scanCount = 0;
14
15
  this._statePaths = _options.statePaths;
16
+ if (this._options.handleTimeMacros) {
17
+ this.handleTimeMacros();
18
+ }
15
19
  }
16
20
  hasDependencyOn(name) {
17
21
  return this.getNames().has(name);
@@ -115,6 +119,31 @@ class VariableDependencyConfig {
115
119
  this._dependencies.add(variableName);
116
120
  }
117
121
  }
122
+ handleTimeMacros() {
123
+ this._sceneObject.addActivationHandler(() => {
124
+ const timeRange = sceneGraph.getTimeRange(this._sceneObject);
125
+ const sub = timeRange.subscribeToState((newState, oldState) => {
126
+ const deps = this.getNames();
127
+ const hasFromDep = deps.has("__from");
128
+ const hasToDep = deps.has("__to");
129
+ const hasTimeZone = deps.has("__timezone");
130
+ if (newState.value !== oldState.value) {
131
+ if (hasFromDep) {
132
+ const variable = new ConstantVariable({ name: "__from", value: newState.from });
133
+ this.variableUpdateCompleted(variable, true);
134
+ } else if (hasToDep) {
135
+ const variable = new ConstantVariable({ name: "__to", value: newState.to });
136
+ this.variableUpdateCompleted(variable, true);
137
+ }
138
+ }
139
+ if (newState.timeZone !== oldState.timeZone && hasTimeZone) {
140
+ const variable = new ConstantVariable({ name: "__timezone", value: newState.timeZone });
141
+ this.variableUpdateCompleted(variable, true);
142
+ }
143
+ });
144
+ return () => sub.unsubscribe();
145
+ });
146
+ }
118
147
  }
119
148
 
120
149
  export { VariableDependencyConfig };
@@ -1 +1 @@
1
- {"version":3,"file":"VariableDependencyConfig.js","sources":["../../../src/variables/VariableDependencyConfig.ts"],"sourcesContent":["import { DataLinkBuiltInVars } from '@grafana/data';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { SceneObject, SceneObjectState } from '../core/types';\nimport { writeSceneLog } from '../utils/writeSceneLog';\nimport { VARIABLE_REGEX } from './constants';\n\nimport { SceneVariable, SceneVariableDependencyConfigLike } from './types';\nimport { safeStringifyValue } from './utils';\n\ninterface VariableDependencyConfigOptions<TState extends SceneObjectState> {\n /**\n * State paths to scan / extract variable dependencies from. Leave empty to scan all paths.\n */\n statePaths?: Array<keyof TState | '*'>;\n\n /**\n * Explicit list of variable names to depend on. Leave empty to scan state for dependencies.\n */\n variableNames?: string[];\n\n /**\n * Optional way to customize how to handle when a dependent variable changes\n * If not specified the default behavior is to trigger a re-render\n */\n onReferencedVariableValueChanged?: (variable: SceneVariable) => void;\n\n /**\n * Two scenarios trigger this callback to be called.\n * 1. When any direct dependency changed value\n * 2. In case hasDependencyInLoadingState was called and returned true we really care about any variable update. So in this scenario this callback is called\n * after any variable update completes. This is to cover scenarios where an object is waiting for indirect dependencies to complete.\n */\n onVariableUpdateCompleted?: () => void;\n\n /**\n * Optional way to subscribe to all variable value changes, even to variables that are not dependencies.\n */\n onAnyVariableChanged?: (variable: SceneVariable) => void;\n}\n\nexport class VariableDependencyConfig<TState extends SceneObjectState> implements SceneVariableDependencyConfigLike {\n private _state: TState | undefined;\n private _dependencies = new Set<string>();\n private _statePaths?: Array<keyof TState | '*'>;\n private _isWaitingForVariables = false;\n\n public scanCount = 0;\n\n public constructor(\n private _sceneObject: SceneObject<TState>,\n private _options: VariableDependencyConfigOptions<TState>\n ) {\n this._statePaths = _options.statePaths;\n }\n\n /**\n * Used to check for dependency on a specific variable\n */\n public hasDependencyOn(name: string): boolean {\n return this.getNames().has(name);\n }\n\n /**\n * This is called whenever any set of variables have new values. It is up to this implementation to check if it's relevant given the current dependencies.\n */\n public variableUpdateCompleted(variable: SceneVariable, hasChanged: boolean) {\n const deps = this.getNames();\n let dependencyChanged = false;\n\n if ((deps.has(variable.state.name) || deps.has(DataLinkBuiltInVars.includeVars)) && hasChanged) {\n dependencyChanged = true;\n }\n\n writeSceneLog(\n 'VariableDependencyConfig',\n 'variableUpdateCompleted',\n variable.state.name,\n dependencyChanged,\n this._isWaitingForVariables\n );\n\n if (this._options.onAnyVariableChanged) {\n this._options.onAnyVariableChanged(variable);\n }\n\n // If custom handler called when dependency is changed or when we are waiting for variables\n if (this._options.onVariableUpdateCompleted && (this._isWaitingForVariables || dependencyChanged)) {\n this._options.onVariableUpdateCompleted();\n }\n\n if (dependencyChanged) {\n if (this._options.onReferencedVariableValueChanged) {\n this._options.onReferencedVariableValueChanged(variable);\n }\n\n // if no callbacks are specified then just do a forceRender\n if (!this._options.onReferencedVariableValueChanged && !this._options.onVariableUpdateCompleted) {\n this._sceneObject.forceRender();\n }\n }\n }\n\n public hasDependencyInLoadingState() {\n if (sceneGraph.hasVariableDependencyInLoadingState(this._sceneObject)) {\n this._isWaitingForVariables = true;\n return true;\n }\n\n this._isWaitingForVariables = false;\n return false;\n }\n\n public getNames(): Set<string> {\n const prevState = this._state;\n const newState = (this._state = this._sceneObject.state);\n\n if (!prevState) {\n // First time we always scan for dependencies\n this.scanStateForDependencies(this._state);\n return this._dependencies;\n }\n\n // Second time we only scan if state is a different and if any specific state path has changed\n if (newState !== prevState) {\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === '*' || newState[path] !== prevState[path]) {\n this.scanStateForDependencies(newState);\n break;\n }\n }\n } else {\n this.scanStateForDependencies(newState);\n }\n }\n\n return this._dependencies;\n }\n\n /**\n * Update variableNames\n */\n public setVariableNames(varNames: string[]) {\n this._options.variableNames = varNames;\n this.scanStateForDependencies(this._state!);\n }\n\n public setPaths(paths: Array<keyof TState | '*'>) {\n this._statePaths = paths;\n }\n\n private scanStateForDependencies(state: TState) {\n this._dependencies.clear();\n this.scanCount += 1;\n\n if (this._options.variableNames) {\n for (const name of this._options.variableNames) {\n this._dependencies.add(name);\n }\n }\n\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === '*') {\n this.extractVariablesFrom(state);\n break;\n } else {\n const value = state[path];\n if (value) {\n this.extractVariablesFrom(value);\n }\n }\n }\n }\n }\n\n private extractVariablesFrom(value: unknown) {\n VARIABLE_REGEX.lastIndex = 0;\n\n const stringToCheck = typeof value !== 'string' ? safeStringifyValue(value) : value;\n\n const matches = stringToCheck.matchAll(VARIABLE_REGEX);\n if (!matches) {\n return;\n }\n\n for (const match of matches) {\n const [, var1, var2, , var3] = match;\n const variableName = var1 || var2 || var3;\n this._dependencies.add(variableName);\n }\n }\n}\n"],"names":[],"mappings":";;;;;;AAwCO,MA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;AAAA,GACF;AAAA,EAEQ,qBAAqB,KAAgB,EAAA;AAC3C,IAAA,cAAA,CAAe,SAAY,GAAA,CAAA,CAAA;AAE3B,IAAA,MAAM,gBAAgB,OAAO,KAAA,KAAU,QAAW,GAAA,kBAAA,CAAmB,KAAK,CAAI,GAAA,KAAA,CAAA;AAE9E,IAAM,MAAA,OAAA,GAAU,aAAc,CAAA,QAAA,CAAS,cAAc,CAAA,CAAA;AACrD,IAAA,IAAI,CAAC,OAAS,EAAA;AACZ,MAAA,OAAA;AAAA,KACF;AAEA,IAAA,KAAA,MAAW,SAAS,OAAS,EAAA;AAC3B,MAAA,MAAM,GAAG,IAAA,EAAM,IAAM,IAAE,IAAI,CAAI,GAAA,KAAA,CAAA;AAC/B,MAAM,MAAA,YAAA,GAAe,QAAQ,IAAQ,IAAA,IAAA,CAAA;AACrC,MAAK,IAAA,CAAA,aAAA,CAAc,IAAI,YAAY,CAAA,CAAA;AAAA,KACrC;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"VariableDependencyConfig.js","sources":["../../../src/variables/VariableDependencyConfig.ts"],"sourcesContent":["import { DataLinkBuiltInVars } from '@grafana/data';\nimport { sceneGraph } from '../core/sceneGraph';\nimport { SceneObject, SceneObjectState } from '../core/types';\nimport { writeSceneLog } from '../utils/writeSceneLog';\nimport { VARIABLE_REGEX } from './constants';\n\nimport { SceneVariable, SceneVariableDependencyConfigLike } from './types';\nimport { safeStringifyValue } from './utils';\nimport { ConstantVariable } from './variants/ConstantVariable';\n\ninterface VariableDependencyConfigOptions<TState extends SceneObjectState> {\n /**\n * State paths to scan / extract variable dependencies from. Leave empty to scan all paths.\n */\n statePaths?: Array<keyof TState | '*'>;\n\n /**\n * Explicit list of variable names to depend on. Leave empty to scan state for dependencies.\n */\n variableNames?: string[];\n\n /**\n * Optional way to customize how to handle when a dependent variable changes\n * If not specified the default behavior is to trigger a re-render\n */\n onReferencedVariableValueChanged?: (variable: SceneVariable) => void;\n\n /**\n * Two scenarios trigger this callback to be called.\n * 1. When any direct dependency changed value\n * 2. In case hasDependencyInLoadingState was called and returned true we really care about any variable update. So in this scenario this callback is called\n * after any variable update completes. This is to cover scenarios where an object is waiting for indirect dependencies to complete.\n */\n onVariableUpdateCompleted?: () => void;\n\n /**\n * Optional way to subscribe to all variable value changes, even to variables that are not dependencies.\n */\n onAnyVariableChanged?: (variable: SceneVariable) => void;\n\n /**\n * Handle time macros.\n */\n handleTimeMacros?: boolean;\n}\n\nexport class VariableDependencyConfig<TState extends SceneObjectState> implements SceneVariableDependencyConfigLike {\n private _state: TState | undefined;\n private _dependencies = new Set<string>();\n private _statePaths?: Array<keyof TState | '*'>;\n private _isWaitingForVariables = false;\n\n public scanCount = 0;\n\n public constructor(\n private _sceneObject: SceneObject<TState>,\n private _options: VariableDependencyConfigOptions<TState>\n ) {\n this._statePaths = _options.statePaths;\n\n if (this._options.handleTimeMacros) {\n this.handleTimeMacros();\n }\n }\n\n /**\n * Used to check for dependency on a specific variable\n */\n public hasDependencyOn(name: string): boolean {\n return this.getNames().has(name);\n }\n\n /**\n * This is called whenever any set of variables have new values. It is up to this implementation to check if it's relevant given the current dependencies.\n */\n public variableUpdateCompleted(variable: SceneVariable, hasChanged: boolean) {\n const deps = this.getNames();\n let dependencyChanged = false;\n\n if ((deps.has(variable.state.name) || deps.has(DataLinkBuiltInVars.includeVars)) && hasChanged) {\n dependencyChanged = true;\n }\n\n writeSceneLog(\n 'VariableDependencyConfig',\n 'variableUpdateCompleted',\n variable.state.name,\n dependencyChanged,\n this._isWaitingForVariables\n );\n\n if (this._options.onAnyVariableChanged) {\n this._options.onAnyVariableChanged(variable);\n }\n\n // If custom handler called when dependency is changed or when we are waiting for variables\n if (this._options.onVariableUpdateCompleted && (this._isWaitingForVariables || dependencyChanged)) {\n this._options.onVariableUpdateCompleted();\n }\n\n if (dependencyChanged) {\n if (this._options.onReferencedVariableValueChanged) {\n this._options.onReferencedVariableValueChanged(variable);\n }\n\n // if no callbacks are specified then just do a forceRender\n if (!this._options.onReferencedVariableValueChanged && !this._options.onVariableUpdateCompleted) {\n this._sceneObject.forceRender();\n }\n }\n }\n\n public hasDependencyInLoadingState() {\n if (sceneGraph.hasVariableDependencyInLoadingState(this._sceneObject)) {\n this._isWaitingForVariables = true;\n return true;\n }\n\n this._isWaitingForVariables = false;\n return false;\n }\n\n public getNames(): Set<string> {\n const prevState = this._state;\n const newState = (this._state = this._sceneObject.state);\n\n if (!prevState) {\n // First time we always scan for dependencies\n this.scanStateForDependencies(this._state);\n return this._dependencies;\n }\n\n // Second time we only scan if state is a different and if any specific state path has changed\n if (newState !== prevState) {\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === '*' || newState[path] !== prevState[path]) {\n this.scanStateForDependencies(newState);\n break;\n }\n }\n } else {\n this.scanStateForDependencies(newState);\n }\n }\n\n return this._dependencies;\n }\n\n /**\n * Update variableNames\n */\n public setVariableNames(varNames: string[]) {\n this._options.variableNames = varNames;\n this.scanStateForDependencies(this._state!);\n }\n\n public setPaths(paths: Array<keyof TState | '*'>) {\n this._statePaths = paths;\n }\n\n private scanStateForDependencies(state: TState) {\n this._dependencies.clear();\n this.scanCount += 1;\n\n if (this._options.variableNames) {\n for (const name of this._options.variableNames) {\n this._dependencies.add(name);\n }\n }\n\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === '*') {\n this.extractVariablesFrom(state);\n break;\n } else {\n const value = state[path];\n if (value) {\n this.extractVariablesFrom(value);\n }\n }\n }\n }\n }\n\n private extractVariablesFrom(value: unknown) {\n VARIABLE_REGEX.lastIndex = 0;\n\n const stringToCheck = typeof value !== 'string' ? safeStringifyValue(value) : value;\n\n const matches = stringToCheck.matchAll(VARIABLE_REGEX);\n if (!matches) {\n return;\n }\n\n for (const match of matches) {\n const [, var1, var2, , var3] = match;\n const variableName = var1 || var2 || var3;\n this._dependencies.add(variableName);\n }\n }\n\n private handleTimeMacros() {\n this._sceneObject.addActivationHandler(() => {\n const timeRange = sceneGraph.getTimeRange(this._sceneObject);\n\n const sub = timeRange.subscribeToState((newState, oldState) => {\n const deps = this.getNames();\n const hasFromDep = deps.has('__from');\n const hasToDep = deps.has('__to');\n const hasTimeZone = deps.has('__timezone');\n\n if (newState.value !== oldState.value) {\n // If you have both __from & __to as dependencies you only get notified that from changed and vice versa\n if (hasFromDep) {\n const variable = new ConstantVariable({ name: '__from', value: newState.from });\n this.variableUpdateCompleted(variable, true);\n } else if (hasToDep) {\n const variable = new ConstantVariable({ name: '__to', value: newState.to });\n this.variableUpdateCompleted(variable, true);\n }\n }\n\n if (newState.timeZone !== oldState.timeZone && hasTimeZone) {\n const variable = new ConstantVariable({ name: '__timezone', value: newState.timeZone });\n this.variableUpdateCompleted(variable, true);\n }\n });\n\n return () => sub.unsubscribe();\n });\n }\n}\n"],"names":[],"mappings":";;;;;;;AA8CO,MAAM,wBAAuG,CAAA;AAAA,EAQ3G,WAAA,CACG,cACA,QACR,EAAA;AAFQ,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA,CAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AARV,IAAQ,IAAA,CAAA,aAAA,uBAAoB,GAAY,EAAA,CAAA;AAExC,IAAA,IAAA,CAAQ,sBAAyB,GAAA,KAAA,CAAA;AAEjC,IAAA,IAAA,CAAO,SAAY,GAAA,CAAA,CAAA;AAMjB,IAAA,IAAA,CAAK,cAAc,QAAS,CAAA,UAAA,CAAA;AAE5B,IAAI,IAAA,IAAA,CAAK,SAAS,gBAAkB,EAAA;AAClC,MAAA,IAAA,CAAK,gBAAiB,EAAA,CAAA;AAAA,KACxB;AAAA,GACF;AAAA,EAKO,gBAAgB,IAAuB,EAAA;AAC5C,IAAA,OAAO,IAAK,CAAA,QAAA,EAAW,CAAA,GAAA,CAAI,IAAI,CAAA,CAAA;AAAA,GACjC;AAAA,EAKO,uBAAA,CAAwB,UAAyB,UAAqB,EAAA;AAC3E,IAAM,MAAA,IAAA,GAAO,KAAK,QAAS,EAAA,CA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AA,CAAA;AACtF,UAAK,IAAA,CAAA,uBAAA,CAAwB,UAAU,IAAI,CAAA,CAAA;AAAA,SAC7C;AAAA,OACD,CAAA,CAAA;AAED,MAAO,OAAA,MAAM,IAAI,WAAY,EAAA,CAAA;AAAA,KAC9B,CAAA,CAAA;AAAA,GACH;AACF;;;;"}
@@ -42,10 +42,12 @@ function AdHocFilterRenderer({ filter, model }) {
42
42
  const [isOperatorOpen, setIsOperatorOpen] = useState(false);
43
43
  const [valueInputValue, setValueInputValue] = useState("");
44
44
  const [valueHasCustomValue, setValueHasCustomValue] = useState(false);
45
- const [uncommittedValue, setUncommittedValue] = useState(filter.values ? filter.values.map((value, index) => {
46
- var _a2;
47
- return keyLabelToOption(value, (_a2 = filter.valueLabels) == null ? void 0 : _a2[index]);
48
- }) : []);
45
+ const [uncommittedValue, setUncommittedValue] = useState(
46
+ filter.values ? filter.values.map((value, index) => {
47
+ var _a2;
48
+ return keyLabelToOption(value, (_a2 = filter.valueLabels) == null ? void 0 : _a2[index]);
49
+ }) : []
50
+ );
49
51
  const isMultiValue = isMultiValueOperator(filter.operator);
50
52
  const keyValue = keyLabelToOption(filter.key, filter.keyLabel);
51
53
  const valueValue = keyLabelToOption(filter.value, (_a = filter.valueLabels) == null ? void 0 : _a[0]);
@@ -68,10 +70,12 @@ function AdHocFilterRenderer({ filter, model }) {
68
70
  setUncommittedValue([]);
69
71
  } else if (!isMultiValueOperator(existingOperator) && isMultiValueOperator(newOperator) && filter.value) {
70
72
  update.values = [filter.value];
71
- setUncommittedValue([{
72
- value: filter.value,
73
- label: (_b2 = (_a2 = filter.valueLabels) == null ? void 0 : _a2[0]) != null ? _b2 : filter.value
74
- }]);
73
+ setUncommittedValue([
74
+ {
75
+ value: filter.value,
76
+ label: (_b2 = (_a2 = filter.valueLabels) == null ? void 0 : _a2[0]) != null ? _b2 : filter.value
77
+ }
78
+ ]);
75
79
  }
76
80
  model._updateFilter(filter, update);
77
81
  };
@@ -1 +1 @@
1
- {"version":3,"file":"AdHocFilterRenderer.js","sources":["../../../../src/variables/adhoc/AdHocFilterRenderer.tsx"],"sourcesContent":["import React, { useMemo, useState } from 'react';\n\nimport { AdHocFiltersVariable, AdHocFilterWithLabels, isMultiValueOperator } from './AdHocFiltersVariable';\nimport { GrafanaTheme2, SelectableValue } from '@grafana/data';\nimport { Button, Field, InputActionMeta, Select, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport { ControlsLabel } from '../../utils/ControlsLabel';\nimport { getAdhocOptionSearcher } from './getAdhocOptionSearcher';\nimport { handleOptionGroups } from '../utils';\nimport { OptionWithCheckbox } from '../components/VariableValueSelect';\n\ninterface Props {\n filter: AdHocFilterWithLabels;\n model: AdHocFiltersVariable;\n}\n\nfunction keyLabelToOption(key: string, label?: string): SelectableValue | null {\n return key !== ''\n ? {\n value: key,\n label: label || key,\n }\n : null;\n}\n\nconst filterNoOp = () => true;\n\nexport function AdHocFilterRenderer({ filter, model }: Props) {\n const styles = useStyles2(getStyles);\n\n const [keys, setKeys] = useState<SelectableValue[]>([]);\n const [values, setValues] = useState<SelectableValue[]>([]);\n const [isKeysLoading, setIsKeysLoading] = useState(false);\n const [isValuesLoading, setIsValuesLoading] = useState(false);\n const [isKeysOpen, setIsKeysOpen] = useState(false);\n const [isValuesOpen, setIsValuesOpen] = useState(false);\n const [isOperatorOpen, setIsOperatorOpen] = useState(false);\n const [valueInputValue, setValueInputValue] = useState('');\n const [valueHasCustomValue, setValueHasCustomValue] = useState(false);\n // To not trigger queries on every selection we store this state locally here and only update the variable onBlur\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n const [uncommittedValue, setUncommittedValue] = useState<SelectableValue>(filter.values ? filter.values.map((value, index) => keyLabelToOption(value, filter.valueLabels?.[index])) : []);\n const isMultiValue = isMultiValueOperator(filter.operator);\n\n const keyValue = keyLabelToOption(filter.key, filter.keyLabel);\n const valueValue = keyLabelToOption(filter.value, filter.valueLabels?.[0]);\n\n const optionSearcher = useMemo(() => getAdhocOptionSearcher(values), [values]);\n\n const onValueInputChange = (value: string, { action }: InputActionMeta) => {\n if (action === 'input-change') {\n setValueInputValue(value);\n }\n return value;\n };\n\n const onOperatorChange = (v: SelectableValue) => {\n const existingOperator = filter.operator;\n const newOperator = v.value;\n\n const update: Partial<AdHocFilterWithLabels> = { operator: newOperator };\n // clear value if operator has changed from multi to single\n if (isMultiValueOperator(existingOperator) && !isMultiValueOperator(newOperator)) {\n update.value = '';\n update.valueLabels = [''];\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n update.values = undefined;\n setUncommittedValue([]);\n // set values if operator has changed from single to multi\n } else if (!isMultiValueOperator(existingOperator) && isMultiValueOperator(newOperator) && filter.value) {\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n update.values = [filter.value];\n setUncommittedValue([{\n value: filter.value,\n label: filter.valueLabels?.[0] ?? filter.value,\n }]);\n }\n model._updateFilter(filter, update);\n }\n\n const filteredValueOptions = useMemo(\n () => handleOptionGroups(optionSearcher(valueInputValue)),\n [optionSearcher, valueInputValue]\n );\n\n const multiValueProps = {\n isMulti: true,\n value: uncommittedValue,\n components: {\n Option: OptionWithCheckbox,\n },\n hideSelectedOptions: false,\n closeMenuOnSelect: false,\n openMenuOnFocus: false,\n onChange: (v: SelectableValue) => {\n setUncommittedValue(v);\n // clear input value when creating a new custom multi value\n if (v.some((value: SelectableValue) => value.__isNew__)) {\n setValueInputValue('');\n }\n },\n onBlur: () => {\n model._updateFilter(filter, {\n value: uncommittedValue[0]?.value ?? '',\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: uncommittedValue.map((option: SelectableValue<string>) => option.value),\n valueLabels: uncommittedValue.map((option: SelectableValue<string>) => option.label),\n });\n }\n }\n\n const valueSelect = (\n <Select\n virtualized\n allowCustomValue={model.state.allowCustomValue ?? true}\n isValidNewOption={(inputValue) => inputValue.trim().length > 0}\n allowCreateWhileLoading\n formatCreateLabel={(inputValue) => `Use custom value: ${inputValue}`}\n disabled={model.state.readOnly}\n className={cx(styles.value, isValuesOpen ? styles.widthWhenOpen : undefined)}\n width=\"auto\"\n value={valueValue}\n filterOption={filterNoOp}\n placeholder={'Select value'}\n options={filteredValueOptions}\n inputValue={valueInputValue}\n onInputChange={onValueInputChange}\n onChange={(v) => {\n model._updateFilter(filter, {\n value: v.value,\n valueLabels: v.label ? [v.label] : [v.value]\n });\n\n if (valueHasCustomValue !== v.__isNew__) {\n setValueHasCustomValue(v.__isNew__);\n }\n }}\n // there's a bug in react-select where the menu doesn't recalculate its position when the options are loaded asynchronously\n // see https://github.com/grafana/grafana/issues/63558\n // instead, we explicitly control the menu visibility and prevent showing it until the options have fully loaded\n isOpen={isValuesOpen && !isValuesLoading}\n isLoading={isValuesLoading}\n openMenuOnFocus={true}\n onOpenMenu={async () => {\n setIsValuesLoading(true);\n setIsValuesOpen(true);\n const values = await model._getValuesFor(filter);\n setIsValuesLoading(false);\n setValues(values);\n if (valueHasCustomValue) {\n setValueInputValue(valueValue?.label ?? '');\n }\n }}\n onCloseMenu={() => {\n setIsValuesOpen(false);\n setValueInputValue('');\n }}\n {...(isMultiValue && multiValueProps)}\n />\n );\n\n const keySelect = (\n <Select\n // By changing the key, we reset the Select component,\n // to ensure that the loaded values are shown after they are loaded\n key={`${isValuesLoading ? 'loading' : 'loaded'}`}\n disabled={model.state.readOnly}\n className={cx(styles.key, isKeysOpen ? styles.widthWhenOpen : undefined)}\n width=\"auto\"\n allowCustomValue={model.state.allowCustomValue ?? true}\n value={keyValue}\n placeholder={'Select label'}\n options={handleOptionGroups(keys)}\n onChange={(v) => {\n model._updateFilter(filter, {\n key: v.value,\n keyLabel: v.label,\n // clear value if key has changed\n value: '',\n valueLabels: [''],\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: undefined\n })\n setUncommittedValue([]);\n }}\n autoFocus={filter.key === ''}\n // there's a bug in react-select where the menu doesn't recalculate its position when the options are loaded asynchronously\n // see https://github.com/grafana/grafana/issues/63558\n // instead, we explicitly control the menu visibility and prevent showing it until the options have fully loaded\n isOpen={isKeysOpen && !isKeysLoading}\n isLoading={isKeysLoading}\n onOpenMenu={async () => {\n setIsKeysOpen(true);\n setIsKeysLoading(true);\n const keys = await model._getKeys(filter.key);\n setIsKeysLoading(false);\n setKeys(keys);\n }}\n onCloseMenu={() => {\n setIsKeysOpen(false);\n }}\n onBlur={() => {\n if (filter.key === '') {\n model._removeFilter(filter);\n }\n }}\n openMenuOnFocus={true}\n />\n );\n\n const operatorSelect = (\n <Select\n className={cx(styles.operator, {\n [styles.widthWhenOpen]: isOperatorOpen,\n })}\n value={filter.operator}\n disabled={model.state.readOnly}\n options={model._getOperators()}\n onChange={onOperatorChange}\n onOpenMenu={() => {\n setIsOperatorOpen(true)\n }}\n onCloseMenu={() => {\n setIsOperatorOpen(false)\n }}\n />\n );\n\n if (model.state.layout === 'vertical') {\n if (filter.key) {\n const label = (\n <ControlsLabel layout=\"vertical\" label={filter.key ?? ''} onRemove={() => model._removeFilter(filter)} />\n );\n\n return (\n <Field label={label} data-testid={`AdHocFilter-${filter.key}`} className={styles.field}>\n <div className={styles.wrapper}>\n {operatorSelect}\n {valueSelect}\n </div>\n </Field>\n );\n } else {\n return (\n <Field label={'Select label'} data-testid={`AdHocFilter-${filter.key}`} className={styles.field}>\n {keySelect}\n </Field>\n );\n }\n }\n\n return (\n <div className={styles.wrapper} data-testid={`AdHocFilter-${filter.key}`}>\n {keySelect}\n {operatorSelect}\n {valueSelect}\n <Button\n variant=\"secondary\"\n aria-label=\"Remove filter\"\n title=\"Remove filter\"\n className={styles.removeButton}\n icon=\"times\"\n data-testid={`AdHocFilter-remove-${filter.key ?? ''}`}\n onClick={() => model._removeFilter(filter)}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => ({\n field: css({\n marginBottom: 0,\n }),\n wrapper: css({\n display: 'flex',\n '> *': {\n '&:not(:first-child)': {\n // Negative margin hides the double-border on adjacent selects\n marginLeft: -1,\n },\n\n '&:first-child': {\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n },\n\n '&:last-child': {\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n },\n\n '&:not(:first-child):not(:last-child)': {\n borderRadius: 0,\n },\n\n // Fix focus state zIndex issues\n position: 'relative',\n zIndex: 0,\n\n // Adjacent borders are overlapping, so raise children up when hovering etc\n // so all that child's borders are visible.\n '&:hover': {\n zIndex: 1,\n },\n\n '&:focus-within': {\n zIndex: 2,\n },\n },\n }),\n widthWhenOpen: css({\n minWidth: theme.spacing(16),\n }),\n value: css({\n flexBasis: 'content',\n flexShrink: 1,\n minWidth: '90px',\n }),\n key: css({\n flexBasis: 'content',\n minWidth: '90px',\n flexShrink: 1,\n }),\n operator: css({\n flexShrink: 0,\n flexBasis: 'content',\n }),\n removeButton: css({\n paddingLeft: theme.spacing(3 / 2),\n paddingRight: theme.spacing(3 / 2),\n borderLeft: 'none',\n width: theme.spacing(3),\n marginRight: theme.spacing(1),\n boxSizing: 'border-box',\n // To not have button background and last select border intersect\n position: 'relative',\n left: '1px',\n }),\n});\n"],"names":["_a","_b","values","keys"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,gBAAA,CAAiB,KAAa,KAAwC,EAAA;AAC7E,EAAA,OAAO,QAAQ,EACX,GAAA;AAAA,IACE,KAAO,EAAA,GAAA;AAAA,IACP,OAAO,KAAS,IAAA,GAAA;AAAA,GAElB,GAAA,IAAA,CAAA;AACN,CAAA;AAEA,MAAM,aAAa,MAAM,IAAA,CAAA;AAElB,SAAS,mBAAoB,CAAA,EAAE,MAAQ,EAAA,KAAA,EAAgB,EAAA;AA3B9D,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AA4BE,EAAM,MAAA,MAAA,GAAS,WAAW,SAAS,CAAA,CAAA;AAEnC,EAAA,MAAM,CAAC,IAAM,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CAAA,OAAA,CAAQ,CAAC,CAAA;AAAA,IACtB,WAAA,EAAa,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAA;AAAA,IAC5B,SAAW,EAAA,YAAA;AAAA,IAEX,QAAU,EAAA,UAAA;AAAA,IACV,IAAM,EAAA,KAAA;AAAA,GACP,CAAA;AACH,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"AdHocFilterRenderer.js","sources":["../../../../src/variables/adhoc/AdHocFilterRenderer.tsx"],"sourcesContent":["import React, { useMemo, useState } from 'react';\n\nimport { AdHocFiltersVariable, AdHocFilterWithLabels, isMultiValueOperator } from './AdHocFiltersVariable';\nimport { GrafanaTheme2, SelectableValue } from '@grafana/data';\nimport { Button, Field, InputActionMeta, Select, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport { ControlsLabel } from '../../utils/ControlsLabel';\nimport { getAdhocOptionSearcher } from './getAdhocOptionSearcher';\nimport { handleOptionGroups } from '../utils';\nimport { OptionWithCheckbox } from '../components/VariableValueSelect';\n\ninterface Props {\n filter: AdHocFilterWithLabels;\n model: AdHocFiltersVariable;\n}\n\nfunction keyLabelToOption(key: string, label?: string): SelectableValue | null {\n return key !== ''\n ? {\n value: key,\n label: label || key,\n }\n : null;\n}\n\nconst filterNoOp = () => true;\n\nexport function AdHocFilterRenderer({ filter, model }: Props) {\n const styles = useStyles2(getStyles);\n\n const [keys, setKeys] = useState<SelectableValue[]>([]);\n const [values, setValues] = useState<SelectableValue[]>([]);\n const [isKeysLoading, setIsKeysLoading] = useState(false);\n const [isValuesLoading, setIsValuesLoading] = useState(false);\n const [isKeysOpen, setIsKeysOpen] = useState(false);\n const [isValuesOpen, setIsValuesOpen] = useState(false);\n const [isOperatorOpen, setIsOperatorOpen] = useState(false);\n const [valueInputValue, setValueInputValue] = useState('');\n const [valueHasCustomValue, setValueHasCustomValue] = useState(false);\n // To not trigger queries on every selection we store this state locally here and only update the variable onBlur\n // TODO remove expect-error when we're on the latest version of @grafana/data\n const [uncommittedValue, setUncommittedValue] = useState<SelectableValue>(\n // @ts-expect-error\n filter.values ? filter.values.map((value, index) => keyLabelToOption(value, filter.valueLabels?.[index])) : []\n );\n const isMultiValue = isMultiValueOperator(filter.operator);\n\n const keyValue = keyLabelToOption(filter.key, filter.keyLabel);\n const valueValue = keyLabelToOption(filter.value, filter.valueLabels?.[0]);\n\n const optionSearcher = useMemo(() => getAdhocOptionSearcher(values), [values]);\n\n const onValueInputChange = (value: string, { action }: InputActionMeta) => {\n if (action === 'input-change') {\n setValueInputValue(value);\n }\n return value;\n };\n\n const onOperatorChange = (v: SelectableValue) => {\n const existingOperator = filter.operator;\n const newOperator = v.value;\n\n const update: Partial<AdHocFilterWithLabels> = { operator: newOperator };\n // clear value if operator has changed from multi to single\n if (isMultiValueOperator(existingOperator) && !isMultiValueOperator(newOperator)) {\n update.value = '';\n update.valueLabels = [''];\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n update.values = undefined;\n setUncommittedValue([]);\n // set values if operator has changed from single to multi\n } else if (!isMultiValueOperator(existingOperator) && isMultiValueOperator(newOperator) && filter.value) {\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n update.values = [filter.value];\n setUncommittedValue([\n {\n value: filter.value,\n label: filter.valueLabels?.[0] ?? filter.value,\n },\n ]);\n }\n model._updateFilter(filter, update);\n };\n\n const filteredValueOptions = useMemo(\n () => handleOptionGroups(optionSearcher(valueInputValue)),\n [optionSearcher, valueInputValue]\n );\n\n const multiValueProps = {\n isMulti: true,\n value: uncommittedValue,\n components: {\n Option: OptionWithCheckbox,\n },\n hideSelectedOptions: false,\n closeMenuOnSelect: false,\n openMenuOnFocus: false,\n onChange: (v: SelectableValue) => {\n setUncommittedValue(v);\n // clear input value when creating a new custom multi value\n if (v.some((value: SelectableValue) => value.__isNew__)) {\n setValueInputValue('');\n }\n },\n onBlur: () => {\n model._updateFilter(filter, {\n value: uncommittedValue[0]?.value ?? '',\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: uncommittedValue.map((option: SelectableValue<string>) => option.value),\n valueLabels: uncommittedValue.map((option: SelectableValue<string>) => option.label),\n });\n },\n };\n\n const valueSelect = (\n <Select\n virtualized\n allowCustomValue={model.state.allowCustomValue ?? true}\n isValidNewOption={(inputValue) => inputValue.trim().length > 0}\n allowCreateWhileLoading\n formatCreateLabel={(inputValue) => `Use custom value: ${inputValue}`}\n disabled={model.state.readOnly}\n className={cx(styles.value, isValuesOpen ? styles.widthWhenOpen : undefined)}\n width=\"auto\"\n value={valueValue}\n filterOption={filterNoOp}\n placeholder={'Select value'}\n options={filteredValueOptions}\n inputValue={valueInputValue}\n onInputChange={onValueInputChange}\n onChange={(v) => {\n model._updateFilter(filter, {\n value: v.value,\n valueLabels: v.label ? [v.label] : [v.value],\n });\n\n if (valueHasCustomValue !== v.__isNew__) {\n setValueHasCustomValue(v.__isNew__);\n }\n }}\n // there's a bug in react-select where the menu doesn't recalculate its position when the options are loaded asynchronously\n // see https://github.com/grafana/grafana/issues/63558\n // instead, we explicitly control the menu visibility and prevent showing it until the options have fully loaded\n isOpen={isValuesOpen && !isValuesLoading}\n isLoading={isValuesLoading}\n openMenuOnFocus={true}\n onOpenMenu={async () => {\n setIsValuesLoading(true);\n setIsValuesOpen(true);\n const values = await model._getValuesFor(filter);\n setIsValuesLoading(false);\n setValues(values);\n if (valueHasCustomValue) {\n setValueInputValue(valueValue?.label ?? '');\n }\n }}\n onCloseMenu={() => {\n setIsValuesOpen(false);\n setValueInputValue('');\n }}\n {...(isMultiValue && multiValueProps)}\n />\n );\n\n const keySelect = (\n <Select\n // By changing the key, we reset the Select component,\n // to ensure that the loaded values are shown after they are loaded\n key={`${isValuesLoading ? 'loading' : 'loaded'}`}\n disabled={model.state.readOnly}\n className={cx(styles.key, isKeysOpen ? styles.widthWhenOpen : undefined)}\n width=\"auto\"\n allowCustomValue={model.state.allowCustomValue ?? true}\n value={keyValue}\n placeholder={'Select label'}\n options={handleOptionGroups(keys)}\n onChange={(v) => {\n model._updateFilter(filter, {\n key: v.value,\n keyLabel: v.label,\n // clear value if key has changed\n value: '',\n valueLabels: [''],\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: undefined,\n });\n setUncommittedValue([]);\n }}\n autoFocus={filter.key === ''}\n // there's a bug in react-select where the menu doesn't recalculate its position when the options are loaded asynchronously\n // see https://github.com/grafana/grafana/issues/63558\n // instead, we explicitly control the menu visibility and prevent showing it until the options have fully loaded\n isOpen={isKeysOpen && !isKeysLoading}\n isLoading={isKeysLoading}\n onOpenMenu={async () => {\n setIsKeysOpen(true);\n setIsKeysLoading(true);\n const keys = await model._getKeys(filter.key);\n setIsKeysLoading(false);\n setKeys(keys);\n }}\n onCloseMenu={() => {\n setIsKeysOpen(false);\n }}\n onBlur={() => {\n if (filter.key === '') {\n model._removeFilter(filter);\n }\n }}\n openMenuOnFocus={true}\n />\n );\n\n const operatorSelect = (\n <Select\n className={cx(styles.operator, {\n [styles.widthWhenOpen]: isOperatorOpen,\n })}\n value={filter.operator}\n disabled={model.state.readOnly}\n options={model._getOperators()}\n onChange={onOperatorChange}\n onOpenMenu={() => {\n setIsOperatorOpen(true);\n }}\n onCloseMenu={() => {\n setIsOperatorOpen(false);\n }}\n />\n );\n\n if (model.state.layout === 'vertical') {\n if (filter.key) {\n const label = (\n <ControlsLabel layout=\"vertical\" label={filter.key ?? ''} onRemove={() => model._removeFilter(filter)} />\n );\n\n return (\n <Field label={label} data-testid={`AdHocFilter-${filter.key}`} className={styles.field}>\n <div className={styles.wrapper}>\n {operatorSelect}\n {valueSelect}\n </div>\n </Field>\n );\n } else {\n return (\n <Field label={'Select label'} data-testid={`AdHocFilter-${filter.key}`} className={styles.field}>\n {keySelect}\n </Field>\n );\n }\n }\n\n return (\n <div className={styles.wrapper} data-testid={`AdHocFilter-${filter.key}`}>\n {keySelect}\n {operatorSelect}\n {valueSelect}\n <Button\n variant=\"secondary\"\n aria-label=\"Remove filter\"\n title=\"Remove filter\"\n className={styles.removeButton}\n icon=\"times\"\n data-testid={`AdHocFilter-remove-${filter.key ?? ''}`}\n onClick={() => model._removeFilter(filter)}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => ({\n field: css({\n marginBottom: 0,\n }),\n wrapper: css({\n display: 'flex',\n '> *': {\n '&:not(:first-child)': {\n // Negative margin hides the double-border on adjacent selects\n marginLeft: -1,\n },\n\n '&:first-child': {\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n },\n\n '&:last-child': {\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n },\n\n '&:not(:first-child):not(:last-child)': {\n borderRadius: 0,\n },\n\n // Fix focus state zIndex issues\n position: 'relative',\n zIndex: 0,\n\n // Adjacent borders are overlapping, so raise children up when hovering etc\n // so all that child's borders are visible.\n '&:hover': {\n zIndex: 1,\n },\n\n '&:focus-within': {\n zIndex: 2,\n },\n },\n }),\n widthWhenOpen: css({\n minWidth: theme.spacing(16),\n }),\n value: css({\n flexBasis: 'content',\n flexShrink: 1,\n minWidth: '90px',\n }),\n key: css({\n flexBasis: 'content',\n minWidth: '90px',\n flexShrink: 1,\n }),\n operator: css({\n flexShrink: 0,\n flexBasis: 'content',\n }),\n removeButton: css({\n paddingLeft: theme.spacing(3 / 2),\n paddingRight: theme.spacing(3 / 2),\n borderLeft: 'none',\n width: theme.spacing(3),\n marginRight: theme.spacing(1),\n boxSizing: 'border-box',\n // To not have button background and last select border intersect\n position: 'relative',\n left: '1px',\n }),\n});\n"],"names":["_a","_b","values","keys"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,gBAAA,CAAiB,KAAa,KAAwC,EAAA;AAC7E,EAAA,OAAO,QAAQ,EACX,GAAA;AAAA,IACE,KAAO,EAAA,GAAA;AAAA,IACP,OAAO,KAAS,IAAA,GAAA;AAAA,GAElB,GAAA,IAAA,CAAA;AACN,CAAA;AAEA,MAAM,aAAa,MAA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,CAAA;AAAA,EACD,cAAc,GAAI,CAAA;AAAA,IAChB,WAAa,EAAA,KAAA,CAAM,OAAQ,CAAA,CAAA,GAAI,CAAC,CAAA;AAAA,IAChC,YAAc,EAAA,KAAA,CAAM,OAAQ,CAAA,CAAA,GAAI,CAAC,CAAA;AAAA,IACjC,UAAY,EAAA,MAAA;AAAA,IACZ,KAAA,EAAO,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAA;AAAA,IACtB,WAAA,EAAa,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAA;AAAA,IAC5B,SAAW,EAAA,YAAA;AAAA,IAEX,QAAU,EAAA,UAAA;AAAA,IACV,IAAM,EAAA,KAAA;AAAA,GACP,CAAA;AACH,CAAA,CAAA;;;;"}
@@ -38,10 +38,7 @@ function deserializeUrlToFilters(value) {
38
38
  }
39
39
  function toArray(filter) {
40
40
  var _a;
41
- const result = [
42
- toUrlCommaDelimitedString(filter.key, filter.keyLabel),
43
- filter.operator
44
- ];
41
+ const result = [toUrlCommaDelimitedString(filter.key, filter.keyLabel), filter.operator];
45
42
  if (isMultiValueOperator(filter.operator)) {
46
43
  filter.values.forEach((value, index) => {
47
44
  var _a2;
@@ -1 +1 @@
1
- {"version":3,"file":"AdHocFiltersVariableUrlSyncHandler.js","sources":["../../../../src/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.ts"],"sourcesContent":["import { SceneObjectUrlSyncHandler, SceneObjectUrlValue, SceneObjectUrlValues } from '../../core/types';\nimport { AdHocFiltersVariable, AdHocFilterWithLabels, isFilterComplete, isMultiValueOperator } from './AdHocFiltersVariable';\nimport { escapeUrlPipeDelimiters, toUrlCommaDelimitedString, unescapeUrlDelimiters } from '../utils';\n\nexport class AdHocFiltersVariableUrlSyncHandler implements SceneObjectUrlSyncHandler {\n public constructor(private _variable: AdHocFiltersVariable) {}\n\n private getKey(): string {\n return `var-${this._variable.state.name}`;\n }\n\n public getKeys(): string[] {\n return [this.getKey()];\n }\n\n public getUrlState(): SceneObjectUrlValues {\n const filters = this._variable.state.filters;\n\n if (filters.length === 0) {\n return { [this.getKey()]: [''] };\n }\n\n const value = filters.filter(isFilterComplete).map((filter) => toArray(filter).map(escapeUrlPipeDelimiters).join('|'));\n return { [this.getKey()]: value };\n }\n\n public updateFromUrl(values: SceneObjectUrlValues): void {\n const urlValue = values[this.getKey()];\n\n if (urlValue == null) {\n return;\n }\n\n const filters = deserializeUrlToFilters(urlValue);\n this._variable.setState({ filters });\n }\n}\n\nfunction deserializeUrlToFilters(value: SceneObjectUrlValue): AdHocFilterWithLabels[] {\n if (Array.isArray(value)) {\n const values = value;\n return values.map(toFilter).filter(isFilter);\n }\n\n const filter = toFilter(value);\n return filter === null ? [] : [filter];\n}\n\nfunction toArray(filter: AdHocFilterWithLabels): string[] {\n const result = [\n toUrlCommaDelimitedString(filter.key, filter.keyLabel),\n filter.operator,\n ];\n if (isMultiValueOperator(filter.operator)) {\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n filter.values.forEach((value, index) => {\n result.push(toUrlCommaDelimitedString(value, filter.valueLabels?.[index]));\n });\n } else {\n result.push(toUrlCommaDelimitedString(filter.value, filter.valueLabels?.[0]));\n }\n return result;\n}\n\nfunction toFilter(urlValue: string | number | boolean | undefined | null): AdHocFilterWithLabels | null {\n if (typeof urlValue !== 'string' || urlValue.length === 0) {\n return null;\n }\n\n const [key, keyLabel, operator, _operatorLabel, ...values] = urlValue\n .split('|')\n .reduce<string[]>((acc, v) => {\n const [key, label] = v.split(',');\n\n acc.push(key, label ?? key);\n\n return acc;\n }, [])\n .map(unescapeUrlDelimiters);\n\n return {\n key,\n keyLabel,\n operator,\n value: values[0],\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: isMultiValueOperator(operator) ? values.filter((_, index) => index % 2 === 0) : undefined,\n valueLabels: values.filter((_, index) => index % 2 === 1),\n condition: '',\n };\n}\n\nfunction isFilter(filter: AdHocFilterWithLabels | null): filter is AdHocFilterWithLab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3,"file":"AdHocFiltersVariableUrlSyncHandler.js","sources":["../../../../src/variables/adhoc/AdHocFiltersVariableUrlSyncHandler.ts"],"sourcesContent":["import { SceneObjectUrlSyncHandler, SceneObjectUrlValue, SceneObjectUrlValues } from '../../core/types';\nimport {\n AdHocFiltersVariable,\n AdHocFilterWithLabels,\n isFilterComplete,\n isMultiValueOperator,\n} from './AdHocFiltersVariable';\nimport { escapeUrlPipeDelimiters, toUrlCommaDelimitedString, unescapeUrlDelimiters } from '../utils';\n\nexport class AdHocFiltersVariableUrlSyncHandler implements SceneObjectUrlSyncHandler {\n public constructor(private _variable: AdHocFiltersVariable) {}\n\n private getKey(): string {\n return `var-${this._variable.state.name}`;\n }\n\n public getKeys(): string[] {\n return [this.getKey()];\n }\n\n public getUrlState(): SceneObjectUrlValues {\n const filters = this._variable.state.filters;\n\n if (filters.length === 0) {\n return { [this.getKey()]: [''] };\n }\n\n const value = filters\n .filter(isFilterComplete)\n .map((filter) => toArray(filter).map(escapeUrlPipeDelimiters).join('|'));\n return { [this.getKey()]: value };\n }\n\n public updateFromUrl(values: SceneObjectUrlValues): void {\n const urlValue = values[this.getKey()];\n\n if (urlValue == null) {\n return;\n }\n\n const filters = deserializeUrlToFilters(urlValue);\n this._variable.setState({ filters });\n }\n}\n\nfunction deserializeUrlToFilters(value: SceneObjectUrlValue): AdHocFilterWithLabels[] {\n if (Array.isArray(value)) {\n const values = value;\n return values.map(toFilter).filter(isFilter);\n }\n\n const filter = toFilter(value);\n return filter === null ? [] : [filter];\n}\n\nfunction toArray(filter: AdHocFilterWithLabels): string[] {\n const result = [toUrlCommaDelimitedString(filter.key, filter.keyLabel), filter.operator];\n if (isMultiValueOperator(filter.operator)) {\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n filter.values.forEach((value, index) => {\n result.push(toUrlCommaDelimitedString(value, filter.valueLabels?.[index]));\n });\n } else {\n result.push(toUrlCommaDelimitedString(filter.value, filter.valueLabels?.[0]));\n }\n return result;\n}\n\nfunction toFilter(urlValue: string | number | boolean | undefined | null): AdHocFilterWithLabels | null {\n if (typeof urlValue !== 'string' || urlValue.length === 0) {\n return null;\n }\n\n const [key, keyLabel, operator, _operatorLabel, ...values] = urlValue\n .split('|')\n .reduce<string[]>((acc, v) => {\n const [key, label] = v.split(',');\n\n acc.push(key, label ?? key);\n\n return acc;\n }, [])\n .map(unescapeUrlDelimiters);\n\n return {\n key,\n keyLabel,\n operator,\n value: values[0],\n // TODO remove expect-error when we're on the latest version of @grafana/data\n // @ts-expect-error\n values: isMultiValueOperator(operator) ? values.filter((_, index) => index % 2 === 0) : undefined,\n valueLabels: values.filter((_, index) => index % 2 === 1),\n condition: '',\n };\n}\n\nfunction isFilter(filter: AdHocFilterWithLabels | null): filter is AdHocFilterWithLabels {\n return filter !== null && typeof filter.key === 'string' && typeof filter.value === 'string';\n}\n"],"names":["_a","key"],"mappings":";;;AASO,MAAM,kCAAwE,CAAA;AAAA,EAC5E,YAAoB,SAAiC,EAAA;AAAjC,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA,CAAA;AAAA,GAAkC;AAAA,EAErD,MAAiB,GAAA;AACvB,IAAO,OAAA,CAAA,IAAA,EAAO,IAAK,CAAA,SAAA,CAAU,KAAM,CAAA,IAAA,CAAA,CAAA,CAAA;AAAA,GACrC;AAAA,EAEO,OAAoB,GAAA;AACzB,IAAO,OAAA,CAAC,IAAK,CAAA,MAAA,EAAQ,CAAA,CAAA;AAAA,GACvB;AAAA,EAEO,WAAoC,GAAA;AACzC,IAAM,MAAA,OAAA,GAAU,IAAK,CAAA,SAAA,CAAU,KAAM,CAAA,OAAA,CAAA;AAErC,IAAI,IAAA,OAAA,CAAQ,WAAW,CAAG,EAAA;AACxB,MAAA,OAAO,EAAE,CAAC,IAAA,CAAK,QAAW,GAAA,CAAC,EAAE,CAAE,EAAA,CAAA;AAAA,KACjC;AAEA,IAAA,MAAM,QAAQ,OACX,CAAA,MAAA,CAAO,gBAAgB,CAAA,CACvB,I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