@grafana/scenes 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +26 -0
  3. package/dist/esm/components/NestedScene.js +119 -0
  4. package/dist/esm/components/NestedScene.js.map +1 -0
  5. package/dist/esm/components/Scene.js +39 -0
  6. package/dist/esm/components/Scene.js.map +1 -0
  7. package/dist/esm/components/SceneCanvasText.js +41 -0
  8. package/dist/esm/components/SceneCanvasText.js.map +1 -0
  9. package/dist/esm/components/SceneDragHandle.js +18 -0
  10. package/dist/esm/components/SceneDragHandle.js.map +1 -0
  11. package/dist/esm/components/ScenePanelRepeater.js +66 -0
  12. package/dist/esm/components/ScenePanelRepeater.js.map +1 -0
  13. package/dist/esm/components/SceneSubMenu.js +18 -0
  14. package/dist/esm/components/SceneSubMenu.js.map +1 -0
  15. package/dist/esm/components/SceneTimePicker.js +40 -0
  16. package/dist/esm/components/SceneTimePicker.js.map +1 -0
  17. package/dist/esm/components/SceneToolbarButton.js +28 -0
  18. package/dist/esm/components/SceneToolbarButton.js.map +1 -0
  19. package/dist/esm/components/VizPanel/VizPanel.js +105 -0
  20. package/dist/esm/components/VizPanel/VizPanel.js.map +1 -0
  21. package/dist/esm/components/VizPanel/VizPanelRenderer.js +76 -0
  22. package/dist/esm/components/VizPanel/VizPanelRenderer.js.map +1 -0
  23. package/dist/esm/components/layout/SceneFlexLayout.js +88 -0
  24. package/dist/esm/components/layout/SceneFlexLayout.js.map +1 -0
  25. package/dist/esm/components/layout/SceneGridLayout.js +288 -0
  26. package/dist/esm/components/layout/SceneGridLayout.js.map +1 -0
  27. package/dist/esm/components/layout/SceneGridRow.js +124 -0
  28. package/dist/esm/components/layout/SceneGridRow.js.map +1 -0
  29. package/dist/esm/components/layout/constants.js +7 -0
  30. package/dist/esm/components/layout/constants.js.map +1 -0
  31. package/dist/esm/core/SceneComponentWrapper.js +84 -0
  32. package/dist/esm/core/SceneComponentWrapper.js.map +1 -0
  33. package/dist/esm/core/SceneDataNode.js +7 -0
  34. package/dist/esm/core/SceneDataNode.js.map +1 -0
  35. package/dist/esm/core/SceneDataTransformer.js +51 -0
  36. package/dist/esm/core/SceneDataTransformer.js.map +1 -0
  37. package/dist/esm/core/SceneObjectBase.js +141 -0
  38. package/dist/esm/core/SceneObjectBase.js.map +1 -0
  39. package/dist/esm/core/SceneTimeRange.js +108 -0
  40. package/dist/esm/core/SceneTimeRange.js.map +1 -0
  41. package/dist/esm/core/events.js +8 -0
  42. package/dist/esm/core/events.js.map +1 -0
  43. package/dist/esm/core/sceneGraph.js +68 -0
  44. package/dist/esm/core/sceneGraph.js.map +1 -0
  45. package/dist/esm/core/types.js +6 -0
  46. package/dist/esm/core/types.js.map +1 -0
  47. package/dist/esm/core/utils.js +57 -0
  48. package/dist/esm/core/utils.js.map +1 -0
  49. package/dist/esm/index.js +33 -0
  50. package/dist/esm/index.js.map +1 -0
  51. package/dist/esm/querying/SceneQueryRunner.js +161 -0
  52. package/dist/esm/querying/SceneQueryRunner.js.map +1 -0
  53. package/dist/esm/services/SceneObjectUrlSyncConfig.js +18 -0
  54. package/dist/esm/services/SceneObjectUrlSyncConfig.js.map +1 -0
  55. package/dist/esm/services/UrlSyncManager.js +133 -0
  56. package/dist/esm/services/UrlSyncManager.js.map +1 -0
  57. package/dist/esm/utils/metricTree.js +53 -0
  58. package/dist/esm/utils/metricTree.js.map +1 -0
  59. package/dist/esm/variables/VariableDependencyConfig.js +86 -0
  60. package/dist/esm/variables/VariableDependencyConfig.js.map +1 -0
  61. package/dist/esm/variables/components/VariableValueSelect.js +58 -0
  62. package/dist/esm/variables/components/VariableValueSelect.js.map +1 -0
  63. package/dist/esm/variables/components/VariableValueSelectors.js +56 -0
  64. package/dist/esm/variables/components/VariableValueSelectors.js.map +1 -0
  65. package/dist/esm/variables/constants.js +6 -0
  66. package/dist/esm/variables/constants.js.map +1 -0
  67. package/dist/esm/variables/interpolation/ScopedVarsVariable.js +49 -0
  68. package/dist/esm/variables/interpolation/ScopedVarsVariable.js.map +1 -0
  69. package/dist/esm/variables/interpolation/defaults.js +17 -0
  70. package/dist/esm/variables/interpolation/defaults.js.map +1 -0
  71. package/dist/esm/variables/interpolation/formatRegistry.js +280 -0
  72. package/dist/esm/variables/interpolation/formatRegistry.js.map +1 -0
  73. package/dist/esm/variables/interpolation/sceneInterpolator.js +83 -0
  74. package/dist/esm/variables/interpolation/sceneInterpolator.js.map +1 -0
  75. package/dist/esm/variables/sets/SceneVariableSet.js +123 -0
  76. package/dist/esm/variables/sets/SceneVariableSet.js.map +1 -0
  77. package/dist/esm/variables/types.js +8 -0
  78. package/dist/esm/variables/types.js.map +1 -0
  79. package/dist/esm/variables/variants/ConstantVariable.js +33 -0
  80. package/dist/esm/variables/variants/ConstantVariable.js.map +1 -0
  81. package/dist/esm/variables/variants/CustomVariable.js +58 -0
  82. package/dist/esm/variables/variants/CustomVariable.js.map +1 -0
  83. package/dist/esm/variables/variants/DataSourceVariable.js +92 -0
  84. package/dist/esm/variables/variants/DataSourceVariable.js.map +1 -0
  85. package/dist/esm/variables/variants/MultiValueVariable.js +183 -0
  86. package/dist/esm/variables/variants/MultiValueVariable.js.map +1 -0
  87. package/dist/esm/variables/variants/TestVariable.js +81 -0
  88. package/dist/esm/variables/variants/TestVariable.js.map +1 -0
  89. package/dist/esm/variables/variants/query/QueryVariable.js +137 -0
  90. package/dist/esm/variables/variants/query/QueryVariable.js.map +1 -0
  91. package/dist/esm/variables/variants/query/createQueryVariableRunner.js +93 -0
  92. package/dist/esm/variables/variants/query/createQueryVariableRunner.js.map +1 -0
  93. package/dist/esm/variables/variants/query/guards.js +18 -0
  94. package/dist/esm/variables/variants/query/guards.js.map +1 -0
  95. package/dist/esm/variables/variants/query/toMetricFindValues.js +93 -0
  96. package/dist/esm/variables/variants/query/toMetricFindValues.js.map +1 -0
  97. package/dist/esm/variables/variants/query/utils.js +93 -0
  98. package/dist/esm/variables/variants/query/utils.js.map +1 -0
  99. package/dist/index.d.ts +796 -0
  100. package/dist/index.js +3356 -0
  101. package/dist/index.js.map +1 -0
  102. package/package.json +103 -0
