@grafana/scenes 4.26.2 → 4.26.3--canary.765.9398400471.0

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.
package/dist/index.js CHANGED
@@ -586,103 +586,22 @@ function registerRuntimeDataSource({ dataSource }) {
586
586
  runtimeDataSources.set(dataSource.uid, dataSource);
587
587
  }
588
588
 
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}`;
601
- }
602
- return key;
603
- }
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));
621
- }
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);
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;
671
596
  }
672
597
  }
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;
598
+ const found = variables.getByName(name);
599
+ if (found) {
600
+ return found;
601
+ } else if (sceneObject.parent) {
602
+ return lookupVariable(name, sceneObject.parent);
684
603
  }
685
- return lodash.isEqual(currentUrlValue, newUrlValue);
604
+ return null;
686
605
  }
687
606
 
688
607
  var __defProp$F = Object.defineProperty;
@@ -1314,730 +1233,712 @@ function sqlStringFormatter(value) {
1314
1233
  })}'`;
1315
1234
  }
1316
1235
 
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
- }
1236
+ class SkipFormattingValue {
1237
+ constructor(_value) {
1238
+ this._value = _value;
1325
1239
  }
1326
- const found = variables.getByName(name);
1327
- if (found) {
1328
- return found;
1329
- } else if (sceneObject.parent) {
1330
- return lookupVariable(name, sceneObject.parent);
1240
+ formatter() {
1241
+ return this._value;
1331
1242
  }
1332
- return null;
1333
1243
  }
1334
1244
 
1335
- function sceneInterpolator(sceneObject, target, scopedVars, format, interpolations) {
1336
- if (!target) {
1337
- return target != null ? target : "";
1245
+ class UrlTimeRangeMacro {
1246
+ constructor(name, sceneObject) {
1247
+ this.state = { name, type: "url_variable" };
1248
+ this._sceneObject = sceneObject;
1338
1249
  }
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;
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;
1264
+ }
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();
1349
1271
  }
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 });
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() });
1353
1279
  }
1354
- return value;
1355
- });
1280
+ }
1356
1281
  }
1357
- function lookupFormatVariable(name, match, scopedVars, sceneObject) {
1358
- const scopedVar = scopedVars == null ? void 0 : scopedVars[name];
1359
- if (scopedVar) {
1360
- return getSceneVariableForScopedVar(name, scopedVar);
1282
+ class TimezoneMacro {
1283
+ constructor(name, sceneObject) {
1284
+ this.state = { name, type: "time_macro" };
1285
+ this._sceneObject = sceneObject;
1361
1286
  }
1362
- const variable = lookupVariable(name, sceneObject);
1363
- if (variable) {
1364
- return variable;
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;
1365
1294
  }
1366
- if (macrosIndex[name]) {
1367
- return new macrosIndex[name](name, sceneObject, match, scopedVars);
1295
+ getValueText() {
1296
+ return this.getValue();
1368
1297
  }
1369
- return null;
1370
1298
  }
1371
- function formatValue(context, variable, value, formatNameOrFn) {
1372
- if (value === null || value === void 0) {
1373
- return "";
1374
- }
1375
- if (isCustomVariableValue(value)) {
1376
- return sceneInterpolator(context, value.formatter(formatNameOrFn));
1299
+ class IntervalMacro {
1300
+ constructor(name, sceneObject, match) {
1301
+ this.state = { name, type: "time_macro", match };
1302
+ this._sceneObject = sceneObject;
1377
1303
  }
1378
- if (!Array.isArray(value) && typeof value === "object") {
1379
- value = `${value}`;
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;
1380
1318
  }
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
- });
1319
+ }
1320
+
1321
+ class AllVariablesMacro {
1322
+ constructor(name, sceneObject) {
1323
+ this.state = { name, type: "url_variable" };
1324
+ this._sceneObject = sceneObject;
1388
1325
  }
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 = [];
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
+ }
1399
1341
  }
1342
+ return new SkipFormattingValue(params.join("&"));
1400
1343
  }
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);
1344
+ getValueText() {
1345
+ return "";
1405
1346
  }
