@grafana/scenes 4.26.3--canary.765.9399849393.0 → 4.26.3

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -586,22 +586,103 @@ function registerRuntimeDataSource({ dataSource }) {
586
586
  runtimeDataSources.set(dataSource.uid, dataSource);
587
587
  }
588
588
 
589
- function lookupVariable(name, sceneObject) {
590
- const variables = sceneObject.state.$variables;
591
- if (!variables) {
592
- if (sceneObject.parent) {
593
- return lookupVariable(name, sceneObject.parent);
594
- } else {
595
- return null;
589
+ class UniqueUrlKeyMapper {
590
+ constructor() {
591
+ this.index = /* @__PURE__ */ new Map();
592
+ }
593
+ getUniqueKey(key, obj) {
594
+ const objectsWithKey = this.index.get(key);
595
+ if (!objectsWithKey) {
596
+ throw new Error("Cannot find any scene object that uses the key '" + key + "'");
597
+ }
598
+ const address = objectsWithKey.findIndex((o) => o.sceneObject === obj);
599
+ if (address > 0) {
600
+ return `${key}-${address + 1}`;
596
601
  }
602
+ return key;
597
603
  }
598
- const found = variables.getByName(name);
599
- if (found) {
600
- return found;
601
- } else if (sceneObject.parent) {
602
- return lookupVariable(name, sceneObject.parent);
604
+ rebuildIndex(root) {
605
+ this.index.clear();
606
+ this.buildIndex(root, 0);
607
+ }
608
+ buildIndex(sceneObject, depth) {
609
+ if (sceneObject.urlSync) {
610
+ for (const key of sceneObject.urlSync.getKeys()) {
611
+ const hit = this.index.get(key);
612
+ if (hit) {
613
+ hit.push({ sceneObject, depth });
614
+ hit.sort((a, b) => a.depth - b.depth);
615
+ } else {
616
+ this.index.set(key, [{ sceneObject, depth }]);
617
+ }
618
+ }
619
+ }
620
+ sceneObject.forEachChild((child) => this.buildIndex(child, depth + 1));
603
621
  }
604
- return null;
622
+ }
623
+
624
+ function getUrlState(root) {
625
+ const urlKeyMapper = new UniqueUrlKeyMapper();
626
+ urlKeyMapper.rebuildIndex(root);
627
+ const result = {};
628
+ const visitNode = (obj) => {
629
+ if (obj.urlSync) {
630
+ const newUrlState = obj.urlSync.getUrlState();
631
+ for (const [key, value] of Object.entries(newUrlState)) {
632
+ if (value != null) {
633
+ const uniqueKey = urlKeyMapper.getUniqueKey(key, obj);
634
+ result[uniqueKey] = value;
635
+ }
636
+ }
637
+ }
638
+ obj.forEachChild(visitNode);
639
+ };
640
+ visitNode(root);
641
+ return result;
642
+ }
643
+ function syncStateFromSearchParams(root, urlParams) {
644
+ const urlKeyMapper = new UniqueUrlKeyMapper();
645
+ urlKeyMapper.rebuildIndex(root);
646
+ syncStateFromUrl(root, urlParams, urlKeyMapper);
647
+ }
648
+ function syncStateFromUrl(sceneObject, urlParams, urlKeyMapper) {
649
+ if (sceneObject.urlSync) {
650
+ const urlState = {};
651
+ const currentState = sceneObject.urlSync.getUrlState();
652
+ for (const key of sceneObject.urlSync.getKeys()) {
653
+ const uniqueKey = urlKeyMapper.getUniqueKey(key, sceneObject);
654
+ const newValue = urlParams.getAll(uniqueKey);
655
+ const currentValue = currentState[key];
656
+ if (isUrlValueEqual(newValue, currentValue)) {
657
+ continue;
658
+ }
659
+ if (newValue.length > 0) {
660
+ if (Array.isArray(currentValue)) {
661
+ urlState[key] = newValue;
662
+ } else {
663
+ urlState[key] = newValue[0];
664
+ }
665
+ } else {
666
+ urlState[key] = null;
667
+ }
668
+ }
669
+ if (Object.keys(urlState).length > 0) {
670
+ sceneObject.urlSync.updateFromUrl(urlState);
671
+ }
672
+ }
673
+ sceneObject.forEachChild((child) => syncStateFromUrl(child, urlParams, urlKeyMapper));
674
+ }
675
+ function isUrlValueEqual(currentUrlValue, newUrlValue) {
676
+ if (currentUrlValue.length === 0 && newUrlValue == null) {
677
+ return true;
678
+ }
679
+ if (!Array.isArray(newUrlValue) && (currentUrlValue == null ? void 0 : currentUrlValue.length) === 1) {
680
+ return newUrlValue === currentUrlValue[0];
681
+ }
682
+ if ((newUrlValue == null ? void 0 : newUrlValue.length) === 0 && currentUrlValue === null) {
683
+ return true;
684
+ }
685
+ return lodash.isEqual(currentUrlValue, newUrlValue);
605
686
  }
606
687
 
607
688
  var __defProp$F = Object.defineProperty;
@@ -1233,712 +1314,730 @@ function sqlStringFormatter(value) {
1233
1314
  })}'`;
1234
1315
  }
1235
1316
 
1236
- class SkipFormattingValue {
1237
- constructor(_value) {
1238
- this._value = _value;
1317
+ function lookupVariable(name, sceneObject) {
1318
+ const variables = sceneObject.state.$variables;
1319
+ if (!variables) {
1320
+ if (sceneObject.parent) {
1321
+ return lookupVariable(name, sceneObject.parent);
1322
+ } else {
1323
+ return null;
1324
+ }
1239
1325
  }
1240
- formatter() {
1241
- return this._value;
1326
+ const found = variables.getByName(name);
1327
+ if (found) {
1328
+ return found;
1329
+ } else if (sceneObject.parent) {
1330
+ return lookupVariable(name, sceneObject.parent);
1242
1331
  }
1332
+ return null;
1243
1333
  }
1244
1334
 
1245
- class UrlTimeRangeMacro {
1246
- constructor(name, sceneObject) {
1247
- this.state = { name, type: "url_variable" };
1248
- this._sceneObject = sceneObject;
1249
- }
1250
- getValue() {
1251
- var _a;
1252
- const timeRange = getTimeRange(this._sceneObject);
1253
- const urlState = (_a = timeRange.urlSync) == null ? void 0 : _a.getUrlState();
1254
- return new SkipFormattingValue(data.urlUtil.toUrlParams(urlState));
1255
- }
1256
- getValueText() {
1257
- return "";
1258
- }
1259
- }
1260
- class TimeFromAndToMacro {
1261
- constructor(name, sceneObject) {
1262
- this.state = { name, type: "time_macro" };
1263
- this._sceneObject = sceneObject;
1335
+ function sceneInterpolator(sceneObject, target, scopedVars, format, interpolations) {
1336
+ if (!target) {
1337
+ return target != null ? target : "";
1264
1338
  }
1265
- getValue() {
1266
- const timeRange = getTimeRange(this._sceneObject);
1267
- if (this.state.name === "__from") {
1268
- return timeRange.state.value.from.valueOf();
1269
- } else {
1270
- return timeRange.state.value.to.valueOf();
1339
+ VARIABLE_REGEX.lastIndex = 0;
1340
+ return target.replace(VARIABLE_REGEX, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
1341
+ const variableName = var1 || var2 || var3;
1342
+ const fmt = fmt2 || fmt3 || format;
1343
+ const variable = lookupFormatVariable(variableName, match, scopedVars, sceneObject);
1344
+ if (!variable) {
1345
+ if (interpolations) {
1346
+ interpolations.push({ match, variableName, fieldPath, format: fmt, value: match, found: false });
1347
+ }
1348
+ return match;
1271
1349
  }
1272
- }
1273
- getValueText() {
1274
- const timeRange = getTimeRange(this._sceneObject);
1275
- if (this.state.name === "__from") {
1276
- return data.dateTimeFormat(timeRange.state.value.from, { timeZone: timeRange.getTimeZone() });
1277
- } else {
1278
- return data.dateTimeFormat(timeRange.state.value.to, { timeZone: timeRange.getTimeZone() });
1350
+ const value = formatValue(sceneObject, variable, variable.getValue(fieldPath), fmt);
1351
+ if (interpolations) {
1352
+ interpolations.push({ match, variableName, fieldPath, format: fmt, value, found: value !== match });
1279
1353
  }
1280
- }
1354
+ return value;
1355
+ });
1281
1356
  }
1282
- class TimezoneMacro {
1283
- constructor(name, sceneObject) {
1284
- this.state = { name, type: "time_macro" };
1285
- this._sceneObject = sceneObject;
1357
+ function lookupFormatVariable(name, match, scopedVars, sceneObject) {
1358
+ const scopedVar = scopedVars == null ? void 0 : scopedVars[name];
1359
+ if (scopedVar) {
1360
+ return getSceneVariableForScopedVar(name, scopedVar);
1286
1361
  }
1287
- getValue() {
1288
- const timeRange = getTimeRange(this._sceneObject);
1289
- const timeZone = timeRange.getTimeZone();
1290
- if (timeZone === "browser") {
1291
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
1292
- }
1293
- return timeZone;
1362
+ const variable = lookupVariable(name, sceneObject);
1363
+ if (variable) {
1364
+ return variable;
1294
1365
  }
1295
- getValueText() {
1296
- return this.getValue();
1366
+ if (macrosIndex[name]) {
1367
+ return new macrosIndex[name](name, sceneObject, match, scopedVars);
1297
1368
  }
1369
+ return null;
1298
1370
  }
1299
- class IntervalMacro {
1300
- constructor(name, sceneObject, match) {
1301
- this.state = { name, type: "time_macro", match };
1302
- this._sceneObject = sceneObject;
1371
+ function formatValue(context, variable, value, formatNameOrFn) {
1372
+ if (value === null || value === void 0) {
1373
+ return "";
1303
1374
  }
1304
- getValue() {
1305
- var _a;
1306
- const data = getData(this._sceneObject);
1307
- if (data) {
1308
- const request = (_a = data.state.data) == null ? void 0 : _a.request;
1309
- if (!request) {
1310
- return this.state.match;
1311
- }
1312
- if (this.state.name === "__interval_ms") {
1313
- return request.intervalMs;
1314
- }
1315
- return request.interval;
1316
- }
1317
- return this.state.match;
1375
+ if (isCustomVariableValue(value)) {
1376
+ return sceneInterpolator(context, value.formatter(formatNameOrFn));
1318
1377
  }
1319
- }
1320
-
1321
- class AllVariablesMacro {
1322
- constructor(name, sceneObject) {
1323
- this.state = { name, type: "url_variable" };
1324
- this._sceneObject = sceneObject;
1378
+ if (!Array.isArray(value) && typeof value === "object") {
1379
+ value = `${value}`;
1325
1380
  }
1326
- getValue() {
1327
- const allVars = collectAllVariables(this._sceneObject);
1328
- const format = formatRegistry.get(schema.VariableFormatID.QueryParam);
1329
- const params = [];
1330
- for (const name of Object.keys(allVars)) {
1331
- const variable = allVars[name];
1332
- const value = variable.getValue();
1333
- if (!value) {
1334
- continue;
1335
- }
1336
- if (isCustomVariableValue(value)) {
1337
- params.push(value.formatter(schema.VariableFormatID.QueryParam));
1338
- } else {
1339
- params.push(format.formatter(value, [], variable));
1340
- }
1381
+ if (typeof formatNameOrFn === "function") {
1382
+ return formatNameOrFn(value, {
1383
+ name: variable.state.name,
1384
+ type: variable.state.type,
1385
+ multi: variable.state.isMulti,
1386
+ includeAll: variable.state.includeAll
1387
+ });
1388
+ }
1389
+ let args = [];
1390
+ if (!formatNameOrFn) {
1391
+ formatNameOrFn = schema.VariableFormatID.Glob;
1392
+ } else {
1393
+ args = formatNameOrFn.split(":");
1394
+ if (args.length > 1) {
1395
+ formatNameOrFn = args[0];
1396
+ args = args.slice(1);
1397
+ } else {
1398
+ args = [];
1341
1399
  }
1342
- return new SkipFormattingValue(params.join("&"));
1343
1400
  }
1344
- getValueText() {
1345
- return "";
1401
+ let formatter = formatRegistry.getIfExists(formatNameOrFn);
1402
+ if (!formatter) {
1403
+ console.error(`Variable format ${formatNameOrFn} not found. Using glob format as fallback.`);
1404
+ formatter = formatRegistry.get(schema.VariableFormatID.Glob);
1346
1405
  }
1406
+ return formatter.formatter(value, args, variable);
1347
1407
  }
1348
- function collectAllVariables(sceneObject, record = {}) {
1349
- if (sceneObject.state.$variables) {
1350
- for (const variable of sceneObject.state.$variables.state.variables) {
1351
- if (variable.state.skipUrlSync) {
1352
- continue;
1353
- }
1354
- if (!record[variable.state.name]) {
1355
- record[variable.state.name] = variable;
1356
- }
1357
- }
1358
- }
1359
- if (sceneObject.parent) {
1360
- collectAllVariables(sceneObject.parent, record);
1361
- }
1362
- return record;
1408
+
1409
+ function isSceneObject(obj) {
1410
+ return obj.useState !== void 0;
1411
+ }
1412
+ function isDataRequestEnricher(obj) {
1413
+ return "enrichDataRequest" in obj;
1414
+ }
1415
+ function isDataLayer(obj) {
1416
+ return "isDataLayer" in obj;
1363
1417
  }
1364
1418
 
1365
- var __defProp$D = Object.defineProperty;
1366
- var __defProps$r = Object.defineProperties;
1367
- var __getOwnPropDescs$r = Object.getOwnPropertyDescriptors;
1368
- var __getOwnPropSymbols$D = Object.getOwnPropertySymbols;
1369
- var __hasOwnProp$D = Object.prototype.hasOwnProperty;
1370
- var __propIsEnum$D = Object.prototype.propertyIsEnumerable;
1371
- var __defNormalProp$D = (obj, key, value) => key in obj ? __defProp$D(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1372
- var __spreadValues$D = (a, b) => {
1373
- for (var prop in b || (b = {}))
1374
- if (__hasOwnProp$D.call(b, prop))
1375
- __defNormalProp$D(a, prop, b[prop]);
1376
- if (__getOwnPropSymbols$D)
1377
- for (var prop of __getOwnPropSymbols$D(b)) {
1378
- if (__propIsEnum$D.call(b, prop))
1379
- __defNormalProp$D(a, prop, b[prop]);
1380
- }
1381
- return a;
1419
+ var __accessCheck = (obj, member, msg) => {
1420
+ if (!member.has(obj))
1421
+ throw TypeError("Cannot " + msg);
1382
1422
  };
1383
- var __spreadProps$r = (a, b) => __defProps$r(a, __getOwnPropDescs$r(b));
1384
- function getTemplateProxyForField(field, frame, frames) {
1385
- return new Proxy(
1386
- {},
1387
- {
1388
- get: (obj, key) => {
1389
- if (key === "name") {
1390
- return field.name;
1391
- }
1392
- if (key === "displayName") {
1393
- return data.getFieldDisplayName(field, frame, frames);
1394
- }
1395
- if (key === "labels" || key === "formattedLabels") {
1396
- if (!field.labels) {
1397
- return "";
1398
- }
1399
- return __spreadProps$r(__spreadValues$D({}, field.labels), {
1400
- __values: Object.values(field.labels).sort().join(", "),
1401
- toString: () => {
1402
- return data.formatLabels(field.labels, "", true);
1403
- }
1404
- });
1405
- }
1406
- return void 0;
1407
- }
1408
- }
1409
- );
1423
+ var __privateGet = (obj, member, getter) => {
1424
+ __accessCheck(obj, member, "read from private field");
1425
+ return getter ? getter.call(obj) : member.get(obj);
1426
+ };
1427
+ var __privateAdd = (obj, member, value) => {
1428
+ if (member.has(obj))
1429
+ throw TypeError("Cannot add the same private member more than once");
1430
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1431
+ };
1432
+ var _running;
1433
+ function isQueryController(s) {
1434
+ return "isQueryController" in s;
1410
1435
  }
1411
-
1412
- class ValueMacro {
1413
- constructor(name, sceneObject, _match, _scopedVars) {
1414
- this._match = _match;
1415
- this._scopedVars = _scopedVars;
1416
- this.state = { name, type: "__value" };
1436
+ class SceneQueryController extends SceneObjectBase {
1437
+ constructor() {
1438
+ super({ isRunning: false });
1439
+ this.isQueryController = true;
1440
+ __privateAdd(this, _running, /* @__PURE__ */ new Set());
1441
+ this.addActivationHandler(() => {
1442
+ return () => __privateGet(this, _running).clear();
1443
+ });
1417
1444
  }
1418
- getValue(fieldPath) {
1419
- var _a, _b;
1420
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1421
- if (!dataContext) {
1422
- return this._match;
1423
- }
1424
- const { frame, rowIndex, field, calculatedValue } = dataContext.value;
1425
- if (calculatedValue) {
1426
- switch (fieldPath) {
1427
- case "numeric":
1428
- return calculatedValue.numeric;
1429
- case "raw":
1430
- return calculatedValue.numeric;
1431
- case "time":
1432
- return "";
1433
- case "text":
1434
- default:
1435
- return data.formattedValueToString(calculatedValue);
1436
- }
1437
- }
1438
- if (rowIndex == null) {
1439
- return this._match;
1440
- }
1441
- if (fieldPath === "time") {
1442
- const timeField = frame.fields.find((f) => f.type === data.FieldType.time);
1443
- return timeField ? timeField.values.get(rowIndex) : void 0;
1444
- }
1445
- if (!field) {
1446
- return this._match;
1445
+ queryStarted(entry) {
1446
+ __privateGet(this, _running).add(entry);
1447
+ this.changeRunningQueryCount(1);
1448
+ if (!this.state.isRunning) {
1449
+ this.setState({ isRunning: true });
1447
1450
  }
1448
- const value = field.values.get(rowIndex);
1449
- if (fieldPath === "raw") {
1450
- return value;
1451
+ }
1452
+ queryCompleted(entry) {
1453
+ if (!__privateGet(this, _running).has(entry)) {
1454
+ return;
1451
1455
  }
1452
- const displayProcessor = (_b = field.display) != null ? _b : fallbackDisplayProcessor;
1453
- const result = displayProcessor(value);
1454
- switch (fieldPath) {
1455
- case "numeric":
1456
- return result.numeric;
1457
- case "text":
1458
- default:
1459
- return data.formattedValueToString(result);
1456
+ __privateGet(this, _running).delete(entry);
1457
+ this.changeRunningQueryCount(-1);
1458
+ if (__privateGet(this, _running).size === 0) {
1459
+ this.setState({ isRunning: false });
1460
1460
  }
1461
1461
  }
1462
- getValueText() {
1463
- return "";
1464
- }
1465
- }
1466
- const fallbackDisplayProcessor = data.getDisplayProcessor();
1467
- class DataMacro {
1468
- constructor(name, sceneObject, _match, _scopedVars) {
1469
- this._match = _match;
1470
- this._scopedVars = _scopedVars;
1471
- this.state = { name, type: "__data" };
1462
+ changeRunningQueryCount(dir) {
1463
+ var _a;
1464
+ window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1472
1465
  }
1473
- getValue(fieldPath) {
1474
- var _a, _b;
1475
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1476
- if (!dataContext || !fieldPath) {
1477
- return this._match;
1478
- }
1479
- const { frame, rowIndex } = dataContext.value;
1480
- if (rowIndex === void 0 || fieldPath === void 0) {
1481
- return this._match;
1466
+ cancelAll() {
1467
+ var _a;
1468
+ for (const entry of __privateGet(this, _running).values()) {
1469
+ (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1482
1470
  }
1483
- const obj = {
1484
- name: frame.name,
1485
- refId: frame.refId,
1486
- fields: data.getFieldDisplayValuesProxy({ frame, rowIndex })
1487
- };
1488
- return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1489
1471
  }
1490
- getValueText() {
1472
+ }
1473
+ _running = new WeakMap();
1474
+
1475
+ function getVariables(sceneObject) {
1476
+ var _a;
1477
+ return (_a = getClosest(sceneObject, (s) => s.state.$variables)) != null ? _a : EmptyVariableSet;
1478
+ }
1479
+ function getData(sceneObject) {
1480
+ var _a;
1481
+ return (_a = getClosest(sceneObject, (s) => s.state.$data)) != null ? _a : EmptyDataNode;
1482
+ }
1483
+ function isSceneLayout(s) {
1484
+ return "isDraggable" in s;
1485
+ }
1486
+ function getLayout(scene) {
1487
+ const parent = getClosest(scene, (s) => isSceneLayout(s) ? s : void 0);
1488
+ if (parent) {
1489
+ return parent;
1490
+ }
1491
+ return null;
1492
+ }
1493
+ function interpolate(sceneObject, value, scopedVars, format, interpolations) {
1494
+ if (value === "" || value == null) {
1491
1495
  return "";
1492
1496
  }
1497
+ return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1493
1498
  }
1494
- class SeriesMacro {
1495
- constructor(name, sceneObject, _match, _scopedVars) {
1496
- this._match = _match;
1497
- this._scopedVars = _scopedVars;
1498
- this.state = { name, type: "__series" };
1499
+ function hasVariableDependencyInLoadingState(sceneObject) {
1500
+ if (!sceneObject.variableDependency) {
1501
+ return false;
1499
1502
  }
1500
- getValue(fieldPath) {
1501
- var _a;
1502
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1503
- if (!dataContext || !fieldPath) {
1504
- return this._match;
1503
+ for (const name of sceneObject.variableDependency.getNames()) {
1504
+ const variable = lookupVariable(name, sceneObject);
1505
+ if (!variable) {
1506
+ continue;
1505
1507
  }
1506
- if (fieldPath !== "name") {
1507
- return this._match;
1508
+ const set = variable.parent;
1509
+ if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1510
+ return true;
1508
1511
  }
1509
- const { frame, frameIndex } = dataContext.value;
1510
- return data.getFrameDisplayName(frame, frameIndex);
1511
- }
1512
- getValueText() {
1513
- return "";
1514
1512
  }
1513
+ return false;
1515
1514
  }
1516
- class FieldMacro {
1517
- constructor(name, sceneObject, _match, _scopedVars) {
1518
- this._match = _match;
1519
- this._scopedVars = _scopedVars;
1520
- this.state = { name, type: "__field" };
1515
+ function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1516
+ if (check(scene)) {
1517
+ return scene;
1521
1518
  }
1522
- getValue(fieldPath) {
1523
- var _a, _b;
1524
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1525
- if (!dataContext || !fieldPath) {
1526
- return this._match;
1519
+ let found = null;
1520
+ scene.forEachChild((child) => {
1521
+ if (child === alreadySearchedChild) {
1522
+ return;
1527
1523
  }
1528
- if (fieldPath === void 0 || fieldPath === "") {
1529
- return this._match;
1524
+ let maybe = findObjectInternal(child, check);
1525
+ if (maybe) {
1526
+ found = maybe;
1530
1527
  }
1531
- const { frame, field, data } = dataContext.value;
1532
- const obj = getTemplateProxyForField(field, frame, data);
1533
- return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1528
+ });
1529
+ if (found) {
1530
+ return found;
1534
1531
  }
1535
- getValueText() {
1536
- return "";
1532
+ if (shouldSearchUp && scene.parent) {
1533
+ return findObjectInternal(scene.parent, check, scene, true);
1537
1534
  }
1535
+ return null;
1538
1536
  }
1539
-
1540
- class UrlMacro {
1541
- constructor(name, _) {
1542
- this.state = { name, type: "url_macro" };
1537
+ function findByKey(sceneObject, key) {
1538
+ const found = findObject(sceneObject, (sceneToCheck) => {
1539
+ return sceneToCheck.state.key === key;
1540
+ });
1541
+ if (!found) {
1542
+ throw new Error("Unable to find scene with key " + key);
1543
1543
  }
1544
- getValue(fieldPath) {
1545
- var _a;
1546
- const location = runtime.locationService.getLocation();
1547
- const subUrl = (_a = runtime.config.appSubUrl) != null ? _a : "";
1548
- switch (fieldPath != null ? fieldPath : "") {
1549
- case "params":
1550
- return new UrlStateFormatter(location.search);
1551
- case "path":
1552
- return subUrl + location.pathname;
1553
- case "":
1554
- default:
1555
- return subUrl + location.pathname + location.search;
1556
- }
1544
+ return found;
1545
+ }
1546
+ function findByKeyAndType(sceneObject, key, targetType) {
1547
+ const found = findObject(sceneObject, (sceneToCheck) => {
1548
+ return sceneToCheck.state.key === key;
1549
+ });
1550
+ if (!found) {
1551
+ throw new Error("Unable to find scene with key " + key);
1557
1552
  }
1558
- getValueText() {
1559
- return "";
1553
+ if (!(found instanceof targetType)) {
1554
+ throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1560
1555
  }
1556
+ return found;
1561
1557
  }
1562
- class UrlStateFormatter {
1563
- constructor(_urlQueryParams) {
1564
- this._urlQueryParams = _urlQueryParams;
1565
- }
1566
- formatter(options) {
1567
- if (!options) {
1568
- return this._urlQueryParams;
1558
+ function findObject(scene, check) {
1559
+ return findObjectInternal(scene, check, void 0, true);
1560
+ }
1561
+ function findAllObjects(scene, check) {
1562
+ const found = [];
1563
+ scene.forEachChild((child) => {
1564
+ if (check(child)) {
1565
+ found.push(child);
1569
1566
  }
1570
- const params = options.split(":");
1571
- if (params[0] === "exclude" && params.length > 1) {
1572
- const allParams = new URLSearchParams(this._urlQueryParams);
1573
- for (const param of params[1].split(",")) {
1574
- allParams.delete(param);
1567
+ found.push(...findAllObjects(child, check));
1568
+ });
1569
+ return found;
1570
+ }
1571
+ function getDataLayers(sceneObject, localOnly = false) {
1572
+ let currentLevel = sceneObject;
1573
+ let collected = [];
1574
+ while (currentLevel) {
1575
+ const dataProvider = currentLevel.state.$data;
1576
+ if (!dataProvider) {
1577
+ currentLevel = currentLevel.parent;
1578
+ continue;
1579
+ }
1580
+ if (isDataLayer(dataProvider)) {
1581
+ collected = collected.concat(dataProvider);
1582
+ } else {
1583
+ if (dataProvider.state.$data && isDataLayer(dataProvider.state.$data)) {
1584
+ collected = collected.concat(dataProvider.state.$data);
1575
1585
  }
1576
- return `?${allParams}`;
1577
1586
  }
1578
- if (params[0] === "include" && params.length > 1) {
1579
- const allParams = new URLSearchParams(this._urlQueryParams);
1580
- const includeOnly = params[1].split(",");
1581
- for (const param of allParams.keys()) {
1582
- if (!includeOnly.includes(param)) {
1583
- allParams.delete(param);
1587
+ if (localOnly && collected.length > 0) {
1588
+ break;
1589
+ }
1590
+ currentLevel = currentLevel.parent;
1591
+ }
1592
+ return collected;
1593
+ }
1594
+ function getAncestor(sceneObject, ancestorType) {
1595
+ let parent = sceneObject;
1596
+ while (parent) {
1597
+ if (parent instanceof ancestorType) {
1598
+ return parent;
1599
+ }
1600
+ parent = parent.parent;
1601
+ }
1602
+ if (!parent) {
1603
+ throw new Error("Unable to find parent of type " + ancestorType.name);
1604
+ }
1605
+ return parent;
1606
+ }
1607
+ function getQueryController(sceneObject) {
1608
+ let parent = sceneObject;
1609
+ while (parent) {
1610
+ if (parent.state.$behaviors) {
1611
+ for (const behavior of parent.state.$behaviors) {
1612
+ if (isQueryController(behavior)) {
1613
+ return behavior;
1584
1614
  }
1585
1615
  }
1586
- return `?${allParams}`;
1587
1616
  }
1588
- return this._urlQueryParams;
1617
+ parent = parent.parent;
1589
1618
  }
1619
+ return void 0;
1590
1620
  }
1591
1621
 
1592
- class UserMacro {
1593
- constructor(name, _) {
1594
- this.state = { name, type: "user_macro" };
1622
+ class SkipFormattingValue {
1623
+ constructor(_value) {
1624
+ this._value = _value;
1595
1625
  }
1596
- getValue(fieldPath) {
1597
- const user = runtime.config.bootData.user;
1598
- switch (fieldPath) {
1599
- case "login":
1600
- return user.login;
1601
- case "email":
1602
- return user.email;
1603
- case "id":
1604
- default:
1605
- return String(user.id);
1606
- }
1626
+ formatter() {
1627
+ return this._value;
1628
+ }
1629
+ }
1630
+
1631
+ class UrlTimeRangeMacro {
1632
+ constructor(name, sceneObject) {
1633
+ this.state = { name, type: "url_variable" };
1634
+ this._sceneObject = sceneObject;
1635
+ }
1636
+ getValue() {
1637
+ var _a;
1638
+ const timeRange = getTimeRange(this._sceneObject);
1639
+ const urlState = (_a = timeRange.urlSync) == null ? void 0 : _a.getUrlState();
1640
+ return new SkipFormattingValue(data.urlUtil.toUrlParams(urlState));
1607
1641
  }
1608
1642
  getValueText() {
1609
1643
  return "";
1610
1644
  }
1611
1645
  }
1612
- class OrgMacro {
1613
- constructor(name, _) {
1614
- this.state = { name, type: "org_macro" };
1646
+ class TimeFromAndToMacro {
1647
+ constructor(name, sceneObject) {
1648
+ this.state = { name, type: "time_macro" };
1649
+ this._sceneObject = sceneObject;
1615
1650
  }
1616
- getValue(fieldPath) {
1617
- const user = runtime.config.bootData.user;
1618
- switch (fieldPath) {
1619
- case "name":
1620
- return user.orgName;
1621
- case "id":
1622
- default:
1623
- return String(user.orgId);
1651
+ getValue() {
1652
+ const timeRange = getTimeRange(this._sceneObject);
1653
+ if (this.state.name === "__from") {
1654
+ return timeRange.state.value.from.valueOf();
1655
+ } else {
1656
+ return timeRange.state.value.to.valueOf();
1624
1657
  }
1625
1658
  }
1626
1659
  getValueText() {
1627
- return "";
1660
+ const timeRange = getTimeRange(this._sceneObject);
1661
+ if (this.state.name === "__from") {
1662
+ return data.dateTimeFormat(timeRange.state.value.from, { timeZone: timeRange.getTimeZone() });
1663
+ } else {
1664
+ return data.dateTimeFormat(timeRange.state.value.to, { timeZone: timeRange.getTimeZone() });
1665
+ }
1628
1666
  }
1629
1667
  }
1630
-
1631
- const macrosIndex = {
1632
- [data.DataLinkBuiltInVars.includeVars]: AllVariablesMacro,
1633
- [data.DataLinkBuiltInVars.keepTime]: UrlTimeRangeMacro,
1634
- ["__value"]: ValueMacro,
1635
- ["__data"]: DataMacro,
1636
- ["__series"]: SeriesMacro,
1637
- ["__field"]: FieldMacro,
1638
- ["__url"]: UrlMacro,
1639
- ["__from"]: TimeFromAndToMacro,
1640
- ["__to"]: TimeFromAndToMacro,
1641
- ["__timezone"]: TimezoneMacro,
1642
- ["__user"]: UserMacro,
1643
- ["__org"]: OrgMacro,
1644
- ["__interval"]: IntervalMacro,
1645
- ["__interval_ms"]: IntervalMacro
1646
- };
1647
- function registerVariableMacro(name, macro) {
1648
- if (macrosIndex[name]) {
1649
- throw new Error(`Macro already registered ${name}`);
1668
+ class TimezoneMacro {
1669
+ constructor(name, sceneObject) {
1670
+ this.state = { name, type: "time_macro" };
1671
+ this._sceneObject = sceneObject;
1672
+ }
1673
+ getValue() {
1674
+ const timeRange = getTimeRange(this._sceneObject);
1675
+ const timeZone = timeRange.getTimeZone();
1676
+ if (timeZone === "browser") {
1677
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
1678
+ }
1679
+ return timeZone;
1680
+ }
1681
+ getValueText() {
1682
+ return this.getValue();
1650
1683
  }
1651
- macrosIndex[name] = macro;
1652
- return () => {
1653
- delete macrosIndex[name];
1654
- };
1655
1684
  }
1656
-
1657
- function sceneInterpolator(sceneObject, target, scopedVars, format, interpolations) {
1658
- if (!target) {
1659
- return target != null ? target : "";
1685
+ class IntervalMacro {
1686
+ constructor(name, sceneObject, match) {
1687
+ this.state = { name, type: "time_macro", match };
1688
+ this._sceneObject = sceneObject;
1660
1689
  }
1661
- VARIABLE_REGEX.lastIndex = 0;
1662
- return target.replace(VARIABLE_REGEX, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
1663
- const variableName = var1 || var2 || var3;
1664
- const fmt = fmt2 || fmt3 || format;
1665
- const variable = lookupFormatVariable(variableName, match, scopedVars, sceneObject);
1666
- if (!variable) {
1667
- if (interpolations) {
1668
- interpolations.push({ match, variableName, fieldPath, format: fmt, value: match, found: false });
1690
+ getValue() {
1691
+ var _a;
1692
+ const data = getData(this._sceneObject);
1693
+ if (data) {
1694
+ const request = (_a = data.state.data) == null ? void 0 : _a.request;
1695
+ if (!request) {
1696
+ return this.state.match;
1669
1697
  }
1670
- return match;
1671
- }
1672
- const value = formatValue(sceneObject, variable, variable.getValue(fieldPath), fmt);
1673
- if (interpolations) {
1674
- interpolations.push({ match, variableName, fieldPath, format: fmt, value, found: value !== match });
1698
+ if (this.state.name === "__interval_ms") {
1699
+ return request.intervalMs;
1700
+ }
1701
+ return request.interval;
1675
1702
  }
1676
- return value;
1677
- });
1678
- }
1679
- function lookupFormatVariable(name, match, scopedVars, sceneObject) {
1680
- const scopedVar = scopedVars == null ? void 0 : scopedVars[name];
1681
- if (scopedVar) {
1682
- return getSceneVariableForScopedVar(name, scopedVar);
1703
+ return this.state.match;
1683
1704
  }
1684
- const variable = lookupVariable(name, sceneObject);
1685
- if (variable) {
1686
- return variable;
1705
+ }
1706
+
1707
+ class AllVariablesMacro {
1708
+ constructor(name, sceneObject) {
1709
+ this.state = { name, type: "url_variable" };
1710
+ this._sceneObject = sceneObject;
1687
1711
  }
1688
- if (macrosIndex[name]) {
1689
- return new macrosIndex[name](name, sceneObject, match, scopedVars);
1712
+ getValue() {
1713
+ const allVars = collectAllVariables(this._sceneObject);
1714
+ const format = formatRegistry.get(schema.VariableFormatID.QueryParam);
1715
+ const params = [];
1716
+ for (const name of Object.keys(allVars)) {
1717
+ const variable = allVars[name];
1718
+ const value = variable.getValue();
1719
+ if (!value) {
1720
+ continue;
1721
+ }
1722
+ if (isCustomVariableValue(value)) {
1723
+ params.push(value.formatter(schema.VariableFormatID.QueryParam));
1724
+ } else {
1725
+ params.push(format.formatter(value, [], variable));
1726
+ }
1727
+ }
1728
+ return new SkipFormattingValue(params.join("&"));
1690
1729
  }
1691
- return null;
1692
- }
1693
- function formatValue(context, variable, value, formatNameOrFn) {
1694
- if (value === null || value === void 0) {
1730
+ getValueText() {
1695
1731
  return "";
1696
1732
  }
1697
- if (isCustomVariableValue(value)) {
1698
- return sceneInterpolator(context, value.formatter(formatNameOrFn));
1699
- }
1700
- if (!Array.isArray(value) && typeof value === "object") {
1701
- value = `${value}`;
1733
+ }
1734
+ function collectAllVariables(sceneObject, record = {}) {
1735
+ if (sceneObject.state.$variables) {
1736
+ for (const variable of sceneObject.state.$variables.state.variables) {
1737
+ if (variable.state.skipUrlSync) {
1738
+ continue;
1739
+ }
1740
+ if (!record[variable.state.name]) {
1741
+ record[variable.state.name] = variable;
1742
+ }
1743
+ }
1702
1744
  }
1703
- if (typeof formatNameOrFn === "function") {
1704
- return formatNameOrFn(value, {
1705
- name: variable.state.name,
1706
- type: variable.state.type,
1707
- multi: variable.state.isMulti,
1708
- includeAll: variable.state.includeAll
1709
- });
1745
+ if (sceneObject.parent) {
1746
+ collectAllVariables(sceneObject.parent, record);
1710
1747
  }
1711
- let args = [];
1712
- if (!formatNameOrFn) {
1713
- formatNameOrFn = schema.VariableFormatID.Glob;
1714
- } else {
1715
- args = formatNameOrFn.split(":");
1716
- if (args.length > 1) {
1717
- formatNameOrFn = args[0];
1718
- args = args.slice(1);
1719
- } else {
1720
- args = [];
1748
+ return record;
1749
+ }
1750
+
1751
+ var __defProp$D = Object.defineProperty;
1752
+ var __defProps$r = Object.defineProperties;
1753
+ var __getOwnPropDescs$r = Object.getOwnPropertyDescriptors;
1754
+ var __getOwnPropSymbols$D = Object.getOwnPropertySymbols;
1755
+ var __hasOwnProp$D = Object.prototype.hasOwnProperty;
1756
+ var __propIsEnum$D = Object.prototype.propertyIsEnumerable;
1757
+ var __defNormalProp$D = (obj, key, value) => key in obj ? __defProp$D(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1758
+ var __spreadValues$D = (a, b) => {
1759
+ for (var prop in b || (b = {}))
1760
+ if (__hasOwnProp$D.call(b, prop))
1761
+ __defNormalProp$D(a, prop, b[prop]);
1762
+ if (__getOwnPropSymbols$D)
1763
+ for (var prop of __getOwnPropSymbols$D(b)) {
1764
+ if (__propIsEnum$D.call(b, prop))
1765
+ __defNormalProp$D(a, prop, b[prop]);
1766
+ }
1767
+ return a;
1768
+ };
1769
+ var __spreadProps$r = (a, b) => __defProps$r(a, __getOwnPropDescs$r(b));
1770
+ function getTemplateProxyForField(field, frame, frames) {
1771
+ return new Proxy(
1772
+ {},
1773
+ {
1774
+ get: (obj, key) => {
1775
+ if (key === "name") {
1776
+ return field.name;
1777
+ }
1778
+ if (key === "displayName") {
1779
+ return data.getFieldDisplayName(field, frame, frames);
1780
+ }
1781
+ if (key === "labels" || key === "formattedLabels") {
1782
+ if (!field.labels) {
1783
+ return "";
1784
+ }
1785
+ return __spreadProps$r(__spreadValues$D({}, field.labels), {
1786
+ __values: Object.values(field.labels).sort().join(", "),
1787
+ toString: () => {
1788
+ return data.formatLabels(field.labels, "", true);
1789
+ }
1790
+ });
1791
+ }
1792
+ return void 0;
1793
+ }
1721
1794
  }
1722
- }
1723
- let formatter = formatRegistry.getIfExists(formatNameOrFn);
1724
- if (!formatter) {
1725
- console.error(`Variable format ${formatNameOrFn} not found. Using glob format as fallback.`);
1726
- formatter = formatRegistry.get(schema.VariableFormatID.Glob);
1727
- }
1728
- return formatter.formatter(value, args, variable);
1729
- }
1730
-
1731
- function isSceneObject(obj) {
1732
- return obj.useState !== void 0;
1733
- }
1734
- function isDataRequestEnricher(obj) {
1735
- return "enrichDataRequest" in obj;
1736
- }
1737
- function isDataLayer(obj) {
1738
- return "isDataLayer" in obj;
1795
+ );
1739
1796
  }
1740
1797
 
1741
- var __accessCheck = (obj, member, msg) => {
1742
- if (!member.has(obj))
1743
- throw TypeError("Cannot " + msg);
1744
- };
1745
- var __privateGet = (obj, member, getter) => {
1746
- __accessCheck(obj, member, "read from private field");
1747
- return getter ? getter.call(obj) : member.get(obj);
1748
- };
1749
- var __privateAdd = (obj, member, value) => {
1750
- if (member.has(obj))
1751
- throw TypeError("Cannot add the same private member more than once");
1752
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1753
- };
1754
- var _running;
1755
- function isQueryController(s) {
1756
- return "isQueryController" in s;
1757
- }
1758
- class SceneQueryController extends SceneObjectBase {
1759
- constructor() {
1760
- super({ isRunning: false });
1761
- this.isQueryController = true;
1762
- __privateAdd(this, _running, /* @__PURE__ */ new Set());
1763
- this.addActivationHandler(() => {
1764
- return () => __privateGet(this, _running).clear();
1765
- });
1798
+ class ValueMacro {
1799
+ constructor(name, sceneObject, _match, _scopedVars) {
1800
+ this._match = _match;
1801
+ this._scopedVars = _scopedVars;
1802
+ this.state = { name, type: "__value" };
1766
1803
  }
1767
- queryStarted(entry) {
1768
- __privateGet(this, _running).add(entry);
1769
- this.changeRunningQueryCount(1);
1770
- if (!this.state.isRunning) {
1771
- this.setState({ isRunning: true });
1804
+ getValue(fieldPath) {
1805
+ var _a, _b;
1806
+ const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1807
+ if (!dataContext) {
1808
+ return this._match;
1772
1809
  }
1773
- }
1774
- queryCompleted(entry) {
1775
- if (!__privateGet(this, _running).has(entry)) {
1776
- return;
1810
+ const { frame, rowIndex, field, calculatedValue } = dataContext.value;
1811
+ if (calculatedValue) {
1812
+ switch (fieldPath) {
1813
+ case "numeric":
1814
+ return calculatedValue.numeric;
1815
+ case "raw":
1816
+ return calculatedValue.numeric;
1817
+ case "time":
1818
+ return "";
1819
+ case "text":
1820
+ default:
1821
+ return data.formattedValueToString(calculatedValue);
1822
+ }
1777
1823
  }
1778
- __privateGet(this, _running).delete(entry);
1779
- this.changeRunningQueryCount(-1);
1780
- if (__privateGet(this, _running).size === 0) {
1781
- this.setState({ isRunning: false });
1824
+ if (rowIndex == null) {
1825
+ return this._match;
1782
1826
  }
1783
- }
1784
- changeRunningQueryCount(dir) {
1785
- var _a;
1786
- window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1787
- }
1788
- cancelAll() {
1789
- var _a;
1790
- for (const entry of __privateGet(this, _running).values()) {
1791
- (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1827
+ if (fieldPath === "time") {
1828
+ const timeField = frame.fields.find((f) => f.type === data.FieldType.time);
1829
+ return timeField ? timeField.values.get(rowIndex) : void 0;
1830
+ }
1831
+ if (!field) {
1832
+ return this._match;
1833
+ }
1834
+ const value = field.values.get(rowIndex);
1835
+ if (fieldPath === "raw") {
1836
+ return value;
1837
+ }
1838
+ const displayProcessor = (_b = field.display) != null ? _b : fallbackDisplayProcessor;
1839
+ const result = displayProcessor(value);
1840
+ switch (fieldPath) {
1841
+ case "numeric":
1842
+ return result.numeric;
1843
+ case "text":
1844
+ default:
1845
+ return data.formattedValueToString(result);
1792
1846
  }
1793
1847
  }
1794
- }
1795
- _running = new WeakMap();
1796
-
1797
- function getVariables(sceneObject) {
1798
- var _a;
1799
- return (_a = getClosest(sceneObject, (s) => s.state.$variables)) != null ? _a : EmptyVariableSet;
1800
- }
1801
- function getData(sceneObject) {
1802
- var _a;
1803
- return (_a = getClosest(sceneObject, (s) => s.state.$data)) != null ? _a : EmptyDataNode;
1804
- }
1805
- function isSceneLayout(s) {
1806
- return "isDraggable" in s;
1807
- }
1808
- function getLayout(scene) {
1809
- const parent = getClosest(scene, (s) => isSceneLayout(s) ? s : void 0);
1810
- if (parent) {
1811
- return parent;
1848
+ getValueText() {
1849
+ return "";
1812
1850
  }
1813
- return null;
1814
1851
  }
1815
- function interpolate(sceneObject, value, scopedVars, format, interpolations) {
1816
- if (value === "" || value == null) {
1852
+ const fallbackDisplayProcessor = data.getDisplayProcessor();
1853
+ class DataMacro {
1854
+ constructor(name, sceneObject, _match, _scopedVars) {
1855
+ this._match = _match;
1856
+ this._scopedVars = _scopedVars;
1857
+ this.state = { name, type: "__data" };
1858
+ }
1859
+ getValue(fieldPath) {
1860
+ var _a, _b;
1861
+ const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1862
+ if (!dataContext || !fieldPath) {
1863
+ return this._match;
1864
+ }
1865
+ const { frame, rowIndex } = dataContext.value;
1866
+ if (rowIndex === void 0 || fieldPath === void 0) {
1867
+ return this._match;
1868
+ }
1869
+ const obj = {
1870
+ name: frame.name,
1871
+ refId: frame.refId,
1872
+ fields: data.getFieldDisplayValuesProxy({ frame, rowIndex })
1873
+ };
1874
+ return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1875
+ }
1876
+ getValueText() {
1817
1877
  return "";
1818
1878
  }
1819
- return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1820
1879
  }
1821
- function hasVariableDependencyInLoadingState(sceneObject) {
1822
- if (!sceneObject.variableDependency) {
1823
- return false;
1880
+ class SeriesMacro {
1881
+ constructor(name, sceneObject, _match, _scopedVars) {
1882
+ this._match = _match;
1883
+ this._scopedVars = _scopedVars;
1884
+ this.state = { name, type: "__series" };
1824
1885
  }
1825
- for (const name of sceneObject.variableDependency.getNames()) {
1826
- const variable = lookupVariable(name, sceneObject);
1827
- if (!variable) {
1828
- continue;
1886
+ getValue(fieldPath) {
1887
+ var _a;
1888
+ const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1889
+ if (!dataContext || !fieldPath) {
1890
+ return this._match;
1829
1891
  }
1830
- const set = variable.parent;
1831
- if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1832
- return true;
1892
+ if (fieldPath !== "name") {
1893
+ return this._match;
1833
1894
  }
1895
+ const { frame, frameIndex } = dataContext.value;
1896
+ return data.getFrameDisplayName(frame, frameIndex);
1897
+ }
1898
+ getValueText() {
1899
+ return "";
1834
1900
  }
1835
- return false;
1836
1901
  }
1837
- function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1838
- if (check(scene)) {
1839
- return scene;
1902
+ class FieldMacro {
1903
+ constructor(name, sceneObject, _match, _scopedVars) {
1904
+ this._match = _match;
1905
+ this._scopedVars = _scopedVars;
1906
+ this.state = { name, type: "__field" };
1840
1907
  }
1841
- let found = null;
1842
- scene.forEachChild((child) => {
1843
- if (child === alreadySearchedChild) {
1844
- return;
1908
+ getValue(fieldPath) {
1909
+ var _a, _b;
1910
+ const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1911
+ if (!dataContext || !fieldPath) {
1912
+ return this._match;
1845
1913
  }
1846
- let maybe = findObjectInternal(child, check);
1847
- if (maybe) {
1848
- found = maybe;
1914
+ if (fieldPath === void 0 || fieldPath === "") {
1915
+ return this._match;
1849
1916
  }
1850
- });
1851
- if (found) {
1852
- return found;
1917
+ const { frame, field, data } = dataContext.value;
1918
+ const obj = getTemplateProxyForField(field, frame, data);
1919
+ return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1853
1920
  }
1854
- if (shouldSearchUp && scene.parent) {
1855
- return findObjectInternal(scene.parent, check, scene, true);
1921
+ getValueText() {
1922
+ return "";
1856
1923
  }
1857
- return null;
1858
1924
  }
1859
- function findByKey(sceneObject, key) {
1860
- const found = findObject(sceneObject, (sceneToCheck) => {
1861
- return sceneToCheck.state.key === key;
1862
- });
1863
- if (!found) {
1864
- throw new Error("Unable to find scene with key " + key);
1925
+
1926
+ class UrlMacro {
1927
+ constructor(name, _) {
1928
+ this.state = { name, type: "url_macro" };
1865
1929
  }
1866
- return found;
1867
- }
1868
- function findByKeyAndType(sceneObject, key, targetType) {
1869
- const found = findObject(sceneObject, (sceneToCheck) => {
1870
- return sceneToCheck.state.key === key;
1871
- });
1872
- if (!found) {
1873
- throw new Error("Unable to find scene with key " + key);
1930
+ getValue(fieldPath) {
1931
+ var _a;
1932
+ const location = runtime.locationService.getLocation();
1933
+ const subUrl = (_a = runtime.config.appSubUrl) != null ? _a : "";
1934
+ switch (fieldPath != null ? fieldPath : "") {
1935
+ case "params":
1936
+ return new UrlStateFormatter(location.search);
1937
+ case "path":
1938
+ return subUrl + location.pathname;
1939
+ case "":
1940
+ default:
1941
+ return subUrl + location.pathname + location.search;
1942
+ }
1874
1943
  }
1875
- if (!(found instanceof targetType)) {
1876
- throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1944
+ getValueText() {
1945
+ return "";
1877
1946
  }
1878
- return found;
1879
- }
1880
- function findObject(scene, check) {
1881
- return findObjectInternal(scene, check, void 0, true);
1882
- }
1883
- function findAllObjects(scene, check) {
1884
- const found = [];
1885
- scene.forEachChild((child) => {
1886
- if (check(child)) {
1887
- found.push(child);
1888
- }
1889
- found.push(...findAllObjects(child, check));
1890
- });
1891
- return found;
1892
1947
  }
1893
- function getDataLayers(sceneObject, localOnly = false) {
1894
- let currentLevel = sceneObject;
1895
- let collected = [];
1896
- while (currentLevel) {
1897
- const dataProvider = currentLevel.state.$data;
1898
- if (!dataProvider) {
1899
- currentLevel = currentLevel.parent;
1900
- continue;
1948
+ class UrlStateFormatter {
1949
+ constructor(_urlQueryParams) {
1950
+ this._urlQueryParams = _urlQueryParams;
1951
+ }
1952
+ formatter(options) {
1953
+ if (!options) {
1954
+ return this._urlQueryParams;
1901
1955
  }
1902
- if (isDataLayer(dataProvider)) {
1903
- collected = collected.concat(dataProvider);
1904
- } else {
1905
- if (dataProvider.state.$data && isDataLayer(dataProvider.state.$data)) {
1906
- collected = collected.concat(dataProvider.state.$data);
1956
+ const params = options.split(":");
1957
+ if (params[0] === "exclude" && params.length > 1) {
1958
+ const allParams = new URLSearchParams(this._urlQueryParams);
1959
+ for (const param of params[1].split(",")) {
1960
+ allParams.delete(param);
1907
1961
  }
1962
+ return `?${allParams}`;
1908
1963
  }
1909
- if (localOnly && collected.length > 0) {
1910
- break;
1964
+ if (params[0] === "include" && params.length > 1) {
1965
+ const allParams = new URLSearchParams(this._urlQueryParams);
1966
+ const includeOnly = params[1].split(",");
1967
+ for (const param of allParams.keys()) {
1968
+ if (!includeOnly.includes(param)) {
1969
+ allParams.delete(param);
1970
+ }
1971
+ }
1972
+ return `?${allParams}`;
1911
1973
  }
1912
- currentLevel = currentLevel.parent;
1974
+ return this._urlQueryParams;
1913
1975
  }
1914
- return collected;
1915
1976
  }
1916
- function getAncestor(sceneObject, ancestorType) {
1917
- let parent = sceneObject;
1918
- while (parent) {
1919
- if (parent instanceof ancestorType) {
1920
- return parent;
1977
+
1978
+ class UserMacro {
1979
+ constructor(name, _) {
1980
+ this.state = { name, type: "user_macro" };
1981
+ }
1982
+ getValue(fieldPath) {
1983
+ const user = runtime.config.bootData.user;
1984
+ switch (fieldPath) {
1985
+ case "login":
1986
+ return user.login;
1987
+ case "email":
1988
+ return user.email;
1989
+ case "id":
1990
+ default:
1991
+ return String(user.id);
1921
1992
  }
1922
- parent = parent.parent;
1923
1993
  }
1924
- if (!parent) {
1925
- throw new Error("Unable to find parent of type " + ancestorType.name);
1994
+ getValueText() {
1995
+ return "";
1926
1996
  }
1927
- return parent;
1928
1997
  }
1929
- function getQueryController(sceneObject) {
1930
- let parent = sceneObject;
1931
- while (parent) {
1932
- if (parent.state.$behaviors) {
1933
- for (const behavior of parent.state.$behaviors) {
1934
- if (isQueryController(behavior)) {
1935
- return behavior;
1936
- }
1937
- }
1998
+ class OrgMacro {
1999
+ constructor(name, _) {
2000
+ this.state = { name, type: "org_macro" };
2001
+ }
2002
+ getValue(fieldPath) {
2003
+ const user = runtime.config.bootData.user;
2004
+ switch (fieldPath) {
2005
+ case "name":
2006
+ return user.orgName;
2007
+ case "id":
2008
+ default:
2009
+ return String(user.orgId);
1938
2010
  }
1939
- parent = parent.parent;
1940
2011
  }
1941
- return void 0;
2012
+ getValueText() {
2013
+ return "";
2014
+ }
2015
+ }
2016
+
2017
+ const macrosIndex = {
2018
+ [data.DataLinkBuiltInVars.includeVars]: AllVariablesMacro,
2019
+ [data.DataLinkBuiltInVars.keepTime]: UrlTimeRangeMacro,
2020
+ ["__value"]: ValueMacro,
2021
+ ["__data"]: DataMacro,
2022
+ ["__series"]: SeriesMacro,
2023
+ ["__field"]: FieldMacro,
2024
+ ["__url"]: UrlMacro,
2025
+ ["__from"]: TimeFromAndToMacro,
2026
+ ["__to"]: TimeFromAndToMacro,
2027
+ ["__timezone"]: TimezoneMacro,
2028
+ ["__user"]: UserMacro,
2029
+ ["__org"]: OrgMacro,
2030
+ ["__interval"]: IntervalMacro,
2031
+ ["__interval_ms"]: IntervalMacro
2032
+ };
2033
+ function registerVariableMacro(name, macro) {
2034
+ if (macrosIndex[name]) {
2035
+ throw new Error(`Macro already registered ${name}`);
2036
+ }
2037
+ macrosIndex[name] = macro;
2038
+ return () => {
2039
+ delete macrosIndex[name];
2040
+ };
1942
2041
  }
1943
2042
 
1944
2043
  const sceneGraph = {
@@ -1958,117 +2057,6 @@ const sceneGraph = {
1958
2057
  getQueryController
1959
2058
  };
1960
2059
 
1961
- class UniqueUrlKeyMapper {
1962
- constructor() {
1963
- this.index = /* @__PURE__ */ new Map();
1964
- }
1965
- getUniqueKey(key, obj) {
1966
- const objectsWithKey = this.index.get(key);
1967
- if (!objectsWithKey) {
1968
- this.index.set(key, [obj]);
1969
- return key;
1970
- }
1971
- let address = objectsWithKey.findIndex((o) => o === obj);
1972
- if (address === -1) {
1973
- filterOutOrphanedObjects(objectsWithKey);
1974
- objectsWithKey.push(obj);
1975
- address = objectsWithKey.length - 1;
1976
- }
1977
- if (address > 0) {
1978
- return `${key}-${address + 1}`;
1979
- }
1980
- return key;
1981
- }
1982
- clear() {
1983
- this.index.clear();
1984
- }
1985
- }
1986
- function filterOutOrphanedObjects(sceneObjects) {
1987
- for (const obj of sceneObjects) {
1988
- if (isOrphanOrInActive(obj)) {
1989
- const index = sceneObjects.indexOf(obj);
1990
- sceneObjects.splice(index, 1);
1991
- }
1992
- }
1993
- }
1994
- function isOrphanOrInActive(obj) {
1995
- const root = obj.getRoot();
1996
- if (!sceneGraph.findObject(root, (child) => child === obj)) {
1997
- return true;
1998
- }
1999
- return false;
2000
- }
2001
-
2002
- function getUrlState(root) {
2003
- const urlKeyMapper = new UniqueUrlKeyMapper();
2004
- const result = {};
2005
- const visitNode = (obj) => {
2006
- if (obj.urlSync) {
2007
- const newUrlState = obj.urlSync.getUrlState();
2008
- for (const [key, value] of Object.entries(newUrlState)) {
2009
- if (value != null) {
2010
- const uniqueKey = urlKeyMapper.getUniqueKey(key, obj);
2011
- result[uniqueKey] = value;
2012
- }
2013
- }
2014
- }
2015
- obj.forEachChild(visitNode);
2016
- };
2017
- visitNode(root);
2018
- return result;
2019
- }
2020
- function syncStateFromSearchParams(root, urlParams) {
2021
- const urlKeyMapper = new UniqueUrlKeyMapper();
2022
- syncStateFromUrl(root, urlParams, urlKeyMapper);
2023
- }
2024
- function syncStateFromUrl(root, urlParams, urlKeyMapper) {
2025
- if (!root.parent) {
2026
- syncUrlStateToObject(root, urlParams, urlKeyMapper);
2027
- }
2028
- root.forEachChild((child) => {
2029
- syncUrlStateToObject(child, urlParams, urlKeyMapper);
2030
- });
2031
- root.forEachChild((child) => syncStateFromUrl(child, urlParams, urlKeyMapper));
2032
- }
2033
- function syncUrlStateToObject(sceneObject, urlParams, urlKeyMapper) {
2034
- if (sceneObject.urlSync) {
2035
- const urlState = {};
2036
- const currentState = sceneObject.urlSync.getUrlState();
2037
- for (const key of sceneObject.urlSync.getKeys()) {
2038
- const uniqueKey = urlKeyMapper.getUniqueKey(key, sceneObject);
2039
- const newValue = urlParams.getAll(uniqueKey);
2040
- const currentValue = currentState[key];
2041
- if (isUrlValueEqual(newValue, currentValue)) {
2042
- continue;
2043
- }
2044
- if (newValue.length > 0) {
2045
- if (Array.isArray(currentValue)) {
2046
- urlState[key] = newValue;
2047
- } else {
2048
- urlState[key] = newValue[0];
2049
- }
2050
- } else {
2051
- urlState[key] = null;
2052
- }
2053
- }
2054
- if (Object.keys(urlState).length > 0) {
2055
- sceneObject.urlSync.updateFromUrl(urlState);
2056
- }
2057
- }
2058
- }
2059
- function isUrlValueEqual(currentUrlValue, newUrlValue) {
2060
- if (currentUrlValue.length === 0 && newUrlValue == null) {
2061
- return true;
2062
- }
2063
- if (!Array.isArray(newUrlValue) && (currentUrlValue == null ? void 0 : currentUrlValue.length) === 1) {
2064
- return newUrlValue === currentUrlValue[0];
2065
- }
2066
- if ((newUrlValue == null ? void 0 : newUrlValue.length) === 0 && currentUrlValue === null) {
2067
- return true;
2068
- }
2069
- return lodash.isEqual(currentUrlValue, newUrlValue);
2070
- }
2071
-
2072
2060
  async function getDataSource(datasource, scopedVars) {
2073
2061
  if (datasource == null ? void 0 : datasource.uid) {
2074
2062
  const runtimeDataSource = runtimeDataSources.get(datasource.uid);
@@ -2971,6 +2959,7 @@ const OptionWithCheckbox = ({
2971
2959
  isSelected,
2972
2960
  renderOptionLabel
2973
2961
  }) => {
2962
+ var _b;
2974
2963
  const _a = innerProps, rest = __objRest$3(_a, ["onMouseMove", "onMouseOver"]);
2975
2964
  const theme = ui.useTheme2();
2976
2965
  const selectStyles = ui.getSelectStyles(theme);
@@ -2979,17 +2968,17 @@ const OptionWithCheckbox = ({
2979
2968
  ref: innerRef,
2980
2969
  className: css.cx(selectStyles.option, isFocused && selectStyles.optionFocused)
2981
2970
  }, rest), {
2982
- "aria-label": "Select option",
2983
- "data-testid": e2eSelectors.selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownOptionTexts(
2984
- data.label || String(data.value)
2985
- ),
2971
+ "data-testid": e2eSelectors.selectors.components.Select.option,
2986
2972
  title: data.title
2987
2973
  }), /* @__PURE__ */ React__default["default"].createElement("div", {
2988
2974
  className: optionStyles.checkbox
2989
2975
  }, /* @__PURE__ */ React__default["default"].createElement(ui.Checkbox, {
2990
2976
  value: isSelected
2991
2977
  })), /* @__PURE__ */ React__default["default"].createElement("div", {
2992
- className: selectStyles.optionBody
2978
+ className: selectStyles.optionBody,
2979
+ "data-testid": e2eSelectors.selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownOptionTexts(
2980
+ (_b = data.label) != null ? _b : String(data.value)
2981
+ )
2993
2982
  }, /* @__PURE__ */ React__default["default"].createElement("span", null, children)));
2994
2983
  };
2995
2984
  OptionWithCheckbox.displayName = "SelectMenuOptions";
@@ -7732,12 +7721,28 @@ class UrlSyncManager {
7732
7721
  constructor() {
7733
7722
  this._urlKeyMapper = new UniqueUrlKeyMapper();
7734
7723
  this._stateSub = null;
7724
+ this._locationSub = null;
7725
+ this._ignoreNextLocationUpdate = false;
7726
+ this._onLocationUpdate = (location) => {
7727
+ if (this._ignoreNextLocationUpdate) {
7728
+ this._ignoreNextLocationUpdate = false;
7729
+ return;
7730
+ }
7731
+ if (this._lastPath !== location.pathname) {
7732
+ return;
7733
+ }
7734
+ const urlParams = new URLSearchParams(location.search);
7735
+ this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7736
+ syncStateFromUrl(this._sceneRoot, urlParams, this._urlKeyMapper);
7737
+ this._lastPath = location.pathname;
7738
+ };
7735
7739
  this._onStateChanged = ({ payload }) => {
7736
7740
  const changedObject = payload.changedObject;
7737
7741
  if (changedObject.urlSync) {
7738
7742
  const newUrlState = changedObject.urlSync.getUrlState();
7739
7743
  const searchParams = runtime.locationService.getSearch();
7740
7744
  const mappedUpdated = {};
7745
+ this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7741
7746
  for (const [key, newUrlValue] of Object.entries(newUrlState)) {
7742
7747
  const uniqueKey = this._urlKeyMapper.getUniqueKey(key, changedObject);
7743
7748
  const currentUrlValue = searchParams.getAll(uniqueKey);
@@ -7746,33 +7751,36 @@ class UrlSyncManager {
7746
7751
  }
7747
7752
  }
7748
7753
  if (Object.keys(mappedUpdated).length > 0) {
7749
- writeSceneLog("UrlSyncManager", "onStateChange updating URL");
7754
+ this._ignoreNextLocationUpdate = true;
7750
7755
  runtime.locationService.partial(mappedUpdated, true);
7751
- this._lastLocation = runtime.locationService.getLocation();
7752
- this._urlParams = new URLSearchParams(this._lastLocation.search);
7753
7756
  }
7754
7757
  }
7755
7758
  };
7756
7759
  }
7757
7760
  initSync(root) {
7758
- var _a;
7761
+ if (!this._locationSub) {
7762
+ writeSceneLog("UrlSyncManager", "New location listen");
7763
+ this._locationSub = runtime.locationService.getHistory().listen(this._onLocationUpdate);
7764
+ }
7759
7765
  if (this._stateSub) {
7760
- writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", (_a = this._sceneRoot) == null ? void 0 : _a.state.key);
7766
+ writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", this._sceneRoot.state.key);
7761
7767
  this._stateSub.unsubscribe();
7762
7768
  }
7763
- writeSceneLog("UrlSyncManager", "init", root.state.key);
7764
7769
  this._sceneRoot = root;
7770
+ this._lastPath = runtime.locationService.getLocation().pathname;
7765
7771
  this._stateSub = root.subscribeToEvent(SceneObjectStateChangedEvent, this._onStateChanged);
7766
- this._urlKeyMapper.clear();
7767
- this._lastLocation = runtime.locationService.getLocation();
7768
- this._urlParams = new URLSearchParams(this._lastLocation.search);
7769
- this.handleNewObject(this._sceneRoot);
7772
+ this.syncFrom(this._sceneRoot);
7770
7773
  }
7771
7774
  cleanUp(root) {
7772
7775
  if (this._sceneRoot !== root) {
7773
7776
  return;
7774
7777
  }
7775
7778
  writeSceneLog("UrlSyncManager", "Clean up");
7779
+ if (this._locationSub) {
7780
+ this._locationSub();
7781
+ writeSceneLog("UrlSyncManager", "Unregister history listen");
7782
+ this._locationSub = null;
7783
+ }
7776
7784
  if (this._stateSub) {
7777
7785
  this._stateSub.unsubscribe();
7778
7786
  this._stateSub = null;
@@ -7783,23 +7791,11 @@ class UrlSyncManager {
7783
7791
  this._sceneRoot.state.key === root.state.key
7784
7792
  );
7785
7793
  }
7786
- this._sceneRoot = void 0;
7787
- this._urlParams = void 0;
7788
- }
7789
- handleNewLocation(location) {
7790
- if (!this._sceneRoot || this._lastLocation === location) {
7791
- return;
7792
- }
7793
- writeSceneLog("UrlSyncManager", "handleNewLocation");
7794
- this._urlParams = new URLSearchParams(location.search);
7795
- this._lastLocation = location;
7796
- syncStateFromUrl(this._sceneRoot, this._urlParams, this._urlKeyMapper);
7797
7794
  }
7798
- handleNewObject(sceneObj) {
7799
- if (!this._sceneRoot || !this._urlParams) {
7800
- return;
7801
- }
7802
- syncStateFromUrl(sceneObj, this._urlParams, this._urlKeyMapper);
7795
+ syncFrom(sceneObj) {
7796
+ const urlParams = runtime.locationService.getSearch();
7797
+ this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7798
+ syncStateFromUrl(sceneObj, urlParams, this._urlKeyMapper);
7803
7799
  }
7804
7800
  getUrlState(root) {
7805
7801
  return getUrlState(root);
@@ -7813,34 +7809,6 @@ function getUrlSyncManager() {
7813
7809
  return urlSyncManager;
7814
7810
  }
7815
7811
 
7816
- function useUrlSync(sceneRoot) {
7817
- const urlSyncManager = getUrlSyncManager();
7818
- const location = reactRouterDom.useLocation();
7819
- const [isInitialized, setIsInitialized] = React.useState(false);
7820
- React.useEffect(() => {
7821
- urlSyncManager.initSync(sceneRoot);
7822
- setIsInitialized(true);
7823
- return () => urlSyncManager.cleanUp(sceneRoot);
7824
- }, [sceneRoot, urlSyncManager]);
7825
- React.useEffect(() => {
7826
- const latestLocation = runtime.locationService.getLocation();
7827
- const locationToHandle = latestLocation !== location ? latestLocation : location;
7828
- if (latestLocation !== location) {
7829
- console.log("latestLocation different from location");
7830
- }
7831
- urlSyncManager.handleNewLocation(locationToHandle);
7832
- }, [sceneRoot, urlSyncManager, location]);
7833
- return isInitialized;
7834
- }
7835
-
7836
- function UrlSyncContextProvider({ children, scene }) {
7837
- const isInitialized = useUrlSync(scene);
7838
- if (!isInitialized) {
7839
- return null;
7840
- }
7841
- return children;
7842
- }
7843
-
7844
7812
  function setWindowGrafanaSceneContext(activeScene) {
7845
7813
  const prevScene = window.__grafanaSceneContext;
7846
7814
  writeSceneLog("setWindowGrafanaScene", "set window.__grafanaSceneContext", activeScene);
@@ -7860,9 +7828,13 @@ class EmbeddedScene extends SceneObjectBase {
7860
7828
  const unsetGlobalScene = setWindowGrafanaSceneContext(this);
7861
7829
  return () => {
7862
7830
  unsetGlobalScene();
7831
+ getUrlSyncManager().cleanUp(this);
7863
7832
  };
7864
7833
  });
7865
7834
  }
7835
+ initUrlSync() {
7836
+ getUrlSyncManager().initSync(this);
7837
+ }
7866
7838
  }
7867
7839
  EmbeddedScene.Component = EmbeddedSceneRenderer;
7868
7840
  function EmbeddedSceneRenderer({ model }) {
@@ -10335,8 +10307,7 @@ function SceneAppPageView({ page, routeProps }) {
10335
10307
  React.useEffect(() => {
10336
10308
  return () => containerPage.setState({ initializedScene: void 0 });
10337
10309
  }, [containerPage]);
10338
- const urlSyncInitialized = useUrlSync(containerPage);
10339
- if (!isInitialized && !urlSyncInitialized) {
10310
+ if (!isInitialized) {
10340
10311
  return null;
10341
10312
  }
10342
10313
  const pageNav = {
@@ -10409,9 +10380,13 @@ class SceneAppPage extends SceneObjectBase {
10409
10380
  super(state);
10410
10381
  this._sceneCache = /* @__PURE__ */ new Map();
10411
10382
  this._drilldownCache = /* @__PURE__ */ new Map();
10383
+ this.addActivationHandler(() => {
10384
+ return () => getUrlSyncManager().cleanUp(this);
10385
+ });
10412
10386
  }
10413
10387
  initializeScene(scene) {
10414
10388
  this.setState({ initializedScene: scene });
10389
+ getUrlSyncManager().initSync(this);
10415
10390
  }
10416
10391
  getScene(routeMatch) {
10417
10392
  let scene = this._sceneCache.get(routeMatch.url);
@@ -11406,7 +11381,6 @@ exports.SceneVariableValueChangedEvent = SceneVariableValueChangedEvent;
11406
11381
  exports.SplitLayout = SplitLayout;
11407
11382
  exports.TestVariable = TestVariable;
11408
11383
  exports.TextBoxVariable = TextBoxVariable;
11409
- exports.UrlSyncContextProvider = UrlSyncContextProvider;
11410
11384
  exports.UrlSyncManager = UrlSyncManager;
11411
11385
  exports.UserActionEvent = UserActionEvent;
11412
11386
  exports.VariableDependencyConfig = VariableDependencyConfig;
@@ -11432,5 +11406,4 @@ exports.sceneGraph = sceneGraph;
11432
11406
  exports.sceneUtils = sceneUtils;
11433
11407
  exports.useSceneApp = useSceneApp;
11434
11408
  exports.useSceneObjectState = useSceneObjectState;
11435
- exports.useUrlSync = useUrlSync;
11436
11409
  //# sourceMappingURL=index.js.map