@grafana/scenes 4.29.0 → 4.29.1--canary.765.9461208757.0

Sign up to get free protection for your applications and to get access to all the features.
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,733 +1233,715 @@ 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 isFiltersRequestEnricher(obj) {
1416
- return "enrichFiltersRequest" in obj;
1417
- }
1418
- function isDataLayer(obj) {
1419
- return "isDataLayer" in obj;
1420
- }
1421
-
1422
- var __accessCheck = (obj, member, msg) => {
1423
- if (!member.has(obj))
1424
- throw TypeError("Cannot " + msg);
1425
- };
1426
- var __privateGet = (obj, member, getter) => {
1427
- __accessCheck(obj, member, "read from private field");
1428
- return getter ? getter.call(obj) : member.get(obj);
1429
- };
1430
- var __privateAdd = (obj, member, value) => {
1431
- if (member.has(obj))
1432
- throw TypeError("Cannot add the same private member more than once");
1433
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1434
- };
1435
- var _running;
1436
- function isQueryController(s) {
1437
- return "isQueryController" in s;
1438
- }
1439
- class SceneQueryController extends SceneObjectBase {
1440
- constructor() {
1441
- super({ isRunning: false });
1442
- this.isQueryController = true;
1443
- __privateAdd(this, _running, /* @__PURE__ */ new Set());
1444
- this.addActivationHandler(() => {
1445
- return () => __privateGet(this, _running).clear();
1446
- });
1447
- }
1448
- queryStarted(entry) {
1449
- __privateGet(this, _running).add(entry);
1450
- this.changeRunningQueryCount(1);
1451
- if (!this.state.isRunning) {
1452
- this.setState({ isRunning: true });
1453
- }
1454
- }
1455
- queryCompleted(entry) {
1456
- if (!__privateGet(this, _running).has(entry)) {
1457
- return;
1458
- }
1459
- __privateGet(this, _running).delete(entry);
1460
- this.changeRunningQueryCount(-1);
1461
- if (__privateGet(this, _running).size === 0) {
1462
- 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
+ }
1463
1357
  }
1464
1358
  }
1465
- changeRunningQueryCount(dir) {
1466
- var _a;
1467
- window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1468
- }
1469
- cancelAll() {
1470
- var _a;
1471
- for (const entry of __privateGet(this, _running).values()) {
1472
- (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1473
- }
1359
+ if (sceneObject.parent) {
1360
+ collectAllVariables(sceneObject.parent, record);
1474
1361
  }
1362
+ return record;
1475
1363
  }
1476
- _running = new WeakMap();
1477
1364
 
1478
- function getVariables(sceneObject) {
1479
- var _a;
1480
- return (_a = getClosest(sceneObject, (s) => s.state.$variables)) != null ? _a : EmptyVariableSet;
1481
- }
1482
- function getData(sceneObject) {
1483
- var _a;
1484
- return (_a = getClosest(sceneObject, (s) => s.state.$data)) != null ? _a : EmptyDataNode;
1485
- }
1486
- function isSceneLayout(s) {
1487
- return "isDraggable" in s;
1488
- }
1489
- function getLayout(scene) {
1490
- const parent = getClosest(scene, (s) => isSceneLayout(s) ? s : void 0);
1491
- if (parent) {
1492
- return parent;
1493
- }
1494
- return null;
1495
- }
1496
- function interpolate(sceneObject, value, scopedVars, format, interpolations) {
1497
- if (value === "" || value == null) {
1498
- return "";
1499
- }
1500
- return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1501
- }
1502
- function hasVariableDependencyInLoadingState(sceneObject) {
1503
- if (!sceneObject.variableDependency) {
1504
- return false;
1505
- }
1506
- for (const name of sceneObject.variableDependency.getNames()) {
1507
- const variable = lookupVariable(name, sceneObject);
1508
- if (!variable) {
1509
- 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]);
1510
1380
  }
1511
- const set = variable.parent;
1512
- if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1513
- 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
+ }
1514
1408
  }
1515
- }
1516
- return false;
1409
+ );
1517
1410
  }
1518
- function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1519
- if (check(scene)) {
1520
- 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" };
1521
1417
  }