1406
- return formatter.formatter(value, args, variable);
1407
1347
  }
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;
1417
- }
1418
-
1419
- var __accessCheck = (obj, member, msg) => {
1420
- if (!member.has(obj))
1421
- throw TypeError("Cannot " + msg);
1422
- };
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;
1435
- }
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
- });
1444
- }
1445
- queryStarted(entry) {
1446
- __privateGet(this, _running).add(entry);
1447
- this.changeRunningQueryCount(1);
1448
- if (!this.state.isRunning) {
1449
- this.setState({ isRunning: true });
1450
- }
1451
- }
1452
- queryCompleted(entry) {
1453
- if (!__privateGet(this, _running).has(entry)) {
1454
- return;
1455
- }
1456
- __privateGet(this, _running).delete(entry);
1457
- this.changeRunningQueryCount(-1);
1458
- if (__privateGet(this, _running).size === 0) {
1459
- this.setState({ isRunning: false });
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
+ }
1460
1357
  }
1461
1358
  }
1462
- changeRunningQueryCount(dir) {
1463
- var _a;
1464
- window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1465
- }
1466
- cancelAll() {
1467
- var _a;
1468
- for (const entry of __privateGet(this, _running).values()) {
1469
- (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1470
- }
1359
+ if (sceneObject.parent) {
1360
+ collectAllVariables(sceneObject.parent, record);
1471
1361
  }
1362
+ return record;
1472
1363
  }
1473
- _running = new WeakMap();
1474
1364
 
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) {
1495
- return "";
1496
- }
1497
- return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1498
- }
1499
- function hasVariableDependencyInLoadingState(sceneObject) {
1500
- if (!sceneObject.variableDependency) {
1501
- return false;
1502
- }
1503
- for (const name of sceneObject.variableDependency.getNames()) {
1504
- const variable = lookupVariable(name, sceneObject);
1505
- if (!variable) {
1506
- continue;
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]);
1507
1380
  }
1508
- const set = variable.parent;
1509
- if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1510
- return true;
1381
+ return a;
1382
+ };
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
+ }
1511
1408
  }
1512
- }
1513
- return false;
1409
+ );
1514
1410
  }
1515
- function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1516
- if (check(scene)) {
1517
- return scene;
1411
+
1412
+ class ValueMacro {
1413
+ constructor(name, sceneObject, _match, _scopedVars) {
1414
+ this._match = _match;
1415
+ this._scopedVars = _scopedVars;
1416
+ this.state = { name, type: "__value" };
1518
1417
  }
1519
- let found = null;
1520
- scene.forEachChild((child) => {
1521
- if (child === alreadySearchedChild) {
1522
- return;
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;
1523
1423
  }
1524
- let maybe = findObjectInternal(child, check);
1525
- if (maybe) {
1526
- found = maybe;
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
+ }
1527
1437
  }
1528
- });
1529
- if (found) {
1530
- return found;
1531
- }
1532
- if (shouldSearchUp && scene.parent) {
1533
- return findObjectInternal(scene.parent, check, scene, true);
1534
- }
1535
- return null;
1536
- }
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
- }
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);
1552
- }
1553
- if (!(found instanceof targetType)) {
1554
- throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1555
- }
1556
- return found;
1557
- }
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);
1438
+ if (rowIndex == null) {
1439
+ return this._match;
1566
1440
  }
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;
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;
1579
1444
  }
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);
1585
- }
1445
+ if (!field) {
1446
+ return this._match;
1586
1447
  }
1587
- if (localOnly && collected.length > 0) {
1588
- break;
1448
+ const value = field.values.get(rowIndex);
1449
+ if (fieldPath === "raw") {
1450
+ return value;
1589
1451
  }
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;
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);
1599
1460
  }
1600
- parent = parent.parent;
1601
1461
  }
1602
- if (!parent) {
1603
- throw new Error("Unable to find parent of type " + ancestorType.name);
1462
+ getValueText() {
1463
+ return "";
1604
1464
  }
1605
- return parent;
1606
1465
  }
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;
1614
- }
1615
- }
1616
- }
1617
- parent = parent.parent;
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" };
1618
1472
  }
1619
- return void 0;
1620
- }
1621
-
1622
- class SkipFormattingValue {
1623
- constructor(_value) {
1624
- this._value = _value;
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;
1482
+ }
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 : "";
1625
1489
  }
1626
- formatter() {
1627
- return this._value;
1490
+ getValueText() {
1491
+ return "";
1628
1492
  }
1629
1493
  }