package/dist/index.js ADDED
@@ -0,0 +1,3356 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var data = require('@grafana/data');
6
+ var React = require('react');
7
+ var rxjs = require('rxjs');
8
+ var uuid = require('uuid');
9
+ var ui = require('@grafana/ui');
10
+ var lodash = require('lodash');
11
+ var runtime = require('@grafana/runtime');
12
+ var e2eSelectors = require('@grafana/e2e-selectors');
13
+ var reactUse = require('react-use');
14
+ var css = require('@emotion/css');
15
+ var experimental = require('@grafana/experimental');
16
+ var ReactGridLayout = require('react-grid-layout');
17
+ var AutoSizer = require('react-virtualized-auto-sizer');
18
+
19
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
20
+
21
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
22
+ var ReactGridLayout__default = /*#__PURE__*/_interopDefaultLegacy(ReactGridLayout);
23
+ var AutoSizer__default = /*#__PURE__*/_interopDefaultLegacy(AutoSizer);
24
+
25
+ function isSceneObject(obj) {
26
+ return obj.useState !== void 0;
27
+ }
28
+
29
+ class SceneObjectStateChangedEvent extends data.BusEventWithPayload {
30
+ }
31
+ SceneObjectStateChangedEvent.type = "scene-object-state-change";
32
+
33
+ var __defProp$f = Object.defineProperty;
34
+ var __defProps$6 = Object.defineProperties;
35
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
36
+ var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
37
+ var __hasOwnProp$f = Object.prototype.hasOwnProperty;
38
+ var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
39
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
40
+ var __spreadValues$f = (a, b) => {
41
+ for (var prop in b || (b = {}))
42
+ if (__hasOwnProp$f.call(b, prop))
43
+ __defNormalProp$f(a, prop, b[prop]);
44
+ if (__getOwnPropSymbols$f)
45
+ for (var prop of __getOwnPropSymbols$f(b)) {
46
+ if (__propIsEnum$f.call(b, prop))
47
+ __defNormalProp$f(a, prop, b[prop]);
48
+ }
49
+ return a;
50
+ };
51
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
52
+ var __objRest = (source, exclude) => {
53
+ var target = {};
54
+ for (var prop in source)
55
+ if (__hasOwnProp$f.call(source, prop) && exclude.indexOf(prop) < 0)
56
+ target[prop] = source[prop];
57
+ if (source != null && __getOwnPropSymbols$f)
58
+ for (var prop of __getOwnPropSymbols$f(source)) {
59
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$f.call(source, prop))
60
+ target[prop] = source[prop];
61
+ }
62
+ return target;
63
+ };
64
+ function SceneComponentWrapper(_a) {
65
+ var _b = _a, {
66
+ model,
67
+ isEditing
68
+ } = _b, otherProps = __objRest(_b, [
69
+ "model",
70
+ "isEditing"
71
+ ]);
72
+ var _a2;
73
+ const Component = (_a2 = model.constructor["Component"]) != null ? _a2 : EmptyRenderer;
74
+ const inner = /* @__PURE__ */ React__default["default"].createElement(Component, __spreadProps$6(__spreadValues$f({}, otherProps), {
75
+ model,
76
+ isEditing
77
+ }));
78
+ React.useEffect(() => {
79
+ if (!model.isActive) {
80
+ model.activate();
81
+ }
82
+ return () => {
83
+ if (model.isActive) {
84
+ model.deactivate();
85
+ }
86
+ };
87
+ }, [model]);
88
+ model._renderCount += 1;
89
+ if (!isEditing) {
90
+ return inner;
91
+ }
92
+ const editor = getSceneEditor$1(model);
93
+ const EditWrapper = getSceneEditor$1(model).getEditComponentWrapper();
94
+ return /* @__PURE__ */ React__default["default"].createElement(EditWrapper, {
95
+ model,
96
+ editor
97
+ }, inner);
98
+ }
99
+ function EmptyRenderer(_) {
100
+ return null;
101
+ }
102
+ function getSceneEditor$1(sceneObject) {
103
+ const { $editor } = sceneObject.state;
104
+ if ($editor) {
105
+ return $editor;
106
+ }
107
+ if (sceneObject.parent) {
108
+ return getSceneEditor$1(sceneObject.parent);
109
+ }
110
+ throw new Error("No editor found in scene tree");
111
+ }
112
+
113
+ var __defProp$e = Object.defineProperty;
114
+ var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
115
+ var __hasOwnProp$e = Object.prototype.hasOwnProperty;
116
+ var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
117
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118
+ var __spreadValues$e = (a, b) => {
119
+ for (var prop in b || (b = {}))
120
+ if (__hasOwnProp$e.call(b, prop))
121
+ __defNormalProp$e(a, prop, b[prop]);
122
+ if (__getOwnPropSymbols$e)
123
+ for (var prop of __getOwnPropSymbols$e(b)) {
124
+ if (__propIsEnum$e.call(b, prop))
125
+ __defNormalProp$e(a, prop, b[prop]);
126
+ }
127
+ return a;
128
+ };
129
+ function forEachSceneObjectInState(state, callback) {
130
+ for (const propValue of Object.values(state)) {
131
+ if (propValue instanceof SceneObjectBase) {
132
+ callback(propValue);
133
+ }
134
+ if (Array.isArray(propValue)) {
135
+ for (const child of propValue) {
136
+ if (child instanceof SceneObjectBase) {
137
+ callback(child);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+ function cloneSceneObject(sceneObject, withState) {
144
+ const clonedState = __spreadValues$e({}, sceneObject.state);
145
+ for (const key in clonedState) {
146
+ const propValue = clonedState[key];
147
+ if (propValue instanceof SceneObjectBase) {
148
+ clonedState[key] = propValue.clone();
149
+ }
150
+ if (Array.isArray(propValue)) {
151
+ const newArray = [];
152
+ for (const child of propValue) {
153
+ if (child instanceof SceneObjectBase) {
154
+ newArray.push(child.clone());
155
+ } else {
156
+ newArray.push(child);
157
+ }
158
+ }
159
+ clonedState[key] = newArray;
160
+ }
161
+ }
162
+ Object.assign(clonedState, withState);
163
+ return new sceneObject.constructor(clonedState);
164
+ }
165
+
166
+ var __defProp$d = Object.defineProperty;
167
+ var __getOwnPropSymbols$d = Object.getOwnPropertySymbols;
168
+ var __hasOwnProp$d = Object.prototype.hasOwnProperty;
169
+ var __propIsEnum$d = Object.prototype.propertyIsEnumerable;
170
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
171
+ var __spreadValues$d = (a, b) => {
172
+ for (var prop in b || (b = {}))
173
+ if (__hasOwnProp$d.call(b, prop))
174
+ __defNormalProp$d(a, prop, b[prop]);
175
+ if (__getOwnPropSymbols$d)
176
+ for (var prop of __getOwnPropSymbols$d(b)) {
177
+ if (__propIsEnum$d.call(b, prop))
178
+ __defNormalProp$d(a, prop, b[prop]);
179
+ }
180
+ return a;
181
+ };
182
+ class SceneObjectBase {
183
+ constructor(state) {
184
+ this._isActive = false;
185
+ this._subject = new rxjs.Subject();
186
+ this._events = new data.EventBusSrv();
187
+ this._renderCount = 0;
188
+ this._subs = new rxjs.Subscription();
189
+ if (!state.key) {
190
+ state.key = uuid.v4();
191
+ }
192
+ this._state = Object.freeze(state);
193
+ this._subject.next(state);
194
+ this.setParent();
195
+ }
196
+ get state() {
197
+ return this._state;
198
+ }
199
+ get isActive() {
200
+ return this._isActive;
201
+ }
202
+ get parent() {
203
+ return this._parent;
204
+ }
205
+ get variableDependency() {
206
+ return this._variableDependency;
207
+ }
208
+ get urlSync() {
209
+ return this._urlSync;
210
+ }
211
+ get Component() {
212
+ return SceneComponentWrapper;
213
+ }
214
+ get Editor() {
215
+ var _a;
216
+ return (_a = this.constructor["Editor"]) != null ? _a : () => null;
217
+ }
218
+ setParent() {
219
+ forEachSceneObjectInState(this._state, (child) => child._parent = this);
220
+ }
221
+ subscribeToState(observerOrNext) {
222
+ return this._subject.subscribe(observerOrNext);
223
+ }
224
+ subscribeToEvent(eventType, handler) {
225
+ return this._events.subscribe(eventType, handler);
226
+ }
227
+ setState(update) {
228
+ const prevState = this._state;
229
+ const newState = __spreadValues$d(__spreadValues$d({}, this._state), update);
230
+ this._state = Object.freeze(newState);
231
+ this.setParent();
232
+ this._subject.next(newState);
233
+ this.publishEvent(
234
+ new SceneObjectStateChangedEvent({
235
+ prevState,
236
+ newState,
237
+ partialUpdate: update,
238
+ changedObject: this
239
+ }),
240
+ true
241
+ );
242
+ }
243
+ publishEvent(event, bubble) {
244
+ this._events.publish(event);
245
+ if (bubble && this.parent) {
246
+ this.parent.publishEvent(event, bubble);
247
+ }
248
+ }
249
+ getRoot() {
250
+ return !this._parent ? this : this._parent.getRoot();
251
+ }
252
+ activate() {
253
+ this._isActive = true;
254
+ const { $data, $variables } = this.state;
255
+ if ($data && !$data.isActive) {
256
+ $data.activate();
257
+ }
258
+ if ($variables && !$variables.isActive) {
259
+ $variables.activate();
260
+ }
261
+ }
262
+ deactivate() {
263
+ this._isActive = false;
264
+ const { $data, $variables } = this.state;
265
+ if ($data && $data.isActive) {
266
+ $data.deactivate();
267
+ }
268
+ if ($variables && $variables.isActive) {
269
+ $variables.deactivate();
270
+ }
271
+ this._events.removeAllListeners();
272
+ this._subs.unsubscribe();
273
+ this._subs = new rxjs.Subscription();
274
+ this._subject.complete();
275
+ this._subject = new rxjs.Subject();
276
+ }
277
+ useState() {
278
+ return useSceneObjectState(this);
279
+ }
280
+ forceRender() {
281
+ this.setState({});
282
+ }
283
+ clone(withState) {
284
+ return cloneSceneObject(this, withState);
285
+ }
286
+ }
287
+ function useSceneObjectState(model) {
288
+ const forceUpdate = ui.useForceUpdate();
289
+ React.useEffect(() => {
290
+ const s = model.subscribeToState({ next: forceUpdate });
291
+ return () => s.unsubscribe();
292
+ }, [model, forceUpdate]);
293
+ return model.state;
294
+ }
295
+
296
+ class SceneDataNode extends SceneObjectBase {
297
+ }
298
+
299
+ class SceneObjectUrlSyncConfig {
300
+ constructor(_sceneObject, _options) {
301
+ this._sceneObject = _sceneObject;
302
+ this._keys = _options.keys;
303
+ }
304
+ getKeys() {
305
+ return this._keys;
306
+ }
307
+ getUrlState(state) {
308
+ return this._sceneObject.getUrlState(state);
309
+ }
310
+ updateFromUrl(values) {
311
+ this._sceneObject.updateFromUrl(values);
312
+ }
313
+ }
314
+
315
+ var __defProp$c = Object.defineProperty;
316
+ var __getOwnPropSymbols$c = Object.getOwnPropertySymbols;
317
+ var __hasOwnProp$c = Object.prototype.hasOwnProperty;
318
+ var __propIsEnum$c = Object.prototype.propertyIsEnumerable;
319
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
320
+ var __spreadValues$c = (a, b) => {
321
+ for (var prop in b || (b = {}))
322
+ if (__hasOwnProp$c.call(b, prop))
323
+ __defNormalProp$c(a, prop, b[prop]);
324
+ if (__getOwnPropSymbols$c)
325
+ for (var prop of __getOwnPropSymbols$c(b)) {
326
+ if (__propIsEnum$c.call(b, prop))
327
+ __defNormalProp$c(a, prop, b[prop]);
328
+ }
329
+ return a;
330
+ };
331
+ class SceneTimeRange extends SceneObjectBase {
332
+ constructor(state = {}) {
333
+ var _a, _b, _c;
334
+ const from = (_a = state.from) != null ? _a : "now-6h";
335
+ const to = (_b = state.to) != null ? _b : "now";
336
+ const timeZone = (_c = state.timeZone) != null ? _c : data.getTimeZone();
337
+ const value = evaluateTimeRange(from, to, timeZone);
338
+ super(__spreadValues$c({ from, to, timeZone, value }, state));
339
+ this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: ["from", "to"] });
340
+ this.onTimeRangeChange = (timeRange) => {
341
+ const update = {};
342
+ if (typeof timeRange.raw.from === "string") {
343
+ update.from = timeRange.raw.from;
344
+ } else {
345
+ update.from = timeRange.raw.from.toISOString();
346
+ }
347
+ if (typeof timeRange.raw.to === "string") {
348
+ update.to = timeRange.raw.to;
349
+ } else {
350
+ update.to = timeRange.raw.to.toISOString();
351
+ }
352
+ update.value = evaluateTimeRange(update.from, update.to, this.state.timeZone);
353
+ this.setState(update);
354
+ };
355
+ this.onRefresh = () => {
356
+ this.setState({ value: evaluateTimeRange(this.state.from, this.state.to, this.state.timeZone) });
357
+ };
358
+ this.onIntervalChanged = (_) => {
359
+ };
360
+ }
361
+ getUrlState(state) {
362
+ return { from: state.from, to: state.to };
363
+ }
364
+ updateFromUrl(values) {
365
+ var _a, _b;
366
+ const update = {};
367
+ const from = parseUrlParam(values.from);
368
+ if (from) {
369
+ update.from = from;
370
+ }
371
+ const to = parseUrlParam(values.to);
372
+ if (to) {
373
+ update.to = to;
374
+ }
375
+ update.value = evaluateTimeRange((_a = update.from) != null ? _a : this.state.from, (_b = update.to) != null ? _b : this.state.to, this.state.timeZone);
376
+ this.setState(update);
377
+ }
378
+ }
379
+ function parseUrlParam(value) {
380
+ if (typeof value !== "string") {
381
+ return null;
382
+ }
383
+ if (value.indexOf("now") !== -1) {
384
+ return value;
385
+ }
386
+ if (value.length === 8) {
387
+ const utcValue = data.toUtc(value, "YYYYMMDD");
388
+ if (utcValue.isValid()) {
389
+ return utcValue.toISOString();
390
+ }
391
+ } else if (value.length === 15) {
392
+ const utcValue = data.toUtc(value, "YYYYMMDDTHHmmss");
393
+ if (utcValue.isValid()) {
394
+ return utcValue.toISOString();
395
+ }
396
+ } else if (value.length === 24) {
397
+ const utcValue = data.toUtc(value);
398
+ return utcValue.toISOString();
399
+ }
400
+ const epoch = parseInt(value, 10);
401
+ if (!isNaN(epoch)) {
402
+ return data.toUtc(epoch).toISOString();
403
+ }
404
+ return null;
405
+ }
406
+ function evaluateTimeRange(from, to, timeZone, fiscalYearStartMonth) {
407
+ return {
408
+ from: data.dateMath.parse(from, false, timeZone, fiscalYearStartMonth),
409
+ to: data.dateMath.parse(to, true, timeZone, fiscalYearStartMonth),
410
+ raw: {
411
+ from,
412
+ to
413
+ }
414
+ };
415
+ }
416
+
417
+ class SceneVariableValueChangedEvent extends data.BusEventWithPayload {
418
+ }
419
+ SceneVariableValueChangedEvent.type = "scene-variable-changed-value";
420
+
421
+ class SceneVariableSet extends SceneObjectBase {
422
+ constructor() {
423
+ super(...arguments);
424
+ this.variablesThatHaveChanged = /* @__PURE__ */ new Set();
425
+ this.variablesToUpdate = /* @__PURE__ */ new Set();
426
+ this.updating = /* @__PURE__ */ new Map();
427
+ this.onVariableValueChanged = (event) => {
428
+ const variableThatChanged = event.payload;
429
+ this.variablesThatHaveChanged.add(variableThatChanged);
430
+ if (this.updating.has(variableThatChanged)) {
431
+ return;
432
+ }
433
+ for (const otherVariable of this.state.variables) {
434
+ if (otherVariable.variableDependency) {
435
+ if (otherVariable.variableDependency.hasDependencyOn(variableThatChanged.state.name)) {
436
+ this.variablesToUpdate.add(otherVariable);
437
+ }
438
+ }
439
+ }
440
+ this.updateNextBatch();
441
+ };
442
+ }
443
+ getByName(name) {
444
+ return this.state.variables.find((x) => x.state.name === name);
445
+ }
446
+ activate() {
447
+ super.activate();
448
+ this._subs.add(this.subscribeToEvent(SceneVariableValueChangedEvent, this.onVariableValueChanged));
449
+ this.validateAndUpdateAll();
450
+ }
451
+ deactivate() {
452
+ var _a;
453
+ super.deactivate();
454
+ this.variablesToUpdate.clear();
455
+ for (const update of this.updating.values()) {
456
+ (_a = update.subscription) == null ? void 0 : _a.unsubscribe();
457
+ }
458
+ }
459
+ updateNextBatch() {
460
+ if (this.variablesToUpdate.size === 0 && this.variablesThatHaveChanged.size > 0) {
461
+ this.notifyDependentSceneObjects();
462
+ return;
463
+ }
464
+ for (const variable of this.variablesToUpdate) {
465
+ if (!variable.validateAndUpdate) {
466
+ throw new Error("Variable added to variablesToUpdate but does not have validateAndUpdate");
467
+ }
468
+ if (this.updating.has(variable)) {
469
+ continue;
470
+ }
471
+ if (this.hasDependendencyInUpdateQueue(variable)) {
472
+ continue;
473
+ }
474
+ const variableToUpdate = {
475
+ variable
476
+ };
477
+ this.updating.set(variable, variableToUpdate);
478
+ variableToUpdate.subscription = variable.validateAndUpdate().subscribe({
479
+ next: () => this.validateAndUpdateCompleted(variable),
480
+ error: (err) => this.handleVariableError(variable, err)
481
+ });
482
+ }
483
+ }
484
+ validateAndUpdateCompleted(variable) {
485
+ var _a;
486
+ const update = this.updating.get(variable);
487
+ (_a = update == null ? void 0 : update.subscription) == null ? void 0 : _a.unsubscribe();
488
+ this.updating.delete(variable);
489
+ this.variablesToUpdate.delete(variable);
490
+ this.updateNextBatch();
491
+ }
492
+ handleVariableError(variable, err) {
493
+ var _a;
494
+ const update = this.updating.get(variable);
495
+ (_a = update == null ? void 0 : update.subscription) == null ? void 0 : _a.unsubscribe();
496
+ this.updating.delete(variable);
497
+ this.variablesToUpdate.delete(variable);
498
+ variable.setState({ loading: false, error: err });
499
+ }
500
+ hasDependendencyInUpdateQueue(variable) {
501
+ var _a;
502
+ if (!variable.variableDependency) {
503
+ return false;
504
+ }
505
+ for (const otherVariable of this.variablesToUpdate.values()) {
506
+ if ((_a = variable.variableDependency) == null ? void 0 : _a.hasDependencyOn(otherVariable.state.name)) {
507
+ return true;
508
+ }
509
+ }
510
+ return false;
511
+ }
512
+ validateAndUpdateAll() {
513
+ for (const variable of this.state.variables) {
514
+ if (variable.validateAndUpdate) {
515
+ this.variablesToUpdate.add(variable);
516
+ }
517
+ }
518
+ this.updateNextBatch();
519
+ }
520
+ notifyDependentSceneObjects() {
521
+ if (!this.parent) {
522
+ return;
523
+ }
524
+ this.traverseSceneAndNotify(this.parent);
525
+ this.variablesThatHaveChanged.clear();
526
+ }
527
+ traverseSceneAndNotify(sceneObject) {
528
+ if (this === sceneObject) {
529
+ return;
530
+ }
531
+ if (sceneObject.variableDependency) {
532
+ sceneObject.variableDependency.variableValuesChanged(this.variablesThatHaveChanged);
533
+ }
534
+ forEachSceneObjectInState(sceneObject.state, (child) => this.traverseSceneAndNotify(child));
535
+ }
536
+ }
537
+
538
+ const EmptyVariableSet = new SceneVariableSet({ variables: [] });
539
+ const EmptyDataNode = new SceneDataNode({
540
+ data: {
541
+ state: data.LoadingState.Done,
542
+ series: [],
543
+ timeRange: data.getDefaultTimeRange()
544
+ }
545
+ });
546
+ const DefaultTimeRange = new SceneTimeRange();
547
+
548
+ const _ScopedVarsVariable = class {
549
+ constructor(name, value) {
550
+ this.state = { name, value, type: "scopedvar" };
551
+ }
552
+ getValue(fieldPath) {
553
+ let { value } = this.state;
554
+ let realValue = value.value;
555
+ if (fieldPath) {
556
+ realValue = this.getFieldAccessor(fieldPath)(value.value);
557
+ } else {
558
+ realValue = value.value;
559
+ }
560
+ if (realValue === "string" || realValue === "number" || realValue === "boolean") {
561
+ return realValue;
562
+ }
563
+ return String(realValue);
564
+ }
565
+ getValueText() {
566
+ const { value } = this.state;
567
+ if (value.text != null) {
568
+ return String(value.text);
569
+ }
570
+ return String(value);
571
+ }
572
+ getFieldAccessor(fieldPath) {
573
+ const accessor = _ScopedVarsVariable.fieldAccessorCache[fieldPath];
574
+ if (accessor) {
575
+ return accessor;
576
+ }
577
+ return _ScopedVarsVariable.fieldAccessorCache[fieldPath] = lodash.property(fieldPath);
578
+ }
579
+ };
580
+ let ScopedVarsVariable = _ScopedVarsVariable;
581
+ ScopedVarsVariable.fieldAccessorCache = {};
582
+ let scopedVarsVariable;
583
+ function getSceneVariableForScopedVar(name, value) {
584
+ if (!scopedVarsVariable) {
585
+ scopedVarsVariable = new ScopedVarsVariable(name, value);
586
+ } else {
587
+ scopedVarsVariable.state.name = name;
588
+ scopedVarsVariable.state.value = value;
589
+ }
590
+ return scopedVarsVariable;
591
+ }
592
+
593
+ const ALL_VARIABLE_TEXT = "All";
594
+ const ALL_VARIABLE_VALUE = "$__all";
595
+ const VARIABLE_REGEX = /\$(\w+)|\[\[(\w+?)(?::(\w+))?\]\]|\${(\w+)(?:\.([^:^\}]+))?(?::([^\}]+))?}/g;
596
+
597
+ var FormatRegistryID = /* @__PURE__ */ ((FormatRegistryID2) => {
598
+ FormatRegistryID2["lucene"] = "lucene";
599
+ FormatRegistryID2["raw"] = "raw";
600
+ FormatRegistryID2["regex"] = "regex";
601
+ FormatRegistryID2["pipe"] = "pipe";
602
+ FormatRegistryID2["distributed"] = "distributed";
603
+ FormatRegistryID2["csv"] = "csv";
604
+ FormatRegistryID2["html"] = "html";
605
+ FormatRegistryID2["json"] = "json";
606
+ FormatRegistryID2["percentEncode"] = "percentencode";
607
+ FormatRegistryID2["singleQuote"] = "singlequote";
608
+ FormatRegistryID2["doubleQuote"] = "doublequote";
609
+ FormatRegistryID2["sqlString"] = "sqlstring";
610
+ FormatRegistryID2["date"] = "date";
611
+ FormatRegistryID2["glob"] = "glob";
612
+ FormatRegistryID2["text"] = "text";
613
+ FormatRegistryID2["queryParam"] = "queryparam";
614
+ return FormatRegistryID2;
615
+ })(FormatRegistryID || {});
616
+ const formatRegistry = new data.Registry(() => {
617
+ const formats = [
618
+ {
619
+ id: "lucene" /* lucene */,
620
+ name: "Lucene",
621
+ description: "Values are lucene escaped and multi-valued variables generate an OR expression",
622
+ formatter: (value) => {
623
+ if (typeof value === "string") {
624
+ return luceneEscape(value);
625
+ }
626
+ if (Array.isArray(value)) {
627
+ if (value.length === 0) {
628
+ return "__empty__";
629
+ }
630
+ const quotedValues = lodash.map(value, (val) => {
631
+ return '"' + luceneEscape(val) + '"';
632
+ });
633
+ return "(" + quotedValues.join(" OR ") + ")";
634
+ } else {
635
+ return luceneEscape(`${value}`);
636
+ }
637
+ }
638
+ },
639
+ {
640
+ id: "raw" /* raw */,
641
+ name: "raw",
642
+ description: "Keep value as is",
643
+ formatter: (value) => String(value)
644
+ },
645
+ {
646
+ id: "regex" /* regex */,
647
+ name: "Regex",
648
+ description: "Values are regex escaped and multi-valued variables generate a (<value>|<value>) expression",
649
+ formatter: (value) => {
650
+ if (typeof value === "string") {
651
+ return data.escapeRegex(value);
652
+ }
653
+ if (Array.isArray(value)) {
654
+ const escapedValues = value.map((item) => {
655
+ if (typeof item === "string") {
656
+ return data.escapeRegex(item);
657
+ } else {
658
+ return data.escapeRegex(String(item));
659
+ }
660
+ });
661
+ if (escapedValues.length === 1) {
662
+ return escapedValues[0];
663
+ }
664
+ return "(" + escapedValues.join("|") + ")";
665
+ }
666
+ return data.escapeRegex(`${value}`);
667
+ }
668
+ },
669
+ {
670
+ id: "pipe" /* pipe */,
671
+ name: "Pipe",
672
+ description: "Values are separated by | character",
673
+ formatter: (value) => {
674
+ if (typeof value === "string") {
675
+ return value;
676
+ }
677
+ if (Array.isArray(value)) {
678
+ return value.join("|");
679
+ }
680
+ return `${value}`;
681
+ }
682
+ },
683
+ {
684
+ id: "distributed" /* distributed */,
685
+ name: "Distributed",
686
+ description: "Multiple values are formatted like variable=value",
687
+ formatter: (value, args, variable) => {
688
+ if (typeof value === "string") {
689
+ return value;
690
+ }
691
+ if (Array.isArray(value)) {
692
+ value = lodash.map(value, (val, index) => {
693
+ if (index !== 0) {
694
+ return variable.state.name + "=" + val;
695
+ } else {
696
+ return val;
697
+ }
698
+ });
699
+ return value.join(",");
700
+ }
701
+ return `${value}`;
702
+ }
703
+ },
704
+ {
705
+ id: "csv" /* csv */,
706
+ name: "Csv",
707
+ description: "Comma-separated values",
708
+ formatter: (value) => {
709
+ if (typeof value === "string") {
710
+ return value;
711
+ }
712
+ if (lodash.isArray(value)) {
713
+ return value.join(",");
714
+ }
715
+ return String(value);
716
+ }
717
+ },
718
+ {
719
+ id: "html" /* html */,
720
+ name: "HTML",
721
+ description: "HTML escaping of values",
722
+ formatter: (value) => {
723
+ if (typeof value === "string") {
724
+ return data.textUtil.escapeHtml(value);
725
+ }
726
+ if (lodash.isArray(value)) {
727
+ return data.textUtil.escapeHtml(value.join(", "));
728
+ }
729
+ return data.textUtil.escapeHtml(String(value));
730
+ }
731
+ },
732
+ {
733
+ id: "json" /* json */,
734
+ name: "JSON",
735
+ description: "JSON stringify value",
736
+ formatter: (value) => {
737
+ return JSON.stringify(value);
738
+ }
739
+ },
740
+ {
741
+ id: "percentencode" /* percentEncode */,
742
+ name: "Percent encode",
743
+ description: "Useful for URL escaping values",
744
+ formatter: (value) => {
745
+ if (lodash.isArray(value)) {
746
+ return encodeURIComponentStrict("{" + value.join(",") + "}");
747
+ }
748
+ return encodeURIComponentStrict(value);
749
+ }
750
+ },
751
+ {
752
+ id: "singlequote" /* singleQuote */,
753
+ name: "Single quote",
754
+ description: "Single quoted values",
755
+ formatter: (value) => {
756
+ const regExp = new RegExp(`'`, "g");
757
+ if (lodash.isArray(value)) {
758
+ return lodash.map(value, (v) => `'${lodash.replace(v, regExp, `\\'`)}'`).join(",");
759
+ }
760
+ let strVal = typeof value === "string" ? value : String(value);
761
+ return `'${lodash.replace(strVal, regExp, `\\'`)}'`;
762
+ }
763
+ },
764
+ {
765
+ id: "doublequote" /* doubleQuote */,
766
+ name: "Double quote",
767
+ description: "Double quoted values",
768
+ formatter: (value) => {
769
+ const regExp = new RegExp('"', "g");
770
+ if (lodash.isArray(value)) {
771
+ return lodash.map(value, (v) => `"${lodash.replace(v, regExp, '\\"')}"`).join(",");
772
+ }
773
+ let strVal = typeof value === "string" ? value : String(value);
774
+ return `"${lodash.replace(strVal, regExp, '\\"')}"`;
775
+ }
776
+ },
777
+ {
778
+ id: "sqlstring" /* sqlString */,
779
+ name: "SQL string",
780
+ description: "SQL string quoting and commas for use in IN statements and other scenarios",
781
+ formatter: (value) => {
782
+ const regExp = new RegExp(`'`, "g");
783
+ if (lodash.isArray(value)) {
784
+ return lodash.map(value, (v) => `'${lodash.replace(v, regExp, "''")}'`).join(",");
785
+ }
786
+ let strVal = typeof value === "string" ? value : String(value);
787
+ return `'${lodash.replace(strVal, regExp, "''")}'`;
788
+ }
789
+ },
790
+ {
791
+ id: "date" /* date */,
792
+ name: "Date",
793
+ description: "Format date in different ways",
794
+ formatter: (value, args) => {
795
+ var _a;
796
+ let nrValue = NaN;
797
+ if (typeof value === "number") {
798
+ nrValue = value;
799
+ } else if (typeof value === "string") {
800
+ nrValue = parseInt(value, 10);
801
+ }
802
+ if (isNaN(nrValue)) {
803
+ return "NaN";
804
+ }
805
+ const arg = (_a = args[0]) != null ? _a : "iso";
806
+ switch (arg) {
807
+ case "ms":
808
+ return String(value);
809
+ case "seconds":
810
+ return `${Math.round(nrValue / 1e3)}`;
811
+ case "iso":
812
+ return data.dateTime(nrValue).toISOString();
813
+ default:
814
+ return data.dateTime(nrValue).format(arg);
815
+ }
816
+ }
817
+ },
818
+ {
819
+ id: "glob" /* glob */,
820
+ name: "Glob",
821
+ description: "Format multi-valued variables using glob syntax, example {value1,value2}",
822
+ formatter: (value) => {
823
+ if (lodash.isArray(value) && value.length > 1) {
824
+ return "{" + value.join(",") + "}";
825
+ }
826
+ return String(value);
827
+ }
828
+ },
829
+ {
830
+ id: "text" /* text */,
831
+ name: "Text",
832
+ description: "Format variables in their text representation. Example in multi-variable scenario A + B + C.",
833
+ formatter: (value, _args, variable) => {
834
+ if (variable.getValueText) {
835
+ return variable.getValueText();
836
+ }
837
+ return String(value);
838
+ }
839
+ },
840
+ {
841
+ id: "queryparam" /* queryParam */,
842
+ name: "Query parameter",
843
+ description: "Format variables as URL parameters. Example in multi-variable scenario A + B + C => var-foo=A&var-foo=B&var-foo=C.",
844
+ formatter: (value, _args, variable) => {
845
+ if (Array.isArray(value)) {
846
+ return value.map((v) => formatQueryParameter(variable.state.name, v)).join("&");
847
+ }
848
+ return formatQueryParameter(variable.state.name, value);
849
+ }
850
+ }
851
+ ];
852
+ return formats;
853
+ });
854
+ function luceneEscape(value) {
855
+ if (isNaN(+value) === false) {
856
+ return value;
857
+ }
858
+ return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, "\\$1");
859
+ }
860
+ function encodeURIComponentStrict(str) {
861
+ if (typeof str === "object") {
862
+ str = String(str);
863
+ }
864
+ return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
865
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
866
+ });
867
+ }
868
+ function formatQueryParameter(name, value) {
869
+ return `var-${name}=${encodeURIComponentStrict(value)}`;
870
+ }
871
+
872
+ function sceneInterpolator(sceneObject, target, getVariables, scopedVars, format) {
873
+ if (!target) {
874
+ return target != null ? target : "";
875
+ }
876
+ if (getVariables(sceneObject) === EmptyVariableSet) {
877
+ return target;
878
+ }
879
+ VARIABLE_REGEX.lastIndex = 0;
880
+ return target.replace(VARIABLE_REGEX, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
881
+ const variableName = var1 || var2 || var3;
882
+ const fmt = fmt2 || fmt3 || format;
883
+ let variable;
884
+ if (scopedVars && scopedVars[variableName]) {
885
+ variable = getSceneVariableForScopedVar(variableName, scopedVars[variableName]);
886
+ } else {
887
+ variable = lookupSceneVariable(variableName, sceneObject);
888
+ }
889
+ if (!variable) {
890
+ return match;
891
+ }
892
+ return formatValue(variable, variable.getValue(fieldPath), fmt);
893
+ });
894
+ }
895
+ function lookupSceneVariable(name, sceneObject) {
896
+ const variables = sceneObject.state.$variables;
897
+ if (!variables) {
898
+ if (sceneObject.parent) {
899
+ return lookupSceneVariable(name, sceneObject.parent);
900
+ } else {
901
+ return null;
902
+ }
903
+ }
904
+ const found = variables.getByName(name);
905
+ if (found) {
906
+ return found;
907
+ } else if (sceneObject.parent) {
908
+ return lookupSceneVariable(name, sceneObject.parent);
909
+ }
910
+ return null;
911
+ }
912
+ function formatValue(variable, value, formatNameOrFn) {
913
+ if (value === null || value === void 0) {
914
+ return "";
915
+ }
916
+ if (typeof value === "object" && "isCustomValue" in value && formatNameOrFn !== FormatRegistryID.text) {
917
+ return value.toString();
918
+ }
919
+ if (!Array.isArray(value) && typeof value === "object") {
920
+ value = `${value}`;
921
+ }
922
+ if (typeof formatNameOrFn === "function") {
923
+ return formatNameOrFn(value, {
924
+ name: variable.state.name,
925
+ type: variable.state.type
926
+ });
927
+ }
928
+ let args = [];
929
+ if (!formatNameOrFn) {
930
+ formatNameOrFn = FormatRegistryID.glob;
931
+ } else {
932
+ args = formatNameOrFn.split(":");
933
+ if (args.length > 1) {
934
+ formatNameOrFn = args[0];
935
+ args = args.slice(1);
936
+ } else {
937
+ args = [];
938
+ }
939
+ }
940
+ let formatter = formatRegistry.getIfExists(formatNameOrFn);
941
+ if (!formatter) {
942
+ console.error(`Variable format ${formatNameOrFn} not found. Using glob format as fallback.`);
943
+ formatter = formatRegistry.get(FormatRegistryID.glob);
944
+ }
945
+ return formatter.formatter(value, args, variable);
946
+ }
947
+
948
+ function getVariables(sceneObject) {
949
+ if (sceneObject.state.$variables) {
950
+ return sceneObject.state.$variables;
951
+ }
952
+ if (sceneObject.parent) {
953
+ return getVariables(sceneObject.parent);
954
+ }
955
+ return EmptyVariableSet;
956
+ }
957
+ function getData(sceneObject) {
958
+ const { $data } = sceneObject.state;
959
+ if ($data) {
960
+ return $data;
961
+ }
962
+ if (sceneObject.parent) {
963
+ return getData(sceneObject.parent);
964
+ }
965
+ return EmptyDataNode;
966
+ }
967
+ function getTimeRange(sceneObject) {
968
+ const { $timeRange } = sceneObject.state;
969
+ if ($timeRange) {
970
+ return $timeRange;
971
+ }
972
+ if (sceneObject.parent) {
973
+ return getTimeRange(sceneObject.parent);
974
+ }
975
+ return DefaultTimeRange;
976
+ }
977
+ function getSceneEditor(sceneObject) {
978
+ const { $editor } = sceneObject.state;
979
+ if ($editor) {
980
+ return $editor;
981
+ }
982
+ if (sceneObject.parent) {
983
+ return getSceneEditor(sceneObject.parent);
984
+ }
985
+ throw new Error("No editor found in scene tree");
986
+ }
987
+ function getLayout(scene) {
988
+ if (scene.constructor.name === "SceneFlexLayout" || scene.constructor.name === "SceneGridLayout") {
989
+ return scene;
990
+ }
991
+ if (scene.parent) {
992
+ return getLayout(scene.parent);
993
+ }
994
+ throw new Error("No layout found in scene tree");
995
+ }
996
+ function interpolate(sceneObject, value, scopedVars, format) {
997
+ if (!value || !sceneObject.variableDependency || sceneObject.variableDependency.getNames().size === 0) {
998
+ return value != null ? value : "";
999
+ }
1000
+ return sceneInterpolator(sceneObject, value, getVariables, scopedVars, format);
1001
+ }
1002
+ const sceneGraph = {
1003
+ getVariables,
1004
+ getData,
1005
+ getTimeRange,
1006
+ getSceneEditor,
1007
+ getLayout,
1008
+ interpolate
1009
+ };
1010
+
1011
+ class VariableDependencyConfig {
1012
+ constructor(_sceneObject, options) {
1013
+ this._sceneObject = _sceneObject;
1014
+ this._dependencies = /* @__PURE__ */ new Set();
1015
+ this.scanCount = 0;
1016
+ this.defaultHandlerReferencedVariableValueChanged = () => {
1017
+ this._sceneObject.forceRender();
1018
+ };
1019
+ var _a;
1020
+ this._statePaths = options.statePaths;
1021
+ this._onReferencedVariableValueChanged = (_a = options.onReferencedVariableValueChanged) != null ? _a : this.defaultHandlerReferencedVariableValueChanged;
1022
+ }
1023
+ hasDependencyOn(name) {
1024
+ return this.getNames().has(name);
1025
+ }
1026
+ variableValuesChanged(variables) {
1027
+ const deps = this.getNames();
1028
+ for (const variable of variables) {
1029
+ if (deps.has(variable.state.name)) {
1030
+ this._onReferencedVariableValueChanged();
1031
+ return;
1032
+ }
1033
+ }
1034
+ }
1035
+ getNames() {
1036
+ const prevState = this._state;
1037
+ const newState = this._state = this._sceneObject.state;
1038
+ if (!prevState) {
1039
+ this.scanStateForDependencies(this._state);
1040
+ return this._dependencies;
1041
+ }
1042
+ if (newState !== prevState) {
1043
+ if (this._statePaths) {
1044
+ for (const path of this._statePaths) {
1045
+ if (newState[path] !== prevState[path]) {
1046
+ this.scanStateForDependencies(newState);
1047
+ break;
1048
+ }
1049
+ }
1050
+ } else {
1051
+ this.scanStateForDependencies(newState);
1052
+ }
1053
+ }
1054
+ return this._dependencies;
1055
+ }
1056
+ scanStateForDependencies(state) {
1057
+ this._dependencies.clear();
1058
+ this.scanCount += 1;
1059
+ if (this._statePaths) {
1060
+ for (const path of this._statePaths) {
1061
+ const value = state[path];
1062
+ if (value) {
1063
+ this.extractVariablesFrom(value);
1064
+ }
1065
+ }
1066
+ } else {
1067
+ this.extractVariablesFrom(state);
1068
+ }
1069
+ }
1070
+ extractVariablesFrom(value) {
1071
+ VARIABLE_REGEX.lastIndex = 0;
1072
+ const stringToCheck = typeof value !== "string" ? safeStringifyValue(value) : value;
1073
+ const matches = stringToCheck.matchAll(VARIABLE_REGEX);
1074
+ if (!matches) {
1075
+ return;
1076
+ }
1077
+ for (const match of matches) {
1078
+ const [, var1, var2, , var3] = match;
1079
+ const variableName = var1 || var2 || var3;
1080
+ this._dependencies.add(variableName);
1081
+ }
1082
+ }
1083
+ }
1084
+ const safeStringifyValue = (value) => {
1085
+ try {
1086
+ return JSON.stringify(value, null);
1087
+ } catch (error) {
1088
+ console.error(error);
1089
+ }
1090
+ return "";
1091
+ };
1092
+
1093
+ var __defProp$b = Object.defineProperty;
1094
+ var __defProps$5 = Object.defineProperties;
1095
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1096
+ var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
1097
+ var __hasOwnProp$b = Object.prototype.hasOwnProperty;
1098
+ var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
1099
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1100
+ var __spreadValues$b = (a, b) => {
1101
+ for (var prop in b || (b = {}))
1102
+ if (__hasOwnProp$b.call(b, prop))
1103
+ __defNormalProp$b(a, prop, b[prop]);
1104
+ if (__getOwnPropSymbols$b)
1105
+ for (var prop of __getOwnPropSymbols$b(b)) {
1106
+ if (__propIsEnum$b.call(b, prop))
1107
+ __defNormalProp$b(a, prop, b[prop]);
1108
+ }
1109
+ return a;
1110
+ };
1111
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1112
+ let counter = 100;
1113
+ function getNextRequestId() {
1114
+ return "QS" + counter++;
1115
+ }
1116
+ class SceneQueryRunner extends SceneObjectBase {
1117
+ constructor() {
1118
+ super(...arguments);
1119
+ this._variableDependency = new VariableDependencyConfig(this, {
1120
+ statePaths: ["queries"],
1121
+ onReferencedVariableValueChanged: () => this.runQueries()
1122
+ });
1123
+ this.onDataReceived = (data) => {
1124
+ this.setState({ data });
1125
+ };
1126
+ }
1127
+ activate() {
1128
+ super.activate();
1129
+ const timeRange = sceneGraph.getTimeRange(this);
1130
+ this._subs.add(
1131
+ timeRange.subscribeToState({
1132
+ next: (timeRange2) => {
1133
+ this.runWithTimeRange(timeRange2.value);
1134
+ }
1135
+ })
1136
+ );
1137
+ if (this.shouldRunQueriesOnActivate()) {
1138
+ this.runQueries();
1139
+ }
1140
+ }
1141
+ shouldRunQueriesOnActivate() {
1142
+ if (this.state.data) {
1143
+ return false;
1144
+ }
1145
+ if (!this.state.maxDataPoints && this.state.maxDataPointsFromWidth && !this._containerWidth) {
1146
+ return false;
1147
+ }
1148
+ return true;
1149
+ }
1150
+ deactivate() {
1151
+ super.deactivate();
1152
+ if (this._querySub) {
1153
+ this._querySub.unsubscribe();
1154
+ this._querySub = void 0;
1155
+ }
1156
+ }
1157
+ setContainerWidth(width) {
1158
+ if (!this._containerWidth && width > 0) {
1159
+ this._containerWidth = width;
1160
+ if (this.state.maxDataPointsFromWidth && !this.state.maxDataPoints) {
1161
+ setTimeout(() => {
1162
+ if (this.isActive && !this._querySub) {
1163
+ this.runQueries();
1164
+ }
1165
+ }, 0);
1166
+ }
1167
+ } else {
1168
+ this._containerWidth = width;
1169
+ }
1170
+ }
1171
+ runQueries() {
1172
+ const timeRange = sceneGraph.getTimeRange(this);
1173
+ this.runWithTimeRange(timeRange.state.value);
1174
+ }
1175
+ getMaxDataPoints() {
1176
+ var _a, _b;
1177
+ return (_b = (_a = this.state.maxDataPoints) != null ? _a : this._containerWidth) != null ? _b : 500;
1178
+ }
1179
+ async runWithTimeRange(timeRange) {
1180
+ const { datasource, minInterval, queries } = this.state;
1181
+ const request = {
1182
+ app: data.CoreApp.Dashboard,
1183
+ requestId: getNextRequestId(),
1184
+ timezone: "browser",
1185
+ panelId: 1,
1186
+ dashboardId: 1,
1187
+ range: timeRange,
1188
+ interval: "1s",
1189
+ intervalMs: 1e3,
1190
+ targets: lodash.cloneDeep(queries),
1191
+ maxDataPoints: this.getMaxDataPoints(),
1192
+ scopedVars: {},
1193
+ startTime: Date.now()
1194
+ };
1195
+ try {
1196
+ const ds = await getDataSource(datasource, request.scopedVars);
1197
+ request.targets = request.targets.map((query) => {
1198
+ if (!query.datasource) {
1199
+ query.datasource = ds.getRef();
1200
+ }
1201
+ return query;
1202
+ });
1203
+ const lowerIntervalLimit = minInterval ? minInterval : ds.interval;
1204
+ const norm = data.rangeUtil.calculateInterval(timeRange, request.maxDataPoints, lowerIntervalLimit);
1205
+ request.scopedVars = Object.assign({}, request.scopedVars, {
1206
+ __interval: { text: norm.interval, value: norm.interval },
1207
+ __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs }
1208
+ });
1209
+ request.interval = norm.interval;
1210
+ request.intervalMs = norm.intervalMs;
1211
+ const runRequest = runtime.getRunRequest();
1212
+ this._querySub = runRequest(ds, request).pipe(getTransformationsStream(this, this.state.transformations)).subscribe({
1213
+ next: this.onDataReceived
1214
+ });
1215
+ } catch (err) {
1216
+ console.error("PanelQueryRunner Error", err);
1217
+ }
1218
+ }
1219
+ }
1220
+ async function getDataSource(datasource, scopedVars) {
1221
+ if (datasource && datasource.query) {
1222
+ return datasource;
1223
+ }
1224
+ return await runtime.getDataSourceSrv().get(datasource, scopedVars);
1225
+ }
1226
+ const getTransformationsStream = (sceneObject, transformations) => (inputStream) => {
1227
+ return inputStream.pipe(
1228
+ rxjs.mergeMap((data$1) => {
1229
+ if (!transformations || transformations.length === 0) {
1230
+ return rxjs.of(data$1);
1231
+ }
1232
+ const replace = (option) => {
1233
+ var _a;
1234
+ return sceneGraph.interpolate(sceneObject, option, (_a = data$1 == null ? void 0 : data$1.request) == null ? void 0 : _a.scopedVars);
1235
+ };
1236
+ transformations.forEach((transform) => {
1237
+ transform.replace = replace;
1238
+ });
1239
+ return data.transformDataFrame(transformations, data$1.series).pipe(rxjs.map((series) => __spreadProps$5(__spreadValues$b({}, data$1), { series })));
1240
+ })
1241
+ );
1242
+ };
1243
+
1244
+ class SceneDataTransformer extends SceneObjectBase {
1245
+ activate() {
1246
+ super.activate();
1247
+ if (!this.parent || !this.parent.parent) {
1248
+ return;
1249
+ }
1250
+ const initialData = sceneGraph.getData(this.parent.parent).state.data;
1251
+ if (initialData) {
1252
+ this.transformData(rxjs.of(initialData));
1253
+ }
1254
+ this._subs.add(
1255
+ sceneGraph.getData(this.parent.parent).subscribeToState({
1256
+ next: (data$1) => {
1257
+ var _a;
1258
+ if (((_a = data$1.data) == null ? void 0 : _a.state) === data.LoadingState.Done) {
1259
+ this.transformData(rxjs.of(data$1.data));
1260
+ } else {
1261
+ this.setState({ data: data$1.data });
1262
+ }
1263
+ }
1264
+ })
1265
+ );
1266
+ }
1267
+ deactivate() {
1268
+ super.deactivate();
1269
+ if (this._transformationsSub) {
1270
+ this._transformationsSub.unsubscribe();
1271
+ this._transformationsSub = void 0;
1272
+ }
1273
+ }
1274
+ transformData(data) {
1275
+ if (this._transformationsSub) {
1276
+ this._transformationsSub.unsubscribe();
1277
+ this._transformationsSub = void 0;
1278
+ }
1279
+ this._transformationsSub = data.pipe(getTransformationsStream(this, this.state.transformations)).subscribe({
1280
+ next: (data2) => {
1281
+ this.setState({ data: data2 });
1282
+ }
1283
+ });
1284
+ }
1285
+ }
1286
+
1287
+ class VariableValueSelectors extends SceneObjectBase {
1288
+ }
1289
+ VariableValueSelectors.Component = VariableValueSelectorsRenderer;
1290
+ function VariableValueSelectorsRenderer({ model }) {
1291
+ const variables = sceneGraph.getVariables(model).useState();
1292
+ return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, variables.variables.map((variable) => /* @__PURE__ */ React__default["default"].createElement(VariableValueSelectWrapper, {
1293
+ key: variable.state.key,
1294
+ variable
1295
+ })));
1296
+ }
1297
+ function VariableValueSelectWrapper({ variable }) {
1298
+ const state = variable.useState();
1299
+ if (state.hide === data.VariableHide.hideVariable) {
1300
+ return null;
1301
+ }
1302
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
1303
+ className: "gf-form"
1304
+ }, /* @__PURE__ */ React__default["default"].createElement(VariableLabel, {
1305
+ state
1306
+ }), /* @__PURE__ */ React__default["default"].createElement(variable.Component, {
1307
+ model: variable
1308
+ }));
1309
+ }
1310
+ function VariableLabel({ state }) {
1311
+ var _a;
1312
+ if (state.hide === data.VariableHide.hideLabel) {
1313
+ return null;
1314
+ }
1315
+ const elementId = `var-${state.key}`;
1316
+ const labelOrName = (_a = state.label) != null ? _a : state.name;
1317
+ if (state.description) {
1318
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Tooltip, {
1319
+ content: state.description,
1320
+ placement: "bottom"
1321
+ }, /* @__PURE__ */ React__default["default"].createElement("label", {
1322
+ className: "gf-form-label gf-form-label--variable",
1323
+ "data-testid": e2eSelectors.selectors.pages.Dashboard.SubMenu.submenuItemLabels(labelOrName),
1324
+ htmlFor: elementId
1325
+ }, labelOrName));
1326
+ }
1327
+ return /* @__PURE__ */ React__default["default"].createElement("label", {
1328
+ className: "gf-form-label gf-form-label--variable",
1329
+ "data-testid": e2eSelectors.selectors.pages.Dashboard.SubMenu.submenuItemLabels(labelOrName),
1330
+ htmlFor: elementId
1331
+ }, labelOrName);
1332
+ }
1333
+
1334
+ var __defProp$a = Object.defineProperty;
1335
+ var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
1336
+ var __hasOwnProp$a = Object.prototype.hasOwnProperty;
1337
+ var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
1338
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1339
+ var __spreadValues$a = (a, b) => {
1340
+ for (var prop in b || (b = {}))
1341
+ if (__hasOwnProp$a.call(b, prop))
1342
+ __defNormalProp$a(a, prop, b[prop]);
1343
+ if (__getOwnPropSymbols$a)
1344
+ for (var prop of __getOwnPropSymbols$a(b)) {
1345
+ if (__propIsEnum$a.call(b, prop))
1346
+ __defNormalProp$a(a, prop, b[prop]);
1347
+ }
1348
+ return a;
1349
+ };
1350
+ class ConstantVariable extends SceneObjectBase {
1351
+ constructor(initialState) {
1352
+ super(__spreadValues$a({
1353
+ type: "constant",
1354
+ value: "",
1355
+ name: ""
1356
+ }, initialState));
1357
+ }
1358
+ getValue() {
1359
+ return this.state.value;
1360
+ }
1361
+ }
1362
+
1363
+ function VariableValueSelect({ model }) {
1364
+ const { value, key, loading } = model.useState();
1365
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Select, {
1366
+ id: key,
1367
+ placeholder: "Select value",
1368
+ width: "auto",
1369
+ value,
1370
+ allowCustomValue: true,
1371
+ tabSelectsValue: false,
1372
+ isLoading: loading,
1373
+ options: model.getOptionsForSelect(),
1374
+ onChange: (newValue) => {
1375
+ model.changeValueTo(newValue.value, newValue.label);
1376
+ }
1377
+ });
1378
+ }
1379
+ function VariableValueSelectMulti({ model }) {
1380
+ const { value, key, loading } = model.useState();
1381
+ const arrayValue = lodash.isArray(value) ? value : [value];
1382
+ return /* @__PURE__ */ React__default["default"].createElement(ui.MultiSelect, {
1383
+ id: key,
1384
+ placeholder: "Select value",
1385
+ width: "auto",
1386
+ value: arrayValue,
1387
+ tabSelectsValue: false,
1388
+ allowCustomValue: true,
1389
+ isLoading: loading,
1390
+ options: model.getOptionsForSelect(),
1391
+ closeMenuOnSelect: false,
1392
+ isClearable: true,
1393
+ onOpenMenu: () => {
1394
+ },
1395
+ onChange: (newValue) => {
1396
+ model.changeValueTo(
1397
+ newValue.map((v) => v.value),
1398
+ newValue.map((v) => v.label)
1399
+ );
1400
+ }
1401
+ });
1402
+ }
1403
+ function renderSelectForVariable(model) {
1404
+ if (model.state.isMulti) {
1405
+ return /* @__PURE__ */ React__default["default"].createElement(VariableValueSelectMulti, {
1406
+ model
1407
+ });
1408
+ } else {
1409
+ return /* @__PURE__ */ React__default["default"].createElement(VariableValueSelect, {
1410
+ model
1411
+ });
1412
+ }
1413
+ }
1414
+
1415
+ class MultiValueVariable extends SceneObjectBase {
1416
+ constructor() {
1417
+ super(...arguments);
1418
+ this._urlSync = new MultiValueUrlSyncHandler(this);
1419
+ }
1420
+ validateAndUpdate() {
1421
+ return this.getValueOptions({}).pipe(
1422
+ rxjs.map((options) => {
1423
+ this.updateValueGivenNewOptions(options);
1424
+ return {};
1425
+ })
1426
+ );
1427
+ }
1428
+ updateValueGivenNewOptions(options) {
1429
+ const stateUpdate = {
1430
+ options,
1431
+ loading: false,
1432
+ value: this.state.value,
1433
+ text: this.state.text
1434
+ };
1435
+ if (options.length === 0) ; else if (this.hasAllValue()) ; else if (this.state.isMulti) {
1436
+ const currentValues = Array.isArray(this.state.value) ? this.state.value : [this.state.value];
1437
+ const validValues = currentValues.filter((v) => options.find((o) => o.value === v));
1438
+ if (validValues.length === 0) {
1439
+ const defaultState = this.getDefaultMultiState(options);
1440
+ stateUpdate.value = defaultState.value;
1441
+ stateUpdate.text = defaultState.text;
1442
+ } else if (!lodash.isEqual(validValues, this.state.value)) {
1443
+ const validTexts = validValues.map((v) => options.find((o) => o.value === v).label);
1444
+ stateUpdate.value = validValues;
1445
+ stateUpdate.text = validTexts;
1446
+ }
1447
+ } else {
1448
+ const foundCurrent = options.find((x) => x.value === this.state.value);
1449
+ if (!foundCurrent) {
1450
+ if (this.state.defaultToAll) {
1451
+ stateUpdate.value = ALL_VARIABLE_VALUE;
1452
+ stateUpdate.text = ALL_VARIABLE_TEXT;
1453
+ } else {
1454
+ stateUpdate.value = options[0].value;
1455
+ stateUpdate.text = options[0].label;
1456
+ }
1457
+ }
1458
+ }
1459
+ const { value: prevValue, text: prevText } = this.state;
1460
+ this.setStateHelper(stateUpdate);
1461
+ if (stateUpdate.value !== prevValue || stateUpdate.text !== prevText || this.hasAllValue()) {
1462
+ this.publishEvent(new SceneVariableValueChangedEvent(this), true);
1463
+ }
1464
+ }
1465
+ getValue() {
1466
+ if (this.hasAllValue()) {
1467
+ if (this.state.allValue) {
1468
+ return new CustomAllValue(this.state.allValue);
1469
+ }
1470
+ return this.state.options.map((x) => x.value);
1471
+ }
1472
+ return this.state.value;
1473
+ }
1474
+ getValueText() {
1475
+ if (this.hasAllValue()) {
1476
+ return ALL_VARIABLE_TEXT;
1477
+ }
1478
+ if (Array.isArray(this.state.text)) {
1479
+ return this.state.text.join(" + ");
1480
+ }
1481
+ return String(this.state.text);
1482
+ }
1483
+ hasAllValue() {
1484
+ const value = this.state.value;
1485
+ return value === ALL_VARIABLE_VALUE || Array.isArray(value) && value[0] === ALL_VARIABLE_VALUE;
1486
+ }
1487
+ getDefaultMultiState(options) {
1488
+ if (this.state.defaultToAll) {
1489
+ return { value: [ALL_VARIABLE_VALUE], text: [ALL_VARIABLE_TEXT] };
1490
+ } else {
1491
+ return { value: [options[0].value], text: [options[0].label] };
1492
+ }
1493
+ }
1494
+ changeValueTo(value, text) {
1495
+ if (value === this.state.value && text === this.state.text) {
1496
+ return;
1497
+ }
1498
+ if (!text) {
1499
+ if (Array.isArray(value)) {
1500
+ text = value.map((v) => this.findLabelTextForValue(v));
1501
+ } else {
1502
+ text = this.findLabelTextForValue(value);
1503
+ }
1504
+ }
1505
+ if (Array.isArray(value)) {
1506
+ if (value.length === 0) {
1507
+ const state = this.getDefaultMultiState(this.state.options);
1508
+ value = state.value;
1509
+ text = state.text;
1510
+ }
1511
+ if (value[value.length - 1] === ALL_VARIABLE_VALUE) {
1512
+ value = [ALL_VARIABLE_VALUE];
1513
+ text = [ALL_VARIABLE_TEXT];
1514
+ } else if (value[0] === ALL_VARIABLE_VALUE && value.length > 1) {
1515
+ value.shift();
1516
+ if (Array.isArray(text)) {
1517
+ text.shift();
1518
+ }
1519
+ }
1520
+ }
1521
+ this.setStateHelper({ value, text, loading: false });
1522
+ this.publishEvent(new SceneVariableValueChangedEvent(this), true);
1523
+ }
1524
+ findLabelTextForValue(value) {
1525
+ const option = this.state.options.find((x) => x.value === value);
1526
+ if (option) {
1527
+ return option.label;
1528
+ }
1529
+ const optionByLabel = this.state.options.find((x) => x.label === value);
1530
+ if (optionByLabel) {
1531
+ return optionByLabel.label;
1532
+ }
1533
+ return value;
1534
+ }
1535
+ setStateHelper(state) {
1536
+ const test = this;
1537
+ test.setState(state);
1538
+ }
1539
+ getOptionsForSelect() {
1540
+ let options = this.state.options;
1541
+ if (this.state.includeAll) {
1542
+ options = [{ value: ALL_VARIABLE_VALUE, label: ALL_VARIABLE_TEXT }, ...options];
1543
+ }
1544
+ if (!Array.isArray(this.state.value)) {
1545
+ const current = options.find((x) => x.value === this.state.value);
1546
+ if (!current) {
1547
+ options = [{ value: this.state.value, label: String(this.state.text) }, ...options];
1548
+ }
1549
+ }
1550
+ return options;
1551
+ }
1552
+ }
1553
+ class CustomAllValue {
1554
+ constructor(_value) {
1555
+ this._value = _value;
1556
+ this.isCustomValue = true;
1557
+ }
1558
+ toString() {
1559
+ return this._value;
1560
+ }
1561
+ }
1562
+ class MultiValueUrlSyncHandler {
1563
+ constructor(_sceneObject) {
1564
+ this._sceneObject = _sceneObject;
1565
+ }
1566
+ getKey() {
1567
+ return `var-${this._sceneObject.state.name}`;
1568
+ }
1569
+ getKeys() {
1570
+ return [this.getKey()];
1571
+ }
1572
+ getUrlState(state) {
1573
+ let urlValue = null;
1574
+ let value = state.value;
1575
+ if (Array.isArray(value)) {
1576
+ urlValue = value.map(String);
1577
+ } else {
1578
+ urlValue = String(value);
1579
+ }
1580
+ return { [this.getKey()]: urlValue };
1581
+ }
1582
+ updateFromUrl(values) {
1583
+ const urlValue = values[this.getKey()];
1584
+ if (urlValue != null) {
1585
+ this._sceneObject.changeValueTo(urlValue);
1586
+ }
1587
+ }
1588
+ }
1589
+
1590
+ var __defProp$9 = Object.defineProperty;
1591
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
1592
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
1593
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
1594
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1595
+ var __spreadValues$9 = (a, b) => {
1596
+ for (var prop in b || (b = {}))
1597
+ if (__hasOwnProp$9.call(b, prop))
1598
+ __defNormalProp$9(a, prop, b[prop]);
1599
+ if (__getOwnPropSymbols$9)
1600
+ for (var prop of __getOwnPropSymbols$9(b)) {
1601
+ if (__propIsEnum$9.call(b, prop))
1602
+ __defNormalProp$9(a, prop, b[prop]);
1603
+ }
1604
+ return a;
1605
+ };
1606
+ class CustomVariable extends MultiValueVariable {
1607
+ constructor(initialState) {
1608
+ super(__spreadValues$9({
1609
+ type: "custom",
1610
+ query: "",
1611
+ value: "",
1612
+ text: "",
1613
+ options: [],
1614
+ name: ""
1615
+ }, initialState));
1616
+ this._variableDependency = new VariableDependencyConfig(this, {
1617
+ statePaths: ["query"]
1618
+ });
1619
+ }
1620
+ getValueOptions(args) {
1621
+ var _a;
1622
+ const match = (_a = this.state.query.match(/(?:\\,|[^,])+/g)) != null ? _a : [];
1623
+ const options = match.map((text) => {
1624
+ var _a2;
1625
+ text = text.replace(/\\,/g, ",");
1626
+ const textMatch = (_a2 = /^(.+)\s:\s(.+)$/g.exec(text)) != null ? _a2 : [];
1627
+ if (textMatch.length === 3) {
1628
+ const [, key, value] = textMatch;
1629
+ return { label: key.trim(), value: value.trim() };
1630
+ } else {
1631
+ return { label: text.trim(), value: text.trim() };
1632
+ }
1633
+ });
1634
+ return rxjs.of(options);
1635
+ }
1636
+ }
1637
+ CustomVariable.Component = ({ model }) => {
1638
+ return renderSelectForVariable(model);
1639
+ };
1640
+
1641
+ var __defProp$8 = Object.defineProperty;
1642
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
1643
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
1644
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
1645
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1646
+ var __spreadValues$8 = (a, b) => {
1647
+ for (var prop in b || (b = {}))
1648
+ if (__hasOwnProp$8.call(b, prop))
1649
+ __defNormalProp$8(a, prop, b[prop]);
1650
+ if (__getOwnPropSymbols$8)
1651
+ for (var prop of __getOwnPropSymbols$8(b)) {
1652
+ if (__propIsEnum$8.call(b, prop))
1653
+ __defNormalProp$8(a, prop, b[prop]);
1654
+ }
1655
+ return a;
1656
+ };
1657
+ class DataSourceVariable extends MultiValueVariable {
1658
+ constructor(initialState) {
1659
+ super(__spreadValues$8({
1660
+ type: "datasource",
1661
+ value: "",
1662
+ text: "",
1663
+ options: [],
1664
+ name: "",
1665
+ regex: "",
1666
+ query: ""
1667
+ }, initialState));
1668
+ this._variableDependency = new VariableDependencyConfig(this, {
1669
+ statePaths: ["regex"]
1670
+ });
1671
+ }
1672
+ getValueOptions(args) {
1673
+ if (!this.state.query) {
1674
+ return rxjs.of([]);
1675
+ }
1676
+ const dataSourceTypes = this.getDataSourceTypes();
1677
+ let regex;
1678
+ if (this.state.regex) {
1679
+ const interpolated = sceneGraph.interpolate(this, this.state.regex, void 0, "regex");
1680
+ regex = data.stringToJsRegex(interpolated);
1681
+ }
1682
+ const options = [];
1683
+ for (let i = 0; i < dataSourceTypes.length; i++) {
1684
+ const source = dataSourceTypes[i];
1685
+ if (source.meta.id !== this.state.query) {
1686
+ continue;
1687
+ }
1688
+ if (isValid(source, regex)) {
1689
+ options.push({ label: source.name, value: source.name });
1690
+ }
1691
+ if (isDefault(source, regex)) {
1692
+ options.push({ label: "default", value: "default" });
1693
+ }
1694
+ }
1695
+ if (options.length === 0) {
1696
+ options.push({ label: "No data sources found", value: "" });
1697
+ }
1698
+ return rxjs.of(options);
1699
+ }
1700
+ getDataSourceTypes() {
1701
+ return runtime.getDataSourceSrv().getList({ metrics: true, variables: false });
1702
+ }
1703
+ }
1704
+ DataSourceVariable.Component = ({ model }) => {
1705
+ return renderSelectForVariable(model);
1706
+ };
1707
+ function isValid(source, regex) {
1708
+ if (!regex) {
1709
+ return true;
1710
+ }
1711
+ return regex.exec(source.name);
1712
+ }
1713
+ function isDefault(source, regex) {
1714
+ if (!source.isDefault) {
1715
+ return false;
1716
+ }
1717
+ if (!regex) {
1718
+ return true;
1719
+ }
1720
+ return regex.exec("default");
1721
+ }
1722
+
1723
+ const hasLegacyVariableSupport = (datasource) => {
1724
+ return Boolean(datasource.metricFindQuery) && !Boolean(datasource.variables);
1725
+ };
1726
+ const hasStandardVariableSupport = (datasource) => {
1727
+ if (!datasource.variables) {
1728
+ return false;
1729
+ }
1730
+ if (datasource.variables.getType() !== data.VariableSupportType.Standard) {
1731
+ return false;
1732
+ }
1733
+ const variableSupport = datasource.variables;
1734
+ return "toDataQuery" in variableSupport && Boolean(variableSupport.toDataQuery);
1735
+ };
1736
+
1737
+ var __defProp$7 = Object.defineProperty;
1738
+ var __defProps$4 = Object.defineProperties;
1739
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1740
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1741
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1742
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1743
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1744
+ var __spreadValues$7 = (a, b) => {
1745
+ for (var prop in b || (b = {}))
1746
+ if (__hasOwnProp$7.call(b, prop))
1747
+ __defNormalProp$7(a, prop, b[prop]);
1748
+ if (__getOwnPropSymbols$7)
1749
+ for (var prop of __getOwnPropSymbols$7(b)) {
1750
+ if (__propIsEnum$7.call(b, prop))
1751
+ __defNormalProp$7(a, prop, b[prop]);
1752
+ }
1753
+ return a;
1754
+ };
1755
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1756
+ class StandardQueryRunner {
1757
+ constructor(datasource, _runRequest = runtime.getRunRequest()) {
1758
+ this.datasource = datasource;
1759
+ this._runRequest = _runRequest;
1760
+ }
1761
+ getTarget(variable) {
1762
+ if (hasStandardVariableSupport(this.datasource)) {
1763
+ return this.datasource.variables.toDataQuery(variable.state.query);
1764
+ }
1765
+ throw new Error("Couldn't create a target with supplied arguments.");
1766
+ }
1767
+ runRequest(_, request) {
1768
+ if (!hasStandardVariableSupport(this.datasource)) {
1769
+ return getEmptyMetricFindValueObservable();
1770
+ }
1771
+ if (!this.datasource.variables.query) {
1772
+ return this._runRequest(this.datasource, request);
1773
+ }
1774
+ return this._runRequest(this.datasource, request, this.datasource.variables.query);
1775
+ }
1776
+ }
1777
+ class LegacyQueryRunner {
1778
+ constructor(datasource) {
1779
+ this.datasource = datasource;
1780
+ }
1781
+ getTarget(variable) {
1782
+ if (hasLegacyVariableSupport(this.datasource)) {
1783
+ return variable.state.query;
1784
+ }
1785
+ throw new Error("Couldn't create a target with supplied arguments.");
1786
+ }
1787
+ runRequest({ variable }, request) {
1788
+ if (!hasLegacyVariableSupport(this.datasource)) {
1789
+ return getEmptyMetricFindValueObservable();
1790
+ }
1791
+ return rxjs.from(
1792
+ this.datasource.metricFindQuery(variable.state.query, __spreadProps$4(__spreadValues$7({}, request), {
1793
+ variable: {
1794
+ name: variable.state.name,
1795
+ type: variable.state.type
1796
+ }
1797
+ }))
1798
+ ).pipe(
1799
+ rxjs.mergeMap((values) => {
1800
+ if (!values || !values.length) {
1801
+ return getEmptyMetricFindValueObservable();
1802
+ }
1803
+ const series = values;
1804
+ return rxjs.of({ series, state: data.LoadingState.Done, timeRange: request.range });
1805
+ })
1806
+ );
1807
+ }
1808
+ }
1809
+ function getEmptyMetricFindValueObservable() {
1810
+ return rxjs.of({ state: data.LoadingState.Done, series: [], timeRange: data.getDefaultTimeRange() });
1811
+ }
1812
+ function createQueryVariableRunnerFactory(datasource) {
1813
+ if (hasStandardVariableSupport(datasource)) {
1814
+ return new StandardQueryRunner(datasource, runtime.getRunRequest());
1815
+ }
1816
+ if (hasLegacyVariableSupport(datasource)) {
1817
+ return new LegacyQueryRunner(datasource);
1818
+ }
1819
+ throw new Error(`Couldn't create a query runner for datasource ${datasource.type}`);
1820
+ }
1821
+ let createQueryVariableRunner = createQueryVariableRunnerFactory;
1822
+
1823
+ const metricNamesToVariableValues = (variableRegEx, sort, metricNames) => {
1824
+ var _a, _b, _c, _d, _e, _f;
1825
+ let regex;
1826
+ let options = [];
1827
+ if (variableRegEx) {
1828
+ regex = data.stringToJsRegex(variableRegEx);
1829
+ }
1830
+ for (let i = 0; i < metricNames.length; i++) {
1831
+ const item = metricNames[i];
1832
+ let text = item.text === void 0 || item.text === null ? item.value : item.text;
1833
+ let value = item.value === void 0 || item.value === null ? item.text : item.value;
1834
+ if (lodash.isNumber(value)) {
1835
+ value = value.toString();
1836
+ }
1837
+ if (lodash.isNumber(text)) {
1838
+ text = text.toString();
1839
+ }
1840
+ if (regex) {
1841
+ const matches = getAllMatches(value, regex);
1842
+ if (!matches.length) {
1843
+ continue;
1844
+ }
1845
+ const valueGroup = matches.find((m) => m.groups && m.groups.value);
1846
+ const textGroup = matches.find((m) => m.groups && m.groups.text);
1847
+ const firstMatch = matches.find((m) => m.length > 1);
1848
+ const manyMatches = matches.length > 1 && firstMatch;
1849
+ if (valueGroup || textGroup) {
1850
+ value = (_c = (_a = valueGroup == null ? void 0 : valueGroup.groups) == null ? void 0 : _a.value) != null ? _c : (_b = textGroup == null ? void 0 : textGroup.groups) == null ? void 0 : _b.text;
1851
+ text = (_f = (_d = textGroup == null ? void 0 : textGroup.groups) == null ? void 0 : _d.text) != null ? _f : (_e = valueGroup == null ? void 0 : valueGroup.groups) == null ? void 0 : _e.value;
1852
+ } else if (manyMatches) {
1853
+ for (let j = 0; j < matches.length; j++) {
1854
+ const match = matches[j];
1855
+ options.push({ label: match[1], value: match[1] });
1856
+ }
1857
+ continue;
1858
+ } else if (firstMatch) {
1859
+ text = firstMatch[1];
1860
+ value = firstMatch[1];
1861
+ }
1862
+ }
1863
+ options.push({ label: text, value });
1864
+ }
1865
+ options = lodash.uniqBy(options, "value");
1866
+ return sortVariableValues(options, sort);
1867
+ };
1868
+ const getAllMatches = (str, regex) => {
1869
+ const results = [];
1870
+ let matches = null;
1871
+ regex.lastIndex = 0;
1872
+ do {
1873
+ matches = regex.exec(str);
1874
+ if (matches) {
1875
+ results.push(matches);
1876
+ }
1877
+ } while (regex.global && matches && matches[0] !== "" && matches[0] !== void 0);
1878
+ return results;
1879
+ };
1880
+ const sortVariableValues = (options, sortOrder) => {
1881
+ if (sortOrder === data.VariableSort.disabled) {
1882
+ return options;
1883
+ }
1884
+ const sortType = Math.ceil(sortOrder / 2);
1885
+ const reverseSort = sortOrder % 2 === 0;
1886
+ if (sortType === 1) {
1887
+ options = lodash.sortBy(options, "text");
1888
+ } else if (sortType === 2) {
1889
+ options = lodash.sortBy(options, (opt) => {
1890
+ if (!opt.text) {
1891
+ return -1;
1892
+ }
1893
+ const matches = opt.text.match(/.*?(\d+).*/);
1894
+ if (!matches || matches.length < 2) {
1895
+ return -1;
1896
+ } else {
1897
+ return parseInt(matches[1], 10);
1898
+ }
1899
+ });
1900
+ } else if (sortType === 3) {
1901
+ options = lodash.sortBy(options, (opt) => {
1902
+ return lodash.toLower(opt.text);
1903
+ });
1904
+ }
1905
+ if (reverseSort) {
1906
+ options = options.reverse();
1907
+ }
1908
+ return options;
1909
+ };
1910
+
1911
+ function toMetricFindValues() {
1912
+ return (source) => source.pipe(
1913
+ rxjs.map((panelData) => {
1914
+ const frames = panelData.series;
1915
+ if (!frames || !frames.length) {
1916
+ return [];
1917
+ }
1918
+ if (areMetricFindValues(frames)) {
1919
+ return frames;
1920
+ }
1921
+ const processedDataFrames = data.getProcessedDataFrames(frames);
1922
+ const metrics = [];
1923
+ let valueIndex = -1;
1924
+ let textIndex = -1;
1925
+ let stringIndex = -1;
1926
+ let expandableIndex = -1;
1927
+ for (const frame of processedDataFrames) {
1928
+ for (let index = 0; index < frame.fields.length; index++) {
1929
+ const field = frame.fields[index];
1930
+ const fieldName = data.getFieldDisplayName(field, frame, frames).toLowerCase();
1931
+ if (field.type === data.FieldType.string && stringIndex === -1) {
1932
+ stringIndex = index;
1933
+ }
1934
+ if (fieldName === "text" && field.type === data.FieldType.string && textIndex === -1) {
1935
+ textIndex = index;
1936
+ }
1937
+ if (fieldName === "value" && field.type === data.FieldType.string && valueIndex === -1) {
1938
+ valueIndex = index;
1939
+ }
1940
+ if (fieldName === "expandable" && (field.type === data.FieldType.boolean || field.type === data.FieldType.number) && expandableIndex === -1) {
1941
+ expandableIndex = index;
1942
+ }
1943
+ }
1944
+ }
1945
+ if (stringIndex === -1) {
1946
+ throw new Error("Couldn't find any field of type string in the results.");
1947
+ }
1948
+ for (const frame of frames) {
1949
+ for (let index = 0; index < frame.length; index++) {
1950
+ const expandable = expandableIndex !== -1 ? frame.fields[expandableIndex].values.get(index) : void 0;
1951
+ const string = frame.fields[stringIndex].values.get(index);
1952
+ const text = textIndex !== -1 ? frame.fields[textIndex].values.get(index) : null;
1953
+ const value = valueIndex !== -1 ? frame.fields[valueIndex].values.get(index) : null;
1954
+ if (valueIndex === -1 && textIndex === -1) {
1955
+ metrics.push({ text: string, value: string, expandable });
1956
+ continue;
1957
+ }
1958
+ if (valueIndex === -1 && textIndex !== -1) {
1959
+ metrics.push({ text, value: text, expandable });
1960
+ continue;
1961
+ }
1962
+ if (valueIndex !== -1 && textIndex === -1) {
1963
+ metrics.push({ text: value, value, expandable });
1964
+ continue;
1965
+ }
1966
+ metrics.push({ text, value, expandable });
1967
+ }
1968
+ }
1969
+ return metrics;
1970
+ })
1971
+ );
1972
+ }
1973
+ function areMetricFindValues(data$1) {
1974
+ if (!data$1) {
1975
+ return false;
1976
+ }
1977
+ if (!data$1.length) {
1978
+ return true;
1979
+ }
1980
+ const firstValue = data$1[0];
1981
+ if (data.isDataFrame(firstValue)) {
1982
+ return false;
1983
+ }
1984
+ for (const firstValueKey in firstValue) {
1985
+ if (!firstValue.hasOwnProperty(firstValueKey)) {
1986
+ continue;
1987
+ }
1988
+ if (firstValue[firstValueKey] !== null && typeof firstValue[firstValueKey] !== "string" && typeof firstValue[firstValueKey] !== "number") {
1989
+ continue;
1990
+ }
1991
+ const key = firstValueKey.toLowerCase();
1992
+ if (key === "text" || key === "value") {
1993
+ return true;
1994
+ }
1995
+ }
1996
+ return false;
1997
+ }
1998
+
1999
+ var __defProp$6 = Object.defineProperty;
2000
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
2001
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
2002
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
2003
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2004
+ var __spreadValues$6 = (a, b) => {
2005
+ for (var prop in b || (b = {}))
2006
+ if (__hasOwnProp$6.call(b, prop))
2007
+ __defNormalProp$6(a, prop, b[prop]);
2008
+ if (__getOwnPropSymbols$6)
2009
+ for (var prop of __getOwnPropSymbols$6(b)) {
2010
+ if (__propIsEnum$6.call(b, prop))
2011
+ __defNormalProp$6(a, prop, b[prop]);
2012
+ }
2013
+ return a;
2014
+ };
2015
+ class QueryVariable extends MultiValueVariable {
2016
+ constructor(initialState) {
2017
+ super(__spreadValues$6({
2018
+ type: "query",
2019
+ name: "",
2020
+ value: "",
2021
+ text: "",
2022
+ query: "",
2023
+ options: [],
2024
+ datasource: null,
2025
+ regex: "",
2026
+ refresh: data.VariableRefresh.onDashboardLoad,
2027
+ sort: data.VariableSort.alphabeticalAsc
2028
+ }, initialState));
2029
+ this._variableDependency = new VariableDependencyConfig(this, {
2030
+ statePaths: ["regex", "query", "datasource"]
2031
+ });
2032
+ }
2033
+ activate() {
2034
+ super.activate();
2035
+ const timeRange = sceneGraph.getTimeRange(this);
2036
+ if (this.state.refresh === data.VariableRefresh.onTimeRangeChanged) {
2037
+ this._subs.add(
2038
+ timeRange.subscribeToState({
2039
+ next: () => {
2040
+ this.updateSubscription = this.validateAndUpdate().subscribe();
2041
+ }
2042
+ })
2043
+ );
2044
+ }
2045
+ }
2046
+ deactivate() {
2047
+ super.deactivate();
2048
+ if (this.updateSubscription) {
2049
+ this.updateSubscription.unsubscribe();
2050
+ }
2051
+ if (this.dataSourceSubject) {
2052
+ this.dataSourceSubject.unsubscribe();
2053
+ }
2054
+ }
2055
+ getValueOptions(args) {
2056
+ if (this.state.query === "" || !this.state.datasource) {
2057
+ return rxjs.of([]);
2058
+ }
2059
+ return rxjs.from(this.getDataSource()).pipe(
2060
+ rxjs.mergeMap((ds) => {
2061
+ const runner = createQueryVariableRunner(ds);
2062
+ const target = runner.getTarget(this);
2063
+ const request = this.getRequest(target);
2064
+ return runner.runRequest({ variable: this }, request).pipe(
2065
+ rxjs.filter((data$1) => data$1.state === data.LoadingState.Done || data$1.state === data.LoadingState.Error),
2066
+ rxjs.take(1),
2067
+ rxjs.mergeMap((data$1) => {
2068
+ if (data$1.state === data.LoadingState.Error) {
2069
+ return rxjs.throwError(() => data$1.error);
2070
+ }
2071
+ return rxjs.of(data$1);
2072
+ }),
2073
+ toMetricFindValues(),
2074
+ rxjs.mergeMap((values) => {
2075
+ let regex = "";
2076
+ if (this.state.regex) {
2077
+ regex = sceneGraph.interpolate(this, this.state.regex, void 0, "regex");
2078
+ }
2079
+ return rxjs.of(metricNamesToVariableValues(regex, this.state.sort, values));
2080
+ }),
2081
+ rxjs.catchError((error) => {
2082
+ if (error.cancelled) {
2083
+ return rxjs.of([]);
2084
+ }
2085
+ return rxjs.throwError(() => error);
2086
+ })
2087
+ );
2088
+ })
2089
+ );
2090
+ }
2091
+ async getDataSource() {
2092
+ return runtime.getDataSourceSrv().get(this.state.datasource, {
2093
+ __sceneObject: { text: "__sceneObject", value: this }
2094
+ });
2095
+ }
2096
+ getRequest(target) {
2097
+ const scopedVars = {
2098
+ __sceneObject: { text: "__sceneObject", value: this }
2099
+ };
2100
+ const range = this.state.refresh === data.VariableRefresh.onTimeRangeChanged ? sceneGraph.getTimeRange(this).state.value : data.getDefaultTimeRange();
2101
+ const request = {
2102
+ app: data.CoreApp.Dashboard,
2103
+ requestId: uuid.v4(),
2104
+ timezone: "",
2105
+ range,
2106
+ interval: "",
2107
+ intervalMs: 0,
2108
+ targets: [target],
2109
+ scopedVars,
2110
+ startTime: Date.now()
2111
+ };
2112
+ return request;
2113
+ }
2114
+ }
2115
+ QueryVariable.Component = ({ model }) => {
2116
+ return /* @__PURE__ */ React__default["default"].createElement(VariableValueSelect, {
2117
+ model
2118
+ });
2119
+ };
2120
+
2121
+ function buildMetricTree(parent, depth) {
2122
+ const chars = ["A", "B", "C", "D", "E", "F", "G", "H"];
2123
+ const children = [];
2124
+ if (depth > 5) {
2125
+ return [];
2126
+ }
2127
+ for (const letter of chars) {
2128
+ const nodeName = `${parent}${letter}`;
2129
+ children.push({
2130
+ name: nodeName,
2131
+ children: buildMetricTree(nodeName, depth + 1)
2132
+ });
2133
+ }
2134
+ return children;
2135
+ }
2136
+ function queryTree(children, query, queryIndex) {
2137
+ if (queryIndex >= query.length) {
2138
+ return children;
2139
+ }
2140
+ if (query[queryIndex] === "*") {
2141
+ return children;
2142
+ }
2143
+ const nodeQuery = query[queryIndex];
2144
+ let result = [];
2145
+ let namesToMatch = [nodeQuery];
2146
+ if (nodeQuery.startsWith("{")) {
2147
+ namesToMatch = nodeQuery.replace(/\{|\}/g, "").split(",");
2148
+ }
2149
+ for (const node of children) {
2150
+ for (const nameToMatch of namesToMatch) {
2151
+ if (nameToMatch.indexOf("*") !== -1) {
2152
+ const pattern = nameToMatch.replace("*", "");
2153
+ const regex = new RegExp(`^${pattern}.*`, "gi");
2154
+ if (regex.test(node.name)) {
2155
+ result = result.concat(queryTree([node], query, queryIndex + 1));
2156
+ }
2157
+ } else if (node.name === nameToMatch) {
2158
+ result = result.concat(queryTree(node.children, query, queryIndex + 1));
2159
+ }
2160
+ }
2161
+ }
2162
+ return result;
2163
+ }
2164
+ function queryMetricTree(query) {
2165
+ if (query.indexOf("value") === 0) {
2166
+ return [{ name: query, children: [] }];
2167
+ }
2168
+ const children = buildMetricTree("", 0);
2169
+ return queryTree(children, query.split("."), 0);
2170
+ }
2171
+
2172
+ var __defProp$5 = Object.defineProperty;
2173
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2174
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2175
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2176
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2177
+ var __spreadValues$5 = (a, b) => {
2178
+ for (var prop in b || (b = {}))
2179
+ if (__hasOwnProp$5.call(b, prop))
2180
+ __defNormalProp$5(a, prop, b[prop]);
2181
+ if (__getOwnPropSymbols$5)
2182
+ for (var prop of __getOwnPropSymbols$5(b)) {
2183
+ if (__propIsEnum$5.call(b, prop))
2184
+ __defNormalProp$5(a, prop, b[prop]);
2185
+ }
2186
+ return a;
2187
+ };
2188
+ class TestVariable extends MultiValueVariable {
2189
+ constructor(initialState) {
2190
+ super(__spreadValues$5({
2191
+ type: "custom",
2192
+ name: "Test",
2193
+ value: "Value",
2194
+ text: "Text",
2195
+ query: "Query",
2196
+ options: []
2197
+ }, initialState));
2198
+ this.completeUpdate = new rxjs.Subject();
2199
+ this.isGettingValues = true;
2200
+ this.getValueOptionsCount = 0;
2201
+ this._variableDependency = new VariableDependencyConfig(this, {
2202
+ statePaths: ["query"]
2203
+ });
2204
+ }
2205
+ getValueOptions(args) {
2206
+ const { delayMs } = this.state;
2207
+ this.getValueOptionsCount += 1;
2208
+ return new rxjs.Observable((observer) => {
2209
+ this.setState({ loading: true });
2210
+ const sub = this.completeUpdate.subscribe({
2211
+ next: () => {
2212
+ observer.next(this.issueQuery());
2213
+ }
2214
+ });
2215
+ let timeout;
2216
+ if (delayMs) {
2217
+ timeout = setTimeout(() => this.signalUpdateCompleted(), delayMs);
2218
+ }
2219
+ this.isGettingValues = true;
2220
+ return () => {
2221
+ sub.unsubscribe();
2222
+ clearTimeout(timeout);
2223
+ this.isGettingValues = false;
2224
+ };
2225
+ });
2226
+ }
2227
+ issueQuery() {
2228
+ const interpolatedQuery = sceneGraph.interpolate(this, this.state.query);
2229
+ const options = queryMetricTree(interpolatedQuery).map((x) => ({ label: x.name, value: x.name }));
2230
+ this.setState({
2231
+ issuedQuery: interpolatedQuery,
2232
+ options
2233
+ });
2234
+ return options;
2235
+ }
2236
+ signalUpdateCompleted() {
2237
+ this.completeUpdate.next(1);
2238
+ }
2239
+ }
2240
+ TestVariable.Component = ({ model }) => {
2241
+ return renderSelectForVariable(model);
2242
+ };
2243
+
2244
+ class UrlSyncManager {
2245
+ constructor(sceneRoot) {
2246
+ this.sceneRoot = sceneRoot;
2247
+ this.initialStates = /* @__PURE__ */ new Map();
2248
+ this.urlKeyMapper = new UniqueUrlKeyMapper();
2249
+ this.onLocationUpdate = (location) => {
2250
+ const urlParams = new URLSearchParams(location.search);
2251
+ this.urlKeyMapper.rebuldIndex(this.sceneRoot);
2252
+ this.syncSceneStateFromUrl(this.sceneRoot, urlParams);
2253
+ };
2254
+ this.onStateChanged = ({ payload }) => {
2255
+ const changedObject = payload.changedObject;
2256
+ if (changedObject.urlSync) {
2257
+ const newUrlState = changedObject.urlSync.getUrlState(payload.newState);
2258
+ const prevUrlState = changedObject.urlSync.getUrlState(payload.prevState);
2259
+ const searchParams = runtime.locationService.getSearch();
2260
+ const mappedUpdated = {};
2261
+ this.urlKeyMapper.rebuldIndex(this.sceneRoot);
2262
+ for (const [key, newUrlValue] of Object.entries(newUrlState)) {
2263
+ const uniqueKey = this.urlKeyMapper.getUniqueKey(key, changedObject);
2264
+ const currentUrlValue = searchParams.getAll(uniqueKey);
2265
+ if (!isUrlValueEqual(currentUrlValue, newUrlValue)) {
2266
+ mappedUpdated[uniqueKey] = newUrlValue;
2267
+ if (!this.initialStates.has(uniqueKey) && prevUrlState[key] !== void 0) {
2268
+ this.initialStates.set(uniqueKey, prevUrlState[key]);
2269
+ }
2270
+ }
2271
+ }
2272
+ if (Object.keys(mappedUpdated).length > 0) {
2273
+ runtime.locationService.partial(mappedUpdated, true);
2274
+ }
2275
+ }
2276
+ };
2277
+ this.stateChangeSub = sceneRoot.subscribeToEvent(SceneObjectStateChangedEvent, this.onStateChanged);
2278
+ this.locationListenerUnsub = runtime.locationService.getHistory().listen(this.onLocationUpdate);
2279
+ }
2280
+ initSync() {
2281
+ const urlParams = runtime.locationService.getSearch();
2282
+ this.urlKeyMapper.rebuldIndex(this.sceneRoot);
2283
+ this.syncSceneStateFromUrl(this.sceneRoot, urlParams);
2284
+ }
2285
+ cleanUp() {
2286
+ this.stateChangeSub.unsubscribe();
2287
+ this.locationListenerUnsub();
2288
+ }
2289
+ syncSceneStateFromUrl(sceneObject, urlParams) {
2290
+ if (sceneObject.urlSync) {
2291
+ const urlState = {};
2292
+ const currentState = sceneObject.urlSync.getUrlState(sceneObject.state);
2293
+ for (const key of sceneObject.urlSync.getKeys()) {
2294
+ const uniqueKey = this.urlKeyMapper.getUniqueKey(key, sceneObject);
2295
+ const newValue = urlParams.getAll(uniqueKey);
2296
+ const currentValue = currentState[key];
2297
+ if (isUrlValueEqual(newValue, currentValue)) {
2298
+ continue;
2299
+ }
2300
+ if (newValue.length > 0) {
2301
+ if (Array.isArray(currentValue)) {
2302
+ urlState[key] = newValue;
2303
+ } else {
2304
+ urlState[key] = newValue[0];
2305
+ }
2306
+ if (!this.initialStates.has(uniqueKey) && currentValue !== void 0) {
2307
+ this.initialStates.set(uniqueKey, currentValue);
2308
+ }
2309
+ } else {
2310
+ const initialValue = this.initialStates.get(uniqueKey);
2311
+ if (initialValue !== void 0) {
2312
+ urlState[key] = initialValue;
2313
+ }
2314
+ }
2315
+ }
2316
+ if (Object.keys(urlState).length > 0) {
2317
+ sceneObject.urlSync.updateFromUrl(urlState);
2318
+ }
2319
+ }
2320
+ forEachSceneObjectInState(sceneObject.state, (obj) => this.syncSceneStateFromUrl(obj, urlParams));
2321
+ }
2322
+ }
2323
+ class UniqueUrlKeyMapper {
2324
+ constructor() {
2325
+ this.index = /* @__PURE__ */ new Map();
2326
+ }
2327
+ getUniqueKey(key, obj) {
2328
+ const objectsWithKey = this.index.get(key);
2329
+ if (!objectsWithKey) {
2330
+ throw new Error("Cannot find any scene object that uses the key '" + key + "'");
2331
+ }
2332
+ const address = objectsWithKey.findIndex((o) => o.sceneObject === obj);
2333
+ if (address > 0) {
2334
+ return `${key}-${address + 1}`;
2335
+ }
2336
+ return key;
2337
+ }
2338
+ rebuldIndex(root) {
2339
+ this.index.clear();
2340
+ this.buildIndex(root, 0);
2341
+ }
2342
+ buildIndex(sceneObject, depth) {
2343
+ if (sceneObject.urlSync) {
2344
+ for (const key of sceneObject.urlSync.getKeys()) {
2345
+ const hit = this.index.get(key);
2346
+ if (hit) {
2347
+ hit.push({ sceneObject, depth });
2348
+ hit.sort((a, b) => a.depth - b.depth);
2349
+ } else {
2350
+ this.index.set(key, [{ sceneObject, depth }]);
2351
+ }
2352
+ }
2353
+ }
2354
+ forEachSceneObjectInState(sceneObject.state, (obj) => this.buildIndex(obj, depth + 1));
2355
+ }
2356
+ }
2357
+ function isUrlValueEqual(currentUrlValue, newUrlValue) {
2358
+ if (currentUrlValue.length === 0 && newUrlValue == null) {
2359
+ return true;
2360
+ }
2361
+ if (!Array.isArray(newUrlValue) && (currentUrlValue == null ? void 0 : currentUrlValue.length) === 1) {
2362
+ return newUrlValue === currentUrlValue[0];
2363
+ }
2364
+ if ((newUrlValue == null ? void 0 : newUrlValue.length) === 0 && currentUrlValue === null) {
2365
+ return true;
2366
+ }
2367
+ return lodash.isEqual(currentUrlValue, newUrlValue);
2368
+ }
2369
+
2370
+ class EmbeddedScene extends SceneObjectBase {
2371
+ activate() {
2372
+ super.activate();
2373
+ this.urlSyncManager = new UrlSyncManager(this);
2374
+ this.urlSyncManager.initSync();
2375
+ }
2376
+ deactivate() {
2377
+ super.deactivate();
2378
+ this.urlSyncManager.cleanUp();
2379
+ }
2380
+ }
2381
+ EmbeddedScene.Component = EmbeddedSceneRenderer;
2382
+ function EmbeddedSceneRenderer({ model }) {
2383
+ const { body, isEditing, subMenu } = model.useState();
2384
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2385
+ style: {
2386
+ flexGrow: 1,
2387
+ display: "flex",
2388
+ gap: "8px",
2389
+ overflow: "auto",
2390
+ minHeight: "100%",
2391
+ flexDirection: "column"
2392
+ }
2393
+ }, subMenu && /* @__PURE__ */ React__default["default"].createElement(subMenu.Component, {
2394
+ model: subMenu
2395
+ }), /* @__PURE__ */ React__default["default"].createElement("div", {
2396
+ style: { flexGrow: 1, display: "flex", gap: "8px", overflow: "auto" }
2397
+ }, /* @__PURE__ */ React__default["default"].createElement(body.Component, {
2398
+ model: body,
2399
+ isEditing
2400
+ })));
2401
+ }
2402
+
2403
+ function SceneDragHandle({ layoutKey, className }) {
2404
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2405
+ className: `${className} grid-drag-handle-${layoutKey}`,
2406
+ style: {
2407
+ width: "20px",
2408
+ height: "20px",
2409
+ cursor: "move"
2410
+ }
2411
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.Icon, {
2412
+ name: "draggabledots"
2413
+ }));
2414
+ }
2415
+
2416
+ function VizPanelRenderer({ model }) {
2417
+ var _a;
2418
+ const theme = ui.useTheme2();
2419
+ const replace = React.useMemo(
2420
+ () => (value, scoped) => sceneGraph.interpolate(model, value, scoped),
2421
+ [model]
2422
+ );
2423
+ const { title, options, fieldConfig, pluginId, pluginLoadError, $data, placement } = model.useState();
2424
+ const [ref, { width, height }] = reactUse.useMeasure();
2425
+ const plugin = model.getPlugin();
2426
+ const { data: data$1 } = sceneGraph.getData(model).useState();
2427
+ const parentLayout = sceneGraph.getLayout(model);
2428
+ const isDraggable = ((_a = parentLayout.state.placement) == null ? void 0 : _a.isDraggable) ? placement == null ? void 0 : placement.isDraggable : false;
2429
+ const dragHandle = /* @__PURE__ */ React__default["default"].createElement(SceneDragHandle, {
2430
+ layoutKey: parentLayout.state.key
2431
+ });
2432
+ const titleInterpolated = sceneGraph.interpolate(model, title);
2433
+ const timeZone = sceneGraph.getTimeRange(model).state.timeZone;
2434
+ const dataWithOverrides = data.useFieldOverrides(plugin, fieldConfig, data$1, timeZone, theme, replace);
2435
+ if (pluginLoadError) {
2436
+ return /* @__PURE__ */ React__default["default"].createElement("div", null, "Failed to load plugin: ", pluginLoadError);
2437
+ }
2438
+ if (!plugin || !plugin.hasPluginId(pluginId)) {
2439
+ return /* @__PURE__ */ React__default["default"].createElement("div", null, "Loading plugin panel...");
2440
+ }
2441
+ if (!plugin.panel) {
2442
+ return /* @__PURE__ */ React__default["default"].createElement("div", null, "Panel plugin has no panel component");
2443
+ }
2444
+ const PanelComponent = plugin.panel;
2445
+ if ($data instanceof SceneQueryRunner) {
2446
+ $data.setContainerWidth(width);
2447
+ }
2448
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2449
+ ref,
2450
+ style: { position: "absolute", width: "100%", height: "100%" }
2451
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.PanelChrome, {
2452
+ title: titleInterpolated,
2453
+ width,
2454
+ height,
2455
+ leftItems: isDraggable ? [dragHandle] : void 0
2456
+ }, (innerWidth, innerHeight) => /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, !dataWithOverrides && /* @__PURE__ */ React__default["default"].createElement("div", null, "No data..."), dataWithOverrides && /* @__PURE__ */ React__default["default"].createElement(ui.ErrorBoundaryAlert, {
2457
+ dependencies: [plugin, data$1]
2458
+ }, /* @__PURE__ */ React__default["default"].createElement(data.PluginContextProvider, {
2459
+ meta: plugin.meta
2460
+ }, /* @__PURE__ */ React__default["default"].createElement(PanelComponent, {
2461
+ id: 1,
2462
+ data: dataWithOverrides,
2463
+ title,
2464
+ timeRange: dataWithOverrides.timeRange,
2465
+ timeZone,
2466
+ options,
2467
+ fieldConfig,
2468
+ transparent: false,
2469
+ width: innerWidth,
2470
+ height: innerHeight,
2471
+ renderCounter: 0,
2472
+ replaceVariables: (str) => str,
2473
+ onOptionsChange: model.onOptionsChange,
2474
+ onFieldConfigChange: model.onFieldConfigChange,
2475
+ onChangeTimeRange: model.onChangeTimeRange,
2476
+ eventBus: runtime.getAppEvents()
2477
+ }))))));
2478
+ }
2479
+ VizPanelRenderer.displayName = "ScenePanelRenderer";
2480
+
2481
+ var __defProp$4 = Object.defineProperty;
2482
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
2483
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
2484
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
2485
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2486
+ var __spreadValues$4 = (a, b) => {
2487
+ for (var prop in b || (b = {}))
2488
+ if (__hasOwnProp$4.call(b, prop))
2489
+ __defNormalProp$4(a, prop, b[prop]);
2490
+ if (__getOwnPropSymbols$4)
2491
+ for (var prop of __getOwnPropSymbols$4(b)) {
2492
+ if (__propIsEnum$4.call(b, prop))
2493
+ __defNormalProp$4(a, prop, b[prop]);
2494
+ }
2495
+ return a;
2496
+ };
2497
+ class VizPanel extends SceneObjectBase {
2498
+ constructor(state) {
2499
+ super(__spreadValues$4({
2500
+ options: {},
2501
+ fieldConfig: { defaults: {}, overrides: [] },
2502
+ title: "Title",
2503
+ pluginId: "timeseries"
2504
+ }, state));
2505
+ this.onChangeTimeRange = (timeRange) => {
2506
+ const sceneTimeRange = sceneGraph.getTimeRange(this);
2507
+ sceneTimeRange.onTimeRangeChange({
2508
+ raw: {
2509
+ from: data.toUtc(timeRange.from),
2510
+ to: data.toUtc(timeRange.to)
2511
+ },
2512
+ from: data.toUtc(timeRange.from),
2513
+ to: data.toUtc(timeRange.to)
2514
+ });
2515
+ };
2516
+ this.onOptionsChange = (options) => {
2517
+ this.setState({ options });
2518
+ };
2519
+ this.onFieldConfigChange = (fieldConfig) => {
2520
+ this.setState({ fieldConfig });
2521
+ };
2522
+ }
2523
+ activate() {
2524
+ super.activate();
2525
+ const { getPanelPluginFromCache, importPanelPlugin } = runtime.getPluginImportUtils();
2526
+ const plugin = getPanelPluginFromCache(this.state.pluginId);
2527
+ if (plugin) {
2528
+ this.pluginLoaded(plugin);
2529
+ } else {
2530
+ importPanelPlugin(this.state.pluginId).then((result) => this.pluginLoaded(result)).catch((err) => {
2531
+ this.setState({ pluginLoadError: err.message });
2532
+ });
2533
+ }
2534
+ }
2535
+ pluginLoaded(plugin) {
2536
+ const { options, fieldConfig, title, pluginId, pluginVersion } = this.state;
2537
+ const panel = { title, options, fieldConfig, id: 1, type: pluginId, pluginVersion };
2538
+ const currentVersion = this.getPluginVersion(plugin);
2539
+ if (plugin.onPanelMigration) {
2540
+ if (currentVersion !== this.state.pluginVersion) {
2541
+ panel.options = plugin.onPanelMigration(panel);
2542
+ }
2543
+ }
2544
+ const withDefaults = data.getPanelOptionsWithDefaults({
2545
+ plugin,
2546
+ currentOptions: panel.options,
2547
+ currentFieldConfig: panel.fieldConfig,
2548
+ isAfterPluginChange: false
2549
+ });
2550
+ this._plugin = plugin;
2551
+ this.setState({
2552
+ options: withDefaults.options,
2553
+ fieldConfig: withDefaults.fieldConfig,
2554
+ pluginVersion: currentVersion
2555
+ });
2556
+ }
2557
+ getPluginVersion(plugin) {
2558
+ return plugin && plugin.meta.info.version ? plugin.meta.info.version : runtime.config.buildInfo.version;
2559
+ }
2560
+ getPlugin() {
2561
+ return this._plugin;
2562
+ }
2563
+ }
2564
+ VizPanel.Component = VizPanelRenderer;
2565
+ VizPanel.Editor = VizPanelEditor;
2566
+ function VizPanelEditor({ model }) {
2567
+ const { title } = model.useState();
2568
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Field, {
2569
+ label: "Title"
2570
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.Input, {
2571
+ defaultValue: title,
2572
+ onBlur: (evt) => model.setState({ title: evt.currentTarget.value })
2573
+ }));
2574
+ }
2575
+
2576
+ var __defProp$3 = Object.defineProperty;
2577
+ var __defProps$3 = Object.defineProperties;
2578
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
2579
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
2580
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
2581
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
2582
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2583
+ var __spreadValues$3 = (a, b) => {
2584
+ for (var prop in b || (b = {}))
2585
+ if (__hasOwnProp$3.call(b, prop))
2586
+ __defNormalProp$3(a, prop, b[prop]);
2587
+ if (__getOwnPropSymbols$3)
2588
+ for (var prop of __getOwnPropSymbols$3(b)) {
2589
+ if (__propIsEnum$3.call(b, prop))
2590
+ __defNormalProp$3(a, prop, b[prop]);
2591
+ }
2592
+ return a;
2593
+ };
2594
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2595
+ class NestedScene extends SceneObjectBase {
2596
+ constructor() {
2597
+ super(...arguments);
2598
+ this.onToggle = () => {
2599
+ this.setState({
2600
+ isCollapsed: !this.state.isCollapsed,
2601
+ placement: __spreadProps$3(__spreadValues$3({}, this.state.placement), {
2602
+ ySizing: this.state.isCollapsed ? "fill" : "content"
2603
+ })
2604
+ });
2605
+ };
2606
+ this.onRemove = () => {
2607
+ const parent = this.parent;
2608
+ if ("children" in parent.state) {
2609
+ parent.setState({
2610
+ children: parent.state.children.filter((x) => x !== this)
2611
+ });
2612
+ }
2613
+ };
2614
+ }
2615
+ }
2616
+ NestedScene.Component = NestedSceneRenderer;
2617
+ function NestedSceneRenderer({ model, isEditing }) {
2618
+ const { title, isCollapsed, canCollapse, canRemove, body, actions } = model.useState();
2619
+ const styles = ui.useStyles2(getStyles);
2620
+ const toolbarActions = (actions != null ? actions : []).map((action) => /* @__PURE__ */ React__default["default"].createElement(action.Component, {
2621
+ key: action.state.key,
2622
+ model: action
2623
+ }));
2624
+ if (canRemove) {
2625
+ toolbarActions.push(
2626
+ /* @__PURE__ */ React__default["default"].createElement(ui.ToolbarButton, {
2627
+ icon: "times",
2628
+ variant: "default",
2629
+ onClick: model.onRemove,
2630
+ key: "remove-button",
2631
+ "aria-label": "Remove scene"
2632
+ })
2633
+ );
2634
+ }
2635
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2636
+ className: styles.row
2637
+ }, /* @__PURE__ */ React__default["default"].createElement("div", {
2638
+ className: styles.rowHeader
2639
+ }, /* @__PURE__ */ React__default["default"].createElement(experimental.Stack, {
2640
+ gap: 0
2641
+ }, /* @__PURE__ */ React__default["default"].createElement("div", {
2642
+ className: styles.title,
2643
+ role: "heading",
2644
+ "aria-level": 1
2645
+ }, title), canCollapse && /* @__PURE__ */ React__default["default"].createElement("div", {
2646
+ className: styles.toggle
2647
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.Button, {
2648
+ size: "sm",
2649
+ icon: isCollapsed ? "angle-down" : "angle-up",
2650
+ fill: "text",
2651
+ variant: "secondary",
2652
+ "aria-label": isCollapsed ? "Expand scene" : "Collapse scene",
2653
+ onClick: model.onToggle
2654
+ }))), /* @__PURE__ */ React__default["default"].createElement("div", {
2655
+ className: styles.actions
2656
+ }, toolbarActions)), !isCollapsed && /* @__PURE__ */ React__default["default"].createElement(body.Component, {
2657
+ model: body,
2658
+ isEditing
2659
+ }));
2660
+ }
2661
+ const getStyles = (theme) => ({
2662
+ row: css.css({
2663
+ display: "flex",
2664
+ flexDirection: "column",
2665
+ flexGrow: 1,
2666
+ gap: theme.spacing(1),
2667
+ cursor: "pointer"
2668
+ }),
2669
+ toggle: css.css({}),
2670
+ title: css.css({
2671
+ fontSize: theme.typography.h5.fontSize
2672
+ }),
2673
+ rowHeader: css.css({
2674
+ display: "flex",
2675
+ alignItems: "center",
2676
+ gap: theme.spacing(2)
2677
+ }),
2678
+ actions: css.css({
2679
+ display: "flex",
2680
+ alignItems: "center",
2681
+ gap: theme.spacing(1),
2682
+ justifyContent: "flex-end",
2683
+ flexGrow: 1
2684
+ })
2685
+ });
2686
+
2687
+ class SceneCanvasText extends SceneObjectBase {
2688
+ constructor() {
2689
+ super(...arguments);
2690
+ this._variableDependency = new VariableDependencyConfig(this, { statePaths: ["text"] });
2691
+ }
2692
+ }
2693
+ SceneCanvasText.Editor = Editor;
2694
+ SceneCanvasText.Component = ({ model }) => {
2695
+ const { text, fontSize = 20, align = "left", key } = model.useState();
2696
+ const style = {
2697
+ fontSize,
2698
+ display: "flex",
2699
+ flexGrow: 1,
2700
+ alignItems: "center",
2701
+ padding: 16,
2702
+ justifyContent: align
2703
+ };
2704
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2705
+ style,
2706
+ "data-testid": key
2707
+ }, sceneGraph.interpolate(model, text));
2708
+ };
2709
+ function Editor({ model }) {
2710
+ const { fontSize } = model.useState();
2711
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Field, {
2712
+ label: "Font size"
2713
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.Input, {
2714
+ type: "number",
2715
+ defaultValue: fontSize,
2716
+ onBlur: (evt) => model.setState({ fontSize: parseInt(evt.currentTarget.value, 10) })
2717
+ }));
2718
+ }
2719
+
2720
+ class SceneToolbarButton extends SceneObjectBase {
2721
+ }
2722
+ SceneToolbarButton.Component = ({ model }) => {
2723
+ const state = model.useState();
2724
+ return /* @__PURE__ */ React__default["default"].createElement(ui.ToolbarButton, {
2725
+ onClick: state.onClick,
2726
+ icon: state.icon
2727
+ });
2728
+ };
2729
+ class SceneToolbarInput extends SceneObjectBase {
2730
+ }
2731
+ SceneToolbarInput.Component = ({ model }) => {
2732
+ const state = model.useState();
2733
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Input, {
2734
+ defaultValue: state.value,
2735
+ width: 8,
2736
+ onBlur: (evt) => {
2737
+ model.state.onChange(parseInt(evt.currentTarget.value, 10));
2738
+ }
2739
+ });
2740
+ };
2741
+
2742
+ class SceneTimePicker extends SceneObjectBase {
2743
+ }
2744
+ SceneTimePicker.Component = SceneTimePickerRenderer;
2745
+ function SceneTimePickerRenderer({ model }) {
2746
+ const { hidePicker } = model.useState();
2747
+ const timeRange = sceneGraph.getTimeRange(model);
2748
+ const timeRangeState = timeRange.useState();
2749
+ if (hidePicker) {
2750
+ return null;
2751
+ }
2752
+ return /* @__PURE__ */ React__default["default"].createElement(ui.ToolbarButtonRow, {
2753
+ alignment: "right"
2754
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.TimeRangePicker, {
2755
+ value: timeRangeState.value,
2756
+ onChange: timeRange.onTimeRangeChange,
2757
+ timeZone: "browser",
2758
+ fiscalYearStartMonth: 0,
2759
+ onMoveBackward: () => {
2760
+ },
2761
+ onMoveForward: () => {
2762
+ },
2763
+ onZoom: () => {
2764
+ },
2765
+ onChangeTimeZone: () => {
2766
+ },
2767
+ onChangeFiscalYearStartMonth: () => {
2768
+ }
2769
+ }), /* @__PURE__ */ React__default["default"].createElement(ui.RefreshPicker, {
2770
+ onRefresh: timeRange.onRefresh,
2771
+ onIntervalChanged: timeRange.onIntervalChanged
2772
+ }));
2773
+ }
2774
+
2775
+ var __defProp$2 = Object.defineProperty;
2776
+ var __defProps$2 = Object.defineProperties;
2777
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
2778
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
2779
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
2780
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
2781
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2782
+ var __spreadValues$2 = (a, b) => {
2783
+ for (var prop in b || (b = {}))
2784
+ if (__hasOwnProp$2.call(b, prop))
2785
+ __defNormalProp$2(a, prop, b[prop]);
2786
+ if (__getOwnPropSymbols$2)
2787
+ for (var prop of __getOwnPropSymbols$2(b)) {
2788
+ if (__propIsEnum$2.call(b, prop))
2789
+ __defNormalProp$2(a, prop, b[prop]);
2790
+ }
2791
+ return a;
2792
+ };
2793
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
2794
+ class ScenePanelRepeater extends SceneObjectBase {
2795
+ activate() {
2796
+ super.activate();
2797
+ this._subs.add(
2798
+ sceneGraph.getData(this).subscribeToState({
2799
+ next: (data$1) => {
2800
+ var _a;
2801
+ if (((_a = data$1.data) == null ? void 0 : _a.state) === data.LoadingState.Done) {
2802
+ this.performRepeat(data$1.data);
2803
+ }
2804
+ }
2805
+ })
2806
+ );
2807
+ }
2808
+ performRepeat(data) {
2809
+ const firstChild = this.state.layout.state.children[0];
2810
+ const newChildren = [];
2811
+ for (const series of data.series) {
2812
+ const clone = firstChild.clone({
2813
+ key: `${newChildren.length}`,
2814
+ $data: new SceneDataNode({
2815
+ data: __spreadProps$2(__spreadValues$2({}, data), {
2816
+ series: [series]
2817
+ })
2818
+ })
2819
+ });
2820
+ newChildren.push(clone);
2821
+ }
2822
+ this.state.layout.setState({ children: newChildren });
2823
+ }
2824
+ }
2825
+ ScenePanelRepeater.Component = ({ model, isEditing }) => {
2826
+ const { layout } = model.useState();
2827
+ return /* @__PURE__ */ React__default["default"].createElement(layout.Component, {
2828
+ model: layout,
2829
+ isEditing
2830
+ });
2831
+ };
2832
+
2833
+ class SceneSubMenu extends SceneObjectBase {
2834
+ }
2835
+ SceneSubMenu.Component = SceneSubMenuRenderer;
2836
+ function SceneSubMenuRenderer({ model }) {
2837
+ const { children } = model.useState();
2838
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2839
+ style: { display: "flex", gap: "16px" }
2840
+ }, children.map((child) => /* @__PURE__ */ React__default["default"].createElement(child.Component, {
2841
+ key: child.state.key,
2842
+ model: child
2843
+ })));
2844
+ }
2845
+
2846
+ class SceneFlexLayout extends SceneObjectBase {
2847
+ toggleDirection() {
2848
+ this.setState({
2849
+ direction: this.state.direction === "row" ? "column" : "row"
2850
+ });
2851
+ }
2852
+ }
2853
+ SceneFlexLayout.Component = FlexLayoutRenderer;
2854
+ SceneFlexLayout.Editor = FlexLayoutEditor;
2855
+ function FlexLayoutRenderer({ model, isEditing }) {
2856
+ const { direction = "row", children } = model.useState();
2857
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2858
+ style: { flexGrow: 1, flexDirection: direction, display: "flex", gap: "8px" }
2859
+ }, children.map((item) => /* @__PURE__ */ React__default["default"].createElement(FlexLayoutChildComponent, {
2860
+ key: item.state.key,
2861
+ item,
2862
+ direction,
2863
+ isEditing
2864
+ })));
2865
+ }
2866
+ function FlexLayoutChildComponent({
2867
+ item,
2868
+ direction,
2869
+ isEditing
2870
+ }) {
2871
+ const { placement } = item.useState();
2872
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2873
+ style: getItemStyles(direction, placement)
2874
+ }, /* @__PURE__ */ React__default["default"].createElement(item.Component, {
2875
+ model: item,
2876
+ isEditing
2877
+ }));
2878
+ }
2879
+ function getItemStyles(direction, layout = {}) {
2880
+ const { xSizing = "fill", ySizing = "fill" } = layout;
2881
+ const style = {
2882
+ display: "flex",
2883
+ flexDirection: direction,
2884
+ minWidth: layout.minWidth,
2885
+ minHeight: layout.minHeight,
2886
+ position: "relative"
2887
+ };
2888
+ if (direction === "column") {
2889
+ if (layout.height) {
2890
+ style.height = layout.height;
2891
+ } else {
2892
+ style.flexGrow = ySizing === "fill" ? 1 : 0;
2893
+ }
2894
+ if (layout.width) {
2895
+ style.width = layout.width;
2896
+ } else {
2897
+ style.alignSelf = xSizing === "fill" ? "stretch" : "flex-start";
2898
+ }
2899
+ } else {
2900
+ if (layout.height) {
2901
+ style.height = layout.height;
2902
+ } else {
2903
+ style.alignSelf = ySizing === "fill" ? "stretch" : "flex-start";
2904
+ }
2905
+ if (layout.width) {
2906
+ style.width = layout.width;
2907
+ } else {
2908
+ style.flexGrow = xSizing === "fill" ? 1 : 0;
2909
+ }
2910
+ }
2911
+ return style;
2912
+ }
2913
+ function FlexLayoutEditor({ model }) {
2914
+ const { direction = "row" } = model.useState();
2915
+ const options = [
2916
+ { icon: "arrow-right", value: "row" },
2917
+ { icon: "arrow-down", value: "column" }
2918
+ ];
2919
+ return /* @__PURE__ */ React__default["default"].createElement(ui.Field, {
2920
+ label: "Direction"
2921
+ }, /* @__PURE__ */ React__default["default"].createElement(ui.RadioButtonGroup, {
2922
+ options,
2923
+ value: direction,
2924
+ onChange: (value) => model.setState({ direction: value })
2925
+ }));
2926
+ }
2927
+
2928
+ const DEFAULT_PANEL_SPAN = 4;
2929
+ const GRID_CELL_HEIGHT = 30;
2930
+ const GRID_CELL_VMARGIN = 8;
2931
+ const GRID_COLUMN_COUNT = 24;
2932
+
2933
+ var __defProp$1 = Object.defineProperty;
2934
+ var __defProps$1 = Object.defineProperties;
2935
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2936
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2937
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2938
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2939
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2940
+ var __spreadValues$1 = (a, b) => {
2941
+ for (var prop in b || (b = {}))
2942
+ if (__hasOwnProp$1.call(b, prop))
2943
+ __defNormalProp$1(a, prop, b[prop]);
2944
+ if (__getOwnPropSymbols$1)
2945
+ for (var prop of __getOwnPropSymbols$1(b)) {
2946
+ if (__propIsEnum$1.call(b, prop))
2947
+ __defNormalProp$1(a, prop, b[prop]);
2948
+ }
2949
+ return a;
2950
+ };
2951
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2952
+ class SceneGridRow extends SceneObjectBase {
2953
+ constructor(state) {
2954
+ super(__spreadProps$1(__spreadValues$1({
2955
+ isCollapsible: true
2956
+ }, state), {
2957
+ placement: __spreadProps$1(__spreadValues$1({
2958
+ isResizable: false,
2959
+ isDraggable: true
2960
+ }, state.placement), {
2961
+ x: 0,
2962
+ height: 1,
2963
+ width: GRID_COLUMN_COUNT
2964
+ })
2965
+ }));
2966
+ this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: ["rowc"] });
2967
+ this.onCollapseToggle = () => {
2968
+ if (!this.state.isCollapsible) {
2969
+ return;
2970
+ }
2971
+ const layout = this.parent;
2972
+ if (!layout || !(layout instanceof SceneGridLayout)) {
2973
+ throw new Error("SceneGridRow must be a child of SceneGridLayout");
2974
+ }
2975
+ layout.toggleRow(this);
2976
+ };
2977
+ }
2978
+ getUrlState(state) {
2979
+ return { rowc: state.isCollapsed ? "1" : "0" };
2980
+ }
2981
+ updateFromUrl(values) {
2982
+ const isCollapsed = values.rowc === "1";
2983
+ if (isCollapsed !== this.state.isCollapsed) {
2984
+ this.onCollapseToggle();
2985
+ }
2986
+ }
2987
+ }
2988
+ SceneGridRow.Component = SceneGridRowRenderer;
2989
+ function SceneGridRowRenderer({ model }) {
2990
+ const styles = ui.useStyles2(getSceneGridRowStyles);
2991
+ const { isCollapsible, isCollapsed, title, placement } = model.useState();
2992
+ const layout = sceneGraph.getLayout(model);
2993
+ const dragHandle = /* @__PURE__ */ React__default["default"].createElement(SceneDragHandle, {
2994
+ layoutKey: layout.state.key
2995
+ });
2996
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
2997
+ className: styles.row
2998
+ }, /* @__PURE__ */ React__default["default"].createElement("div", {
2999
+ className: css.cx(styles.rowHeader, isCollapsed && styles.rowHeaderCollapsed)
3000
+ }, /* @__PURE__ */ React__default["default"].createElement("div", {
3001
+ onClick: model.onCollapseToggle,
3002
+ className: styles.rowTitleWrapper
3003
+ }, isCollapsible && /* @__PURE__ */ React__default["default"].createElement(ui.Icon, {
3004
+ name: isCollapsed ? "angle-right" : "angle-down"
3005
+ }), /* @__PURE__ */ React__default["default"].createElement("span", {
3006
+ className: styles.rowTitle
3007
+ }, title)), (placement == null ? void 0 : placement.isDraggable) && isCollapsed && /* @__PURE__ */ React__default["default"].createElement("div", null, dragHandle)));
3008
+ }
3009
+ const getSceneGridRowStyles = (theme) => {
3010
+ return {
3011
+ row: css.css({
3012
+ width: "100%",
3013
+ height: "100%",
3014
+ position: "relative",
3015
+ zIndex: 0,
3016
+ display: "flex",
3017
+ flexDirection: "column"
3018
+ }),
3019
+ rowHeader: css.css({
3020
+ width: "100%",
3021
+ height: "30px",
3022
+ display: "flex",
3023
+ justifyContent: "space-between",
3024
+ marginBottom: "8px",
3025
+ border: `1px solid transparent`
3026
+ }),
3027
+ rowTitleWrapper: css.css({
3028
+ display: "flex",
3029
+ alignItems: "center",
3030
+ cursor: "pointer"
3031
+ }),
3032
+ rowHeaderCollapsed: css.css({
3033
+ marginBottom: "0px",
3034
+ background: theme.colors.background.primary,
3035
+ border: `1px solid ${theme.colors.border.weak}`,
3036
+ borderRadius: theme.shape.borderRadius(1)
3037
+ }),
3038
+ rowTitle: css.css({
3039
+ fontSize: theme.typography.h6.fontSize,
3040
+ fontWeight: theme.typography.h6.fontWeight
3041
+ })
3042
+ };
3043
+ };
3044
+
3045
+ var __defProp = Object.defineProperty;
3046
+ var __defProps = Object.defineProperties;
3047
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
3048
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3049
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
3050
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
3051
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3052
+ var __spreadValues = (a, b) => {
3053
+ for (var prop in b || (b = {}))
3054
+ if (__hasOwnProp.call(b, prop))
3055
+ __defNormalProp(a, prop, b[prop]);
3056
+ if (__getOwnPropSymbols)
3057
+ for (var prop of __getOwnPropSymbols(b)) {
3058
+ if (__propIsEnum.call(b, prop))
3059
+ __defNormalProp(a, prop, b[prop]);
3060
+ }
3061
+ return a;
3062
+ };
3063
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3064
+ class SceneGridLayout extends SceneObjectBase {
3065
+ constructor(state) {
3066
+ super(__spreadProps(__spreadValues({}, state), {
3067
+ placement: __spreadValues({
3068
+ isDraggable: true
3069
+ }, state.placement),
3070
+ children: sortChildrenByPosition(state.children)
3071
+ }));
3072
+ this._skipOnLayoutChange = false;
3073
+ this.onLayoutChange = (layout) => {
3074
+ if (this._skipOnLayoutChange) {
3075
+ this._skipOnLayoutChange = false;
3076
+ return;
3077
+ }
3078
+ for (const item of layout) {
3079
+ const child = this.getSceneLayoutChild(item.i);
3080
+ const nextSize = {
3081
+ x: item.x,
3082
+ y: item.y,
3083
+ width: item.w,
3084
+ height: item.h
3085
+ };
3086
+ if (!isItemSizeEqual(child.state.placement, nextSize)) {
3087
+ child.setState({
3088
+ placement: __spreadValues(__spreadValues({}, child.state.placement), nextSize)
3089
+ });
3090
+ }
3091
+ }
3092
+ this.setState({ children: sortChildrenByPosition(this.state.children) });
3093
+ };
3094
+ this.onResizeStop = (_, o, n) => {
3095
+ const child = this.getSceneLayoutChild(n.i);
3096
+ child.setState({
3097
+ placement: __spreadProps(__spreadValues({}, child.state.placement), {
3098
+ width: n.w,
3099
+ height: n.h
3100
+ })
3101
+ });
3102
+ };
3103
+ this.onDragStop = (gridLayout, o, updatedItem) => {
3104
+ const sceneChild = this.getSceneLayoutChild(updatedItem.i);
3105
+ gridLayout = sortGridLayout(gridLayout);
3106
+ for (let i = 0; i < gridLayout.length; i++) {
3107
+ const gridItem = gridLayout[i];
3108
+ const child = this.getSceneLayoutChild(gridItem.i);
3109
+ const childSize = child.state.placement;
3110
+ if ((childSize == null ? void 0 : childSize.x) !== gridItem.x || (childSize == null ? void 0 : childSize.y) !== gridItem.y) {
3111
+ child.setState({
3112
+ placement: __spreadProps(__spreadValues({}, child.state.placement), {
3113
+ x: gridItem.x,
3114
+ y: gridItem.y
3115
+ })
3116
+ });
3117
+ }
3118
+ }
3119
+ const indexOfUpdatedItem = gridLayout.findIndex((item) => item.i === updatedItem.i);
3120
+ const newParent = this.findGridItemSceneParent(gridLayout, indexOfUpdatedItem - 1);
3121
+ let newChildren = this.state.children;
3122
+ if (newParent !== sceneChild.parent) {
3123
+ newChildren = this.moveChildTo(sceneChild, newParent);
3124
+ }
3125
+ this.setState({ children: sortChildrenByPosition(newChildren) });
3126
+ this._skipOnLayoutChange = true;
3127
+ };
3128
+ }
3129
+ toggleRow(row) {
3130
+ var _a, _b, _c, _d, _e, _f, _g;
3131
+ const isCollapsed = row.state.isCollapsed;
3132
+ if (!isCollapsed) {
3133
+ row.setState({ isCollapsed: true });
3134
+ this.setState({});
3135
+ return;
3136
+ }
3137
+ const rowChildren = row.state.children;
3138
+ if (rowChildren.length === 0) {
3139
+ row.setState({ isCollapsed: false });
3140
+ this.setState({});
3141
+ return;
3142
+ }
3143
+ const rowY = (_a = row.state.placement) == null ? void 0 : _a.y;
3144
+ const firstPanelYPos = (_c = (_b = rowChildren[0].state.placement) == null ? void 0 : _b.y) != null ? _c : rowY;
3145
+ const yDiff = firstPanelYPos - (rowY + 1);
3146
+ let yMax = rowY;
3147
+ for (const panel of rowChildren) {
3148
+ const newSize = __spreadValues({}, panel.state.placement);
3149
+ newSize.y = (_d = newSize.y) != null ? _d : rowY;
3150
+ newSize.y -= yDiff;
3151
+ if (newSize.y > ((_e = panel.state.placement) == null ? void 0 : _e.y)) {
3152
+ panel.setState({ placement: newSize });
3153
+ }
3154
+ yMax = Math.max(yMax, Number(newSize.y) + Number(newSize.height));
3155
+ }
3156
+ const pushDownAmount = yMax - rowY - 1;
3157
+ for (const child of this.state.children) {
3158
+ if (((_f = child.state.placement) == null ? void 0 : _f.y) > rowY) {
3159
+ this.pushChildDown(child, pushDownAmount);
3160
+ }
3161
+ if (child instanceof SceneGridRow && child !== row) {
3162
+ for (const rowChild of child.state.children) {
3163
+ if (((_g = rowChild.state.placement) == null ? void 0 : _g.y) > rowY) {
3164
+ this.pushChildDown(rowChild, pushDownAmount);
3165
+ }
3166
+ }
3167
+ }
3168
+ }
3169
+ row.setState({ isCollapsed: false });
3170
+ this.setState({});
3171
+ }
3172
+ getSceneLayoutChild(key) {
3173
+ for (const child of this.state.children) {
3174
+ if (child.state.key === key) {
3175
+ return child;
3176
+ }
3177
+ if (child instanceof SceneGridRow) {
3178
+ for (const rowChild of child.state.children) {
3179
+ if (rowChild.state.key === key) {
3180
+ return rowChild;
3181
+ }
3182
+ }
3183
+ }
3184
+ }
3185
+ throw new Error("Scene layout child not found for GridItem");
3186
+ }
3187
+ pushChildDown(child, amount) {
3188
+ var _a;
3189
+ child.setState({
3190
+ placement: __spreadProps(__spreadValues({}, child.state.placement), {
3191
+ y: ((_a = child.state.placement) == null ? void 0 : _a.y) + amount
3192
+ })
3193
+ });
3194
+ }
3195
+ findGridItemSceneParent(layout, startAt) {
3196
+ for (let i = startAt; i >= 0; i--) {
3197
+ const gridItem = layout[i];
3198
+ const sceneChild = this.getSceneLayoutChild(gridItem.i);
3199
+ if (sceneChild instanceof SceneGridRow) {
3200
+ if (sceneChild.state.isCollapsed) {
3201
+ return this;
3202
+ }
3203
+ return sceneChild;
3204
+ }
3205
+ }
3206
+ return this;
3207
+ }
3208
+ moveChildTo(child, target) {
3209
+ const currentParent = child.parent;
3210
+ let rootChildren = this.state.children;
3211
+ const newChild = child.clone({ key: child.state.key });
3212
+ if (currentParent instanceof SceneGridRow) {
3213
+ const newRow = currentParent.clone({
3214
+ children: currentParent.state.children.filter((c) => c.state.key !== child.state.key)
3215
+ });
3216
+ rootChildren = rootChildren.map((c) => c === currentParent ? newRow : c);
3217
+ if (target instanceof SceneGridRow) {
3218
+ const targetRow = target.clone({ children: [...target.state.children, newChild] });
3219
+ rootChildren = rootChildren.map((c) => c === target ? targetRow : c);
3220
+ } else {
3221
+ rootChildren = [...rootChildren, newChild];
3222
+ }
3223
+ } else {
3224
+ rootChildren = rootChildren.filter((c) => c.state.key !== child.state.key);
3225
+ const targetRow = target.clone({ children: [...target.state.children, newChild] });
3226
+ rootChildren = rootChildren.map((c) => c === target ? targetRow : c);
3227
+ }
3228
+ return rootChildren;
3229
+ }
3230
+ toGridCell(child) {
3231
+ var _a, _b, _c, _d;
3232
+ const size = child.state.placement;
3233
+ let x = (_a = size.x) != null ? _a : 0;
3234
+ let y = (_b = size.y) != null ? _b : 0;
3235
+ const w = Number.isInteger(Number(size.width)) ? Number(size.width) : DEFAULT_PANEL_SPAN;
3236
+ const h = Number.isInteger(Number(size.height)) ? Number(size.height) : DEFAULT_PANEL_SPAN;
3237
+ let isDraggable = Boolean((_c = child.state.placement) == null ? void 0 : _c.isDraggable);
3238
+ let isResizable = Boolean((_d = child.state.placement) == null ? void 0 : _d.isResizable);
3239
+ if (child instanceof SceneGridRow) {
3240
+ isDraggable = child.state.isCollapsed ? true : false;
3241
+ isResizable = false;
3242
+ }
3243
+ return { i: child.state.key, x, y, h, w, isResizable, isDraggable };
3244
+ }
3245
+ buildGridLayout(width) {
3246
+ let cells = [];
3247
+ for (const child of this.state.children) {
3248
+ cells.push(this.toGridCell(child));
3249
+ if (child instanceof SceneGridRow && !child.state.isCollapsed) {
3250
+ for (const rowChild of child.state.children) {
3251
+ cells.push(this.toGridCell(rowChild));
3252
+ }
3253
+ }
3254
+ }
3255
+ cells = sortGridLayout(cells);
3256
+ if (width < 768) {
3257
+ this._skipOnLayoutChange = true;
3258
+ return cells.map((cell) => __spreadProps(__spreadValues({}, cell), { w: 24 }));
3259
+ }
3260
+ this._skipOnLayoutChange = false;
3261
+ return cells;
3262
+ }
3263
+ }
3264
+ SceneGridLayout.Component = SceneGridLayoutRenderer;
3265
+ function SceneGridLayoutRenderer({ model }) {
3266
+ const { children } = model.useState();
3267
+ validateChildrenSize(children);
3268
+ return /* @__PURE__ */ React__default["default"].createElement(AutoSizer__default["default"], {
3269
+ disableHeight: true
3270
+ }, ({ width }) => {
3271
+ if (width === 0) {
3272
+ return null;
3273
+ }
3274
+ const layout = model.buildGridLayout(width);
3275
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
3276
+ style: { width: `${width}px`, height: "100%" }
3277
+ }, /* @__PURE__ */ React__default["default"].createElement(ReactGridLayout__default["default"], {
3278
+ width,
3279
+ isDraggable: width > 768,
3280
+ isResizable: false,
3281
+ containerPadding: [0, 0],
3282
+ useCSSTransforms: false,
3283
+ margin: [GRID_CELL_VMARGIN, GRID_CELL_VMARGIN],
3284
+ cols: GRID_COLUMN_COUNT,
3285
+ rowHeight: GRID_CELL_HEIGHT,
3286
+ draggableHandle: `.grid-drag-handle-${model.state.key}`,
3287
+ layout,
3288
+ onDragStop: model.onDragStop,
3289
+ onResizeStop: model.onResizeStop,
3290
+ onLayoutChange: model.onLayoutChange,
3291
+ isBounded: false
3292
+ }, layout.map((gridItem) => {
3293
+ const sceneChild = model.getSceneLayoutChild(gridItem.i);
3294
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
3295
+ key: sceneChild.state.key,
3296
+ style: { display: "flex" }
3297
+ }, /* @__PURE__ */ React__default["default"].createElement(sceneChild.Component, {
3298
+ model: sceneChild,
3299
+ key: sceneChild.state.key
3300
+ }));
3301
+ })));
3302
+ });
3303
+ }
3304
+ function validateChildrenSize(children) {
3305
+ if (children.find(
3306
+ (c) => !c.state.placement || c.state.placement.height === void 0 || c.state.placement.width === void 0 || c.state.placement.x === void 0 || c.state.placement.y === void 0
3307
+ )) {
3308
+ throw new Error("All children must have a size specified");
3309
+ }
3310
+ }
3311
+ function isItemSizeEqual(a, b) {
3312
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
3313
+ }
3314
+ function sortChildrenByPosition(children) {
3315
+ return [...children].sort((a, b) => {
3316
+ var _a, _b, _c, _d;
3317
+ return ((_a = a.state.placement) == null ? void 0 : _a.y) - ((_b = b.state.placement) == null ? void 0 : _b.y) || ((_c = a.state.placement) == null ? void 0 : _c.x) - ((_d = b.state.placement) == null ? void 0 : _d.x);
3318
+ });
3319
+ }
3320
+ function sortGridLayout(layout) {
3321
+ return [...layout].sort((a, b) => a.y - b.y || a.x - b.x);
3322
+ }
3323
+
3324
+ exports.ConstantVariable = ConstantVariable;
3325
+ exports.CustomVariable = CustomVariable;
3326
+ exports.DataSourceVariable = DataSourceVariable;
3327
+ exports.EmbeddedScene = EmbeddedScene;
3328
+ exports.FormatRegistryID = FormatRegistryID;
3329
+ exports.NestedScene = NestedScene;
3330
+ exports.QueryVariable = QueryVariable;
3331
+ exports.SceneCanvasText = SceneCanvasText;
3332
+ exports.SceneDataNode = SceneDataNode;
3333
+ exports.SceneDataTransformer = SceneDataTransformer;
3334
+ exports.SceneFlexLayout = SceneFlexLayout;
3335
+ exports.SceneGridLayout = SceneGridLayout;
3336
+ exports.SceneGridRow = SceneGridRow;
3337
+ exports.SceneObjectBase = SceneObjectBase;
3338
+ exports.SceneObjectStateChangedEvent = SceneObjectStateChangedEvent;
3339
+ exports.SceneObjectUrlSyncConfig = SceneObjectUrlSyncConfig;
3340
+ exports.ScenePanelRepeater = ScenePanelRepeater;
3341
+ exports.SceneQueryRunner = SceneQueryRunner;
3342
+ exports.SceneSubMenu = SceneSubMenu;
3343
+ exports.SceneTimePicker = SceneTimePicker;
3344
+ exports.SceneTimeRange = SceneTimeRange;
3345
+ exports.SceneToolbarButton = SceneToolbarButton;
3346
+ exports.SceneToolbarInput = SceneToolbarInput;
3347
+ exports.SceneVariableSet = SceneVariableSet;
3348
+ exports.SceneVariableValueChangedEvent = SceneVariableValueChangedEvent;
3349
+ exports.TestVariable = TestVariable;
3350
+ exports.UrlSyncManager = UrlSyncManager;
3351
+ exports.VariableValueSelectors = VariableValueSelectors;
3352
+ exports.VizPanel = VizPanel;
3353
+ exports.formatRegistry = formatRegistry;
3354
+ exports.isSceneObject = isSceneObject;
3355
+ exports.sceneGraph = sceneGraph;
3356
+ //# sourceMappingURL=index.js.map