1522
- let found = null;
1523
- scene.forEachChild((child) => {
1524
- if (child === alreadySearchedChild) {
1525
- 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;
1526
1423
  }
1527
- let maybe = findObjectInternal(child, check);
1528
- if (maybe) {
1529
- 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
+ }
1530
1437
  }
1531
- });
1532
- if (found) {
1533
- return found;
1534
- }
1535
- if (shouldSearchUp && scene.parent) {
1536
- return findObjectInternal(scene.parent, check, scene, true);
1537
- }
1538
- return null;
1539
- }
1540
- function findByKey(sceneObject, key) {
1541
- const found = findObject(sceneObject, (sceneToCheck) => {
1542
- return sceneToCheck.state.key === key;
1543
- });
1544
- if (!found) {
1545
- throw new Error("Unable to find scene with key " + key);
1546
- }
1547
- return found;
1548
- }
1549
- function findByKeyAndType(sceneObject, key, targetType) {
1550
- const found = findObject(sceneObject, (sceneToCheck) => {
1551
- return sceneToCheck.state.key === key;
1552
- });
1553
- if (!found) {
1554
- throw new Error("Unable to find scene with key " + key);
1555
- }
1556
- if (!(found instanceof targetType)) {
1557
- throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1558
- }
1559
- return found;
1560
- }
1561
- function findObject(scene, check) {
1562
- return findObjectInternal(scene, check, void 0, true);
1563
- }
1564
- function findAllObjects(scene, check) {
1565
- const found = [];
1566
- scene.forEachChild((child) => {
1567
- if (check(child)) {
1568
- found.push(child);
1438
+ if (rowIndex == null) {
1439
+ return this._match;
1569
1440
  }
1570
- found.push(...findAllObjects(child, check));
1571
- });
1572
- return found;
1573
- }
1574
- function getDataLayers(sceneObject, localOnly = false) {
1575
- let currentLevel = sceneObject;
1576
- let collected = [];
1577
- while (currentLevel) {
1578
- const dataProvider = currentLevel.state.$data;
1579
- if (!dataProvider) {
1580
- currentLevel = currentLevel.parent;
1581
- 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;
1582
1444
  }
1583
- if (isDataLayer(dataProvider)) {
1584
- collected = collected.concat(dataProvider);
1585
- } else {
1586
- if (dataProvider.state.$data && isDataLayer(dataProvider.state.$data)) {
1587
- collected = collected.concat(dataProvider.state.$data);
1588
- }
1445
+ if (!field) {
1446
+ return this._match;
1589
1447
  }
1590
- if (localOnly && collected.length > 0) {
1591
- break;
1448
+ const value = field.values.get(rowIndex);
1449
+ if (fieldPath === "raw") {
1450
+ return value;
1592
1451
  }
1593
- currentLevel = currentLevel.parent;
1594
- }
1595
- return collected;
1596
- }
1597
- function getAncestor(sceneObject, ancestorType) {
1598
- let parent = sceneObject;
1599
- while (parent) {
1600
- if (parent instanceof ancestorType) {
1601
- 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);
1602
1460
  }
1603
- parent = parent.parent;
1604
1461
  }
1605
- if (!parent) {
1606
- throw new Error("Unable to find parent of type " + ancestorType.name);
1462
+ getValueText() {
1463
+ return "";
1607
1464
  }
1608
- return parent;
1609
1465
  }
1610
- function getQueryController(sceneObject) {
1611
- let parent = sceneObject;
1612
- while (parent) {
1613
- if (parent.state.$behaviors) {
1614
- for (const behavior of parent.state.$behaviors) {
1615
- if (isQueryController(behavior)) {
1616
- return behavior;
1617
- }
1618
- }
1619
- }
1620
- 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" };
1621
1472
  }
1622
- return void 0;
1623
- }
1624
-
1625
- class SkipFormattingValue {
1626
- constructor(_value) {
1627
- 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 : "";
1628
1489
  }
1629
- formatter() {
1630
- return this._value;
1490
+ getValueText() {
1491
+ return "";
1631
1492
  }
1632
1493
  }
1633
-
1634
- class UrlTimeRangeMacro {
1635
- constructor(name, sceneObject) {
1636
- this.state = { name, type: "url_variable" };
1637
- 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" };
1638
1499
  }
1639
- getValue() {
1500
+ getValue(fieldPath) {
1640
1501
  var _a;
1641
- const timeRange = getTimeRange(this._sceneObject);
1642
- const urlState = (_a = timeRange.urlSync) == null ? void 0 : _a.getUrlState();
1643
- 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);
1644
1511
  }
1645
1512
  getValueText() {
1646
1513
  return "";
1647
1514
  }
1648
1515
  }
1649
- class TimeFromAndToMacro {
1650
- constructor(name, sceneObject) {
1651
- this.state = { name, type: "time_macro" };
1652
- 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" };
1653
1521
  }
1654
- getValue() {
1655
- const timeRange = getTimeRange(this._sceneObject);
1656
- if (this.state.name === "__from") {
1657
- return timeRange.state.value.from.valueOf();
1658
- } else {
1659
- 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;
1660
1527
  }
1528
+ if (fieldPath === void 0 || fieldPath === "") {
1529
+ return this._match;
1530
+ }
1531
+ const { frame, field, data } = dataContext.value;
1532
+ const obj = getTemplateProxyForField(field, frame, data);
1533
+ return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1661
1534
  }
1662
1535
  getValueText() {
1663
- const timeRange = getTimeRange(this._sceneObject);
1664
- if (this.state.name === "__from") {
1665
- return data.dateTimeFormat(timeRange.state.value.from, { timeZone: timeRange.getTimeZone() });
1666
- } else {
1667
- return data.dateTimeFormat(timeRange.state.value.to, { timeZone: timeRange.getTimeZone() });
1668
- }
1536
+ return "";
1669
1537
  }
1670
1538
  }
1671
- class TimezoneMacro {
1672
- constructor(name, sceneObject) {
1673
- this.state = { name, type: "time_macro" };
1674
- this._sceneObject = sceneObject;
1539
+
1540
+ class UrlMacro {
1541
+ constructor(name, _) {
1542
+ this.state = { name, type: "url_macro" };
1675
1543
  }
1676
- getValue() {
1677
- const timeRange = getTimeRange(this._sceneObject);
1678
- const timeZone = timeRange.getTimeZone();
1679
- if (timeZone === "browser") {
1680
- 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;
1681
1556
  }
1682
- return timeZone;
1683
1557
  }
1684
1558
  getValueText() {
1685
- return this.getValue();
1559
+ return "";
1686
1560
  }
1687
1561
  }
1688
- class IntervalMacro {
1689
- constructor(name, sceneObject, match) {
1690
- this.state = { name, type: "time_macro", match };
1691
- this._sceneObject = sceneObject;
1562
+ class UrlStateFormatter {
1563
+ constructor(_urlQueryParams) {
1564
+ this._urlQueryParams = _urlQueryParams;
1692
1565
  }
1693
- getValue() {
1694
- var _a;
1695
- const data = getData(this._sceneObject);
1696
- if (data) {
1697
- const request = (_a = data.state.data) == null ? void 0 : _a.request;
1698
- if (!request) {
1699
- 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);
1700
1575
  }
1701
- if (this.state.name === "__interval_ms") {
1702
- 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
+ }
1703
1585
  }
1704
- return request.interval;
1586
+ return `?${allParams}`;
1705
1587
  }
1706
- return this.state.match;
1588
+ return this._urlQueryParams;
1707
1589
  }
1708
1590
  }
1709
1591
 
1710
- class AllVariablesMacro {
1711
- constructor(name, sceneObject) {
1712
- this.state = { name, type: "url_variable" };
1713
- this._sceneObject = sceneObject;
1592
+ class UserMacro {
1593
+ constructor(name, _) {
1594
+ this.state = { name, type: "user_macro" };
1714
1595
  }
1715
- getValue() {
1716
- const allVars = collectAllVariables(this._sceneObject);
1717
- const format = formatRegistry.get(schema.VariableFormatID.QueryParam);
1718
- const params = [];
1719
- for (const name of Object.keys(allVars)) {
1720
- const variable = allVars[name];
1721
- const value = variable.getValue();
1722
- if (!value) {
1723
- continue;
1724
- }
1725
- if (isCustomVariableValue(value)) {
1726
- params.push(value.formatter(schema.VariableFormatID.QueryParam));
1727
- } else {
1728
- params.push(format.formatter(value, [], variable));
1729
- }
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);
1730
1606
  }
1731
- return new SkipFormattingValue(params.join("&"));
1732
1607
  }
1733
1608
  getValueText() {
1734
1609
  return "";
1735
1610
  }
1736
1611
  }
1737
- function collectAllVariables(sceneObject, record = {}) {
1738
- if (sceneObject.state.$variables) {
1739
- for (const variable of sceneObject.state.$variables.state.variables) {
1740
- if (variable.state.skipUrlSync) {
1741
- continue;
1742
- }
1743
- if (!record[variable.state.name]) {
1744
- record[variable.state.name] = variable;
1745
- }
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);
1746
1624
  }
1747
1625
  }
1748
- if (sceneObject.parent) {
1749
- collectAllVariables(sceneObject.parent, record);
1626
+ getValueText() {
1627
+ return "";
1750
1628
  }
1751
- return record;
1752
1629
  }
1753
1630
 
1754
- var __defProp$D = Object.defineProperty;
1755
- var __defProps$r = Object.defineProperties;
1756
- var __getOwnPropDescs$r = Object.getOwnPropertyDescriptors;
1757
- var __getOwnPropSymbols$D = Object.getOwnPropertySymbols;
1758
- var __hasOwnProp$D = Object.prototype.hasOwnProperty;
1759
- var __propIsEnum$D = Object.prototype.propertyIsEnumerable;
1760
- var __defNormalProp$D = (obj, key, value) => key in obj ? __defProp$D(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1761
- var __spreadValues$D = (a, b) => {
1762
- for (var prop in b || (b = {}))
1763
- if (__hasOwnProp$D.call(b, prop))
1764
- __defNormalProp$D(a, prop, b[prop]);
1765
- if (__getOwnPropSymbols$D)
1766
- for (var prop of __getOwnPropSymbols$D(b)) {
1767
- if (__propIsEnum$D.call(b, prop))
1768
- __defNormalProp$D(a, prop, b[prop]);
1769
- }
1770
- 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
1771
1646
  };
1772
- var __spreadProps$r = (a, b) => __defProps$r(a, __getOwnPropDescs$r(b));
1773
- function getTemplateProxyForField(field, frame, frames) {
1774
- return new Proxy(
1775
- {},
1776
- {
1777
- get: (obj, key) => {
1778
- if (key === "name") {
1779
- return field.name;
1780
- }
1781
- if (key === "displayName") {
1782
- return data.getFieldDisplayName(field, frame, frames);
1783
- }
1784
- if (key === "labels" || key === "formattedLabels") {
1785
- if (!field.labels) {
1786
- return "";
1787
- }
1788
- return __spreadProps$r(__spreadValues$D({}, field.labels), {
1789
- __values: Object.values(field.labels).sort().join(", "),
1790
- toString: () => {
1791
- return data.formatLabels(field.labels, "", true);
1792
- }
1793
- });
1794
- }
1795
- 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 });
1796
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 = [];
1797
1721
  }
1798
- );
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);
1799
1729
  }
1800
1730
 
1801
- class ValueMacro {
1802
- constructor(name, sceneObject, _match, _scopedVars) {
1803
- this._match = _match;
1804
- this._scopedVars = _scopedVars;
1805
- 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 isFiltersRequestEnricher(obj) {
1738
+ return "enrichFiltersRequest" in obj;
1739
+ }
1740
+ function isDataLayer(obj) {
1741
+ return "isDataLayer" in obj;
1742
+ }
1743
+
1744
+ var __accessCheck = (obj, member, msg) => {
1745
+ if (!member.has(obj))
1746
+ throw TypeError("Cannot " + msg);
1747
+ };
1748
+ var __privateGet = (obj, member, getter) => {
1749
+ __accessCheck(obj, member, "read from private field");
1750
+ return getter ? getter.call(obj) : member.get(obj);
1751
+ };
1752
+ var __privateAdd = (obj, member, value) => {
1753
+ if (member.has(obj))
1754
+ throw TypeError("Cannot add the same private member more than once");
1755
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1756
+ };
1757
+ var _running;
1758
+ function isQueryController(s) {
1759
+ return "isQueryController" in s;
1760
+ }
1761
+ class SceneQueryController extends SceneObjectBase {
1762
+ constructor() {
1763
+ super({ isRunning: false });
1764
+ this.isQueryController = true;
1765
+ __privateAdd(this, _running, /* @__PURE__ */ new Set());
1766
+ this.addActivationHandler(() => {
1767
+ return () => __privateGet(this, _running).clear();
1768
+ });
1806
1769
  }
1807
- getValue(fieldPath) {
1808
- var _a, _b;
1809
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1810
- if (!dataContext) {
1811
- return this._match;
1812
- }
1813
- const { frame, rowIndex, field, calculatedValue } = dataContext.value;
1814
- if (calculatedValue) {
1815
- switch (fieldPath) {
1816
- case "numeric":
1817
- return calculatedValue.numeric;
1818
- case "raw":
1819
- return calculatedValue.numeric;
1820
- case "time":
1821
- return "";
1822
- case "text":
1823
- default:
1824
- return data.formattedValueToString(calculatedValue);
1825
- }
1826
- }
1827
- if (rowIndex == null) {
1828
- return this._match;
1829
- }
1830
- if (fieldPath === "time") {
1831
- const timeField = frame.fields.find((f) => f.type === data.FieldType.time);
1832
- return timeField ? timeField.values.get(rowIndex) : void 0;
1833
- }
1834
- if (!field) {
1835
- return this._match;
1770
+ queryStarted(entry) {
1771
+ __privateGet(this, _running).add(entry);
1772
+ this.changeRunningQueryCount(1);
1773
+ if (!this.state.isRunning) {
1774
+ this.setState({ isRunning: true });
1836
1775
  }
1837
- const value = field.values.get(rowIndex);
1838
- if (fieldPath === "raw") {
1839
- return value;
1776
+ }
1777
+ queryCompleted(entry) {
1778
+ if (!__privateGet(this, _running).has(entry)) {
1779
+ return;
1840
1780
  }
1841
- const displayProcessor = (_b = field.display) != null ? _b : fallbackDisplayProcessor;
1842
- const result = displayProcessor(value);
1843
- switch (fieldPath) {
1844
- case "numeric":
1845
- return result.numeric;
1846
- case "text":
1847
- default:
1848
- return data.formattedValueToString(result);
1781
+ __privateGet(this, _running).delete(entry);
1782
+ this.changeRunningQueryCount(-1);
1783
+ if (__privateGet(this, _running).size === 0) {
1784
+ this.setState({ isRunning: false });
1849
1785
  }
1850
1786
  }
1851
- getValueText() {
1852
- return "";
1853
- }
1854
- }
1855
- const fallbackDisplayProcessor = data.getDisplayProcessor();
1856
- class DataMacro {
1857
- constructor(name, sceneObject, _match, _scopedVars) {
1858
- this._match = _match;
1859
- this._scopedVars = _scopedVars;
1860
- this.state = { name, type: "__data" };
1787
+ changeRunningQueryCount(dir) {
1788
+ var _a;
1789
+ window.__grafanaRunningQueryCount = ((_a = window.__grafanaRunningQueryCount) != null ? _a : 0) + dir;
1861
1790
  }
1862
- getValue(fieldPath) {
1863
- var _a, _b;
1864
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1865
- if (!dataContext || !fieldPath) {
1866
- return this._match;
1867
- }
1868
- const { frame, rowIndex } = dataContext.value;
1869
- if (rowIndex === void 0 || fieldPath === void 0) {
1870
- return this._match;
1791
+ cancelAll() {
1792
+ var _a;
1793
+ for (const entry of __privateGet(this, _running).values()) {
1794
+ (_a = entry.cancel) == null ? void 0 : _a.call(entry);
1871
1795
  }
1872
- const obj = {
1873
- name: frame.name,
1874
- refId: frame.refId,
1875
- fields: data.getFieldDisplayValuesProxy({ frame, rowIndex })
1876
- };
1877
- return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1878
1796
  }
1879
- getValueText() {
1797
+ }
1798
+ _running = new WeakMap();
1799
+
1800
+ function getVariables(sceneObject) {
1801
+ var _a;
1802
+ return (_a = getClosest(sceneObject, (s) => s.state.$variables)) != null ? _a : EmptyVariableSet;
1803
+ }
1804
+ function getData(sceneObject) {
1805
+ var _a;
1806
+ return (_a = getClosest(sceneObject, (s) => s.state.$data)) != null ? _a : EmptyDataNode;
1807
+ }
1808
+ function isSceneLayout(s) {
1809
+ return "isDraggable" in s;
1810
+ }
1811
+ function getLayout(scene) {
1812
+ const parent = getClosest(scene, (s) => isSceneLayout(s) ? s : void 0);
1813
+ if (parent) {
1814
+ return parent;
1815
+ }
1816
+ return null;
1817
+ }
1818
+ function interpolate(sceneObject, value, scopedVars, format, interpolations) {
1819
+ if (value === "" || value == null) {
1880
1820
  return "";
1881
1821
  }
1822
+ return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);
1882
1823
  }
1883
- class SeriesMacro {
1884
- constructor(name, sceneObject, _match, _scopedVars) {
1885
- this._match = _match;
1886
- this._scopedVars = _scopedVars;
1887
- this.state = { name, type: "__series" };
1824
+ function hasVariableDependencyInLoadingState(sceneObject) {
1825
+ if (!sceneObject.variableDependency) {
1826
+ return false;
1888
1827
  }
1889
- getValue(fieldPath) {
1890
- var _a;
1891
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1892
- if (!dataContext || !fieldPath) {
1893
- return this._match;
1828
+ for (const name of sceneObject.variableDependency.getNames()) {
1829
+ const variable = lookupVariable(name, sceneObject);
1830
+ if (!variable) {
1831
+ continue;
1894
1832
  }
1895
- if (fieldPath !== "name") {
1896
- return this._match;
1833
+ const set = variable.parent;
1834
+ if (set.isVariableLoadingOrWaitingToUpdate(variable)) {
1835
+ return true;
1897
1836
  }
1898
- const { frame, frameIndex } = dataContext.value;
1899
- return data.getFrameDisplayName(frame, frameIndex);
1900
- }
1901
- getValueText() {
1902
- return "";
1903
1837
  }
1838
+ return false;
1904
1839
  }
1905
- class FieldMacro {
1906
- constructor(name, sceneObject, _match, _scopedVars) {
1907
- this._match = _match;
1908
- this._scopedVars = _scopedVars;
1909
- this.state = { name, type: "__field" };
1840
+ function findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {
1841
+ if (check(scene)) {
1842
+ return scene;
1910
1843
  }
1911
- getValue(fieldPath) {
1912
- var _a, _b;
1913
- const dataContext = (_a = this._scopedVars) == null ? void 0 : _a.__dataContext;
1914
- if (!dataContext || !fieldPath) {
1915
- return this._match;
1844
+ let found = null;
1845
+ scene.forEachChild((child) => {
1846
+ if (child === alreadySearchedChild) {
1847
+ return;
1916
1848
  }
1917
- if (fieldPath === void 0 || fieldPath === "") {
1918
- return this._match;
1849
+ let maybe = findObjectInternal(child, check);
1850
+ if (maybe) {
1851
+ found = maybe;
1919
1852
  }
1920
- const { frame, field, data } = dataContext.value;
1921
- const obj = getTemplateProxyForField(field, frame, data);
1922
- return (_b = getFieldAccessor(fieldPath)(obj)) != null ? _b : "";
1853
+ });
1854
+ if (found) {
1855
+ return found;
1923
1856
  }
1924
- getValueText() {
1925
- return "";
1857
+ if (shouldSearchUp && scene.parent) {
1858
+ return findObjectInternal(scene.parent, check, scene, true);
1926
1859
  }
1860
+ return null;
1927
1861
  }
1928
-
1929
- class UrlMacro {
1930
- constructor(name, _) {
1931
- this.state = { name, type: "url_macro" };
1862
+ function findByKey(sceneObject, key) {
1863
+ const found = findObject(sceneObject, (sceneToCheck) => {
1864
+ return sceneToCheck.state.key === key;
1865
+ });
1866
+ if (!found) {
1867
+ throw new Error("Unable to find scene with key " + key);
1932
1868
  }
1933
- getValue(fieldPath) {
1934
- var _a;
1935
- const location = runtime.locationService.getLocation();
1936
- const subUrl = (_a = runtime.config.appSubUrl) != null ? _a : "";
1937
- switch (fieldPath != null ? fieldPath : "") {
1938
- case "params":
1939
- return new UrlStateFormatter(location.search);
1940
- case "path":
1941
- return subUrl + location.pathname;
1942
- case "":
1943
- default:
1944
- return subUrl + location.pathname + location.search;
1945
- }
1869
+ return found;
1870
+ }
1871
+ function findByKeyAndType(sceneObject, key, targetType) {
1872
+ const found = findObject(sceneObject, (sceneToCheck) => {
1873
+ return sceneToCheck.state.key === key;
1874
+ });
1875
+ if (!found) {
1876
+ throw new Error("Unable to find scene with key " + key);
1946
1877
  }
1947
- getValueText() {
1948
- return "";
1878
+ if (!(found instanceof targetType)) {
1879
+ throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);
1949
1880
  }
1881
+ return found;
1950
1882
  }
1951
- class UrlStateFormatter {
1952
- constructor(_urlQueryParams) {
1953
- this._urlQueryParams = _urlQueryParams;
1954
- }
1955
- formatter(options) {
1956
- if (!options) {
1957
- return this._urlQueryParams;
1883
+ function findObject(scene, check) {
1884
+ return findObjectInternal(scene, check, void 0, true);
1885
+ }
1886
+ function findAllObjects(scene, check) {
1887
+ const found = [];
1888
+ scene.forEachChild((child) => {
1889
+ if (check(child)) {
1890
+ found.push(child);
1958
1891
  }
1959
- const params = options.split(":");
1960
- if (params[0] === "exclude" && params.length > 1) {
1961
- const allParams = new URLSearchParams(this._urlQueryParams);
1962
- for (const param of params[1].split(",")) {
1963
- allParams.delete(param);
1964
- }
1965
- return `?${allParams}`;
1892
+ found.push(...findAllObjects(child, check));
1893
+ });
1894
+ return found;
1895
+ }
1896
+ function getDataLayers(sceneObject, localOnly = false) {
1897
+ let currentLevel = sceneObject;
1898
+ let collected = [];
1899
+ while (currentLevel) {
1900
+ const dataProvider = currentLevel.state.$data;
1901
+ if (!dataProvider) {
1902
+ currentLevel = currentLevel.parent;
1903
+ continue;
1966
1904
  }
1967
- if (params[0] === "include" && params.length > 1) {
1968
- const allParams = new URLSearchParams(this._urlQueryParams);
1969
- const includeOnly = params[1].split(",");
1970
- for (const param of allParams.keys()) {
1971
- if (!includeOnly.includes(param)) {
1972
- allParams.delete(param);
1973
- }
1905
+ if (isDataLayer(dataProvider)) {
1906
+ collected = collected.concat(dataProvider);
1907
+ } else {
1908
+ if (dataProvider.state.$data && isDataLayer(dataProvider.state.$data)) {
1909
+ collected = collected.concat(dataProvider.state.$data);
1974
1910
  }
1975
- return `?${allParams}`;
1976
1911
  }
1977
- return this._urlQueryParams;
1978
- }
1979
- }
1980
-
1981
- class UserMacro {
1982
- constructor(name, _) {
1983
- this.state = { name, type: "user_macro" };
1984
- }
1985
- getValue(fieldPath) {
1986
- const user = runtime.config.bootData.user;
1987
- switch (fieldPath) {
1988
- case "login":
1989
- return user.login;
1990
- case "email":
1991
- return user.email;
1992
- case "id":
1993
- default:
1994
- return String(user.id);
1912
+ if (localOnly && collected.length > 0) {
1913
+ break;
1995
1914
  }
1915
+ currentLevel = currentLevel.parent;
1996
1916
  }
1997
- getValueText() {
1998
- return "";
1999
- }
1917
+ return collected;
2000
1918
  }
2001
- class OrgMacro {
2002
- constructor(name, _) {
2003
- this.state = { name, type: "org_macro" };
2004
- }
2005
- getValue(fieldPath) {
2006
- const user = runtime.config.bootData.user;
2007
- switch (fieldPath) {
2008
- case "name":
2009
- return user.orgName;
2010
- case "id":
2011
- default:
2012
- return String(user.orgId);
1919
+ function getAncestor(sceneObject, ancestorType) {
1920
+ let parent = sceneObject;
1921
+ while (parent) {
1922
+ if (parent instanceof ancestorType) {
1923
+ return parent;
2013
1924
  }
1925
+ parent = parent.parent;
2014
1926
  }
2015
- getValueText() {
2016
- return "";
1927
+ if (!parent) {
1928
+ throw new Error("Unable to find parent of type " + ancestorType.name);
2017
1929
  }
1930
+ return parent;
2018
1931
  }
2019
-
2020
- const macrosIndex = {
2021
- [data.DataLinkBuiltInVars.includeVars]: AllVariablesMacro,
2022
- [data.DataLinkBuiltInVars.keepTime]: UrlTimeRangeMacro,
2023
- ["__value"]: ValueMacro,
2024
- ["__data"]: DataMacro,
2025
- ["__series"]: SeriesMacro,
2026
- ["__field"]: FieldMacro,
2027
- ["__url"]: UrlMacro,
2028
- ["__from"]: TimeFromAndToMacro,
2029
- ["__to"]: TimeFromAndToMacro,
2030
- ["__timezone"]: TimezoneMacro,
2031
- ["__user"]: UserMacro,
2032
- ["__org"]: OrgMacro,
2033
- ["__interval"]: IntervalMacro,
2034
- ["__interval_ms"]: IntervalMacro
2035
- };
2036
- function registerVariableMacro(name, macro) {
2037
- if (macrosIndex[name]) {
2038
- throw new Error(`Macro already registered ${name}`);
1932
+ function getQueryController(sceneObject) {
1933
+ let parent = sceneObject;
1934
+ while (parent) {
1935
+ if (parent.state.$behaviors) {
1936
+ for (const behavior of parent.state.$behaviors) {
1937
+ if (isQueryController(behavior)) {
1938
+ return behavior;
1939
+ }
1940
+ }
1941
+ }
1942
+ parent = parent.parent;
2039
1943
  }
2040
- macrosIndex[name] = macro;
2041
- return () => {
2042
- delete macrosIndex[name];
2043
- };
1944
+ return void 0;
2044
1945
  }
2045
1946
 
2046
1947
  const sceneGraph = {
@@ -2060,6 +1961,117 @@ const sceneGraph = {
2060
1961
  getQueryController
2061
1962
  };
2062
1963
 
1964
+ class UniqueUrlKeyMapper {
1965
+ constructor() {
1966
+ this.index = /* @__PURE__ */ new Map();
1967
+ }
1968
+ getUniqueKey(key, obj) {
1969
+ const objectsWithKey = this.index.get(key);
1970
+ if (!objectsWithKey) {
1971
+ this.index.set(key, [obj]);
1972
+ return key;
1973
+ }
1974
+ let address = objectsWithKey.findIndex((o) => o === obj);
1975
+ if (address === -1) {
1976
+ filterOutOrphanedObjects(objectsWithKey);
1977
+ objectsWithKey.push(obj);
1978
+ address = objectsWithKey.length - 1;
1979
+ }
1980
+ if (address > 0) {
1981
+ return `${key}-${address + 1}`;
1982
+ }
1983
+ return key;
1984
+ }
1985
+ clear() {
1986
+ this.index.clear();
1987
+ }
1988
+ }
1989
+ function filterOutOrphanedObjects(sceneObjects) {
1990
+ for (const obj of sceneObjects) {
1991
+ if (isOrphanOrInActive(obj)) {
1992
+ const index = sceneObjects.indexOf(obj);
1993
+ sceneObjects.splice(index, 1);
1994
+ }
1995
+ }
1996
+ }
1997
+ function isOrphanOrInActive(obj) {
1998
+ const root = obj.getRoot();
1999
+ if (!sceneGraph.findObject(root, (child) => child === obj)) {
2000
+ return true;
2001
+ }
2002
+ return false;
2003
+ }
2004
+
2005
+ function getUrlState(root) {
2006
+ const urlKeyMapper = new UniqueUrlKeyMapper();
2007
+ const result = {};
2008
+ const visitNode = (obj) => {
2009
+ if (obj.urlSync) {
2010
+ const newUrlState = obj.urlSync.getUrlState();
2011
+ for (const [key, value] of Object.entries(newUrlState)) {
2012
+ if (value != null) {
2013
+ const uniqueKey = urlKeyMapper.getUniqueKey(key, obj);
2014
+ result[uniqueKey] = value;
2015
+ }
2016
+ }
2017
+ }
2018
+ obj.forEachChild(visitNode);
2019
+ };
2020
+ visitNode(root);
2021
+ return result;
2022
+ }
2023
+ function syncStateFromSearchParams(root, urlParams) {
2024
+ const urlKeyMapper = new UniqueUrlKeyMapper();
2025
+ syncStateFromUrl(root, urlParams, urlKeyMapper);
2026
+ }
2027
+ function syncStateFromUrl(root, urlParams, urlKeyMapper) {
2028
+ if (!root.parent) {
2029
+ syncUrlStateToObject(root, urlParams, urlKeyMapper);
2030
+ }
2031
+ root.forEachChild((child) => {
2032
+ syncUrlStateToObject(child, urlParams, urlKeyMapper);
2033
+ });
2034
+ root.forEachChild((child) => syncStateFromUrl(child, urlParams, urlKeyMapper));
2035
+ }
2036
+ function syncUrlStateToObject(sceneObject, urlParams, urlKeyMapper) {
2037
+ if (sceneObject.urlSync) {
2038
+ const urlState = {};
2039
+ const currentState = sceneObject.urlSync.getUrlState();
2040
+ for (const key of sceneObject.urlSync.getKeys()) {
2041
+ const uniqueKey = urlKeyMapper.getUniqueKey(key, sceneObject);
2042
+ const newValue = urlParams.getAll(uniqueKey);
2043
+ const currentValue = currentState[key];
2044
+ if (isUrlValueEqual(newValue, currentValue)) {
2045
+ continue;
2046
+ }
2047
+ if (newValue.length > 0) {
2048
+ if (Array.isArray(currentValue)) {
2049
+ urlState[key] = newValue;
2050
+ } else {
2051
+ urlState[key] = newValue[0];
2052
+ }
2053
+ } else {
2054
+ urlState[key] = null;
2055
+ }
2056
+ }
2057
+ if (Object.keys(urlState).length > 0) {
2058
+ sceneObject.urlSync.updateFromUrl(urlState);
2059
+ }
2060
+ }
2061
+ }
2062
+ function isUrlValueEqual(currentUrlValue, newUrlValue) {
2063
+ if (currentUrlValue.length === 0 && newUrlValue == null) {
2064
+ return true;
2065
+ }
2066
+ if (!Array.isArray(newUrlValue) && (currentUrlValue == null ? void 0 : currentUrlValue.length) === 1) {
2067
+ return newUrlValue === currentUrlValue[0];
2068
+ }
2069
+ if ((newUrlValue == null ? void 0 : newUrlValue.length) === 0 && currentUrlValue === null) {
2070
+ return true;
2071
+ }
2072
+ return lodash.isEqual(currentUrlValue, newUrlValue);
2073
+ }
2074
+
2063
2075
  async function getDataSource(datasource, scopedVars) {
2064
2076
  if (datasource == null ? void 0 : datasource.uid) {
2065
2077
  const runtimeDataSource = runtimeDataSources.get(datasource.uid);
@@ -7772,28 +7784,12 @@ class UrlSyncManager {
7772
7784
  constructor() {
7773
7785
  this._urlKeyMapper = new UniqueUrlKeyMapper();
7774
7786
  this._stateSub = null;
7775
- this._locationSub = null;
7776
- this._ignoreNextLocationUpdate = false;
7777
- this._onLocationUpdate = (location) => {
7778
- if (this._ignoreNextLocationUpdate) {
7779
- this._ignoreNextLocationUpdate = false;
7780
- return;
7781
- }
7782
- if (this._lastPath !== location.pathname) {
7783
- return;
7784
- }
7785
- const urlParams = new URLSearchParams(location.search);
7786
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7787
- syncStateFromUrl(this._sceneRoot, urlParams, this._urlKeyMapper);
7788
- this._lastPath = location.pathname;
7789
- };
7790
7787
  this._onStateChanged = ({ payload }) => {
7791
7788
  const changedObject = payload.changedObject;
7792
7789
  if (changedObject.urlSync) {
7793
7790
  const newUrlState = changedObject.urlSync.getUrlState();
7794
7791
  const searchParams = runtime.locationService.getSearch();
7795
7792
  const mappedUpdated = {};
7796
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7797
7793
  for (const [key, newUrlValue] of Object.entries(newUrlState)) {
7798
7794
  const uniqueKey = this._urlKeyMapper.getUniqueKey(key, changedObject);
7799
7795
  const currentUrlValue = searchParams.getAll(uniqueKey);
@@ -7802,36 +7798,33 @@ class UrlSyncManager {
7802
7798
  }
7803
7799
  }
7804
7800
  if (Object.keys(mappedUpdated).length > 0) {
7805
- this._ignoreNextLocationUpdate = true;
7801
+ writeSceneLog("UrlSyncManager", "onStateChange updating URL");
7806
7802
  runtime.locationService.partial(mappedUpdated, true);
7803
+ this._lastLocation = runtime.locationService.getLocation();
7804
+ this._urlParams = new URLSearchParams(this._lastLocation.search);
7807
7805
  }
7808
7806
  }
7809
7807
  };
7810
7808
  }
7811
7809
  initSync(root) {
7812
- if (!this._locationSub) {
7813
- writeSceneLog("UrlSyncManager", "New location listen");
7814
- this._locationSub = runtime.locationService.getHistory().listen(this._onLocationUpdate);
7815
- }
7810
+ var _a;
7816
7811
  if (this._stateSub) {
7817
- writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", this._sceneRoot.state.key);
7812
+ writeSceneLog("UrlSyncManager", "Unregister previous scene state subscription", (_a = this._sceneRoot) == null ? void 0 : _a.state.key);
7818
7813
  this._stateSub.unsubscribe();
7819
7814
  }
7815
+ writeSceneLog("UrlSyncManager", "init", root.state.key);
7820
7816
  this._sceneRoot = root;
7821
- this._lastPath = runtime.locationService.getLocation().pathname;
7822
7817
  this._stateSub = root.subscribeToEvent(SceneObjectStateChangedEvent, this._onStateChanged);
7823
- this.syncFrom(this._sceneRoot);
7818
+ this._urlKeyMapper.clear();
7819
+ this._lastLocation = runtime.locationService.getLocation();
7820
+ this._urlParams = new URLSearchParams(this._lastLocation.search);
7821
+ this.handleNewObject(this._sceneRoot);
7824
7822
  }
7825
7823
  cleanUp(root) {
7826
7824
  if (this._sceneRoot !== root) {
7827
7825
  return;
7828
7826
  }
7829
7827
  writeSceneLog("UrlSyncManager", "Clean up");
7830
- if (this._locationSub) {
7831
- this._locationSub();
7832
- writeSceneLog("UrlSyncManager", "Unregister history listen");
7833
- this._locationSub = null;
7834
- }
7835
7828
  if (this._stateSub) {
7836
7829
  this._stateSub.unsubscribe();
7837
7830
  this._stateSub = null;
@@ -7842,11 +7835,23 @@ class UrlSyncManager {
7842
7835
  this._sceneRoot.state.key === root.state.key
7843
7836
  );
7844
7837
  }
7838
+ this._sceneRoot = void 0;
7839
+ this._urlParams = void 0;
7840
+ }
7841
+ handleNewLocation(location) {
7842
+ if (!this._sceneRoot || this._lastLocation === location) {
7843
+ return;
7844
+ }
7845
+ writeSceneLog("UrlSyncManager", "handleNewLocation");
7846
+ this._urlParams = new URLSearchParams(location.search);
7847
+ this._lastLocation = location;
7848
+ syncStateFromUrl(this._sceneRoot, this._urlParams, this._urlKeyMapper);
7845
7849
  }
7846
- syncFrom(sceneObj) {
7847
- const urlParams = runtime.locationService.getSearch();
7848
- this._urlKeyMapper.rebuildIndex(this._sceneRoot);
7849
- syncStateFromUrl(sceneObj, urlParams, this._urlKeyMapper);
7850
+ handleNewObject(sceneObj) {
7851
+ if (!this._sceneRoot || !this._urlParams) {
7852
+ return;
7853
+ }
7854
+ syncStateFromUrl(sceneObj, this._urlParams, this._urlKeyMapper);
7850
7855
  }
7851
7856
  getUrlState(root) {
7852
7857
  return getUrlState(root);
@@ -7860,6 +7865,34 @@ function getUrlSyncManager() {
7860
7865
  return urlSyncManager;
7861
7866
  }
7862
7867
 
7868
+ function useUrlSync(sceneRoot) {
7869
+ const urlSyncManager = getUrlSyncManager();
7870
+ const location = reactRouterDom.useLocation();
7871
+ const [isInitialized, setIsInitialized] = React.useState(false);
7872
+ React.useEffect(() => {
7873
+ urlSyncManager.initSync(sceneRoot);
7874
+ setIsInitialized(true);
7875
+ return () => urlSyncManager.cleanUp(sceneRoot);
7876
+ }, [sceneRoot, urlSyncManager]);
7877
+ React.useEffect(() => {
7878
+ const latestLocation = runtime.locationService.getLocation();
7879
+ const locationToHandle = latestLocation !== location ? latestLocation : location;
7880
+ if (latestLocation !== location) {
7881
+ console.log("latestLocation different from location");
7882
+ }
7883
+ urlSyncManager.handleNewLocation(locationToHandle);
7884
+ }, [sceneRoot, urlSyncManager, location]);
7885
+ return isInitialized;
7886
+ }
7887
+
7888
+ function UrlSyncContextProvider({ children, scene }) {
7889
+ const isInitialized = useUrlSync(scene);
7890
+ if (!isInitialized) {
7891
+ return null;
7892
+ }
7893
+ return children;
7894
+ }
7895
+
7863
7896
  function setWindowGrafanaSceneContext(activeScene) {
7864
7897
  const prevScene = window.__grafanaSceneContext;
7865
7898
  writeSceneLog("setWindowGrafanaScene", "set window.__grafanaSceneContext", activeScene);
@@ -7879,13 +7912,9 @@ class EmbeddedScene extends SceneObjectBase {
7879
7912
  const unsetGlobalScene = setWindowGrafanaSceneContext(this);
7880
7913
  return () => {
7881
7914
  unsetGlobalScene();
7882
- getUrlSyncManager().cleanUp(this);
7883
7915
  };
7884
7916
  });
7885
7917
  }
7886
- initUrlSync() {
7887
- getUrlSyncManager().initSync(this);
7888
- }
7889
7918
  }
7890
7919
  EmbeddedScene.Component = EmbeddedSceneRenderer;
7891
7920
  function EmbeddedSceneRenderer({ model }) {
@@ -10358,7 +10387,8 @@ function SceneAppPageView({ page, routeProps }) {
10358
10387
  React.useEffect(() => {
10359
10388
  return () => containerPage.setState({ initializedScene: void 0 });
10360
10389
  }, [containerPage]);
10361
- if (!isInitialized) {
10390
+ const urlSyncInitialized = useUrlSync(containerPage);
10391
+ if (!isInitialized && !urlSyncInitialized) {
10362
10392
  return null;
10363
10393
  }
10364
10394
  const pageNav = {
@@ -10431,13 +10461,9 @@ class SceneAppPage extends SceneObjectBase {
10431
10461
  super(state);
10432
10462
  this._sceneCache = /* @__PURE__ */ new Map();
10433
10463
  this._drilldownCache = /* @__PURE__ */ new Map();
10434
- this.addActivationHandler(() => {
10435
- return () => getUrlSyncManager().cleanUp(this);
10436
- });
10437
10464
  }
10438
10465
  initializeScene(scene) {
10439
10466
  this.setState({ initializedScene: scene });
10440
- getUrlSyncManager().initSync(this);
10441
10467
  }
10442
10468
  getScene(routeMatch) {
10443
10469
  let scene = this._sceneCache.get(routeMatch.url);
@@ -11432,6 +11458,7 @@ exports.SceneVariableValueChangedEvent = SceneVariableValueChangedEvent;
11432
11458
  exports.SplitLayout = SplitLayout;
11433
11459
  exports.TestVariable = TestVariable;
11434
11460
  exports.TextBoxVariable = TextBoxVariable;
11461
+ exports.UrlSyncContextProvider = UrlSyncContextProvider;
11435
11462
  exports.UrlSyncManager = UrlSyncManager;
11436
11463
  exports.UserActionEvent = UserActionEvent;
11437
11464
  exports.VariableDependencyConfig = VariableDependencyConfig;
@@ -11458,4 +11485,5 @@ exports.sceneGraph = sceneGraph;
11458
11485
  exports.sceneUtils = sceneUtils;
11459
11486
  exports.useSceneApp = useSceneApp;
11460
11487
  exports.useSceneObjectState = useSceneObjectState;
11488
+ exports.useUrlSync = useUrlSync;
11461
11489
  //# sourceMappingURL=index.js.map