1630
-
1631
- class UrlTimeRangeMacro {
1632
- constructor(name, sceneObject) {
1633
- this.state = { name, type: "url_variable" };
1634
- this._sceneObject = sceneObject;
1494
+ class SeriesMacro {
1495
+ constructor(name, sceneObject, _match, _scopedVars) {
1496
+ this._match = _match;
1497
+ this._scopedVars = _scopedVars;
1498
+ this.state = { name, type: "__series" };
1635
1499
  }
1636
- getValue() {
1500
+ getValue(fieldPath) {
1637
1501
  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));
1502
+ const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1503
+ if (!dataContext || !fieldPath) {
1504
+ return this._match;
1505
+ }
1506
+ if (fieldPath !== "name") {
1507
+ return this._match;
1508
+ }
1509
+ const { frame, frameIndex } = dataContext.value;
1510
+ return data.getFrameDisplayName(frame, frameIndex);
1641
1511
  }
1642
1512
  getValueText() {
1643
1513
  return "";
1644
1514
  }
1645
1515
  }
1646
- class TimeFromAndToMacro {
1647
- constructor(name, sceneObject) {
1648
- this.state = { name, type: "time_macro" };
1649
- this._sceneObject = sceneObject;
1516
+ class FieldMacro {
1517
+ constructor(name, sceneObject, _match, _scopedVars) {
1518
+ this._match = _match;
1519
+ this._scopedVars = _scopedVars;
1520
+ this.state = { name, type: "__field" };
1650
1521
  }
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();
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;
1527
+ }
1528
+ if (fieldPath === void 0 || fieldPath === "") {
1529
+ return this._match;
1657
1530
  }
1531
+ const { frame, field, data } = dataContext.value;
1532
+ const obj = getTemplateProxyForField(field, frame, data);
1533
+ return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1658
1534
  }
1659
1535
  getValueText() {
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
- }
1536
+ return "";
1666
1537
  }
1667
1538
  }
1668
- class TimezoneMacro {
1669
- constructor(name, sceneObject) {
1670
- this.state = { name, type: "time_macro" };
1671
- this._sceneObject = sceneObject;
1539
+
1540
+ class UrlMacro {
1541
+ constructor(name, _) {
1542
+ this.state = { name, type: "url_macro" };
1672
1543
  }
1673
- getValue() {
1674
- const timeRange = getTimeRange(this._sceneObject);
1675
- const timeZone = timeRange.getTimeZone();
1676
- if (timeZone === "browser") {
1677
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
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;
1678
1556
  }
1679
- return timeZone;
1680
1557
  }
1681
1558
  getValueText() {
1682
- return this.getValue();
1559
+ return "";
1683
1560
  }
1684
1561
  }
1685
- class IntervalMacro {
1686
- constructor(name, sceneObject, match) {
1687
- this.state = { name, type: "time_macro", match };
1688
- this._sceneObject = sceneObject;
1562
+ class UrlStateFormatter {
1563
+ constructor(_urlQueryParams) {
1564
+ this._urlQueryParams = _urlQueryParams;
1689
1565
  }
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;
1566
+ formatter(options) {
1567
+ if (!options) {
1568
+ return this._urlQueryParams;
1569
+ }
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);
1697
1575
  }
1698
- if (this.state.name === "__interval_ms") {
1699
- return request.intervalMs;
1576
+ return `?${allParams}`;
1577
+ }
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);
1584
+ }
1700
1585
  }
1701
- return request.interval;
1586
+ return `?${allParams}`;
1702
1587
  }
1703
- return this.state.match;
1588
+ return this._urlQueryParams;
1704
1589
  }
1705
1590
  }
1706
1591
 
1707
- class AllVariablesMacro {
1708
- constructor(name, sceneObject) {
1709
- this.state = { name, type: "url_variable" };
1710
- this._sceneObject = sceneObject;
1592
+ class UserMacro {
1593
+ constructor(name, _) {
1594
+ this.state = { name, type: "user_macro" };
1711
1595
  }
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
- }
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);
1727
1606
  }
1728
- return new SkipFormattingValue(params.join("&"));
1729
1607
  }
1730
1608
  getValueText() {
1731
1609
  return "";
1732
1610
  }
1733
1611
  }
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
- }
1612
+ class OrgMacro {
1613
+ constructor(name, _) {
1614
+ this.state = { name, type: "org_macro" };
1615
+ }
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);
1743
1624
  }
1744
1625
  }
1745
- if (sceneObject.parent) {
1746
- collectAllVariables(sceneObject.parent, record);
1626
+ getValueText() {
1627
+ return "";
1747
1628
  }
1748
- return record;
1749
1629
  }
1750
1630
 
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;
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
1768
1646
  };
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;
1647
+ function registerVariableMacro(name, macro) {
1648
+ if (macrosIndex[name]) {
1649
+ throw new Error(`Macro already registered ${name}`);
1650
+ }
1651
+ macrosIndex[name] = macro;
1652
+ return () => {
1653
+ delete macrosIndex[name];
1654
+ };
1655
+ }
1656
+
1657
+ function sceneInterpolator(sceneObject, target, scopedVars, format, interpolations) {
1658
+ if (!target) {
1659
+ return target != null ? target : "";
1660
+ }
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 });
1793
1669
  }
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 });
1675
+ }
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);
1683
+ }
1684
+ const variable = lookupVariable(name, sceneObject);
1685
+ if (variable) {
1686
+ return variable;
1687
+ }
1688
+ if (macrosIndex[name]) {
1689
+ return new macrosIndex[name](name, sceneObject, match, scopedVars);
1690
+ }
1691
+ return null;
1692
+ }
1693
+ function formatValue(context, variable, value, formatNameOrFn) {
1694
+ if (value === null || value === void 0) {
1695
+ return "";
1696
+ }
1697
+ if (isCustomVariableValue(value)) {
1698
+ return sceneInterpolator(context, value.formatter(formatNameOrFn));
1699
+ }
1700
+ if (!Array.isArray(value) && typeof value === "object") {
1701
+ value = `${value}`;
1702
+ }
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
+ });
1710
+ }
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 = [];
1794
1721
  }
1795
- );
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);
1796
1729
  }
1797
1730
 
1798
- class ValueMacro {
1799
- constructor(name, sceneObject, _match, _scopedVars) {
1800
- this._match = _match;
1801
- this._scopedVars = _scopedVars;
1802
- this.state = { name, type: "__value" };
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;
1739
+ }
1740
+
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
+ });
1803
1766
  }
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;
1809
- }
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
- }
1823
- }
1824
- if (rowIndex == null) {
1825
- return this._match;
1826
- }
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;
1767
+ queryStarted(entry) {
1768
+ __privateGet(this, _running).add(entry);
1769
+ this.changeRunningQueryCount(1);
1770
+ if (!this.state.isRunning) {
1771
+ this.setState({ isRunning: true });
1833
1772
  }
1834
- const value = field.values.get(rowIndex);
1835
- if (fieldPath === "raw") {
1836
- return value;
1773
+ }
1774
+ queryCompleted(entry) {
1775
+ if (!__privateGet(this, _running).has(entry)) {
1776
+ return;
1837
1777
  }
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);
1778
+ __privateGet(this, _running).delete(entry);
1779
+ this.changeRunningQueryCount(-1);
1780
+ if (__privateGet(this, _running).size === 0) {
1781
+ this.setState({ isRunning: false });
1846
1782
  }
1847
1783
  }
1848
- getValueText() {
1849
- return "";
1850
- }
1851
- }
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" };
1784
+ changeRunningQueryCount(dir) {
1785
+ var _a;
1786
+ window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1858
1787
  }
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;
1788
+ cancelAll() {
1789
+ var _a;
1790
+ for (const entry of __privateGet(this, _running).values()) {
1791
+ (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1868
1792
  }
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
1793
  }
1876
- getValueText() {
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;
1812
+ }
1813
+ return null;
1814
+ }
1815
+ function interpolate(sceneObject, value, scopedVars, format, interpolations) {
1816
+ if (value === "" || value == null) {
1877
1817
  return "";
1878
1818
  }
1819
+ return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1879
1820
  }
1880
- class SeriesMacro {
1881
- constructor(name, sceneObject, _match, _scopedVars) {
1882
- this._match = _match;
1883
- this._scopedVars = _scopedVars;
1884
- this.state = { name, type: "__series" };
1821
+ function hasVariableDependencyInLoadingState(sceneObject) {
1822
+ if (!sceneObject.variableDependency) {
1823
+ return false;
1885
1824
  }
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;
1825
+ for (const name of sceneObject.variableDependency.getNames()) {
1826
+ const variable = lookupVariable(name, sceneObject);
1827
+ if (!variable) {
1828
+ continue;
1891
1829
  }
1892
- if (fieldPath !== "name") {
1893
- return this._match;
1830
+ const set = variable.parent;
1831
+ if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1832
+ return true;
1894
1833
  }
1895
- const { frame, frameIndex } = dataContext.value;
1896
- return data.getFrameDisplayName(frame, frameIndex);
1897
- }
1898
- getValueText() {
1899
- return "";
1900
1834
  }
1835
+ return false;
1901
1836
  }
1902
- class FieldMacro {
1903
- constructor(name, sceneObject, _match, _scopedVars) {
1904
- this._match = _match;
1905
- this._scopedVars = _scopedVars;
1906
- this.state = { name, type: "__field" };
1837
+ function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1838
+ if (check(scene)) {
1839
+ return scene;
1907
1840
  }
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;
1841
+ let found = null;
1842
+ scene.forEachChild((child) => {
1843
+ if (child === alreadySearchedChild) {
1844
+ return;
1913
1845
  }
1914
- if (fieldPath === void 0 || fieldPath === "") {
1915
- return this._match;
1846
+ let maybe = findObjectInternal(child, check);
1847
+ if (maybe) {
1848
+ found = maybe;
1916
1849
  }
1917
- const { frame, field, data } = dataContext.value;
1918
- const obj = getTemplateProxyForField(field, frame, data);
1919
- return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1850
+ });
1851
+ if (found) {
1852
+ return found;
1920
1853
  }
1921
- getValueText() {
1922
- return "";
1854
+ if (shouldSearchUp && scene.parent) {
1855
+ return findObjectInternal(scene.parent, check, scene, true);
1923
1856
  }
1857
+ return null;
1924
1858
  }
1925
-
1926
- class UrlMacro {
1927
- constructor(name, _) {
1928
- this.state = { name, type: "url_macro" };
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);
1929
1865
  }
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
- }
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);
1943
1874
  }
1944
- getValueText() {
1945
- return "";
1875
+ if (!(found instanceof targetType)) {
1876
+ throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1946
1877
  }
1878
+ return found;
1947
1879
  }
1948
- class UrlStateFormatter {
1949
- constructor(_urlQueryParams) {
1950
- this._urlQueryParams = _urlQueryParams;
1951
- }
1952
- formatter(options) {
1953
- if (!options) {
1954
- return this._urlQueryParams;
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);
1955
1888
  }
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);
1961
- }
1962
- return `?${allParams}`;
1889
+ found.push(...findAllObjects(child, check));
1890
+ });
1891
+ return found;
1892
+ }
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;
1963
1901
  }
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
- }
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);
1971
1907
  }
1972
- return `?${allParams}`;
1973
1908
  }
1974
- return this._urlQueryParams;
1975
- }
1976
- }
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);
1909
+ if (localOnly && collected.length > 0) {
1910
+ break;
1992
1911
  }
1912
+ currentLevel = currentLevel.parent;
1993
1913
  }
1994
- getValueText() {
1995
- return "";
1996
- }
1914
+ return collected;
1997
1915
  }
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);
1916
+ function getAncestor(sceneObject, ancestorType) {
1917
+ let parent = sceneObject;
1918
+ while (parent) {
1919
+ if (parent instanceof ancestorType) {
1920
+ return parent;
2010
1921
  }
1922
+ parent = parent.parent;
2011
1923
  }
2012
- getValueText() {
2013
- return "";
1924
+ if (!parent) {
1925
+ throw new Error("Unable to find parent of type " + ancestorType.name);
2014
1926
  }
1927
+ return parent;
2015
1928
  }
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}`);
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
+ }
1938
+ }
1939
+ parent = parent.parent;
2036
1940
  }
2037
- macrosIndex[name] = macro;
2038
- return () => {
2039
- delete macrosIndex[name];
2040
- };
1941
+ return void 0;
2041
1942
  }
2042
1943
 
2043
1944
  const sceneGraph = {
@@ -2057,6 +1958,117 @@ const sceneGraph = {
2057
1958
  getQueryController
2058
1959
  };
2059
1960
 
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
+
2060
2072
  async function getDataSource(datasource, scopedVars) {
2061
2073
  if (datasource == null ? void 0 : datasource.uid) {
2062
2074
  const runtimeDataSource = runtimeDataSources.get(datasource.uid);
@@ -7720,28 +7732,12 @@ class UrlSyncManager {
7720
7732
  constructor() {
7721
7733
  this._urlKeyMapper = new UniqueUrlKeyMapper();
7722
7734
  this._stateSub = null;
7723
- this._locationSub = null;
7724
- this._ignoreNextLocationUpdate = false;
7725
- this._onLocationUpdate = (location) => {
7726
- if (this._ignoreNextLocationUpdate) {
7727
- this._ignoreNextLocationUpdate = false;
7728
- return;
7729
- }
7730
- if (this._lastPath !== location.pathname) {
7731
- return;
7732
- }
7733
- const urlParams = new URLSearchParams(location.search);
7734
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7735
- syncStateFromUrl(this._sceneRoot, urlParams, this._urlKeyMapper);
7736
- this._lastPath = location.pathname;
7737
- };
7738
7735
  this._onStateChanged = ({ payload }) => {
7739
7736
  const changedObject = payload.changedObject;
7740
7737
  if (changedObject.urlSync) {
7741
7738
  const newUrlState = changedObject.urlSync.getUrlState();
7742
7739
  const searchParams = runtime.locationService.getSearch();
7743
7740
  const mappedUpdated = {};
7744
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7745
7741
  for (const [key, newUrlValue] of Object.entries(newUrlState)) {
7746
7742
  const uniqueKey = this._urlKeyMapper.getUniqueKey(key, changedObject);
7747
7743
  const currentUrlValue = searchParams.getAll(uniqueKey);
@@ -7750,36 +7746,33 @@ class UrlSyncManager {
7750
7746
  }
7751
7747
  }
7752
7748
  if (Object.keys(mappedUpdated).length > 0) {
7753
- this._ignoreNextLocationUpdate = true;
7749
+ writeSceneLog("UrlSyncManager", "onStateChange updating URL");
7754
7750
  runtime.locationService.partial(mappedUpdated, true);
7751
+ this._lastLocation = runtime.locationService.getLocation();
7752
+ this._urlParams = new URLSearchParams(this._lastLocation.search);
7755
7753
  }
7756
7754
  }
7757
7755
  };
7758
7756
  }
7759
7757
  initSync(root) {
7760
- if (!this._locationSub) {
7761
- writeSceneLog("UrlSyncManager", "New location listen");
7762
- this._locationSub = runtime.locationService.getHistory().listen(this._onLocationUpdate);
7763
- }
7758
+ var _a;
7764
7759
  if (this._stateSub) {
7765
- writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", this._sceneRoot.state.key);
7760
+ writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", (_a = this._sceneRoot) == null ? void 0 : _a.state.key);
7766
7761
  this._stateSub.unsubscribe();
7767
7762
  }
7763
+ writeSceneLog("UrlSyncManager", "init", root.state.key);
7768
7764
  this._sceneRoot = root;
7769
- this._lastPath = runtime.locationService.getLocation().pathname;
7770
7765
  this._stateSub = root.subscribeToEvent(SceneObjectStateChangedEvent, this._onStateChanged);
7771
- this.syncFrom(this._sceneRoot);
7766
+ this._urlKeyMapper.clear();
7767
+ this._lastLocation = runtime.locationService.getLocation();
7768
+ this._urlParams = new URLSearchParams(this._lastLocation.search);
7769
+ this.handleNewObject(this._sceneRoot);
7772
7770
  }
7773
7771
  cleanUp(root) {
7774
7772
  if (this._sceneRoot !== root) {
7775
7773
  return;
7776
7774
  }
7777
7775
  writeSceneLog("UrlSyncManager", "Clean up");
7778
- if (this._locationSub) {
7779
- this._locationSub();
7780
- writeSceneLog("UrlSyncManager", "Unregister history listen");
7781
- this._locationSub = null;
7782
- }
7783
7776
  if (this._stateSub) {
7784
7777
  this._stateSub.unsubscribe();
7785
7778
  this._stateSub = null;
@@ -7790,11 +7783,23 @@ class UrlSyncManager {
7790
7783
  this._sceneRoot.state.key === root.state.key
7791
7784
  );
7792
7785
  }
7786
+ this._sceneRoot = void 0;
7787
+ this._urlParams = void 0;
7793
7788
  }
7794
- syncFrom(sceneObj) {
7795
- const urlParams = runtime.locationService.getSearch();
7796
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7797
- syncStateFromUrl(sceneObj, urlParams, this._urlKeyMapper);
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
+ }
7798
+ handleNewObject(sceneObj) {
7799
+ if (!this._sceneRoot || !this._urlParams) {
7800
+ return;
7801
+ }
7802
+ syncStateFromUrl(sceneObj, this._urlParams, this._urlKeyMapper);
7798
7803
  }
7799
7804
  getUrlState(root) {
7800
7805
  return getUrlState(root);
@@ -7808,6 +7813,29 @@ function getUrlSyncManager() {
7808
7813
  return urlSyncManager;
7809
7814
  }
7810
7815
 
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
+ urlSyncManager.handleNewLocation(location);
7827
+ }, [sceneRoot, urlSyncManager, location]);
7828
+ return isInitialized;
7829
+ }
7830
+
7831
+ function UrlSyncContextProvider({ children, scene }) {
7832
+ const isInitialized = useUrlSync(scene);
7833
+ if (!isInitialized) {
7834
+ return null;
7835
+ }
7836
+ return children;
7837
+ }
7838
+
7811
7839
  function setWindowGrafanaSceneContext(activeScene) {
7812
7840
  const prevScene = window.__grafanaSceneContext;
7813
7841
  writeSceneLog("setWindowGrafanaScene", "set window.__grafanaSceneContext", activeScene);
@@ -7827,13 +7855,9 @@ class EmbeddedScene extends SceneObjectBase {
7827
7855
  const unsetGlobalScene = setWindowGrafanaSceneContext(this);
7828
7856
  return () => {
7829
7857
  unsetGlobalScene();
7830
- getUrlSyncManager().cleanUp(this);
7831
7858
  };
7832
7859
  });
7833
7860
  }
7834
- initUrlSync() {
7835
- getUrlSyncManager().initSync(this);
7836
- }
7837
7861
  }
7838
7862
  EmbeddedScene.Component = EmbeddedSceneRenderer;
7839
7863
  function EmbeddedSceneRenderer({ model }) {
@@ -10306,7 +10330,8 @@ function SceneAppPageView({ page, routeProps }) {
10306
10330
  React.useEffect(() => {
10307
10331
  return () => containerPage.setState({ initializedScene: void 0 });
10308
10332
  }, [containerPage]);
10309
- if (!isInitialized) {
10333
+ const urlSyncInitialized = useUrlSync(containerPage);
10334
+ if (!isInitialized && !urlSyncInitialized) {
10310
10335
  return null;
10311
10336
  }
10312
10337
  const pageNav = {
@@ -10379,13 +10404,9 @@ class SceneAppPage extends SceneObjectBase {
10379
10404
  super(state);
10380
10405
  this._sceneCache = /* @__PURE__ */ new Map();
10381
10406
  this._drilldownCache = /* @__PURE__ */ new Map();
10382
- this.addActivationHandler(() => {
10383
- return () => getUrlSyncManager().cleanUp(this);
10384
- });
10385
10407
  }
10386
10408
  initializeScene(scene) {
10387
10409
  this.setState({ initializedScene: scene });
10388
- getUrlSyncManager().initSync(this);
10389
10410
  }
10390
10411
  getScene(routeMatch) {
10391
10412
  let scene = this._sceneCache.get(routeMatch.url);
@@ -11380,6 +11401,7 @@ exports.SceneVariableValueChangedEvent = SceneVariableValueChangedEvent;
11380
11401
  exports.SplitLayout = SplitLayout;
11381
11402
  exports.TestVariable = TestVariable;
11382
11403
  exports.TextBoxVariable = TextBoxVariable;
11404
+ exports.UrlSyncContextProvider = UrlSyncContextProvider;
11383
11405
  exports.UrlSyncManager = UrlSyncManager;
11384
11406
  exports.UserActionEvent = UserActionEvent;
11385
11407
  exports.VariableDependencyConfig = VariableDependencyConfig;
@@ -11405,4 +11427,5 @@ exports.sceneGraph = sceneGraph;
11405
11427
  exports.sceneUtils = sceneUtils;
11406
11428
  exports.useSceneApp = useSceneApp;
11407
11429
  exports.useSceneObjectState = useSceneObjectState;
11430
+ exports.useUrlSync = useUrlSync;
11408
11431
  //# sourceMappingURL=index.js.map