@modelform/react-native 0.0.0-stage → 0.1.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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -2
  3. package/dist/chunk-L4SQVIJV.js +10630 -0
  4. package/dist/chunk-PIHXMZ4G.mjs +10630 -0
  5. package/dist/core/configSchema.d.ts +29 -0
  6. package/dist/core/dashboardSettings.d.ts +34 -0
  7. package/dist/core/datasource.d.ts +61 -0
  8. package/dist/core/documents.d.ts +35 -0
  9. package/dist/core/editing.d.ts +129 -0
  10. package/dist/core/fieldconfig.d.ts +12 -0
  11. package/dist/core/format.d.ts +29 -0
  12. package/dist/core/frame.d.ts +51 -0
  13. package/dist/core/gazetteer.d.ts +25 -0
  14. package/dist/core/grafana.d.ts +85 -0
  15. package/dist/core/index.d.ts +27 -0
  16. package/dist/core/index.js +380 -0
  17. package/dist/core/index.mjs +380 -0
  18. package/dist/core/inputs.d.ts +99 -0
  19. package/dist/core/jsonEdit.d.ts +30 -0
  20. package/dist/core/layout.d.ts +49 -0
  21. package/dist/core/layoutEdit.d.ts +87 -0
  22. package/dist/core/links.d.ts +56 -0
  23. package/dist/core/local.d.ts +95 -0
  24. package/dist/core/manifest.d.ts +201 -0
  25. package/dist/core/mappings.d.ts +46 -0
  26. package/dist/core/navigation.d.ts +19 -0
  27. package/dist/core/panelOptions.d.ts +109 -0
  28. package/dist/core/reduce.d.ts +6 -0
  29. package/dist/core/resolveVariables.d.ts +38 -0
  30. package/dist/core/sample.d.ts +13 -0
  31. package/dist/core/schema.d.ts +202 -0
  32. package/dist/core/time.d.ts +66 -0
  33. package/dist/core/transform.d.ts +12 -0
  34. package/dist/core/variables.d.ts +76 -0
  35. package/dist/index.d.ts +11 -0
  36. package/dist/index.js +4156 -0
  37. package/dist/index.mjs +4156 -0
  38. package/dist/ui/Chip.d.ts +5 -0
  39. package/dist/ui/DashboardView.d.ts +22 -0
  40. package/dist/ui/RenderBoundary.d.ts +25 -0
  41. package/dist/ui/TimeRangeSheet.d.ts +24 -0
  42. package/dist/ui/Toolbar.d.ts +6 -0
  43. package/dist/ui/chart.d.ts +69 -0
  44. package/dist/ui/context.d.ts +68 -0
  45. package/dist/ui/geomap.d.ts +157 -0
  46. package/dist/ui/inputs/InputForm.d.ts +36 -0
  47. package/dist/ui/inputs/InputPanels.d.ts +4 -0
  48. package/dist/ui/inputs/formContext.d.ts +14 -0
  49. package/dist/ui/links.d.ts +28 -0
  50. package/dist/ui/panels/GaugePanels.d.ts +5 -0
  51. package/dist/ui/panels/GeomapPanel.d.ts +6 -0
  52. package/dist/ui/panels/OtherPanels.d.ts +18 -0
  53. package/dist/ui/panels/StatPanel.d.ts +14 -0
  54. package/dist/ui/panels/TimeSeriesPanel.d.ts +8 -0
  55. package/dist/ui/panels/XYChartPanel.d.ts +6 -0
  56. package/dist/ui/panels/common.d.ts +78 -0
  57. package/dist/ui/panels/registry.d.ts +5 -0
  58. package/dist/ui/table.d.ts +62 -0
  59. package/dist/ui/theme.d.ts +21 -0
  60. package/dist/ui/xychart.d.ts +27 -0
  61. package/package.json +89 -3
  62. package/schema/app.schema.json +184 -0
  63. package/schema/dashboard.schema.json +940 -0
  64. package/tools/dashboards.js +90 -0
  65. package/tools/metro.js +21 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,4156 @@
1
+ import {
2
+ ALL,
3
+ BUNDLE_ACCEPT,
4
+ BUNDLE_TYPE,
5
+ CANVAS_GAP,
6
+ CANVAS_ROW_HEADER,
7
+ ConfigLoader,
8
+ DASHBOARD_DS,
9
+ DEFAULT_GAZETTEER,
10
+ EDITABLE_VARIABLE_TYPES,
11
+ GRID_COLUMNS,
12
+ GrafanaClient,
13
+ GrafanaDataSource,
14
+ GrafanaError,
15
+ HttpConfigFiles,
16
+ INPUT_OPTION_KEYS,
17
+ INPUT_TYPES,
18
+ LOCAL_DATASOURCE_TYPE,
19
+ LocalDataSource,
20
+ MANIFEST_VERSION,
21
+ MAPPING_TYPES,
22
+ MemoryEntryStore,
23
+ NAMED_COLORS,
24
+ OPTION_CATEGORIES,
25
+ OVERRIDE_MATCHERS,
26
+ PANEL_TYPES,
27
+ REDUCER_LABELS,
28
+ REFRESH_CHOICES,
29
+ RELATIVE_RANGES,
30
+ SERIES_PALETTE,
31
+ SPECIAL_MATCHES,
32
+ SaveConflictError,
33
+ TIME_PRESETS,
34
+ UNIT_CHOICES,
35
+ addTime,
36
+ appSchema,
37
+ applyDashboardLink,
38
+ applyJsonEdits,
39
+ applyTransformations,
40
+ assembleBundle,
41
+ assembleFromResponse,
42
+ buildFrames,
43
+ bundleFromFiles,
44
+ bundleRoot,
45
+ calculateInterval,
46
+ checkFiles,
47
+ cleanDashboard,
48
+ cleanPanelOptions,
49
+ dashboardSchema,
50
+ dashboardSchemaIssues,
51
+ dashboardSourceIds,
52
+ defaultFetchJson,
53
+ describeRange,
54
+ diffJson,
55
+ documentIdFor,
56
+ documentUses,
57
+ dropTarget,
58
+ duplicatePanel,
59
+ entriesSavedWith,
60
+ entryToInputValue,
61
+ expandRow,
62
+ fetchBundle,
63
+ fetchJsonWithToken,
64
+ fieldDisplayName,
65
+ fieldMatches,
66
+ formatClock,
67
+ formatDisplay,
68
+ formatDuration,
69
+ formatJsonText,
70
+ formatLocalDateTime,
71
+ formatValue,
72
+ frameLength,
73
+ framesToOptions,
74
+ fromWire,
75
+ getPath,
76
+ gridUnitsToPx,
77
+ initialVariableValues,
78
+ inputPanels,
79
+ inputProblem,
80
+ insertPanel,
81
+ interpolate,
82
+ interpolateDeep,
83
+ isBundleResponse,
84
+ isEditableVariableType,
85
+ isInputPanel,
86
+ isInputType,
87
+ isLocalDatasource,
88
+ isReducer,
89
+ isRow,
90
+ isSqlDatasource,
91
+ layoutCanvas,
92
+ layoutDashboard,
93
+ lineColumn,
94
+ loadGazetteer,
95
+ locate,
96
+ manifestSchemaIssues,
97
+ mappedResult,
98
+ mappingProblem,
99
+ mappingRow,
100
+ mappingRows,
101
+ metricChanges,
102
+ movePanel,
103
+ newDocument,
104
+ newPanel,
105
+ newVariable,
106
+ nextPanelId,
107
+ normalizeRef,
108
+ numberFields,
109
+ optionValue,
110
+ overrideProperties,
111
+ panelEdits,
112
+ panelHasQueries,
113
+ panelKey,
114
+ panelOptions,
115
+ panelOverrides,
116
+ panelSize,
117
+ panelSpan,
118
+ parseClockDigits,
119
+ parseDashboardLink,
120
+ parseDuration,
121
+ parseGazetteer,
122
+ parseJsonText,
123
+ parseLocalDateTime,
124
+ parseRange,
125
+ parseTime,
126
+ pointerToPath,
127
+ prepareDashboard,
128
+ queryPanel,
129
+ queryParam,
130
+ readConfigFiles,
131
+ readingOrder,
132
+ reduce,
133
+ refineOptions,
134
+ refreshedVariables,
135
+ removeDocumentFromManifest,
136
+ removePanel,
137
+ renameDocumentInManifest,
138
+ renameVariableInPanels,
139
+ repack,
140
+ repeatOptions,
141
+ resizePanel,
142
+ resolveColor,
143
+ resolveFieldConfig,
144
+ resolveLinks,
145
+ resolveTimezone,
146
+ resolveUrl,
147
+ resolveVariables,
148
+ rowsToMappings,
149
+ sampleEntries,
150
+ screenDocuments,
151
+ screenOfType,
152
+ selectValue,
153
+ seriesColor,
154
+ setHiddenOnPhones,
155
+ setJsonValue,
156
+ setOption,
157
+ setOptionValue,
158
+ setOverrides,
159
+ splitPath,
160
+ startOf,
161
+ stringifyCompact,
162
+ tabIdFor,
163
+ textSuggestions,
164
+ thresholdStep,
165
+ timeExprError,
166
+ timeField,
167
+ toEntries,
168
+ toMillis,
169
+ toSeries,
170
+ toXYSeries,
171
+ uniqueNames,
172
+ validateBundle,
173
+ validateDashboard,
174
+ validateManifest,
175
+ valueColor,
176
+ valueText,
177
+ variableDependents,
178
+ variableInfo,
179
+ variableNameError,
180
+ variableOptions,
181
+ variableOrder,
182
+ variableReferences,
183
+ variableUses,
184
+ variableWithCurrent,
185
+ variableWithFlags,
186
+ variableWithQuery,
187
+ variableWithType,
188
+ visibleVariables,
189
+ zoomRange
190
+ } from "./chunk-PIHXMZ4G.mjs";
191
+
192
+ // src/ui/theme.tsx
193
+ import { createContext, useContext } from "react";
194
+ import { useColorScheme } from "react-native";
195
+ import { jsx } from "react/jsx-runtime";
196
+ var lightTheme = {
197
+ scheme: "light",
198
+ background: "#f4f4f2",
199
+ surface: "#fcfcfb",
200
+ border: "#e4e3df",
201
+ grid: "#ecebe7",
202
+ text: "#0b0b0b",
203
+ textSecondary: "#52514e",
204
+ textMuted: "#85847f",
205
+ accent: "#2a78d6",
206
+ danger: "#d03b3b"
207
+ };
208
+ var darkTheme = {
209
+ scheme: "dark",
210
+ background: "#111110",
211
+ surface: "#1a1a19",
212
+ border: "#2c2c2a",
213
+ grid: "#262624",
214
+ text: "#ffffff",
215
+ textSecondary: "#c3c2b7",
216
+ textMuted: "#8d8c84",
217
+ accent: "#3987e5",
218
+ danger: "#e66767"
219
+ };
220
+ var ThemeContext = createContext(null);
221
+ function DashThemeProvider({ theme, children }) {
222
+ return /* @__PURE__ */ jsx(ThemeContext.Provider, { value: theme, children });
223
+ }
224
+ function useDashTheme() {
225
+ const explicit = useContext(ThemeContext);
226
+ const scheme = useColorScheme();
227
+ return explicit ?? (scheme === "dark" ? darkTheme : lightTheme);
228
+ }
229
+
230
+ // src/ui/context.tsx
231
+ import { createContext as createContext2, useCallback, useContext as useContext2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
232
+
233
+ // src/ui/links.tsx
234
+ import { Linking, Modal, Pressable, StyleSheet, Text, View } from "react-native";
235
+ import { useSafeAreaInsets } from "react-native-safe-area-context";
236
+ import Svg, { Path } from "react-native-svg";
237
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
238
+ function openLinkDefault(link) {
239
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(link.href)) {
240
+ console.warn(`modelform: can't open relative link "${link.href}" without an onLink handler`);
241
+ return;
242
+ }
243
+ Linking.openURL(link.href).catch((e) => console.warn(`modelform: couldn't open ${link.href}: ${e}`));
244
+ }
245
+ function mergeLinks(groups) {
246
+ const seen = /* @__PURE__ */ new Set();
247
+ const titles = /* @__PURE__ */ new Map();
248
+ for (const g of groups) for (const l of g.links) (titles.get(l.title) ?? titles.set(l.title, /* @__PURE__ */ new Set()).get(l.title)).add(l.href);
249
+ const out = [];
250
+ for (const g of groups) {
251
+ for (const l of g.links) {
252
+ const key = `${l.title}
253
+ ${l.href}`;
254
+ if (seen.has(key)) continue;
255
+ seen.add(key);
256
+ out.push(titles.get(l.title).size > 1 ? { ...l, title: `${g.name}: ${l.title}` } : l);
257
+ }
258
+ }
259
+ return out;
260
+ }
261
+ var LinkIcon = ({ color, size = 14 }) => /* @__PURE__ */ jsx2(Svg, { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx2(Path, { d: "M10 14a4.5 4.5 0 0 0 6.4 0l3.2-3.2a4.5 4.5 0 0 0-6.4-6.4L12 5.6M14 10a4.5 4.5 0 0 0-6.4 0l-3.2 3.2a4.5 4.5 0 0 0 6.4 6.4l1.2-1.2" }) });
262
+ function TooltipLinks({ links, onOpen }) {
263
+ const theme = useDashTheme();
264
+ if (!links.length) return null;
265
+ return /* @__PURE__ */ jsx2(View, { style: [styles.tooltipLinks, { borderColor: theme.border }], children: links.map((l) => /* @__PURE__ */ jsxs(
266
+ Pressable,
267
+ {
268
+ onPress: () => onOpen(l),
269
+ accessibilityRole: "link",
270
+ hitSlop: 4,
271
+ style: ({ pressed }) => [styles.tooltipLink, pressed && { opacity: 0.6 }],
272
+ children: [
273
+ /* @__PURE__ */ jsx2(LinkIcon, { color: theme.accent, size: 12 }),
274
+ /* @__PURE__ */ jsx2(Text, { style: [styles.tooltipLinkText, { color: theme.accent }], numberOfLines: 1, children: l.title })
275
+ ]
276
+ },
277
+ `${l.title}
278
+ ${l.href}`
279
+ )) });
280
+ }
281
+ function LinkMenu({
282
+ links,
283
+ title,
284
+ visible,
285
+ onOpen,
286
+ onClose
287
+ }) {
288
+ const theme = useDashTheme();
289
+ const insets = useSafeAreaInsets();
290
+ return /* @__PURE__ */ jsx2(Modal, { visible, transparent: true, animationType: "fade", supportedOrientations: ["portrait", "landscape"], onRequestClose: onClose, children: /* @__PURE__ */ jsx2(Pressable, { style: styles.backdrop, onPress: onClose, accessibilityLabel: "Close links", children: /* @__PURE__ */ jsxs(
291
+ View,
292
+ {
293
+ onStartShouldSetResponder: () => true,
294
+ style: [styles.sheet, { backgroundColor: theme.surface, borderColor: theme.border, paddingBottom: Math.max(12, insets.bottom) }],
295
+ children: [
296
+ title ? /* @__PURE__ */ jsx2(Text, { style: [styles.sheetTitle, { color: theme.textSecondary }], numberOfLines: 2, children: title }) : null,
297
+ links.map((l, i) => /* @__PURE__ */ jsxs(
298
+ Pressable,
299
+ {
300
+ onPress: () => onOpen(l),
301
+ accessibilityRole: "link",
302
+ style: ({ pressed }) => [
303
+ styles.sheetRow,
304
+ (i > 0 || !!title) && { borderTopWidth: StyleSheet.hairlineWidth, borderColor: theme.border },
305
+ pressed && { backgroundColor: theme.grid }
306
+ ],
307
+ children: [
308
+ /* @__PURE__ */ jsx2(LinkIcon, { color: theme.accent, size: 16 }),
309
+ /* @__PURE__ */ jsxs(View, { style: styles.sheetLabels, children: [
310
+ /* @__PURE__ */ jsx2(Text, { style: [styles.sheetLink, { color: theme.text }], numberOfLines: 1, children: l.title }),
311
+ /* @__PURE__ */ jsx2(Text, { style: [styles.sheetHref, { color: theme.textMuted }], numberOfLines: 1, children: l.href })
312
+ ] })
313
+ ]
314
+ },
315
+ `${l.title}
316
+ ${l.href}`
317
+ )),
318
+ /* @__PURE__ */ jsx2(
319
+ Pressable,
320
+ {
321
+ onPress: onClose,
322
+ accessibilityRole: "button",
323
+ style: ({ pressed }) => [styles.cancel, { borderColor: theme.border }, pressed && { backgroundColor: theme.grid }],
324
+ children: /* @__PURE__ */ jsx2(Text, { style: [styles.cancelText, { color: theme.accent }], children: "Cancel" })
325
+ }
326
+ )
327
+ ]
328
+ }
329
+ ) }) });
330
+ }
331
+ var styles = StyleSheet.create({
332
+ tooltipLinks: { borderTopWidth: StyleSheet.hairlineWidth, marginTop: 5, paddingTop: 3 },
333
+ tooltipLink: { flexDirection: "row", alignItems: "center", gap: 5, paddingVertical: 4 },
334
+ tooltipLinkText: { fontSize: 12, fontWeight: "600", flexShrink: 1 },
335
+ backdrop: { flex: 1, justifyContent: "flex-end", backgroundColor: "rgba(0,0,0,0.35)" },
336
+ sheet: {
337
+ borderTopLeftRadius: 14,
338
+ borderTopRightRadius: 14,
339
+ borderWidth: StyleSheet.hairlineWidth,
340
+ paddingTop: 6,
341
+ width: "100%",
342
+ maxWidth: 560,
343
+ alignSelf: "center"
344
+ },
345
+ sheetTitle: { fontSize: 13, fontWeight: "600", paddingHorizontal: 16, paddingVertical: 10 },
346
+ sheetRow: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 16, paddingVertical: 12 },
347
+ sheetLabels: { flex: 1, gap: 2 },
348
+ sheetLink: { fontSize: 15, fontWeight: "500" },
349
+ sheetHref: { fontSize: 11 },
350
+ cancel: { borderTopWidth: StyleSheet.hairlineWidth, paddingVertical: 14, alignItems: "center" },
351
+ cancelText: { fontSize: 16, fontWeight: "600" }
352
+ });
353
+
354
+ // src/ui/context.tsx
355
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
356
+ var Ctx = createContext2(null);
357
+ function DashboardProvider({ dashboard, resolve, refreshKey: externalKey = 0, onLink, children }) {
358
+ const [rawRange, setRawRange] = useState(dashboard.time ?? { from: "now-6h", to: "now" });
359
+ const [tick, setTick] = useState(0);
360
+ const vars = useDashboardVariables(dashboard, resolve, rawRange);
361
+ const refresh = useCallback(() => setTick((t) => t + 1), []);
362
+ const [pinned, setPinned] = useState(null);
363
+ const [menu, setMenu] = useState(null);
364
+ const onLinkRef = useRef(onLink);
365
+ useLayoutEffect(() => {
366
+ onLinkRef.current = onLink;
367
+ });
368
+ const open = useCallback((link) => (onLinkRef.current ?? openLinkDefault)(link), []);
369
+ const openLinks = useCallback(
370
+ (links, title) => {
371
+ if (links.length === 1) open(links[0]);
372
+ else if (links.length > 1) setMenu({ links, title });
373
+ },
374
+ [open]
375
+ );
376
+ useEffect(() => {
377
+ if (!dashboard.refresh) return;
378
+ let ms;
379
+ try {
380
+ ms = parseDuration(dashboard.refresh);
381
+ } catch {
382
+ return;
383
+ }
384
+ const id = setInterval(refresh, Math.max(ms, 5e3));
385
+ return () => clearInterval(id);
386
+ }, [dashboard.refresh, refresh]);
387
+ const refreshKey = tick + externalKey;
388
+ const range3 = useMemo(() => parseRange(rawRange), [rawRange, refreshKey]);
389
+ const shared = useMemo(() => /* @__PURE__ */ new Map(), [range3, vars.variables, vars.variableInfo]);
390
+ const value = useMemo(
391
+ () => ({
392
+ dashboard,
393
+ resolve,
394
+ rawRange,
395
+ setRawRange,
396
+ range: range3,
397
+ ...vars,
398
+ refresh,
399
+ refreshKey,
400
+ shared,
401
+ openLinks,
402
+ pinned,
403
+ setPinned
404
+ }),
405
+ [dashboard, resolve, rawRange, range3, vars, refresh, refreshKey, shared, openLinks, pinned]
406
+ );
407
+ return /* @__PURE__ */ jsxs2(Ctx.Provider, { value, children: [
408
+ children,
409
+ /* @__PURE__ */ jsx3(
410
+ LinkMenu,
411
+ {
412
+ links: menu?.links ?? [],
413
+ title: menu?.title,
414
+ visible: !!menu,
415
+ onOpen: (l) => {
416
+ setMenu(null);
417
+ open(l);
418
+ },
419
+ onClose: () => setMenu(null)
420
+ }
421
+ )
422
+ ] });
423
+ }
424
+ function useDashboardVariables(dashboard, resolve, rawRange) {
425
+ const [state, setState] = useState(() => ({ values: initialVariableValues(dashboard), options: {}, errors: {} }));
426
+ const [resolving, setResolving] = useState(() => !!resolve && refreshedVariables(dashboard, "load").length > 0);
427
+ const [runKey, setRunKey] = useState(0);
428
+ const pending = useRef(/* @__PURE__ */ new Set());
429
+ const stateRef = useRef(state);
430
+ const resolveRef = useRef(resolve);
431
+ useLayoutEffect(() => {
432
+ stateRef.current = state;
433
+ resolveRef.current = resolve;
434
+ });
435
+ const schedule = useCallback((names) => {
436
+ const before = pending.current.size;
437
+ for (const n of names) pending.current.add(n);
438
+ if (pending.current.size === before) return;
439
+ setResolving(true);
440
+ setRunKey((k) => k + 1);
441
+ }, []);
442
+ useEffect(() => {
443
+ if (!pending.current.size) return;
444
+ const resolve2 = resolveRef.current;
445
+ if (!resolve2) {
446
+ pending.current.clear();
447
+ setResolving(false);
448
+ return;
449
+ }
450
+ const names = new Set(pending.current);
451
+ const controller = new AbortController();
452
+ const { values, options } = stateRef.current;
453
+ const finish = (update) => {
454
+ if (controller.signal.aborted) return;
455
+ names.forEach((n) => pending.current.delete(n));
456
+ setState(update);
457
+ setResolving(false);
458
+ };
459
+ resolveVariables(dashboard, { values, options, names, resolve: resolve2, range: parseRange(rawRange), signal: controller.signal }).then(
460
+ (res) => finish((s) => ({
461
+ // Only the re-run variables change, so a pick made while this ran isn't overwritten.
462
+ values: { ...s.values, ...Object.fromEntries([...names].filter((n) => n in res.values).map((n) => [n, res.values[n]])) },
463
+ options: { ...s.options, ...res.options },
464
+ errors: { ...Object.fromEntries(Object.entries(s.errors).filter(([n]) => !names.has(n))), ...res.errors }
465
+ })),
466
+ (e) => finish((s) => ({ ...s, errors: { ...s.errors, ...Object.fromEntries([...names].map((n) => [n, String(e?.message ?? e)])) } }))
467
+ );
468
+ return () => controller.abort();
469
+ }, [runKey, dashboard]);
470
+ const [loadedDashboard, setLoadedDashboard] = useState(dashboard);
471
+ if (dashboard !== loadedDashboard) {
472
+ setLoadedDashboard(dashboard);
473
+ setState((s) => ({ ...s, values: { ...initialVariableValues(dashboard), ...s.values } }));
474
+ }
475
+ useEffect(() => {
476
+ const roots = refreshedVariables(dashboard, "load");
477
+ schedule([...roots, ...variableDependents(dashboard, roots)]);
478
+ }, [dashboard, schedule]);
479
+ const mounted = useRef(false);
480
+ useEffect(() => {
481
+ if (!mounted.current) {
482
+ mounted.current = true;
483
+ return;
484
+ }
485
+ const roots = refreshedVariables(dashboard, "range");
486
+ schedule([...roots, ...variableDependents(dashboard, roots)]);
487
+ }, [rawRange]);
488
+ const setVariable = useCallback(
489
+ (name, value) => {
490
+ setState((s) => ({ ...s, values: { ...s.values, [name]: value } }));
491
+ schedule(variableDependents(dashboard, [name]));
492
+ },
493
+ [dashboard, schedule]
494
+ );
495
+ const info = useMemo(() => variableInfo(dashboard, state.options), [dashboard, state.options]);
496
+ return useMemo(
497
+ () => ({
498
+ variables: state.values,
499
+ variableInfo: info,
500
+ variableErrors: state.errors,
501
+ variablesReady: !resolving,
502
+ setVariable
503
+ }),
504
+ [state.values, info, state.errors, resolving, setVariable]
505
+ );
506
+ }
507
+ function useDashboard() {
508
+ const v = useContext2(Ctx);
509
+ if (!v) throw new Error("useDashboard must be used inside <DashboardProvider>");
510
+ return v;
511
+ }
512
+ var IDLE = { frames: [], loading: false };
513
+ var NO_DATASOURCE = { frames: [], loading: false, error: "No datasource configured" };
514
+ function usePanelData(panel, widthPx, enabled = true) {
515
+ const { dashboard, resolve, range: range3, variables, variableInfo: variableInfo2, variablesReady, shared } = useDashboard();
516
+ const widthBucket = Math.ceil(widthPx / 100) * 100;
517
+ const request = useMemo(
518
+ () => resolve ? { panel, options: { resolve, range: range3, variables, variableInfo: variableInfo2, widthPx: widthBucket, dashboard, shared } } : null,
519
+ [panel, resolve, range3, variables, variableInfo2, widthBucket, dashboard, shared]
520
+ );
521
+ const [result, setResult] = useState(null);
522
+ useEffect(() => {
523
+ if (!enabled || !request || !variablesReady) return;
524
+ const controller = new AbortController();
525
+ queryPanel(request.panel, request.options, controller.signal).then((frames) => !controller.signal.aborted && setResult({ request, frames })).catch((e) => !controller.signal.aborted && setResult({ request, frames: [], error: String(e?.message ?? e) }));
526
+ return () => controller.abort();
527
+ }, [enabled, request, variablesReady]);
528
+ if (!enabled) return IDLE;
529
+ if (!request) return NO_DATASOURCE;
530
+ return { frames: result?.frames ?? [], error: result?.error, loading: !variablesReady || result?.request !== request };
531
+ }
532
+ function usePanelLinks(panel) {
533
+ const { dashboard, variables, variableInfo: variableInfo2, range: range3, openLinks } = useDashboard();
534
+ const resolve = useCallback(
535
+ (links, data) => resolveLinks(links, { dashboard, values: variables, info: variableInfo2, scoped: panel.scopedVars, range: range3, timezone: dashboard.timezone, data }),
536
+ [dashboard, variables, variableInfo2, panel.scopedVars, range3]
537
+ );
538
+ return { resolve, openLinks };
539
+ }
540
+
541
+ // src/ui/DashboardView.tsx
542
+ import { useCallback as useCallback3, useContext as useContext4, useMemo as useMemo8, useRef as useRef4, useState as useState10 } from "react";
543
+ import {
544
+ ActivityIndicator,
545
+ Pressable as Pressable11,
546
+ RefreshControl,
547
+ ScrollView as ScrollView5,
548
+ StyleSheet as StyleSheet13,
549
+ Text as Text12,
550
+ View as View12,
551
+ useWindowDimensions
552
+ } from "react-native";
553
+ import { useSafeAreaInsets as useSafeAreaInsets4 } from "react-native-safe-area-context";
554
+
555
+ // src/ui/RenderBoundary.tsx
556
+ import { Component } from "react";
557
+ var changed = (a, b) => a.length !== b.length || a.some((v, i) => !Object.is(v, b[i]));
558
+ var RenderBoundary = class extends Component {
559
+ state = { error: null, keys: this.props.resetKeys };
560
+ static getDerivedStateFromError(error) {
561
+ return { error: error instanceof Error ? error : new Error(String(error)) };
562
+ }
563
+ static getDerivedStateFromProps(props, state) {
564
+ return changed(props.resetKeys, state.keys) ? { error: null, keys: props.resetKeys } : null;
565
+ }
566
+ componentDidCatch(error) {
567
+ console.warn("[modelform] render failed:", error.message);
568
+ }
569
+ render() {
570
+ return this.state.error ? this.props.fallback(this.state.error) : this.props.children;
571
+ }
572
+ };
573
+
574
+ // src/ui/inputs/formContext.ts
575
+ import { createContext as createContext3, useContext as useContext3 } from "react";
576
+ var InputFormContext = createContext3(null);
577
+ function useInputForm() {
578
+ const v = useContext3(InputFormContext);
579
+ if (!v) throw new Error("Input panels must be rendered inside <InputForm>");
580
+ return v;
581
+ }
582
+
583
+ // src/ui/inputs/InputPanels.tsx
584
+ import { useEffect as useEffect2, useState as useState5 } from "react";
585
+ import { Platform, Pressable as Pressable5, ScrollView as ScrollView3, StyleSheet as StyleSheet6, Switch, Text as Text6, TextInput as TextInput2, View as View5 } from "react-native";
586
+
587
+ // src/ui/Toolbar.tsx
588
+ import { useState as useState3 } from "react";
589
+ import { Modal as Modal3, Pressable as Pressable4, ScrollView as ScrollView2, StyleSheet as StyleSheet4, Text as Text4, View as View3 } from "react-native";
590
+ import { useSafeAreaInsets as useSafeAreaInsets3 } from "react-native-safe-area-context";
591
+ import Svg3, { Path as Path3 } from "react-native-svg";
592
+
593
+ // src/ui/TimeRangeSheet.tsx
594
+ import { useState as useState2 } from "react";
595
+ import { Modal as Modal2, Pressable as Pressable3, ScrollView, StyleSheet as StyleSheet3, Text as Text3, TextInput, View as View2 } from "react-native";
596
+ import { useSafeAreaInsets as useSafeAreaInsets2 } from "react-native-safe-area-context";
597
+ import Svg2, { Path as Path2 } from "react-native-svg";
598
+
599
+ // src/ui/Chip.tsx
600
+ import { Pressable as Pressable2, StyleSheet as StyleSheet2, Text as Text2 } from "react-native";
601
+ import { jsx as jsx4 } from "react/jsx-runtime";
602
+ function Chip({ label, selected, onPress }) {
603
+ const theme = useDashTheme();
604
+ return /* @__PURE__ */ jsx4(
605
+ Pressable2,
606
+ {
607
+ onPress,
608
+ accessibilityRole: "button",
609
+ accessibilityState: { selected },
610
+ style: ({ pressed }) => [
611
+ styles2.chip,
612
+ { borderColor: selected ? theme.accent : theme.border, backgroundColor: selected ? theme.accent : theme.surface },
613
+ pressed && { opacity: 0.7 }
614
+ ],
615
+ children: /* @__PURE__ */ jsx4(Text2, { style: [styles2.chipText, { color: selected ? "#fff" : theme.text }], numberOfLines: 1, children: label })
616
+ }
617
+ );
618
+ }
619
+ var styles2 = StyleSheet2.create({
620
+ chip: { paddingHorizontal: 12, paddingVertical: 7, borderRadius: 16, borderWidth: 1, maxWidth: 240 },
621
+ chipText: { fontSize: 13, fontWeight: "500" }
622
+ });
623
+
624
+ // src/ui/TimeRangeSheet.tsx
625
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
626
+ var WEEKDAYS = ["S", "M", "T", "W", "T", "F", "S"];
627
+ var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
628
+ var ArrowIcon = ({ color, dir }) => /* @__PURE__ */ jsx5(Svg2, { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx5(Path2, { d: dir === "left" ? "M15 6l-6 6 6 6" : "M9 6l6 6-6 6" }) });
629
+ function displayExpr(expr) {
630
+ if (expr.trim().startsWith("now")) return expr;
631
+ try {
632
+ return formatLocalDateTime(parseTime(expr));
633
+ } catch {
634
+ return expr;
635
+ }
636
+ }
637
+ function tryParse(expr, roundUp, now = Date.now()) {
638
+ try {
639
+ return parseTime(expr, now, roundUp);
640
+ } catch {
641
+ return null;
642
+ }
643
+ }
644
+ function startOfDay(ms) {
645
+ const d = new Date(ms);
646
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
647
+ }
648
+ function endOfDay(ms) {
649
+ const d = new Date(ms);
650
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime() - 1e3;
651
+ }
652
+ function resolveTo(expr) {
653
+ return /^\s*\d{4}-\d{1,2}-\d{1,2}\s*$/.test(expr) ? formatLocalDateTime(endOfDay(parseTime(expr))) : expr;
654
+ }
655
+ function TimeRangeSheet({ visible, value, onApply, onClose }) {
656
+ const theme = useDashTheme();
657
+ const insets = useSafeAreaInsets2();
658
+ const [from, setFrom] = useState2(() => displayExpr(value.from));
659
+ const [to, setTo] = useState2(() => displayExpr(value.to));
660
+ const [active, setActive] = useState2("from");
661
+ const [now] = useState2(() => Date.now());
662
+ const [month, setMonth] = useState2(() => new Date(tryParse(value.from, false) ?? now));
663
+ const fromMs = tryParse(from, false, now);
664
+ const toMs = tryParse(timeExprError(to) ? to : resolveTo(to), true, now);
665
+ const fromError = timeExprError(from);
666
+ const toError = timeExprError(to);
667
+ const orderError = fromMs != null && toMs != null && fromMs >= toMs ? "\u201CTo\u201D must be after \u201CFrom\u201D" : null;
668
+ const valid = !fromError && !toError && !orderError;
669
+ const normalize = (expr) => expr.trim().startsWith("now") ? expr.trim() : formatLocalDateTime(parseTime(expr));
670
+ const apply = () => {
671
+ if (!valid) return;
672
+ onApply({ from: normalize(from), to: normalize(resolveTo(to)) });
673
+ onClose();
674
+ };
675
+ const pickDay = (day) => {
676
+ const end = endOfDay(day);
677
+ if (active === "from") {
678
+ setFrom(formatLocalDateTime(day));
679
+ if (toMs == null || toMs <= day) setTo(formatLocalDateTime(end));
680
+ setActive("to");
681
+ } else if (fromMs != null && day < startOfDay(fromMs)) {
682
+ setFrom(formatLocalDateTime(day));
683
+ setTo(formatLocalDateTime(end));
684
+ } else {
685
+ setTo(formatLocalDateTime(end));
686
+ }
687
+ };
688
+ return /* @__PURE__ */ jsx5(
689
+ Modal2,
690
+ {
691
+ visible,
692
+ animationType: "slide",
693
+ presentationStyle: "pageSheet",
694
+ supportedOrientations: ["portrait", "landscape"],
695
+ onRequestClose: onClose,
696
+ children: /* @__PURE__ */ jsxs3(View2, { style: [styles3.sheet, { paddingLeft: insets.left, paddingRight: insets.right, backgroundColor: theme.background }], children: [
697
+ /* @__PURE__ */ jsxs3(View2, { style: [styles3.header, { borderColor: theme.border }], children: [
698
+ /* @__PURE__ */ jsx5(Pressable3, { onPress: onClose, accessibilityRole: "button", hitSlop: 8, children: /* @__PURE__ */ jsx5(Text3, { style: [styles3.headerButton, { color: theme.accent }], children: "Cancel" }) }),
699
+ /* @__PURE__ */ jsx5(Text3, { style: [styles3.title, { color: theme.text }], children: "Time range" }),
700
+ /* @__PURE__ */ jsx5(Pressable3, { onPress: apply, disabled: !valid, accessibilityRole: "button", accessibilityState: { disabled: !valid }, hitSlop: 8, children: /* @__PURE__ */ jsx5(Text3, { style: [styles3.headerButton, styles3.apply, { color: valid ? theme.accent : theme.textMuted }], children: "Apply" }) })
701
+ ] }),
702
+ /* @__PURE__ */ jsxs3(ScrollView, { keyboardShouldPersistTaps: "handled", contentContainerStyle: [styles3.body, { paddingBottom: Math.max(16, insets.bottom) }], children: [
703
+ /* @__PURE__ */ jsxs3(View2, { style: styles3.fields, children: [
704
+ /* @__PURE__ */ jsx5(TimeField, { label: "From", value: from, onChange: setFrom, active: active === "from", onFocus: () => setActive("from"), onBlur: () => fromMs != null && setMonth(new Date(fromMs)), error: fromError }),
705
+ /* @__PURE__ */ jsx5(TimeField, { label: "To", value: to, onChange: setTo, active: active === "to", onFocus: () => setActive("to"), onBlur: () => toMs != null && setMonth(new Date(toMs)), error: toError })
706
+ ] }),
707
+ orderError && /* @__PURE__ */ jsx5(Text3, { style: [styles3.error, { color: theme.danger }], children: orderError }),
708
+ /* @__PURE__ */ jsx5(Text3, { style: [styles3.hint, { color: theme.textMuted }], children: "Tap days below, or type a date (2026-03-01 14:00) or a relative time (now-7d, now/M)." }),
709
+ /* @__PURE__ */ jsx5(
710
+ Calendar,
711
+ {
712
+ month,
713
+ onMonth: setMonth,
714
+ from: fromMs,
715
+ to: toMs,
716
+ today: startOfDay(now),
717
+ onPick: pickDay
718
+ }
719
+ ),
720
+ /* @__PURE__ */ jsx5(Text3, { style: [styles3.sectionTitle, { color: theme.textSecondary }], children: "Relative ranges" }),
721
+ /* @__PURE__ */ jsx5(View2, { style: styles3.chips, children: RELATIVE_RANGES.map((r) => /* @__PURE__ */ jsx5(
722
+ Chip,
723
+ {
724
+ label: r.label,
725
+ selected: value.from === r.from && value.to === r.to,
726
+ onPress: () => {
727
+ onApply({ from: r.from, to: r.to });
728
+ onClose();
729
+ }
730
+ },
731
+ r.label
732
+ )) })
733
+ ] })
734
+ ] })
735
+ }
736
+ );
737
+ }
738
+ function TimeField({
739
+ label,
740
+ value,
741
+ onChange,
742
+ active,
743
+ onFocus,
744
+ onBlur,
745
+ error
746
+ }) {
747
+ const theme = useDashTheme();
748
+ const showError = error && value.trim() !== "";
749
+ return /* @__PURE__ */ jsxs3(View2, { style: styles3.field, children: [
750
+ /* @__PURE__ */ jsx5(Text3, { style: [styles3.fieldLabel, { color: theme.textSecondary }], children: label }),
751
+ /* @__PURE__ */ jsx5(
752
+ TextInput,
753
+ {
754
+ value,
755
+ onChangeText: onChange,
756
+ onFocus,
757
+ onBlur,
758
+ autoCapitalize: "none",
759
+ autoCorrect: false,
760
+ spellCheck: false,
761
+ placeholder: "now-7d",
762
+ placeholderTextColor: theme.textMuted,
763
+ accessibilityLabel: label,
764
+ style: [
765
+ styles3.input,
766
+ { color: theme.text, backgroundColor: theme.surface, borderColor: showError ? theme.danger : active ? theme.accent : theme.border },
767
+ active && styles3.inputActive
768
+ ]
769
+ }
770
+ ),
771
+ showError && /* @__PURE__ */ jsx5(Text3, { style: [styles3.error, { color: theme.danger }], children: error })
772
+ ] });
773
+ }
774
+ function Calendar({
775
+ month,
776
+ onMonth,
777
+ from,
778
+ to,
779
+ today,
780
+ onPick
781
+ }) {
782
+ const theme = useDashTheme();
783
+ const year = month.getFullYear();
784
+ const m = month.getMonth();
785
+ const first = new Date(year, m, 1);
786
+ const daysInMonth = new Date(year, m + 1, 0).getDate();
787
+ const cells = [
788
+ ...Array.from({ length: first.getDay() }, () => null),
789
+ ...Array.from({ length: daysInMonth }, (_, i) => new Date(year, m, i + 1).getTime())
790
+ ];
791
+ while (cells.length % 7) cells.push(null);
792
+ const fromDay = from != null ? startOfDay(from) : null;
793
+ const toDay = to != null ? startOfDay(to) : null;
794
+ return /* @__PURE__ */ jsxs3(View2, { style: [styles3.calendar, { borderColor: theme.border, backgroundColor: theme.surface }], children: [
795
+ /* @__PURE__ */ jsxs3(View2, { style: styles3.monthRow, children: [
796
+ /* @__PURE__ */ jsx5(Pressable3, { onPress: () => onMonth(new Date(year, m - 1, 1)), accessibilityRole: "button", accessibilityLabel: "Previous month", hitSlop: 8, style: styles3.monthButton, children: /* @__PURE__ */ jsx5(ArrowIcon, { color: theme.textSecondary, dir: "left" }) }),
797
+ /* @__PURE__ */ jsxs3(Text3, { style: [styles3.monthTitle, { color: theme.text }], children: [
798
+ MONTHS[m],
799
+ " ",
800
+ year
801
+ ] }),
802
+ /* @__PURE__ */ jsx5(Pressable3, { onPress: () => onMonth(new Date(year, m + 1, 1)), accessibilityRole: "button", accessibilityLabel: "Next month", hitSlop: 8, style: styles3.monthButton, children: /* @__PURE__ */ jsx5(ArrowIcon, { color: theme.textSecondary, dir: "right" }) })
803
+ ] }),
804
+ /* @__PURE__ */ jsx5(View2, { style: styles3.week, children: WEEKDAYS.map((d, i) => /* @__PURE__ */ jsx5(Text3, { style: [styles3.weekday, { color: theme.textMuted }], children: d }, i)) }),
805
+ Array.from({ length: cells.length / 7 }, (_, row) => /* @__PURE__ */ jsx5(View2, { style: styles3.week, children: cells.slice(row * 7, row * 7 + 7).map((day, i) => {
806
+ if (day == null) return /* @__PURE__ */ jsx5(View2, { style: styles3.day }, i);
807
+ const isEnd = day === fromDay || day === toDay;
808
+ const inRange = fromDay != null && toDay != null && day > fromDay && day < toDay;
809
+ return /* @__PURE__ */ jsx5(
810
+ Pressable3,
811
+ {
812
+ onPress: () => onPick(day),
813
+ accessibilityRole: "button",
814
+ accessibilityState: { selected: isEnd || inRange },
815
+ accessibilityLabel: new Date(day).toDateString(),
816
+ style: ({ pressed }) => [styles3.day, inRange && { backgroundColor: theme.grid }, pressed && { opacity: 0.6 }],
817
+ children: /* @__PURE__ */ jsx5(View2, { style: [styles3.dayInner, isEnd && { backgroundColor: theme.accent }, !isEnd && day === today && { borderColor: theme.accent, borderWidth: 1 }], children: /* @__PURE__ */ jsx5(Text3, { style: [styles3.dayText, { color: isEnd ? "#fff" : theme.text }, isEnd && styles3.dayTextSelected], children: new Date(day).getDate() }) })
818
+ },
819
+ i
820
+ );
821
+ }) }, row))
822
+ ] });
823
+ }
824
+ var styles3 = StyleSheet3.create({
825
+ sheet: { flex: 1 },
826
+ header: {
827
+ flexDirection: "row",
828
+ alignItems: "center",
829
+ justifyContent: "space-between",
830
+ paddingHorizontal: 16,
831
+ paddingVertical: 14,
832
+ borderBottomWidth: StyleSheet3.hairlineWidth
833
+ },
834
+ title: { fontSize: 17, fontWeight: "600" },
835
+ headerButton: { fontSize: 16 },
836
+ apply: { fontWeight: "600" },
837
+ body: { padding: 16, gap: 12 },
838
+ fields: { flexDirection: "row", gap: 10 },
839
+ field: { flex: 1, gap: 4 },
840
+ fieldLabel: { fontSize: 13, fontWeight: "600" },
841
+ input: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 10, paddingVertical: 9, fontSize: 14, fontVariant: ["tabular-nums"] },
842
+ inputActive: { borderWidth: 1.5 },
843
+ error: { fontSize: 12 },
844
+ hint: { fontSize: 12 },
845
+ sectionTitle: { fontSize: 13, fontWeight: "600", marginTop: 4 },
846
+ chips: { flexDirection: "row", flexWrap: "wrap", gap: 8 },
847
+ calendar: { borderRadius: 12, borderWidth: StyleSheet3.hairlineWidth, padding: 10, maxWidth: 420, width: "100%", alignSelf: "center" },
848
+ monthRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginBottom: 6 },
849
+ monthButton: { padding: 6 },
850
+ monthTitle: { fontSize: 15, fontWeight: "600" },
851
+ week: { flexDirection: "row" },
852
+ weekday: { flex: 1, textAlign: "center", fontSize: 12, fontWeight: "600", paddingVertical: 4 },
853
+ day: { flex: 1, aspectRatio: 1, maxHeight: 44, alignItems: "center", justifyContent: "center" },
854
+ dayInner: { width: 34, height: 34, borderRadius: 17, alignItems: "center", justifyContent: "center" },
855
+ dayText: { fontSize: 14, fontVariant: ["tabular-nums"] },
856
+ dayTextSelected: { fontWeight: "700" }
857
+ });
858
+
859
+ // src/ui/Toolbar.tsx
860
+ import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
861
+ var FilterIcon = ({ color }) => /* @__PURE__ */ jsx6(Svg3, { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx6(Path3, { d: "M3 5h18l-7 8.5V19l-4 2v-7.5L3 5z" }) });
862
+ var CalendarIcon = ({ color }) => /* @__PURE__ */ jsx6(Svg3, { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx6(Path3, { d: "M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1zM4 10h16M8 3v4M16 3v4" }) });
863
+ var ChevronIcon = ({ color, open }) => /* @__PURE__ */ jsx6(Svg3, { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx6(Path3, { d: open ? "M6 15l6-6 6 6" : "M6 9l6 6 6-6" }) });
864
+ var CheckIcon = ({ color }) => /* @__PURE__ */ jsx6(Svg3, { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 2.4, strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx6(Path3, { d: "M5 12.5l4.5 4.5L19 7" }) });
865
+ function DashboardToolbar({ presets = TIME_PRESETS }) {
866
+ const theme = useDashTheme();
867
+ const { dashboard, rawRange, setRawRange, variables, variableErrors } = useDashboard();
868
+ const [filtersOpen, setFiltersOpen] = useState3(false);
869
+ const [rangeOpen, setRangeOpen] = useState3(false);
870
+ const [rangeKey, setRangeKey] = useState3(0);
871
+ const custom = !presets.some((p) => rawRange.from === p.from && rawRange.to === p.to);
872
+ const vars = visibleVariables(dashboard);
873
+ const active = vars.filter((v) => {
874
+ const cur = variables[v.name];
875
+ return v.includeAll && cur != null && !(Array.isArray(cur) ? cur.includes(ALL) : cur === ALL);
876
+ }).length;
877
+ const hasError = vars.some((v) => variableErrors[v.name]);
878
+ return /* @__PURE__ */ jsxs4(View3, { style: styles4.toolbar, children: [
879
+ /* @__PURE__ */ jsx6(ScrollView2, { horizontal: true, showsHorizontalScrollIndicator: false, style: styles4.segmentScroll, children: /* @__PURE__ */ jsx6(View3, { style: [styles4.segments, { borderColor: theme.border, backgroundColor: theme.surface }], children: presets.map((p) => {
880
+ const selected = rawRange.from === p.from && rawRange.to === p.to;
881
+ return /* @__PURE__ */ jsx6(
882
+ Pressable4,
883
+ {
884
+ onPress: () => setRawRange(p),
885
+ accessibilityRole: "button",
886
+ accessibilityState: { selected },
887
+ style: ({ pressed }) => [styles4.segment, selected && { backgroundColor: theme.accent }, pressed && { opacity: 0.7 }],
888
+ children: /* @__PURE__ */ jsx6(Text4, { style: [styles4.segmentText, { color: selected ? "#fff" : theme.textSecondary }], children: p.label })
889
+ },
890
+ p.label
891
+ );
892
+ }) }) }),
893
+ /* @__PURE__ */ jsxs4(
894
+ Pressable4,
895
+ {
896
+ onPress: () => {
897
+ setRangeKey((k) => k + 1);
898
+ setRangeOpen(true);
899
+ },
900
+ accessibilityRole: "button",
901
+ accessibilityLabel: custom ? `Time range, ${describeRange(rawRange)}` : "Custom time range",
902
+ style: ({ pressed }) => [
903
+ custom ? styles4.rangeButton : styles4.iconButton,
904
+ { borderColor: custom ? theme.accent : theme.border, backgroundColor: theme.surface },
905
+ pressed && { opacity: 0.7 }
906
+ ],
907
+ children: [
908
+ /* @__PURE__ */ jsx6(CalendarIcon, { color: custom ? theme.accent : theme.textSecondary }),
909
+ custom && /* @__PURE__ */ jsx6(Text4, { style: [styles4.rangeLabel, { color: theme.accent }], numberOfLines: 1, children: describeRange(rawRange) })
910
+ ]
911
+ }
912
+ ),
913
+ vars.length > 0 && /* @__PURE__ */ jsxs4(
914
+ Pressable4,
915
+ {
916
+ onPress: () => setFiltersOpen(true),
917
+ accessibilityRole: "button",
918
+ accessibilityLabel: `Filters${active ? `, ${active} active` : ""}`,
919
+ style: ({ pressed }) => [styles4.iconButton, { borderColor: theme.border, backgroundColor: theme.surface }, pressed && { opacity: 0.7 }],
920
+ children: [
921
+ /* @__PURE__ */ jsx6(FilterIcon, { color: active ? theme.accent : theme.textSecondary }),
922
+ (active > 0 || hasError) && /* @__PURE__ */ jsx6(View3, { style: [styles4.badge, { backgroundColor: hasError ? theme.danger : theme.accent, borderColor: theme.background }], children: /* @__PURE__ */ jsx6(Text4, { style: styles4.badgeText, children: hasError ? "!" : active }) })
923
+ ]
924
+ }
925
+ ),
926
+ /* @__PURE__ */ jsx6(TimeRangeSheet, { visible: rangeOpen, value: rawRange, onApply: setRawRange, onClose: () => setRangeOpen(false) }, rangeKey),
927
+ /* @__PURE__ */ jsx6(FilterSheet, { vars, visible: filtersOpen, onClose: () => setFiltersOpen(false) })
928
+ ] });
929
+ }
930
+ function FilterSheet({ vars, visible, onClose }) {
931
+ const theme = useDashTheme();
932
+ const [expanded, setExpanded] = useState3(vars.length === 1 ? vars[0].name : null);
933
+ const insets = useSafeAreaInsets3();
934
+ const sides = { paddingLeft: insets.left, paddingRight: insets.right };
935
+ return /* @__PURE__ */ jsx6(
936
+ Modal3,
937
+ {
938
+ visible,
939
+ animationType: "slide",
940
+ presentationStyle: "pageSheet",
941
+ supportedOrientations: ["portrait", "landscape"],
942
+ onRequestClose: onClose,
943
+ children: /* @__PURE__ */ jsxs4(View3, { style: [styles4.sheet, sides, { backgroundColor: theme.background }], children: [
944
+ /* @__PURE__ */ jsxs4(View3, { style: [styles4.sheetHeader, { borderColor: theme.border }], children: [
945
+ /* @__PURE__ */ jsx6(Text4, { style: [styles4.sheetTitle, { color: theme.text }], children: "Filters" }),
946
+ /* @__PURE__ */ jsx6(Pressable4, { onPress: onClose, accessibilityRole: "button", hitSlop: 8, children: /* @__PURE__ */ jsx6(Text4, { style: [styles4.done, { color: theme.accent }], children: "Done" }) })
947
+ ] }),
948
+ /* @__PURE__ */ jsx6(ScrollView2, { contentContainerStyle: [styles4.sheetBody, { paddingBottom: Math.max(12, insets.bottom) }], children: vars.map((v) => /* @__PURE__ */ jsx6(
949
+ FilterSection,
950
+ {
951
+ variable: v,
952
+ open: expanded === v.name,
953
+ onToggle: () => setExpanded(expanded === v.name ? null : v.name)
954
+ },
955
+ v.name
956
+ )) })
957
+ ] })
958
+ }
959
+ );
960
+ }
961
+ function FilterSection({ variable: v, open, onToggle }) {
962
+ const theme = useDashTheme();
963
+ const { variables, variableInfo: variableInfo2, variableErrors, variablesReady, setVariable } = useDashboard();
964
+ const current = variables[v.name];
965
+ const summary = valueText(current, variableInfo2[v.name]) || (variablesReady ? "None" : "\u2026");
966
+ const options = [...v.includeAll ? [{ text: "All", value: ALL }] : [], ...variableInfo2[v.name]?.options ?? []];
967
+ const error = variableErrors[v.name];
968
+ const choose = (value, selected) => {
969
+ if (v.multi && value !== ALL) {
970
+ const cur = (Array.isArray(current) ? current : [current]).filter((c) => c && c !== ALL);
971
+ const next = selected ? cur.filter((c) => c !== value) : [...cur, value];
972
+ setVariable(v.name, next.length ? next : [ALL]);
973
+ } else {
974
+ setVariable(v.name, v.multi ? [value] : value);
975
+ if (!v.multi) onToggle();
976
+ }
977
+ };
978
+ return /* @__PURE__ */ jsxs4(View3, { style: [styles4.section, { borderColor: theme.border, backgroundColor: theme.surface }], children: [
979
+ /* @__PURE__ */ jsxs4(
980
+ Pressable4,
981
+ {
982
+ onPress: onToggle,
983
+ accessibilityRole: "button",
984
+ accessibilityState: { expanded: open },
985
+ style: ({ pressed }) => [styles4.sectionHeader, pressed && { opacity: 0.7 }],
986
+ children: [
987
+ /* @__PURE__ */ jsxs4(View3, { style: styles4.sectionLabels, children: [
988
+ /* @__PURE__ */ jsx6(Text4, { style: [styles4.sectionTitle, { color: theme.text }], children: v.label ?? v.name }),
989
+ !open && /* @__PURE__ */ jsx6(Text4, { style: [styles4.sectionValue, { color: error ? theme.danger : theme.textMuted }], numberOfLines: 1, children: error ? `\u26A0 ${summary}` : summary })
990
+ ] }),
991
+ /* @__PURE__ */ jsx6(ChevronIcon, { color: theme.textMuted, open })
992
+ ]
993
+ }
994
+ ),
995
+ open && /* @__PURE__ */ jsxs4(View3, { style: [styles4.optionList, { borderColor: theme.border }], children: [
996
+ error && /* @__PURE__ */ jsxs4(Text4, { style: [styles4.hint, { color: theme.danger }], children: [
997
+ "Couldn\u2019t load options: ",
998
+ error
999
+ ] }),
1000
+ !error && !options.length && /* @__PURE__ */ jsx6(Text4, { style: [styles4.hint, { color: theme.textMuted }], children: variablesReady ? "No options" : "Loading\u2026" }),
1001
+ options.map((o, i) => {
1002
+ const selected = Array.isArray(current) ? current.includes(o.value) : current === o.value;
1003
+ return /* @__PURE__ */ jsxs4(
1004
+ Pressable4,
1005
+ {
1006
+ onPress: () => choose(o.value, selected),
1007
+ accessibilityRole: v.multi ? "checkbox" : "radio",
1008
+ accessibilityState: { checked: selected },
1009
+ style: ({ pressed }) => [
1010
+ styles4.option,
1011
+ i > 0 && { borderTopWidth: StyleSheet4.hairlineWidth, borderColor: theme.border },
1012
+ pressed && { backgroundColor: theme.grid }
1013
+ ],
1014
+ children: [
1015
+ /* @__PURE__ */ jsx6(Text4, { style: [styles4.optionText, { color: selected ? theme.accent : theme.text }, selected && styles4.optionSelected], children: o.text }),
1016
+ /* @__PURE__ */ jsx6(View3, { style: styles4.check, children: selected && /* @__PURE__ */ jsx6(CheckIcon, { color: theme.accent }) })
1017
+ ]
1018
+ },
1019
+ o.value
1020
+ );
1021
+ })
1022
+ ] })
1023
+ ] });
1024
+ }
1025
+ var styles4 = StyleSheet4.create({
1026
+ toolbar: { flexDirection: "row", alignItems: "center", gap: 8, marginBottom: 4 },
1027
+ rangeButton: { flexDirection: "row", alignItems: "center", gap: 6, height: 34, paddingHorizontal: 9, borderRadius: 10, borderWidth: StyleSheet4.hairlineWidth, maxWidth: 200 },
1028
+ rangeLabel: { fontSize: 13, fontWeight: "600", flexShrink: 1 },
1029
+ segmentScroll: { flexGrow: 1, flexShrink: 1 },
1030
+ segments: { flexDirection: "row", padding: 2, borderRadius: 10, borderWidth: StyleSheet4.hairlineWidth },
1031
+ segment: { paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8, minWidth: 36, alignItems: "center" },
1032
+ segmentText: { fontSize: 13, fontWeight: "600" },
1033
+ iconButton: { width: 36, height: 34, borderRadius: 10, borderWidth: StyleSheet4.hairlineWidth, alignItems: "center", justifyContent: "center" },
1034
+ badge: {
1035
+ position: "absolute",
1036
+ top: -5,
1037
+ right: -5,
1038
+ minWidth: 16,
1039
+ height: 16,
1040
+ paddingHorizontal: 3,
1041
+ borderRadius: 8,
1042
+ borderWidth: 1.5,
1043
+ alignItems: "center",
1044
+ justifyContent: "center"
1045
+ },
1046
+ badgeText: { color: "#fff", fontSize: 9, fontWeight: "700" },
1047
+ sheet: { flex: 1 },
1048
+ sheetHeader: {
1049
+ flexDirection: "row",
1050
+ alignItems: "center",
1051
+ justifyContent: "space-between",
1052
+ paddingHorizontal: 16,
1053
+ paddingVertical: 14,
1054
+ borderBottomWidth: StyleSheet4.hairlineWidth
1055
+ },
1056
+ sheetTitle: { fontSize: 17, fontWeight: "600" },
1057
+ done: { fontSize: 16, fontWeight: "600" },
1058
+ sheetBody: { padding: 12, gap: 10 },
1059
+ section: { borderRadius: 12, borderWidth: StyleSheet4.hairlineWidth, overflow: "hidden" },
1060
+ sectionHeader: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 14, paddingVertical: 12 },
1061
+ sectionLabels: { flex: 1, gap: 2 },
1062
+ sectionTitle: { fontSize: 15, fontWeight: "600" },
1063
+ sectionValue: { fontSize: 13 },
1064
+ optionList: { borderTopWidth: StyleSheet4.hairlineWidth },
1065
+ option: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 14, paddingVertical: 11 },
1066
+ optionText: { flex: 1, fontSize: 15 },
1067
+ optionSelected: { fontWeight: "600" },
1068
+ check: { width: 18 },
1069
+ hint: { fontSize: 12, paddingHorizontal: 14, paddingVertical: 10 }
1070
+ });
1071
+
1072
+ // src/ui/panels/common.tsx
1073
+ import { useCallback as useCallback2, useState as useState4 } from "react";
1074
+ import { StyleSheet as StyleSheet5, Text as Text5, View as View4 } from "react-native";
1075
+ import { Text as SvgText } from "react-native-svg";
1076
+
1077
+ // src/ui/chart.ts
1078
+ function niceTicks(min, max, count = 4) {
1079
+ if (min === max) {
1080
+ const pad = Math.abs(min) * 0.1 || 1;
1081
+ min -= pad;
1082
+ max += pad;
1083
+ }
1084
+ const rough = (max - min) / count;
1085
+ const mag = 10 ** Math.floor(Math.log10(rough));
1086
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= rough) ?? rough;
1087
+ const start = Math.floor(min / step) * step;
1088
+ const ticks = [];
1089
+ for (let t = start; ticks.length === 0 || ticks[ticks.length - 1] < max; t += step) ticks.push(Number(t.toFixed(10)));
1090
+ return ticks;
1091
+ }
1092
+ function tickDecimals(ticks) {
1093
+ return Math.max(0, ...ticks.map((t) => (String(t).split(".")[1] ?? "").length));
1094
+ }
1095
+ function linearScale(d0, d1, r0, r1) {
1096
+ const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0);
1097
+ return (v) => r0 + (v - d0) * k;
1098
+ }
1099
+ function formatTimeTick(t, spanMs) {
1100
+ const d = new Date(t);
1101
+ if (spanMs <= 2 * 864e5) return d.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
1102
+ if (spanMs <= 180 * 864e5) return d.toLocaleDateString(void 0, { month: "short", day: "numeric" });
1103
+ return d.toLocaleDateString(void 0, { month: "short", year: "2-digit" });
1104
+ }
1105
+ function barCategory(panel, frame) {
1106
+ const xField = panel.options?.xField;
1107
+ if (xField) return frame.fields.find((f) => f.name === xField);
1108
+ return frame.fields.find((f) => f.type === "string") ?? frame.fields.find((f) => f.type === "time");
1109
+ }
1110
+ function categoryLabels(field) {
1111
+ if (field.type !== "time") return field.values.map((v) => v == null ? "" : String(v));
1112
+ const times = field.values.map((v) => v == null ? null : toMillis(v));
1113
+ let step = Infinity;
1114
+ times.forEach((t, i) => {
1115
+ const prev = times[i - 1];
1116
+ if (t != null && prev != null && t !== prev) step = Math.min(step, Math.abs(t - prev));
1117
+ });
1118
+ return times.map((t) => {
1119
+ if (t == null) return "";
1120
+ const d = new Date(t);
1121
+ if (step < 864e5) return d.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
1122
+ if (step < 28 * 864e5) return d.toLocaleDateString(void 0, { month: "short", day: "numeric" });
1123
+ return d.toLocaleDateString(void 0, { month: "short", year: "2-digit" });
1124
+ });
1125
+ }
1126
+ function barAxes(configs, values, tickCount) {
1127
+ const placement = (c) => c.custom?.axisPlacement;
1128
+ const sides = ["left", "right"];
1129
+ return sides.flatMap((side) => {
1130
+ const fields = configs.map((_, i) => i).filter((i) => placement(configs[i]) === "right" === (side === "right"));
1131
+ if (!fields.length) return [];
1132
+ const config = configs[fields[0]];
1133
+ const all = fields.flatMap((i) => values[i].map((v) => v ?? 0));
1134
+ const max = Math.max(0, ...all);
1135
+ const min = config.min ?? Math.min(0, ...all);
1136
+ const ticks = niceTicks(min, config.max ?? Math.max(max, min + 1), tickCount);
1137
+ const top = config.max ?? ticks[ticks.length - 1];
1138
+ const bottom = config.min ?? ticks[0];
1139
+ return [
1140
+ {
1141
+ side,
1142
+ fields,
1143
+ // A max that isn't a round number cuts the top tick off rather than drawing it above the plot.
1144
+ ticks: ticks.filter((t) => t <= top && t >= bottom),
1145
+ top,
1146
+ bottom,
1147
+ config,
1148
+ label: fields.map((i) => configs[i].custom?.axisLabel).find((l) => !!l),
1149
+ show: fields.some((i) => placement(configs[i]) !== "hidden")
1150
+ }
1151
+ ];
1152
+ });
1153
+ }
1154
+ function formatTooltipTime(t) {
1155
+ return new Date(t).toLocaleString(void 0, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
1156
+ }
1157
+ function styledSeries(panel, frames, scheme) {
1158
+ return styleSeries(panel, toSeries(frames), frames, scheme);
1159
+ }
1160
+ function styledXYSeries(panel, frames, scheme) {
1161
+ const { series, x } = toXYSeries(frames, panel.options?.xField || void 0);
1162
+ const xConfig = x ? resolveFieldConfig(panel, x.field, x.frame, x.field.name) : {};
1163
+ return { series: styleSeries(panel, series, frames, scheme), xConfig };
1164
+ }
1165
+ function styleSeries(panel, series, frames, scheme) {
1166
+ const frameOf = /* @__PURE__ */ new Map();
1167
+ frames.forEach((f) => f.fields.forEach((field) => frameOf.set(field, f)));
1168
+ return series.map((s, i) => {
1169
+ const config = resolveFieldConfig(panel, s.field, frameOf.get(s.field), s.name);
1170
+ return { ...s, name: config.displayName ?? s.name, config, color: seriesColor(i, scheme, config) };
1171
+ });
1172
+ }
1173
+ function reducedValues(panel, frames, scheme) {
1174
+ const calc = panel.options?.reduceOptions?.calcs?.[0] ?? "lastNotNull";
1175
+ const out = [];
1176
+ const multiple = frames.length > 1;
1177
+ frames.forEach(
1178
+ (frame, fi) => numberFields(frame).forEach((field) => {
1179
+ const raw = fieldDisplayName(field, frame, multiple);
1180
+ const config = resolveFieldConfig(panel, field, frame, raw);
1181
+ const values = field.values.map((v) => v == null ? null : Number(v));
1182
+ const value = reduce(values, calc);
1183
+ const color = seriesColor(out.length, scheme, config);
1184
+ const step = thresholdStep(value, config);
1185
+ const mapped = mappedResult(value, config);
1186
+ out.push({
1187
+ key: `${fi}/${field.name}/${JSON.stringify(field.labels ?? {})}`,
1188
+ name: config.displayName ?? raw,
1189
+ value,
1190
+ text: mapped?.text || formatValue(value, config),
1191
+ mapped,
1192
+ config,
1193
+ color,
1194
+ stateColor: mapped?.color ? resolveColor(mapped.color, color) : step ? resolveColor(step.color, color) : color,
1195
+ sparkline: values,
1196
+ field,
1197
+ frame
1198
+ });
1199
+ })
1200
+ );
1201
+ return uniqueNames(out, (v) => v.field, frames);
1202
+ }
1203
+ function yDomain(series, includeZero) {
1204
+ let min = Infinity;
1205
+ let max = -Infinity;
1206
+ for (const s of series) {
1207
+ for (const v of s.values) {
1208
+ if (v == null) continue;
1209
+ if (v < min) min = v;
1210
+ if (v > max) max = v;
1211
+ }
1212
+ }
1213
+ if (min === Infinity) return [0, 1];
1214
+ if (includeZero) {
1215
+ min = Math.min(0, min);
1216
+ max = Math.max(0, max);
1217
+ }
1218
+ const cfgMin = series.find((s) => s.config.min != null)?.config.min;
1219
+ const cfgMax = series.find((s) => s.config.max != null)?.config.max;
1220
+ return [cfgMin ?? min, cfgMax ?? max];
1221
+ }
1222
+ function barFraction(axis, v) {
1223
+ return Math.min(1, Math.max(0, (v - axis.bottom) / (axis.top - axis.bottom || 1)));
1224
+ }
1225
+
1226
+ // src/ui/panels/common.tsx
1227
+ import { Fragment, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
1228
+ function useLayout() {
1229
+ const [size, setSize] = useState4({ width: 0, height: 0 });
1230
+ const onLayout = useCallback2((e) => {
1231
+ const { width, height } = e.nativeEvent.layout;
1232
+ setSize((s) => s.width === width && s.height === height ? s : { width, height });
1233
+ }, []);
1234
+ return [size, onLayout];
1235
+ }
1236
+ function Legend({ items }) {
1237
+ const theme = useDashTheme();
1238
+ return /* @__PURE__ */ jsx7(View4, { style: styles5.legend, children: items.map((i) => /* @__PURE__ */ jsxs5(View4, { style: styles5.legendItem, children: [
1239
+ /* @__PURE__ */ jsx7(View4, { style: [styles5.swatch, { backgroundColor: i.color }] }),
1240
+ /* @__PURE__ */ jsxs5(Text5, { style: [styles5.legendText, { color: theme.textSecondary }], numberOfLines: 1, children: [
1241
+ i.name,
1242
+ i.value != null ? /* @__PURE__ */ jsx7(Text5, { style: { color: theme.text }, children: ` ${i.value}` }) : null
1243
+ ] })
1244
+ ] }, i.key)) });
1245
+ }
1246
+ var AXIS_TITLE_SPACE = 14;
1247
+ var axisTitle = (config) => config?.custom?.axisLabel || void 0;
1248
+ function AxisTitles({ x, y, plot, height }) {
1249
+ const theme = useDashTheme();
1250
+ const cy = plot.top + plot.height / 2;
1251
+ return /* @__PURE__ */ jsxs5(Fragment, { children: [
1252
+ y && /* @__PURE__ */ jsx7(SvgText, { x: 9, y: cy, fontSize: 10, fill: theme.textMuted, textAnchor: "middle", transform: `rotate(-90 9 ${cy})`, children: y }),
1253
+ x && /* @__PURE__ */ jsx7(SvgText, { x: plot.left + plot.width / 2, y: height - 3, fontSize: 10, fill: theme.textMuted, textAnchor: "middle", children: x })
1254
+ ] });
1255
+ }
1256
+ function NoData({ message = "No data" }) {
1257
+ const theme = useDashTheme();
1258
+ return /* @__PURE__ */ jsx7(View4, { style: styles5.center, children: /* @__PURE__ */ jsx7(Text5, { style: { color: theme.textMuted, fontSize: 13 }, children: message }) });
1259
+ }
1260
+ function rowTooltipItems(panel, frame, row, multiple) {
1261
+ return frame.fields.flatMap((f) => {
1262
+ const name = fieldDisplayName(f, frame, multiple);
1263
+ const config = resolveFieldConfig(panel, f, frame, name);
1264
+ if (config.custom?.hideFrom?.tooltip) return [];
1265
+ const v = f.values[row];
1266
+ const value = v == null ? "\u2014" : f.type === "number" ? formatDisplay(Number(v), config) : f.type === "time" ? formatTooltipTime(toMillis(v)) : String(v);
1267
+ return [{ name: config.displayName ?? name, value }];
1268
+ });
1269
+ }
1270
+ function rowLinks(panel, frame, row, multiple, resolve) {
1271
+ return mergeLinks(
1272
+ frame.fields.flatMap((f) => {
1273
+ const name = fieldDisplayName(f, frame, multiple);
1274
+ const config = resolveFieldConfig(panel, f, frame, name);
1275
+ if (!config.links?.length) return [];
1276
+ const v = f.values[row];
1277
+ const text = v == null ? void 0 : f.type === "number" ? formatDisplay(Number(v), config) : String(v);
1278
+ return [{ name: config.displayName ?? name, links: resolve(config.links, { frame, row, field: f, fieldName: config.displayName ?? name, value: v, text }) }];
1279
+ })
1280
+ );
1281
+ }
1282
+ function valueLinks(panel, v, resolve) {
1283
+ if (!v.config.links?.length) return [];
1284
+ return resolve(v.config.links, {
1285
+ frame: v.frame,
1286
+ field: v.field,
1287
+ fieldName: v.name,
1288
+ seriesName: v.name,
1289
+ value: v.value,
1290
+ text: formatValue(v.value, v.config),
1291
+ calc: panel.options?.reduceOptions?.calcs?.[0] ?? "lastNotNull"
1292
+ });
1293
+ }
1294
+ function RowTooltip({
1295
+ at,
1296
+ size,
1297
+ color,
1298
+ title,
1299
+ rows,
1300
+ links,
1301
+ onOpenLink
1302
+ }) {
1303
+ const theme = useDashTheme();
1304
+ const tappable = !!links?.length && !!onOpenLink;
1305
+ return /* @__PURE__ */ jsxs5(
1306
+ View4,
1307
+ {
1308
+ pointerEvents: tappable ? "auto" : "none",
1309
+ onStartShouldSetResponder: () => tappable,
1310
+ style: [
1311
+ styles5.tooltip,
1312
+ { backgroundColor: theme.surface, borderColor: theme.border },
1313
+ at.x > size.width / 2 ? { right: size.width - at.x + 12 } : { left: at.x + 12 },
1314
+ at.y > size.height / 2 ? { bottom: size.height - at.y } : { top: at.y }
1315
+ ],
1316
+ children: [
1317
+ /* @__PURE__ */ jsxs5(View4, { style: styles5.tooltipHead, children: [
1318
+ /* @__PURE__ */ jsx7(View4, { style: [styles5.dot, { backgroundColor: color }] }),
1319
+ /* @__PURE__ */ jsx7(Text5, { style: [styles5.tooltipTitle, { color: theme.text }], numberOfLines: 1, children: title })
1320
+ ] }),
1321
+ rows.map((r) => /* @__PURE__ */ jsxs5(View4, { style: styles5.tooltipRow, children: [
1322
+ /* @__PURE__ */ jsx7(Text5, { style: [styles5.tooltipName, { color: theme.textSecondary }], numberOfLines: 1, children: r.name }),
1323
+ /* @__PURE__ */ jsx7(Text5, { style: [styles5.tooltipValue, { color: theme.text }], children: r.value })
1324
+ ] }, r.name)),
1325
+ tappable && /* @__PURE__ */ jsx7(TooltipLinks, { links, onOpen: onOpenLink })
1326
+ ]
1327
+ }
1328
+ );
1329
+ }
1330
+ var showLegend = (panel, seriesCount) => seriesCount >= 2 && panel.options?.legend?.showLegend !== false && panel.options?.legend?.displayMode !== "hidden";
1331
+ var styles5 = StyleSheet5.create({
1332
+ legend: { flexDirection: "row", flexWrap: "wrap", gap: 10, paddingTop: 6 },
1333
+ legendItem: { flexDirection: "row", alignItems: "center", gap: 5, maxWidth: "100%" },
1334
+ swatch: { width: 12, height: 3, borderRadius: 2 },
1335
+ legendText: { fontSize: 11, flexShrink: 1 },
1336
+ center: { flex: 1, alignItems: "center", justifyContent: "center" },
1337
+ tooltip: {
1338
+ position: "absolute",
1339
+ paddingHorizontal: 8,
1340
+ paddingVertical: 6,
1341
+ borderRadius: 6,
1342
+ borderWidth: StyleSheet5.hairlineWidth,
1343
+ maxWidth: 220,
1344
+ minWidth: 140,
1345
+ shadowColor: "#000",
1346
+ shadowOpacity: 0.12,
1347
+ shadowRadius: 6,
1348
+ shadowOffset: { width: 0, height: 2 },
1349
+ elevation: 3
1350
+ },
1351
+ tooltipHead: { flexDirection: "row", alignItems: "center", gap: 6, marginBottom: 3 },
1352
+ tooltipTitle: { fontSize: 12, fontWeight: "600", flexShrink: 1 },
1353
+ dot: { width: 8, height: 8, borderRadius: 4 },
1354
+ tooltipRow: { flexDirection: "row", alignItems: "center", gap: 6 },
1355
+ tooltipName: { fontSize: 12, flexShrink: 1 },
1356
+ tooltipValue: { fontSize: 12, fontWeight: "600", marginLeft: "auto", paddingLeft: 8 }
1357
+ });
1358
+
1359
+ // src/ui/inputs/InputPanels.tsx
1360
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
1361
+ function InputPanelBody({ panel }) {
1362
+ const form = useInputForm();
1363
+ const metric = panel.options.metric;
1364
+ const props = { panel, value: form.value(metric), onChange: (v) => form.setValue(metric, v) };
1365
+ switch (panel.type) {
1366
+ case "input-number":
1367
+ return /* @__PURE__ */ jsx8(NumberInput, { ...props });
1368
+ case "input-slider":
1369
+ return /* @__PURE__ */ jsx8(SliderInput, { ...props });
1370
+ case "input-select":
1371
+ return /* @__PURE__ */ jsx8(SelectInput, { ...props });
1372
+ case "input-toggle":
1373
+ return /* @__PURE__ */ jsx8(ToggleInput, { ...props });
1374
+ case "input-rating":
1375
+ return /* @__PURE__ */ jsx8(RatingInput, { ...props });
1376
+ case "input-text":
1377
+ return panel.options.suggest ? /* @__PURE__ */ jsx8(SuggestTextInput, { ...props }) : /* @__PURE__ */ jsx8(FreeTextInput, { ...props });
1378
+ case "input-counter":
1379
+ return /* @__PURE__ */ jsx8(CounterInput, { panel });
1380
+ case "input-duration":
1381
+ return /* @__PURE__ */ jsx8(DurationInput, { ...props });
1382
+ default:
1383
+ return null;
1384
+ }
1385
+ }
1386
+ var COMPACT_NUMBER_WIDTH = 260;
1387
+ var decimalsOf = (step) => (String(step).split(".")[1] ?? "").length;
1388
+ function NumberInput({ panel, value, onChange }) {
1389
+ const theme = useDashTheme();
1390
+ const { step = 1, min, max, unit, placeholder } = panel.options;
1391
+ const [text, setText] = useState5(value == null ? "" : String(value));
1392
+ const [size, onLayout] = useLayout();
1393
+ const compact = size.width > 0 && size.width < COMPACT_NUMBER_WIDTH;
1394
+ const [syncedValue, setSyncedValue] = useState5(value);
1395
+ if (value !== syncedValue) {
1396
+ setSyncedValue(value);
1397
+ setText((t) => value == null ? "" : Number(t.replace(",", ".")) === value && t.trim() ? t : String(value));
1398
+ }
1399
+ const clamp2 = (n) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));
1400
+ const integer = Number.isInteger(step);
1401
+ const signed = min == null || min < 0;
1402
+ const keyboardType = signed ? Platform.OS === "ios" ? "numbers-and-punctuation" : "numeric" : integer ? "number-pad" : "decimal-pad";
1403
+ const bump = (dir) => {
1404
+ const base = typeof value === "number" ? value : Number(text) || 0;
1405
+ onChange(Number(clamp2(base + dir * step).toFixed(decimalsOf(step))));
1406
+ };
1407
+ return /* @__PURE__ */ jsxs6(View5, { style: [styles6.numberRow, compact && styles6.numberRowCompact], onLayout, children: [
1408
+ /* @__PURE__ */ jsx8(StepButton, { label: "\u2212", onPress: () => bump(-1), compact }),
1409
+ /* @__PURE__ */ jsxs6(View5, { style: [styles6.numberField, compact && styles6.numberFieldCompact, { borderColor: theme.border }], children: [
1410
+ /* @__PURE__ */ jsx8(
1411
+ TextInput2,
1412
+ {
1413
+ value: text,
1414
+ onChangeText: (t) => {
1415
+ setText(t);
1416
+ const n = Number(t.replace(",", "."));
1417
+ if (t.trim() && !Number.isNaN(n)) onChange(clamp2(integer ? Math.round(n) : n));
1418
+ else if (!t.trim()) onChange(null);
1419
+ },
1420
+ keyboardType,
1421
+ placeholder: placeholder ?? "\u2014",
1422
+ placeholderTextColor: theme.textMuted,
1423
+ style: [styles6.numberText, compact && styles6.numberTextCompact, { color: theme.text }],
1424
+ accessibilityLabel: unit ? `${panel.title} (${unit})` : panel.title,
1425
+ selectTextOnFocus: true
1426
+ }
1427
+ ),
1428
+ unit && !compact ? /* @__PURE__ */ jsx8(Text6, { style: [styles6.unit, { color: theme.textMuted }], children: unit }) : null
1429
+ ] }),
1430
+ /* @__PURE__ */ jsx8(StepButton, { label: "+", onPress: () => bump(1), compact })
1431
+ ] });
1432
+ }
1433
+ function DurationInput({ panel, value, onChange }) {
1434
+ const theme = useDashTheme();
1435
+ const toDigits = (v) => typeof v === "number" ? formatClock(v).replace(/\D/g, "").replace(/^0+/, "") : "";
1436
+ const [digits, setDigits] = useState5(toDigits(value));
1437
+ const [syncedValue, setSyncedValue] = useState5(value);
1438
+ if (value !== syncedValue) {
1439
+ setSyncedValue(value);
1440
+ setDigits((d) => value == null ? parseClockDigits(d) == null ? d : "" : parseClockDigits(d) === value ? d : toDigits(value));
1441
+ }
1442
+ const masked = digits ? maskClock(digits) : "";
1443
+ const invalid = !!digits && parseClockDigits(digits) == null;
1444
+ return /* @__PURE__ */ jsx8(View5, { style: [styles6.numberField, { borderColor: invalid ? theme.danger : theme.border }], children: /* @__PURE__ */ jsx8(
1445
+ TextInput2,
1446
+ {
1447
+ value: masked,
1448
+ onChangeText: (t) => {
1449
+ const d = t.replace(/\D/g, "").replace(/^0+/, "").slice(0, 6);
1450
+ setDigits(d);
1451
+ onChange(parseClockDigits(d));
1452
+ },
1453
+ keyboardType: "number-pad",
1454
+ placeholder: panel.options.placeholder ?? "00:00.00",
1455
+ placeholderTextColor: theme.textMuted,
1456
+ style: [styles6.numberText, { color: invalid ? theme.danger : theme.text }],
1457
+ accessibilityLabel: panel.title,
1458
+ accessibilityHint: "Type the digits only, for example 13245 for 1 minute 32.45 seconds",
1459
+ selection: { start: masked.length, end: masked.length }
1460
+ }
1461
+ ) });
1462
+ }
1463
+ function maskClock(digits) {
1464
+ const p = digits.slice(-6).padStart(6, "0");
1465
+ return `${p.slice(0, 2)}:${p.slice(2, 4)}.${p.slice(4, 6)}`;
1466
+ }
1467
+ function StepButton({ label, onPress, compact }) {
1468
+ const theme = useDashTheme();
1469
+ return /* @__PURE__ */ jsx8(
1470
+ Pressable5,
1471
+ {
1472
+ onPress,
1473
+ accessibilityRole: "button",
1474
+ accessibilityLabel: label === "+" ? "Increase" : "Decrease",
1475
+ style: ({ pressed }) => [styles6.stepBtn, compact && styles6.stepBtnCompact, { borderColor: theme.border, backgroundColor: pressed ? theme.grid : theme.surface }],
1476
+ children: /* @__PURE__ */ jsx8(Text6, { style: [styles6.stepText, { color: theme.text }], children: label })
1477
+ }
1478
+ );
1479
+ }
1480
+ function SliderInput({ panel, value, onChange }) {
1481
+ const theme = useDashTheme();
1482
+ const [size, onLayout] = useLayout();
1483
+ const { min = 0, max = 10, step = 1, unit, labels } = panel.options;
1484
+ const v = typeof value === "number" ? value : null;
1485
+ const toFrac = (x) => (x - min) / (max - min || 1);
1486
+ const frac = v == null ? 0 : toFrac(v);
1487
+ const origin = min < 0 && max > 0 ? toFrac(0) : 0;
1488
+ const fillStart = Math.min(origin, frac);
1489
+ const labelAt = (x) => {
1490
+ if (!labels?.length) return void 0;
1491
+ const i = labels.length === 1 ? 0 : toFrac(x) * (labels.length - 1);
1492
+ return Number.isInteger(Math.round(i * 1e6) / 1e6) ? labels[Math.round(i)] : void 0;
1493
+ };
1494
+ const display = v == null ? "Drag to set" : labelAt(v) ?? `${v}${unit ? ` ${unit}` : ""}`;
1495
+ const set = (x) => {
1496
+ if (!size.width) return;
1497
+ const raw = min + Math.min(1, Math.max(0, x / size.width)) * (max - min);
1498
+ onChange(Number((Math.round((raw - min) / step) * step + min).toFixed(decimalsOf(step))));
1499
+ };
1500
+ return /* @__PURE__ */ jsxs6(View5, { style: styles6.sliderWrap, children: [
1501
+ /* @__PURE__ */ jsxs6(View5, { style: styles6.sliderLabels, children: [
1502
+ !labels?.length && /* @__PURE__ */ jsx8(Text6, { style: [styles6.minmax, { color: theme.textMuted }], children: min }),
1503
+ /* @__PURE__ */ jsx8(Text6, { style: [styles6.sliderValue, { color: theme.text }, !!labels?.length && styles6.sliderValueCentered], children: display }),
1504
+ !labels?.length && /* @__PURE__ */ jsx8(Text6, { style: [styles6.minmax, { color: theme.textMuted }], children: max })
1505
+ ] }),
1506
+ /* @__PURE__ */ jsxs6(
1507
+ View5,
1508
+ {
1509
+ onLayout,
1510
+ style: styles6.sliderHit,
1511
+ onStartShouldSetResponder: () => true,
1512
+ onMoveShouldSetResponder: () => true,
1513
+ onResponderTerminationRequest: () => false,
1514
+ onResponderGrant: (e) => set(e.nativeEvent.locationX),
1515
+ onResponderMove: (e) => set(e.nativeEvent.locationX),
1516
+ accessibilityRole: "adjustable",
1517
+ accessibilityValue: { min, max, now: v ?? void 0, text: v == null ? void 0 : display },
1518
+ accessibilityActions: [{ name: "increment" }, { name: "decrement" }],
1519
+ onAccessibilityAction: (e) => onChange(Math.min(max, Math.max(min, (v ?? min) + (e.nativeEvent.actionName === "increment" ? step : -step)))),
1520
+ children: [
1521
+ /* @__PURE__ */ jsx8(View5, { pointerEvents: "none", style: [styles6.track, { backgroundColor: theme.grid }], children: /* @__PURE__ */ jsx8(
1522
+ View5,
1523
+ {
1524
+ style: [
1525
+ styles6.trackFill,
1526
+ { left: `${fillStart * 100}%`, width: `${v == null ? 0 : Math.abs(frac - origin) * 100}%`, backgroundColor: theme.accent }
1527
+ ]
1528
+ }
1529
+ ) }),
1530
+ v != null && /* @__PURE__ */ jsx8(
1531
+ View5,
1532
+ {
1533
+ pointerEvents: "none",
1534
+ style: [styles6.thumb, { left: frac * size.width - 11, backgroundColor: theme.accent, borderColor: theme.surface }]
1535
+ }
1536
+ )
1537
+ ]
1538
+ }
1539
+ ),
1540
+ !!labels?.length && /* @__PURE__ */ jsx8(View5, { style: styles6.tickRow, children: labels.map((l, i) => {
1541
+ const last = labels.length - 1;
1542
+ const edge = i === 0 ? styles6.tickStart : i === last ? styles6.tickEnd : { left: `${i / last * 100}%` };
1543
+ return /* @__PURE__ */ jsx8(Text6, { style: [styles6.minmax, styles6.tick, edge, { color: theme.textMuted }], numberOfLines: 1, children: l }, i);
1544
+ }) })
1545
+ ] });
1546
+ }
1547
+ function SelectInput({ panel, value, onChange }) {
1548
+ const theme = useDashTheme();
1549
+ const form = useInputForm();
1550
+ const { choicesFrom, multi, placeholder } = panel.options;
1551
+ const choices = (choicesFrom ? form.choices[choicesFrom] : panel.options.choices) ?? [];
1552
+ const selected = Array.isArray(value) ? value : value == null ? [] : [value];
1553
+ if (!choices.length && placeholder) return /* @__PURE__ */ jsx8(Text6, { style: { color: theme.textMuted }, children: placeholder });
1554
+ return /* @__PURE__ */ jsx8(View5, { style: styles6.wrap, children: choices.map((c) => {
1555
+ const on = selected.includes(c.value);
1556
+ return /* @__PURE__ */ jsx8(
1557
+ Chip,
1558
+ {
1559
+ label: c.label,
1560
+ selected: on,
1561
+ onPress: () => {
1562
+ if (!multi) return onChange(on ? null : c.value);
1563
+ const next = on ? selected.filter((s) => s !== c.value) : [...selected, c.value];
1564
+ onChange(next.length ? next : null);
1565
+ }
1566
+ },
1567
+ String(c.value)
1568
+ );
1569
+ }) });
1570
+ }
1571
+ function ToggleInput({ panel, value, onChange }) {
1572
+ const theme = useDashTheme();
1573
+ return /* @__PURE__ */ jsxs6(View5, { style: styles6.toggleRow, children: [
1574
+ /* @__PURE__ */ jsx8(Text6, { style: { color: theme.textSecondary, flex: 1 }, children: value == null ? "Not set" : value ? "Yes" : "No" }),
1575
+ /* @__PURE__ */ jsx8(Switch, { value: !!value, onValueChange: (v) => onChange(v), trackColor: { true: theme.accent }, accessibilityLabel: panel.title })
1576
+ ] });
1577
+ }
1578
+ var MAX_RATING_LEVELS = 10;
1579
+ function RatingInput({ panel, value, onChange }) {
1580
+ const theme = useDashTheme();
1581
+ const min = Math.round(panel.options.min ?? 1);
1582
+ const max = Math.round(panel.options.max ?? 5);
1583
+ const levels = Array.from({ length: Math.min(Math.max(0, max - min + 1), MAX_RATING_LEVELS) }, (_, i) => min + i);
1584
+ return /* @__PURE__ */ jsx8(View5, { style: styles6.rating, children: levels.map((n) => {
1585
+ const on = typeof value === "number" && n <= value;
1586
+ return /* @__PURE__ */ jsx8(
1587
+ Pressable5,
1588
+ {
1589
+ onPress: () => onChange(value === n ? null : n),
1590
+ accessibilityRole: "button",
1591
+ accessibilityLabel: `${n} of ${max}`,
1592
+ accessibilityState: { selected: value === n },
1593
+ style: [styles6.ratingDot, { borderColor: on ? theme.accent : theme.border, backgroundColor: on ? theme.accent : theme.surface }],
1594
+ children: /* @__PURE__ */ jsx8(Text6, { style: { color: on ? "#fff" : theme.textSecondary, fontWeight: "600" }, children: n })
1595
+ },
1596
+ n
1597
+ );
1598
+ }) });
1599
+ }
1600
+ function FreeTextInput({ panel, value, onChange }) {
1601
+ const theme = useDashTheme();
1602
+ return /* @__PURE__ */ jsx8(
1603
+ TextInput2,
1604
+ {
1605
+ value: typeof value === "string" ? value : "",
1606
+ onChangeText: (t) => onChange(t || null),
1607
+ placeholder: panel.options.placeholder ?? "Type here",
1608
+ placeholderTextColor: theme.textMuted,
1609
+ multiline: true,
1610
+ style: [styles6.textArea, { color: theme.text, borderColor: theme.border }]
1611
+ }
1612
+ );
1613
+ }
1614
+ function SuggestTextInput({ panel, value, onChange }) {
1615
+ const theme = useDashTheme();
1616
+ const form = useInputForm();
1617
+ const { metric, suggestWith, placeholder } = panel.options;
1618
+ const [entries, setEntries] = useState5([]);
1619
+ const [typed, setTyped] = useState5(false);
1620
+ const text = typeof value === "string" ? value : "";
1621
+ const { store } = form;
1622
+ useEffect2(() => {
1623
+ let run = 0;
1624
+ const load = () => {
1625
+ const mine = ++run;
1626
+ store.list({ metrics: suggestWith ? [metric, suggestWith] : [metric] }).then((rows) => mine === run && setEntries(rows));
1627
+ };
1628
+ load();
1629
+ const unsubscribe = store.subscribe(load);
1630
+ return () => {
1631
+ run = -1;
1632
+ unsubscribe();
1633
+ };
1634
+ }, [store, metric, suggestWith]);
1635
+ const withText = suggestWith ? form.value(suggestWith) : null;
1636
+ const own = entries.filter((e) => e.metric === metric);
1637
+ const scoped = suggestWith && typeof withText === "string" && withText.trim() ? entriesSavedWith(entries, metric, suggestWith, withText) : [];
1638
+ const query = typed ? text : "";
1639
+ const fromScoped = textSuggestions(scoped, query);
1640
+ const suggestions = (fromScoped.length ? fromScoped : textSuggestions(own, query)).filter((s) => s.toLowerCase() !== text.trim().toLowerCase());
1641
+ return /* @__PURE__ */ jsxs6(View5, { style: styles6.suggest, children: [
1642
+ /* @__PURE__ */ jsx8(
1643
+ TextInput2,
1644
+ {
1645
+ value: text,
1646
+ onChangeText: (t) => {
1647
+ setTyped(!!t);
1648
+ onChange(t || null);
1649
+ },
1650
+ placeholder: placeholder ?? "Type here",
1651
+ placeholderTextColor: theme.textMuted,
1652
+ style: [styles6.textLine, { color: theme.text, borderColor: theme.border }],
1653
+ accessibilityLabel: panel.title,
1654
+ autoCorrect: false,
1655
+ autoCapitalize: "words",
1656
+ returnKeyType: "done",
1657
+ selectTextOnFocus: true
1658
+ }
1659
+ ),
1660
+ /* @__PURE__ */ jsx8(ScrollView3, { horizontal: true, keyboardShouldPersistTaps: "handled", showsHorizontalScrollIndicator: false, contentContainerStyle: styles6.wrap, children: suggestions.map((s) => /* @__PURE__ */ jsx8(
1661
+ Chip,
1662
+ {
1663
+ label: s,
1664
+ onPress: () => {
1665
+ setTyped(false);
1666
+ onChange(s);
1667
+ }
1668
+ },
1669
+ s
1670
+ )) })
1671
+ ] });
1672
+ }
1673
+ function CounterInput({ panel }) {
1674
+ const theme = useDashTheme();
1675
+ const { store } = useInputForm();
1676
+ const { metric, increment = 1, unit } = panel.options;
1677
+ const [today, setToday] = useState5(0);
1678
+ useEffect2(() => {
1679
+ const load = () => store.list({ metrics: [metric], from: startOf(/* @__PURE__ */ new Date(), "d").getTime() }).then((rows) => setToday(rows.reduce((a, e) => a + (e.value ?? 0), 0)));
1680
+ load();
1681
+ return store.subscribe(load);
1682
+ }, [store, metric]);
1683
+ return /* @__PURE__ */ jsxs6(View5, { style: styles6.counter, children: [
1684
+ /* @__PURE__ */ jsxs6(View5, { style: { flex: 1 }, children: [
1685
+ /* @__PURE__ */ jsxs6(Text6, { style: [styles6.counterValue, { color: theme.text }], children: [
1686
+ today,
1687
+ unit ? /* @__PURE__ */ jsx8(Text6, { style: { fontSize: 14, color: theme.textMuted }, children: ` ${unit}` }) : null
1688
+ ] }),
1689
+ /* @__PURE__ */ jsx8(Text6, { style: { color: theme.textMuted, fontSize: 12 }, children: "today" })
1690
+ ] }),
1691
+ /* @__PURE__ */ jsx8(
1692
+ Pressable5,
1693
+ {
1694
+ onPress: () => store.add([{ metric, ts: Date.now(), value: increment, text: null }]),
1695
+ accessibilityRole: "button",
1696
+ accessibilityLabel: `Add ${increment}`,
1697
+ style: ({ pressed }) => [styles6.counterBtn, { backgroundColor: theme.accent, opacity: pressed ? 0.8 : 1 }],
1698
+ children: /* @__PURE__ */ jsxs6(Text6, { style: styles6.counterBtnText, children: [
1699
+ "+",
1700
+ increment
1701
+ ] })
1702
+ }
1703
+ )
1704
+ ] });
1705
+ }
1706
+ var styles6 = StyleSheet6.create({
1707
+ numberRow: { flex: 1, flexDirection: "row", alignItems: "center", gap: 8 },
1708
+ numberField: { flex: 1, flexDirection: "row", alignItems: "center", borderWidth: 1, borderRadius: 8, paddingHorizontal: 10, height: 44 },
1709
+ // Android gives TextInput default padding that eats into narrow fields.
1710
+ numberText: { flex: 1, minWidth: 0, width: "100%", paddingHorizontal: 0, paddingVertical: 0, fontSize: 20, fontWeight: "600", fontVariant: ["tabular-nums"], textAlign: "center" },
1711
+ unit: { fontSize: 14 },
1712
+ numberRowCompact: { gap: 4 },
1713
+ numberFieldCompact: { paddingHorizontal: 4 },
1714
+ numberTextCompact: { fontSize: 17 },
1715
+ stepBtnCompact: { width: 32 },
1716
+ stepBtn: { width: 44, height: 44, borderRadius: 8, borderWidth: 1, alignItems: "center", justifyContent: "center" },
1717
+ stepText: { fontSize: 22, fontWeight: "500" },
1718
+ sliderWrap: { flex: 1, justifyContent: "center", gap: 6 },
1719
+ sliderLabels: { flexDirection: "row", justifyContent: "space-between", alignItems: "baseline" },
1720
+ minmax: { fontSize: 11 },
1721
+ sliderValue: { fontSize: 16, fontWeight: "600" },
1722
+ sliderValueCentered: { flex: 1, textAlign: "center" },
1723
+ tickRow: { height: 14 },
1724
+ // Middle labels are centred on their point along the track; the ends hug the edges.
1725
+ tick: { position: "absolute", width: 120, marginLeft: -60, textAlign: "center" },
1726
+ tickStart: { left: 0, marginLeft: 0, textAlign: "left" },
1727
+ tickEnd: { right: 0, marginLeft: 0, textAlign: "right" },
1728
+ sliderHit: { height: 32, justifyContent: "center" },
1729
+ track: { height: 6, borderRadius: 3, overflow: "hidden" },
1730
+ trackFill: { position: "absolute", height: "100%" },
1731
+ thumb: { position: "absolute", width: 22, height: 22, borderRadius: 11, borderWidth: 2, top: 5 },
1732
+ wrap: { flexDirection: "row", flexWrap: "wrap", gap: 6 },
1733
+ toggleRow: { flex: 1, flexDirection: "row", alignItems: "center" },
1734
+ rating: { flex: 1, flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 6 },
1735
+ ratingDot: { flex: 1, maxWidth: 52, aspectRatio: 1, borderRadius: 26, borderWidth: 1, alignItems: "center", justifyContent: "center" },
1736
+ suggest: { flex: 1, gap: 8 },
1737
+ textLine: { height: 44, borderWidth: 1, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 0, fontSize: 16 },
1738
+ textArea: { flex: 1, borderWidth: 1, borderRadius: 8, padding: 10, fontSize: 15, textAlignVertical: "top" },
1739
+ counter: { flex: 1, flexDirection: "row", alignItems: "center", gap: 12 },
1740
+ counterValue: { fontSize: 28, fontWeight: "600", fontVariant: ["tabular-nums"] },
1741
+ counterBtn: { paddingHorizontal: 20, height: 48, borderRadius: 24, alignItems: "center", justifyContent: "center" },
1742
+ counterBtnText: { color: "#fff", fontSize: 18, fontWeight: "700" }
1743
+ });
1744
+
1745
+ // src/ui/panels/GaugePanels.tsx
1746
+ import { useMemo as useMemo3 } from "react";
1747
+ import { Pressable as Pressable7, StyleSheet as StyleSheet8, Text as Text8, View as View7 } from "react-native";
1748
+ import Svg5, { Path as Path5 } from "react-native-svg";
1749
+
1750
+ // src/ui/panels/StatPanel.tsx
1751
+ import { useMemo as useMemo2 } from "react";
1752
+ import { Pressable as Pressable6, StyleSheet as StyleSheet7, Text as Text7, View as View6 } from "react-native";
1753
+ import Svg4, { Path as Path4 } from "react-native-svg";
1754
+ import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
1755
+ function StatPanel({ panel, frames }) {
1756
+ const theme = useDashTheme();
1757
+ const values = useMemo2(() => reducedValues(panel, frames, theme.scheme), [panel, frames, theme.scheme]);
1758
+ if (!values.length) return /* @__PURE__ */ jsx9(NoData, {});
1759
+ const horizontal = panel.options?.orientation === "horizontal";
1760
+ return /* @__PURE__ */ jsx9(View6, { style: [styles7.grid, { flexDirection: horizontal ? "column" : "row" }], children: values.map((v) => /* @__PURE__ */ jsx9(StatTile, { v, showName: values.length > 1, panel }, v.key)) });
1761
+ }
1762
+ function StatTile({ v, showName, panel }) {
1763
+ const theme = useDashTheme();
1764
+ const [size, onLayout] = useLayout();
1765
+ const colorMode = panel.options?.colorMode ?? "value";
1766
+ const graph = (panel.options?.graphMode ?? "area") === "area" && v.sparkline.filter((x) => x != null).length > 1;
1767
+ const fontSize = Math.max(18, Math.min(56, size.height * (graph ? 0.4 : 0.5), size.width / 4.5));
1768
+ const { resolve, openLinks } = usePanelLinks(panel);
1769
+ const hasLinks = !!v.config.links?.length;
1770
+ return /* @__PURE__ */ jsxs7(
1771
+ Pressable6,
1772
+ {
1773
+ onLayout,
1774
+ disabled: !hasLinks,
1775
+ onPress: () => openLinks(valueLinks(panel, v, resolve), v.name),
1776
+ accessibilityRole: hasLinks ? "link" : void 0,
1777
+ style: ({ pressed }) => [
1778
+ styles7.tile,
1779
+ // With a sparkline, the number sits in the top half so the line runs beneath it.
1780
+ graph && { justifyContent: "flex-start", paddingTop: 4 },
1781
+ colorMode === "background" && { backgroundColor: withAlpha(v.stateColor, 0.14) },
1782
+ pressed && { opacity: 0.7 }
1783
+ ],
1784
+ children: [
1785
+ colorMode !== "none" && /* @__PURE__ */ jsx9(View6, { style: [styles7.accent, { backgroundColor: v.stateColor }] }),
1786
+ graph && size.width > 0 && /* @__PURE__ */ jsx9(Sparkline, { values: v.sparkline, width: size.width, height: size.height * 0.4, color: v.stateColor }),
1787
+ showName && /* @__PURE__ */ jsx9(Text7, { style: [styles7.name, { color: theme.textSecondary }], numberOfLines: 1, children: v.name }),
1788
+ /* @__PURE__ */ jsx9(Text7, { style: [styles7.value, { color: theme.text, fontSize }], numberOfLines: 1, adjustsFontSizeToFit: true, children: v.text })
1789
+ ]
1790
+ }
1791
+ );
1792
+ }
1793
+ function Sparkline({ values, width, height, color }) {
1794
+ const nums = values.filter((v) => v != null);
1795
+ const min = Math.min(...nums);
1796
+ const max = Math.max(...nums);
1797
+ const x = linearScale(0, Math.max(values.length - 1, 1), 0, width);
1798
+ const y = linearScale(min, max === min ? min + 1 : max, height - 2, 2);
1799
+ let line = "";
1800
+ values.forEach((v, i) => {
1801
+ if (v != null) line += `${line ? "L" : "M"}${x(i)},${y(v)}`;
1802
+ });
1803
+ return /* @__PURE__ */ jsxs7(Svg4, { width, height, style: styles7.spark, children: [
1804
+ /* @__PURE__ */ jsx9(Path4, { d: `${line}L${width},${height}L0,${height}Z`, fill: color, opacity: 0.1 }),
1805
+ /* @__PURE__ */ jsx9(Path4, { d: line, stroke: color, strokeWidth: 2, fill: "none", strokeLinejoin: "round" })
1806
+ ] });
1807
+ }
1808
+ function withAlpha(hex, alpha) {
1809
+ if (!/^#[0-9a-f]{6}$/i.test(hex)) return hex;
1810
+ return `${hex}${Math.round(alpha * 255).toString(16).padStart(2, "0")}`;
1811
+ }
1812
+ var styles7 = StyleSheet7.create({
1813
+ grid: { flex: 1, gap: 8 },
1814
+ tile: { flex: 1, justifyContent: "center", paddingLeft: 12, borderRadius: 6, overflow: "hidden" },
1815
+ accent: { position: "absolute", left: 0, top: 6, bottom: 6, width: 3, borderRadius: 2 },
1816
+ name: { fontSize: 12, marginBottom: 2 },
1817
+ value: { fontWeight: "600", fontVariant: ["tabular-nums"] },
1818
+ spark: { position: "absolute", bottom: 0, left: 0 }
1819
+ });
1820
+
1821
+ // src/ui/panels/GaugePanels.tsx
1822
+ import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
1823
+ var SWEEP = 240;
1824
+ function GaugePanel({ panel, frames }) {
1825
+ const theme = useDashTheme();
1826
+ const values = useMemo3(() => reducedValues(panel, frames, theme.scheme), [panel, frames, theme.scheme]);
1827
+ if (!values.length) return /* @__PURE__ */ jsx10(NoData, {});
1828
+ return /* @__PURE__ */ jsx10(View7, { style: styles8.row, children: values.map((v) => /* @__PURE__ */ jsx10(Gauge, { v, showName: values.length > 1, panel }, v.key)) });
1829
+ }
1830
+ function Gauge({ v, showName, panel }) {
1831
+ const theme = useDashTheme();
1832
+ const [size, onLayout] = useLayout();
1833
+ const { resolve, openLinks } = usePanelLinks(panel);
1834
+ const hasLinks = !!v.config.links?.length;
1835
+ const min = v.config.min ?? 0;
1836
+ const max = v.config.max ?? 100;
1837
+ const frac = v.value == null ? 0 : Math.min(1, Math.max(0, (v.value - min) / (max - min || 1)));
1838
+ const d = Math.min(size.width, size.height * 1.15);
1839
+ const stroke = Math.max(6, d * 0.09);
1840
+ const r = d / 2 - stroke;
1841
+ const cx = size.width / 2;
1842
+ const cy = size.height / 2 + d * 0.08;
1843
+ return /* @__PURE__ */ jsxs8(
1844
+ Pressable7,
1845
+ {
1846
+ style: ({ pressed }) => [styles8.fill, pressed && { opacity: 0.7 }],
1847
+ onLayout,
1848
+ disabled: !hasLinks,
1849
+ onPress: () => openLinks(valueLinks(panel, v, resolve), v.name),
1850
+ accessibilityRole: hasLinks ? "link" : void 0,
1851
+ children: [
1852
+ size.width > 0 && r > 0 && /* @__PURE__ */ jsxs8(Svg5, { width: size.width, height: size.height, children: [
1853
+ /* @__PURE__ */ jsx10(Path5, { d: arc(cx, cy, r, 0, 1), stroke: withAlpha(v.stateColor, 0.18), strokeWidth: stroke, fill: "none", strokeLinecap: "round" }),
1854
+ frac > 0 && /* @__PURE__ */ jsx10(Path5, { d: arc(cx, cy, r, 0, frac), stroke: v.stateColor, strokeWidth: stroke, fill: "none", strokeLinecap: "round" })
1855
+ ] }),
1856
+ /* @__PURE__ */ jsxs8(View7, { style: [StyleSheet8.absoluteFill, styles8.center, { top: d * 0.12 }], pointerEvents: "none", children: [
1857
+ /* @__PURE__ */ jsx10(Text8, { style: [styles8.value, { color: theme.text, fontSize: Math.max(14, d * 0.18) }], numberOfLines: 1, adjustsFontSizeToFit: true, children: v.text }),
1858
+ showName && /* @__PURE__ */ jsx10(Text8, { style: [styles8.name, { color: theme.textSecondary }], numberOfLines: 1, children: v.name })
1859
+ ] })
1860
+ ]
1861
+ }
1862
+ );
1863
+ }
1864
+ function arc(cx, cy, r, a, b) {
1865
+ const start = -90 - SWEEP / 2 + a * SWEEP;
1866
+ const end = -90 - SWEEP / 2 + b * SWEEP;
1867
+ const p = (deg) => [cx + r * Math.cos(deg * Math.PI / 180), cy + r * Math.sin(deg * Math.PI / 180)];
1868
+ const [x1, y1] = p(start);
1869
+ const [x2, y2] = p(end);
1870
+ return `M${x1},${y1}A${r},${r} 0 ${end - start > 180 ? 1 : 0} 1 ${x2},${y2}`;
1871
+ }
1872
+ function BarGaugePanel({ panel, frames }) {
1873
+ const theme = useDashTheme();
1874
+ const values = useMemo3(() => reducedValues(panel, frames, theme.scheme), [panel, frames, theme.scheme]);
1875
+ const { resolve, openLinks } = usePanelLinks(panel);
1876
+ if (!values.length) return /* @__PURE__ */ jsx10(NoData, {});
1877
+ return /* @__PURE__ */ jsx10(View7, { style: styles8.bars, children: values.map((v) => {
1878
+ const min = v.config.min ?? 0;
1879
+ const max = v.config.max ?? Math.max(...values.map((o) => o.value ?? 0), 1);
1880
+ const frac = v.value == null ? 0 : Math.min(1, Math.max(0, (v.value - min) / (max - min || 1)));
1881
+ const color = v.config.thresholds || v.mapped?.color ? v.stateColor : resolveColor(v.config.color?.fixedColor, v.color);
1882
+ const hasLinks = !!v.config.links?.length;
1883
+ return /* @__PURE__ */ jsxs8(
1884
+ Pressable7,
1885
+ {
1886
+ style: ({ pressed }) => [styles8.barRow, pressed && { opacity: 0.7 }],
1887
+ disabled: !hasLinks,
1888
+ onPress: () => openLinks(valueLinks(panel, v, resolve), v.name),
1889
+ accessibilityRole: hasLinks ? "link" : void 0,
1890
+ children: [
1891
+ /* @__PURE__ */ jsxs8(View7, { style: styles8.barLabels, children: [
1892
+ /* @__PURE__ */ jsx10(Text8, { style: [styles8.name, { color: theme.textSecondary }], numberOfLines: 1, children: v.name }),
1893
+ /* @__PURE__ */ jsx10(Text8, { style: [styles8.barValue, { color: theme.text }], children: v.text })
1894
+ ] }),
1895
+ /* @__PURE__ */ jsx10(View7, { style: [styles8.track, { backgroundColor: withAlpha(color, 0.18) }], children: /* @__PURE__ */ jsx10(View7, { style: [styles8.meter, { width: `${frac * 100}%`, backgroundColor: color }] }) })
1896
+ ]
1897
+ },
1898
+ v.key
1899
+ );
1900
+ }) });
1901
+ }
1902
+ var styles8 = StyleSheet8.create({
1903
+ fill: { flex: 1 },
1904
+ row: { flex: 1, flexDirection: "row", gap: 8 },
1905
+ center: { alignItems: "center", justifyContent: "center" },
1906
+ value: { fontWeight: "600", fontVariant: ["tabular-nums"] },
1907
+ name: { fontSize: 12, flexShrink: 1 },
1908
+ bars: { flex: 1, justifyContent: "space-evenly", gap: 6 },
1909
+ barRow: { gap: 4 },
1910
+ barLabels: { flexDirection: "row", justifyContent: "space-between", gap: 8 },
1911
+ barValue: { fontSize: 12, fontWeight: "600", fontVariant: ["tabular-nums"] },
1912
+ track: { height: 10, borderRadius: 4, overflow: "hidden" },
1913
+ meter: { height: "100%", borderRadius: 4 }
1914
+ });
1915
+
1916
+ // src/ui/panels/GeomapPanel.tsx
1917
+ import { useEffect as useEffect3, useMemo as useMemo4, useRef as useRef2, useState as useState6 } from "react";
1918
+ import { Image, PixelRatio, Pressable as Pressable8, StyleSheet as StyleSheet9, Text as Text9, View as View8 } from "react-native";
1919
+ import Svg6, { Path as Path6, Text as SvgText2 } from "react-native-svg";
1920
+
1921
+ // src/ui/geomap.ts
1922
+ var TILE = 256;
1923
+ var MAX_LAT = 85.0511287798;
1924
+ var MAX_ZOOM = 18;
1925
+ var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
1926
+ function project(lon, lat) {
1927
+ const phi = clamp(lat, -MAX_LAT, MAX_LAT) * Math.PI / 180;
1928
+ return [(lon + 180) / 360, (1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2];
1929
+ }
1930
+ function unproject(x, y) {
1931
+ return { lon: x * 360 - 180, lat: Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI };
1932
+ }
1933
+ var ESRI = {
1934
+ streets: { service: "World_Street_Map", maxZoom: 18 },
1935
+ "world-imagery": { service: "World_Imagery", maxZoom: 18 },
1936
+ "world-physical": { service: "World_Physical_Map", maxZoom: 8 },
1937
+ topo: { service: "World_Topo_Map", maxZoom: 18 },
1938
+ "usa-topo": { service: "USA_Topo_Maps", maxZoom: 15 },
1939
+ ocean: { service: "Ocean/World_Ocean_Base", maxZoom: 10 }
1940
+ };
1941
+ var TILE_LAYERS = /* @__PURE__ */ new Set(["default", "carto", "esri-xyz", "xyz", "osm-standard"]);
1942
+ var fillTemplate = (template, z, x, y) => template.replace("{z}", String(z)).replace("{x}", String(x)).replace("{-y}", String(2 ** z - 1 - y)).replace("{y}", String(y));
1943
+ var stripTags = (html) => html.replace(/<[^>]*>/g, "").replace(/&copy;/g, "\xA9").trim();
1944
+ function tileSource(layer, scheme, retina = false) {
1945
+ const config = layer?.config ?? {};
1946
+ switch (layer?.type) {
1947
+ case "osm-standard":
1948
+ return { url: (z, x, y) => `https://tile.openstreetmap.org/${z}/${x}/${y}.png`, maxZoom: 19, attribution: "\xA9 OpenStreetMap contributors" };
1949
+ case "esri-xyz": {
1950
+ const server = ESRI[config.server];
1951
+ if (!server && config.url) return xyz(config.url, config.attribution, 18);
1952
+ const { service, maxZoom } = server ?? ESRI.streets;
1953
+ return {
1954
+ url: (z, x, y) => `https://services.arcgisonline.com/arcgis/rest/services/${service}/MapServer/tile/${z}/${y}/${x}`,
1955
+ maxZoom,
1956
+ attribution: "Tiles \xA9 Esri"
1957
+ };
1958
+ }
1959
+ case "xyz":
1960
+ if (config.url) return xyz(config.url, config.attribution, config.maxZoom ?? MAX_ZOOM);
1961
+ }
1962
+ const dark = config.theme === "dark" || config.theme !== "light" && scheme === "dark";
1963
+ const style = `${dark ? "dark" : "light"}_${config.showLabels === false ? "nolabels" : "all"}`;
1964
+ return {
1965
+ url: (z, x, y) => `https://${"abcd"[(x + y) % 4]}.basemaps.cartocdn.com/${style}/${z}/${x}/${y}${retina ? "@2x" : ""}.png`,
1966
+ maxZoom: 20,
1967
+ attribution: "\xA9 CARTO \xA9 OpenStreetMap contributors"
1968
+ };
1969
+ }
1970
+ function xyz(template, attribution, maxZoom) {
1971
+ return { url: (z, x, y) => fillTemplate(template, z, x, y), maxZoom, attribution: typeof attribution === "string" ? stripTags(attribution) : "" };
1972
+ }
1973
+ function visibleTiles(source, view, width, height) {
1974
+ const z = clamp(Math.round(view.zoom), 0, source.maxZoom);
1975
+ const n = 2 ** z;
1976
+ const size = TILE * 2 ** (view.zoom - z);
1977
+ const [cx, cy] = project(view.lon, view.lat);
1978
+ const ox = width / 2 - cx * n * size;
1979
+ const oy = height / 2 - cy * n * size;
1980
+ const out = [];
1981
+ const tx0 = Math.floor(-ox / size);
1982
+ const tx1 = Math.ceil((width - ox) / size) - 1;
1983
+ const ty0 = Math.max(0, Math.floor(-oy / size));
1984
+ const ty1 = Math.min(n - 1, Math.ceil((height - oy) / size) - 1);
1985
+ for (let ty = ty0; ty <= ty1; ty++) {
1986
+ for (let tx = tx0; tx <= tx1; tx++) {
1987
+ const wx = (tx % n + n) % n;
1988
+ out.push({ key: `${z}/${tx}/${ty}`, url: source.url(z, wx, ty), left: ox + tx * size, top: oy + ty * size, size });
1989
+ }
1990
+ }
1991
+ return out;
1992
+ }
1993
+ var REGIONS = {
1994
+ zero: { lat: 0, lon: 0, zoom: 1 },
1995
+ "north-america": { lat: 40, lon: -100, zoom: 4 },
1996
+ "south-america": { lat: -20, lon: -60, zoom: 3 },
1997
+ europe: { lat: 46, lon: 14, zoom: 4 },
1998
+ africa: { lat: 0, lon: 30, zoom: 3 },
1999
+ "west-asia": { lat: 26, lon: 53, zoom: 4 },
2000
+ "south-asia": { lat: 19.5, lon: 80, zoom: 4 },
2001
+ "south-east-asia": { lat: 10, lon: 106, zoom: 4 },
2002
+ "east-asia": { lat: 33, lon: 120, zoom: 4 },
2003
+ australia: { lat: -25, lon: 135, zoom: 4 },
2004
+ oceania: { lat: -10, lon: -140, zoom: 3 }
2005
+ };
2006
+ function zoomLimits(panel) {
2007
+ const v = panel.options?.view ?? {};
2008
+ return [v.minZoom ?? 0, v.maxZoom ?? MAX_ZOOM];
2009
+ }
2010
+ function initialView(panel, layers, width, height) {
2011
+ const v = panel.options?.view ?? {};
2012
+ const [minZoom, maxZoom] = zoomLimits(panel);
2013
+ const limit = (view) => ({ ...view, zoom: clamp(view.zoom, minZoom, maxZoom) });
2014
+ if (v.id === "coords") return limit({ lat: v.lat ?? 0, lon: v.lon ?? 0, zoom: v.zoom ?? 1 });
2015
+ if (v.id !== "fit") {
2016
+ const region = REGIONS[v.id] ?? REGIONS.zero;
2017
+ return limit({ ...region, zoom: v.zoom ?? region.zoom });
2018
+ }
2019
+ const fitted = layers.filter((l) => l.type !== "tiles" && (v.allLayers !== false || l.name === v.layer));
2020
+ let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity];
2021
+ for (const l of fitted) {
2022
+ for (const p of l.points) {
2023
+ const from = v.lastOnly ? p.xs.length - 1 : 0;
2024
+ for (let i = Math.max(0, from); i < p.xs.length; i++) {
2025
+ x0 = Math.min(x0, p.xs[i]);
2026
+ x1 = Math.max(x1, p.xs[i]);
2027
+ y0 = Math.min(y0, p.ys[i]);
2028
+ y1 = Math.max(y1, p.ys[i]);
2029
+ }
2030
+ }
2031
+ }
2032
+ if (x0 === Infinity) return limit(REGIONS.zero);
2033
+ const cap = Math.min(v.zoom ?? v.maxZoom ?? 15, maxZoom);
2034
+ const { lon, lat } = unproject((x0 + x1) / 2, (y0 + y1) / 2);
2035
+ const span = Math.max((x1 - x0) / Math.max(width, 1), (y1 - y0) / Math.max(height, 1)) * TILE;
2036
+ const fit = span > 0 ? -Math.log2(span) - Math.log2(1 + (v.padding ?? 5) / 100) : cap;
2037
+ return { lon, lat, zoom: clamp(Math.min(fit, cap), minZoom, maxZoom) };
2038
+ }
2039
+ var DEFAULT_LAYERS = [{ type: "markers", name: "Layer 1", config: {}, location: { mode: "auto" } }];
2040
+ function geomapLayers(panel, frames, scheme, retina = false, gazetteers = {}) {
2041
+ const o = panel.options ?? {};
2042
+ const out = [];
2043
+ const basemap = o.basemap;
2044
+ out.push({ type: "tiles", key: "basemap", name: basemap?.name ?? "Basemap", opacity: basemap?.opacity ?? 1, source: tileSource(basemap, scheme, retina) });
2045
+ const multiple = frames.length > 1;
2046
+ (o.layers ?? DEFAULT_LAYERS).forEach((layer, li) => {
2047
+ const key = `${li}/${layer.type}`;
2048
+ const name = layer.name ?? `Layer ${li + 1}`;
2049
+ const opacity = layer.opacity ?? 1;
2050
+ const config = layer.config ?? {};
2051
+ if (layer.type && TILE_LAYERS.has(layer.type)) {
2052
+ out.push({ type: "tiles", key, name, opacity, source: tileSource(layer, scheme, retina) });
2053
+ return;
2054
+ }
2055
+ if (!isDataLayer(layer.type)) return;
2056
+ const filter = layer.filterData;
2057
+ const chosen = filter?.id === "byRefId" && filter.options ? frames.filter((f) => f.refId === filter.options) : frames;
2058
+ const style = config.style ?? {};
2059
+ const color = style.color ?? {};
2060
+ const size = style.size ?? {};
2061
+ const text = style.text;
2062
+ const fixedColor = resolveColor(color.fixed ?? "dark-green", "#37872D");
2063
+ const heat = layer.type === "heatmap";
2064
+ const weight = config.weight ?? {};
2065
+ const legend = [];
2066
+ const points = [];
2067
+ for (const frame of chosen) {
2068
+ const located = locate2(frame, layer.location, gazetteers);
2069
+ if (!located) continue;
2070
+ let { rows } = located;
2071
+ let { xs, ys } = located;
2072
+ if (layer.type === "lastPointTracker" && rows.length) [rows, xs, ys] = [rows.slice(-1), xs.slice(-1), ys.slice(-1)];
2073
+ const find = (field) => field ? fieldByName(frame, field, multiple) : void 0;
2074
+ const configOf = (f) => resolveFieldConfig(panel, f, frame, fieldDisplayName(f, frame, multiple));
2075
+ let colors = rows.map(() => fixedColor);
2076
+ const colorField = !heat ? find(color.field) : void 0;
2077
+ if (colorField) {
2078
+ const cConfig = configOf(colorField);
2079
+ const values = rows.map((i) => num(colorField.values[i]));
2080
+ const extent = range(values);
2081
+ colors = values.map((v) => valueColor(v, cConfig, fixedColor, extent));
2082
+ if (showsLegend(layer) && legend.length === 0) legend.push(...thresholdLegend(`${key}/${frames.indexOf(frame)}`, cConfig, fixedColor));
2083
+ }
2084
+ const dim = heat ? weight : size;
2085
+ const sizeField = find(dim.field);
2086
+ let sizes = rows.map(() => dim.fixed ?? (heat ? 1 : 5));
2087
+ if (sizeField) {
2088
+ const values = rows.map((i) => num(sizeField.values[i]));
2089
+ const sConfig = configOf(sizeField);
2090
+ const ext = range(values) ?? [0, 1];
2091
+ const [lo, hi] = [sConfig.min ?? ext[0], sConfig.max ?? ext[1]];
2092
+ const [min, max] = [dim.min ?? (heat ? 0 : 2), dim.max ?? (heat ? 1 : 15)];
2093
+ sizes = values.map((v) => v == null ? min : min + clamp((v - lo) / (hi - lo || 1), 0, 1) * (max - min));
2094
+ }
2095
+ let labels;
2096
+ if (text && !heat) {
2097
+ const textField = text.mode === "field" || text.field && text.mode !== "fixed" ? find(text.field) : void 0;
2098
+ if (textField) {
2099
+ const tConfig = configOf(textField);
2100
+ labels = rows.map((i) => cellText(textField, textField.values[i], tConfig));
2101
+ } else if (text.fixed) labels = rows.map(() => String(text.fixed));
2102
+ }
2103
+ points.push({ frame, rows, xs, ys, colors, sizes, labels });
2104
+ }
2105
+ const tooltip = layer.tooltip !== false;
2106
+ if (heat) out.push({ type: "heatmap", key, name, opacity, points, radius: config.radius ?? 5, blur: config.blur ?? 15, tooltip: false });
2107
+ else if (layer.type === "route")
2108
+ out.push({ type: "route", key, name, opacity: opacity * (style.opacity ?? 1), points, lineWidth: style.lineWidth ?? 2, tooltip, legend });
2109
+ else {
2110
+ const textConfig = style.textConfig ?? {};
2111
+ out.push({
2112
+ type: "markers",
2113
+ key,
2114
+ name,
2115
+ opacity,
2116
+ points,
2117
+ symbol: markerSymbol(style.symbol?.fixed),
2118
+ fillOpacity: style.opacity ?? 0.4,
2119
+ fontSize: textConfig.fontSize ?? 12,
2120
+ labelOffset: [textConfig.offsetX ?? 0, textConfig.offsetY ?? 0],
2121
+ tooltip,
2122
+ legend
2123
+ });
2124
+ }
2125
+ });
2126
+ return out;
2127
+ }
2128
+ var showsLegend = (layer) => layer.config?.showLegend !== false;
2129
+ function markerSymbol(path) {
2130
+ const name = typeof path === "string" ? path.replace(/^.*\//, "").replace(/\.svg$/, "") : "";
2131
+ return name === "square" || name === "triangle" || name === "star" || name === "cross" || name === "x" ? name : "circle";
2132
+ }
2133
+ function thresholdLegend(key, config, fallback) {
2134
+ if (config.color?.mode && config.color.mode !== "thresholds") return [];
2135
+ const steps = config.thresholds?.steps ?? [];
2136
+ if (steps.length < 2) return [];
2137
+ return steps.map((s, i) => ({
2138
+ key: `${key}/${i}`,
2139
+ name: s.value == null ? `< ${formatValue(steps[i + 1].value, config)}` : `${formatValue(s.value, config)}+`,
2140
+ color: resolveColor(s.color, fallback)
2141
+ }));
2142
+ }
2143
+ var isDataLayer = (type) => type === "markers" || type === "heatmap" || type === "route" || type === "lastPointTracker";
2144
+ var lookupField = (frame) => frame.fields.find((f) => f.name.toLowerCase() === "lookup");
2145
+ function gazetteerPaths(panel, frames) {
2146
+ const paths = /* @__PURE__ */ new Set();
2147
+ for (const layer of panel.options?.layers ?? DEFAULT_LAYERS) {
2148
+ if (!isDataLayer(layer.type)) continue;
2149
+ const mode = layer.location?.mode ?? "auto";
2150
+ if (mode === "lookup") paths.add(layer.location?.gazetteer || DEFAULT_GAZETTEER);
2151
+ else if (mode === "auto" && frames.some(lookupField)) paths.add(DEFAULT_GAZETTEER);
2152
+ }
2153
+ return [...paths];
2154
+ }
2155
+ var LAT_NAMES = ["lat", "latitude"];
2156
+ var LON_NAMES = ["lon", "lng", "long", "longitude"];
2157
+ function fieldByName(frame, name, multiple) {
2158
+ return frame.fields.find((f) => f.name === name) ?? frame.fields.find((f) => fieldDisplayName(f, frame, multiple) === name);
2159
+ }
2160
+ function locate2(frame, location = {}, gazetteers = {}) {
2161
+ const mode = location.mode ?? "auto";
2162
+ const named = (names) => frame.fields.find((f) => names.includes(f.name.toLowerCase()));
2163
+ let lat;
2164
+ let lon;
2165
+ let hash;
2166
+ let lookup;
2167
+ let gazetteer;
2168
+ if (mode === "coords") {
2169
+ lat = location.latitude ? fieldByName(frame, location.latitude, false) : void 0;
2170
+ lon = location.longitude ? fieldByName(frame, location.longitude, false) : void 0;
2171
+ } else if (mode === "geohash") {
2172
+ hash = location.geohash ? fieldByName(frame, location.geohash, false) : named(["geohash"]);
2173
+ } else if (mode === "auto") {
2174
+ lat = named(LAT_NAMES);
2175
+ lon = named(LON_NAMES);
2176
+ if (!lat || !lon) hash = named(["geohash"]);
2177
+ if ((!lat || !lon) && !hash) [lookup, gazetteer] = [lookupField(frame), gazetteers[DEFAULT_GAZETTEER]];
2178
+ } else if (mode === "lookup") {
2179
+ lookup = location.lookup ? fieldByName(frame, location.lookup, false) : lookupField(frame);
2180
+ gazetteer = gazetteers[location.gazetteer || DEFAULT_GAZETTEER];
2181
+ }
2182
+ const rows = [];
2183
+ const xs = [];
2184
+ const ys = [];
2185
+ const add = (i, lo, la) => {
2186
+ if (!Number.isFinite(lo) || !Number.isFinite(la) || Math.abs(la) > 90) return;
2187
+ const [x, y] = project(lo, la);
2188
+ rows.push(i);
2189
+ xs.push(x);
2190
+ ys.push(y);
2191
+ };
2192
+ if (lat && lon) {
2193
+ const n = Math.min(lat.values.length, lon.values.length);
2194
+ for (let i = 0; i < n; i++) if (lat.values[i] != null && lon.values[i] != null) add(i, Number(lon.values[i]), Number(lat.values[i]));
2195
+ } else if (hash) {
2196
+ hash.values.forEach((v, i) => {
2197
+ const p = typeof v === "string" ? decodeGeohash(v) : void 0;
2198
+ if (p) add(i, p.lon, p.lat);
2199
+ });
2200
+ } else if (lookup && gazetteer) {
2201
+ lookup.values.forEach((v, i) => {
2202
+ const p = v == null || v === "" ? void 0 : gazetteer.find(String(v));
2203
+ if (p) add(i, p.lon, p.lat);
2204
+ });
2205
+ } else return void 0;
2206
+ return { rows, xs, ys };
2207
+ }
2208
+ var BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
2209
+ function decodeGeohash(hash) {
2210
+ if (!hash) return void 0;
2211
+ const lat = [-90, 90];
2212
+ const lon = [-180, 180];
2213
+ let even = true;
2214
+ for (const c of hash.toLowerCase()) {
2215
+ const d = BASE32.indexOf(c);
2216
+ if (d < 0) return void 0;
2217
+ for (let bit = 4; bit >= 0; bit--) {
2218
+ const r = even ? lon : lat;
2219
+ const mid = (r[0] + r[1]) / 2;
2220
+ if (d >> bit & 1) r[0] = mid;
2221
+ else r[1] = mid;
2222
+ even = !even;
2223
+ }
2224
+ }
2225
+ return { lon: (lon[0] + lon[1]) / 2, lat: (lat[0] + lat[1]) / 2 };
2226
+ }
2227
+ function cellText(field, v, config) {
2228
+ if (v == null) return "";
2229
+ if (field.type === "number") return formatDisplay(Number(v), config);
2230
+ if (field.type === "time") return new Date(toMillis(v)).toLocaleString();
2231
+ return String(v);
2232
+ }
2233
+ function num(v) {
2234
+ if (v == null) return null;
2235
+ const n = Number(v);
2236
+ return Number.isFinite(n) ? n : null;
2237
+ }
2238
+ function range(values) {
2239
+ let lo = Infinity;
2240
+ let hi = -Infinity;
2241
+ for (const v of values) {
2242
+ if (v == null) continue;
2243
+ lo = Math.min(lo, v);
2244
+ hi = Math.max(hi, v);
2245
+ }
2246
+ return lo === Infinity ? void 0 : [lo, hi];
2247
+ }
2248
+ function screenProjector(view, width, height) {
2249
+ const [cx, cy] = project(view.lon, view.lat);
2250
+ const world = TILE * 2 ** view.zoom;
2251
+ return (x, y) => [(x - cx - Math.round(x - cx)) * world + width / 2, (y - cy) * world + height / 2];
2252
+ }
2253
+ function panView(view, dx, dy) {
2254
+ const [cx, cy] = project(view.lon, view.lat);
2255
+ const world = TILE * 2 ** view.zoom;
2256
+ const x = cx - dx / world;
2257
+ const { lon, lat } = unproject(x - Math.floor(x), clamp(cy - dy / world, 0, 1));
2258
+ return { ...view, lon, lat };
2259
+ }
2260
+ function symbolPath(symbol, x, y, r) {
2261
+ switch (symbol) {
2262
+ case "square":
2263
+ return `M${x - r},${y - r}h${2 * r}v${2 * r}h${-2 * r}Z`;
2264
+ case "triangle":
2265
+ return `M${x},${y - r}L${x + r * 0.866},${y + r / 2}L${x - r * 0.866},${y + r / 2}Z`;
2266
+ case "star": {
2267
+ let d = "";
2268
+ for (let i = 0; i < 10; i++) {
2269
+ const a = -Math.PI / 2 + i * Math.PI / 5;
2270
+ const rr = i % 2 ? r * 0.45 : r;
2271
+ d += `${i ? "L" : "M"}${x + rr * Math.cos(a)},${y + rr * Math.sin(a)}`;
2272
+ }
2273
+ return `${d}Z`;
2274
+ }
2275
+ case "cross":
2276
+ return `M${x - r},${y}h${2 * r}M${x},${y - r}v${2 * r}`;
2277
+ case "x": {
2278
+ const k = r * 0.707;
2279
+ return `M${x - k},${y - k}l${2 * k},${2 * k}M${x - k},${y + k}l${2 * k},${-2 * k}`;
2280
+ }
2281
+ default:
2282
+ return `M${x - r},${y}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0`;
2283
+ }
2284
+ }
2285
+ var HEAT_GRADIENT = ["#0000ff", "#00ffff", "#00ff00", "#ffff00", "#ff0000"];
2286
+ var HEAT_LEVELS = 32;
2287
+ function heatColor(t) {
2288
+ const at = t * (HEAT_GRADIENT.length - 1);
2289
+ const i = Math.min(Math.floor(at), HEAT_GRADIENT.length - 2);
2290
+ const ch = (hex, k) => parseInt(hex.slice(1 + k * 2, 3 + k * 2), 16);
2291
+ const f = at - i;
2292
+ return `#${[0, 1, 2].map((k) => Math.round(ch(HEAT_GRADIENT[i], k) + (ch(HEAT_GRADIENT[i + 1], k) - ch(HEAT_GRADIENT[i], k)) * f).toString(16).padStart(2, "0")).join("")}`;
2293
+ }
2294
+ function heatmapCells(px, py, weights, radius, blur, width, height, cell = 4) {
2295
+ const cols = Math.ceil(width / cell);
2296
+ const rowsN = Math.ceil(height / cell);
2297
+ if (cols <= 0 || rowsN <= 0) return [];
2298
+ const acc = new Float32Array(cols * rowsN);
2299
+ const sigma = blur / 2;
2300
+ const s2 = sigma * sigma + radius * radius / 2;
2301
+ const peak = sigma > 0 ? 1 - Math.exp(-(radius * radius) / (2 * sigma * sigma)) : 1;
2302
+ const reach = 3 * Math.sqrt(s2);
2303
+ for (let i = 0; i < px.length; i++) {
2304
+ const w = clamp(weights[i], 0, 1) * peak;
2305
+ if (w <= 0) continue;
2306
+ const c0 = Math.max(0, Math.floor((px[i] - reach) / cell));
2307
+ const c1 = Math.min(cols - 1, Math.floor((px[i] + reach) / cell));
2308
+ const r0 = Math.max(0, Math.floor((py[i] - reach) / cell));
2309
+ const r1 = Math.min(rowsN - 1, Math.floor((py[i] + reach) / cell));
2310
+ for (let r = r0; r <= r1; r++) {
2311
+ const dy = (r + 0.5) * cell - py[i];
2312
+ for (let c = c0; c <= c1; c++) {
2313
+ const dx = (c + 0.5) * cell - px[i];
2314
+ const a = w * Math.exp(-(dx * dx + dy * dy) / (2 * s2));
2315
+ if (a > 1e-3) acc[r * cols + c] += -Math.log(1 - Math.min(a, 0.999));
2316
+ }
2317
+ }
2318
+ }
2319
+ const paths = Array.from({ length: HEAT_LEVELS }, () => []);
2320
+ for (let r = 0; r < rowsN; r++) {
2321
+ for (let c = 0; c < cols; c++) {
2322
+ const s = acc[r * cols + c];
2323
+ if (!s) continue;
2324
+ const level = Math.round((1 - Math.exp(-s)) * (HEAT_LEVELS - 1));
2325
+ if (level > 0) paths[level].push(`M${c * cell},${r * cell}h${cell}v${cell}h${-cell}Z`);
2326
+ }
2327
+ }
2328
+ return paths.flatMap((parts, level) => {
2329
+ const t = level / (HEAT_LEVELS - 1);
2330
+ return parts.length ? [{ color: heatColor(t), opacity: t, d: parts.join("") }] : [];
2331
+ });
2332
+ }
2333
+
2334
+ // src/ui/panels/GeomapPanel.tsx
2335
+ import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
2336
+ var HIT_PX = 24;
2337
+ var DRAG_PX = 6;
2338
+ var MAX_LABELS = 300;
2339
+ function GeomapPanel({ panel, frames }) {
2340
+ const theme = useDashTheme();
2341
+ const [size, onLayout] = useLayout();
2342
+ const retina = PixelRatio.get() > 1;
2343
+ const { gazetteers, error } = useGazetteers(panel, frames);
2344
+ const layers = useMemo4(() => geomapLayers(panel, frames, theme.scheme, retina, gazetteers), [panel, frames, theme.scheme, retina, gazetteers]);
2345
+ const home = useMemo4(() => initialView(panel, layers, size.width, size.height), [panel, layers, size.width, size.height]);
2346
+ const [moved, setMoved] = useState6(null);
2347
+ const [picked, setPicked] = useState6(null);
2348
+ const links = usePanelLinks(panel);
2349
+ const view = moved ?? home;
2350
+ const [minZoom, maxZoom] = zoomLimits(panel);
2351
+ const zoomTo = (v, zoom) => setMoved({ ...v, zoom: Math.min(maxZoom, Math.max(minZoom, zoom)) });
2352
+ const screen = useMemo4(() => {
2353
+ const at = screenProjector(view, size.width, size.height);
2354
+ return new Map(
2355
+ layers.map((l) => [
2356
+ l.key,
2357
+ l.type === "tiles" ? [] : l.points.map((p) => {
2358
+ const px = [];
2359
+ const py = [];
2360
+ p.xs.forEach((x, i) => {
2361
+ const [sx, sy] = at(x, p.ys[i]);
2362
+ px.push(sx);
2363
+ py.push(sy);
2364
+ });
2365
+ return { px, py };
2366
+ })
2367
+ ])
2368
+ );
2369
+ }, [layers, view, size.width, size.height]);
2370
+ const tooltips = panel.options?.tooltip?.mode !== "none";
2371
+ const pick = (x, y) => {
2372
+ let best = null;
2373
+ let bestD = HIT_PX * HIT_PX;
2374
+ for (const l of layers) {
2375
+ if (l.type === "tiles" || l.type === "heatmap" || !l.tooltip) continue;
2376
+ screen.get(l.key)?.forEach(({ px, py }, group) => {
2377
+ for (let i = 0; i < px.length; i++) {
2378
+ const d = (px[i] - x) ** 2 + (py[i] - y) ** 2;
2379
+ if (d <= bestD) {
2380
+ bestD = d;
2381
+ best = { layer: l, group, index: i, px: px[i], py: py[i] };
2382
+ }
2383
+ }
2384
+ });
2385
+ }
2386
+ return best;
2387
+ };
2388
+ const gesture = useRef2(null);
2389
+ const responder = {
2390
+ onStartShouldSetResponder: () => true,
2391
+ // Keep the gesture while panning instead of handing it to the dashboard's scroll view.
2392
+ onResponderTerminationRequest: () => false,
2393
+ onResponderGrant: (e) => {
2394
+ const t = e.nativeEvent;
2395
+ gesture.current = { x: t.pageX, y: t.pageY, lx: t.locationX, ly: t.locationY, view, moved: false };
2396
+ },
2397
+ onResponderMove: (e) => {
2398
+ const g = gesture.current;
2399
+ if (!g) return;
2400
+ const touches = e.nativeEvent.touches ?? [];
2401
+ if (touches.length >= 2) {
2402
+ const dist = Math.hypot(touches[0].pageX - touches[1].pageX, touches[0].pageY - touches[1].pageY);
2403
+ if (g.dist == null) Object.assign(g, { dist, view, moved: true });
2404
+ else if (dist > 0) zoomTo(g.view, g.view.zoom + Math.log2(dist / g.dist));
2405
+ return;
2406
+ }
2407
+ if (g.dist != null) return;
2408
+ const dx = e.nativeEvent.pageX - g.x;
2409
+ const dy = e.nativeEvent.pageY - g.y;
2410
+ if (!g.moved && Math.hypot(dx, dy) < DRAG_PX) return;
2411
+ g.moved = true;
2412
+ setMoved(panView(g.view, dx, dy));
2413
+ },
2414
+ onResponderRelease: () => {
2415
+ const g = gesture.current;
2416
+ gesture.current = null;
2417
+ if (!g || g.moved || !tooltips) return;
2418
+ const hit = pick(g.lx, g.ly);
2419
+ setPicked(hit && { layer: hit.layer.key, group: hit.group, index: hit.index });
2420
+ },
2421
+ onResponderTerminate: () => {
2422
+ gesture.current = null;
2423
+ }
2424
+ };
2425
+ const shown = picked && resolvePicked(layers, screen, picked);
2426
+ const controls = panel.options?.controls ?? {};
2427
+ const attribution = [...new Set(layers.flatMap((l) => l.type === "tiles" && l.source.attribution ? [l.source.attribution] : []))].join(" ");
2428
+ const legend = layers.flatMap((l) => l.type === "markers" || l.type === "route" ? l.legend : []);
2429
+ const ready = size.width > 0 && size.height > 0;
2430
+ return /* @__PURE__ */ jsxs9(View8, { style: styles9.fill, children: [
2431
+ /* @__PURE__ */ jsxs9(View8, { style: [styles9.fill, styles9.map, { backgroundColor: theme.grid }], onLayout, ...responder, children: [
2432
+ ready && // Nothing inside takes touches, so locationX/Y are always relative to the map.
2433
+ /* @__PURE__ */ jsxs9(View8, { pointerEvents: "none", style: StyleSheet9.absoluteFill, children: [
2434
+ layers.map(
2435
+ (l) => l.type === "tiles" ? /* @__PURE__ */ jsx11(Tiles, { layer: l, view, width: size.width, height: size.height }, l.key) : /* @__PURE__ */ jsx11(DataLayerSvg, { layer: l, screen: screen.get(l.key) ?? [], width: size.width, height: size.height, textColor: theme.text }, l.key)
2436
+ ),
2437
+ shown && /* @__PURE__ */ jsx11(Svg6, { width: size.width, height: size.height, style: StyleSheet9.absoluteFill, children: /* @__PURE__ */ jsx11(
2438
+ Path6,
2439
+ {
2440
+ d: symbolPath("circle", shown.px, shown.py, Math.max(shown.layer.type === "markers" ? shown.radius + 2 : 5, 5)),
2441
+ fill: "none",
2442
+ stroke: theme.text,
2443
+ strokeWidth: 2
2444
+ }
2445
+ ) })
2446
+ ] }),
2447
+ shown && /* @__PURE__ */ jsx11(
2448
+ RowTooltip,
2449
+ {
2450
+ at: { x: shown.px, y: shown.py },
2451
+ size,
2452
+ color: shown.color,
2453
+ title: shown.layer.name,
2454
+ rows: rowTooltipItems(panel, shown.frame, shown.row, frames.length > 1),
2455
+ links: rowLinks(panel, shown.frame, shown.row, frames.length > 1, links.resolve),
2456
+ onOpenLink: (l) => links.openLinks([l])
2457
+ }
2458
+ ),
2459
+ controls.showZoom !== false && /* @__PURE__ */ jsxs9(View8, { style: styles9.zoom, children: [
2460
+ /* @__PURE__ */ jsx11(MapButton, { label: "+", onPress: () => zoomTo(view, Math.round(view.zoom) + 1) }),
2461
+ /* @__PURE__ */ jsx11(MapButton, { label: "\u2212", onPress: () => zoomTo(view, Math.round(view.zoom) - 1) }),
2462
+ moved && /* @__PURE__ */ jsx11(MapButton, { label: "\u27F2", onPress: () => setMoved(null) })
2463
+ ] }),
2464
+ error ? /* @__PURE__ */ jsx11(Text9, { pointerEvents: "none", style: [styles9.error, { color: theme.danger, backgroundColor: theme.surface }], numberOfLines: 2, children: error }) : null,
2465
+ controls.showAttribution !== false && attribution ? /* @__PURE__ */ jsx11(Text9, { pointerEvents: "none", style: [styles9.attribution, { color: theme.textSecondary, backgroundColor: theme.surface }], numberOfLines: 1, children: attribution }) : null
2466
+ ] }),
2467
+ legend.length > 0 && /* @__PURE__ */ jsx11(Legend, { items: legend })
2468
+ ] });
2469
+ }
2470
+ var NONE = {};
2471
+ function useGazetteers(panel, frames) {
2472
+ const { resolve } = useDashboard();
2473
+ const key = gazetteerPaths(panel, frames).join("\n");
2474
+ const [state, setState] = useState6({ key: "", gazetteers: NONE });
2475
+ useEffect3(() => {
2476
+ if (!key) return;
2477
+ let live = true;
2478
+ let ds;
2479
+ try {
2480
+ ds = resolve?.(normalizeRef(panel.datasource));
2481
+ } catch {
2482
+ }
2483
+ const paths = key.split("\n");
2484
+ Promise.allSettled(paths.map((p) => loadGazetteer(p, ds))).then((results) => {
2485
+ if (!live) return;
2486
+ const gazetteers = {};
2487
+ const errors = [];
2488
+ results.forEach((r, i) => {
2489
+ if (r.status === "fulfilled") gazetteers[paths[i]] = r.value;
2490
+ else errors.push(`Couldn't load ${paths[i]}: ${r.reason?.message ?? r.reason}`);
2491
+ });
2492
+ setState({ key, gazetteers, error: errors.join("\n") || void 0 });
2493
+ });
2494
+ return () => {
2495
+ live = false;
2496
+ };
2497
+ }, [key, resolve, panel.datasource]);
2498
+ return state.key === key ? state : { gazetteers: NONE };
2499
+ }
2500
+ function MapButton({ label, onPress }) {
2501
+ const theme = useDashTheme();
2502
+ return /* @__PURE__ */ jsx11(Pressable8, { onPress, hitSlop: 4, style: [styles9.button, { backgroundColor: theme.surface, borderColor: theme.border }], children: /* @__PURE__ */ jsx11(Text9, { style: [styles9.buttonText, { color: theme.text }], children: label }) });
2503
+ }
2504
+ function Tiles({ layer, view, width, height }) {
2505
+ const tiles = visibleTiles(layer.source, view, width, height);
2506
+ return /* @__PURE__ */ jsx11(View8, { style: [StyleSheet9.absoluteFill, { opacity: layer.opacity }], children: tiles.map((t) => (
2507
+ // Half a pixel of overlap hides seams between scaled tiles.
2508
+ /* @__PURE__ */ jsx11(
2509
+ Image,
2510
+ {
2511
+ source: { uri: t.url },
2512
+ fadeDuration: 0,
2513
+ style: { position: "absolute", left: t.left, top: t.top, width: t.size + 0.5, height: t.size + 0.5 }
2514
+ },
2515
+ t.key
2516
+ )
2517
+ )) });
2518
+ }
2519
+ function DataLayerSvg({ layer, screen, width, height, textColor }) {
2520
+ const body = useMemo4(() => {
2521
+ if (layer.type === "heatmap") {
2522
+ const px = screen.flatMap((s) => s.px);
2523
+ const py = screen.flatMap((s) => s.py);
2524
+ const weights = layer.points.flatMap((p) => p.sizes);
2525
+ return heatmapCells(px, py, weights, layer.radius, layer.blur, width, height).map((c) => /* @__PURE__ */ jsx11(Path6, { d: c.d, fill: c.color, fillOpacity: c.opacity }, c.color));
2526
+ }
2527
+ if (layer.type === "route") return routePaths(layer, screen);
2528
+ return markerPaths(layer, screen, width, height, textColor);
2529
+ }, [layer, screen, width, height, textColor]);
2530
+ return /* @__PURE__ */ jsx11(Svg6, { width, height, style: [StyleSheet9.absoluteFill, { opacity: layer.opacity }], children: body });
2531
+ }
2532
+ function markerPaths(layer, screen, width, height, textColor) {
2533
+ const byColor = /* @__PURE__ */ new Map();
2534
+ const labels = [];
2535
+ layer.points.forEach((p, g) => {
2536
+ const { px, py } = screen[g];
2537
+ for (let i = 0; i < px.length; i++) {
2538
+ const r = p.sizes[i];
2539
+ if (px[i] < -r || px[i] > width + r || py[i] < -r || py[i] > height + r) continue;
2540
+ const parts = byColor.get(p.colors[i]) ?? byColor.set(p.colors[i], []).get(p.colors[i]);
2541
+ parts.push(symbolPath(layer.symbol, px[i], py[i], r));
2542
+ const label = p.labels?.[i];
2543
+ if (label && labels.length < MAX_LABELS)
2544
+ labels.push(
2545
+ /* @__PURE__ */ jsx11(
2546
+ SvgText2,
2547
+ {
2548
+ x: px[i] + layer.labelOffset[0],
2549
+ y: py[i] - layer.labelOffset[1] + layer.fontSize / 3,
2550
+ fontSize: layer.fontSize,
2551
+ fill: textColor,
2552
+ textAnchor: "middle",
2553
+ children: label
2554
+ },
2555
+ `${g}/${i}`
2556
+ )
2557
+ );
2558
+ }
2559
+ });
2560
+ const outline = layer.symbol === "cross" || layer.symbol === "x";
2561
+ return [
2562
+ ...[...byColor].map(([color, parts]) => /* @__PURE__ */ jsx11(Path6, { d: parts.join(""), fill: outline ? "none" : color, fillOpacity: layer.fillOpacity, stroke: color, strokeWidth: outline ? 2 : 1 }, color)),
2563
+ ...labels
2564
+ ];
2565
+ }
2566
+ function routePaths(layer, screen) {
2567
+ const byColor = /* @__PURE__ */ new Map();
2568
+ layer.points.forEach((p, g) => {
2569
+ const { px, py } = screen[g];
2570
+ for (let i = 0; i + 1 < px.length; i++) {
2571
+ const parts = byColor.get(p.colors[i]) ?? byColor.set(p.colors[i], []).get(p.colors[i]);
2572
+ parts.push(`M${px[i]},${py[i]}L${px[i + 1]},${py[i + 1]}`);
2573
+ }
2574
+ });
2575
+ return [...byColor].map(([color, parts]) => /* @__PURE__ */ jsx11(Path6, { d: parts.join(""), stroke: color, strokeWidth: layer.lineWidth, strokeLinecap: "round", fill: "none" }, color));
2576
+ }
2577
+ function resolvePicked(layers, screen, picked) {
2578
+ const layer = layers.find((l) => l.key === picked.layer);
2579
+ if (!layer || layer.type !== "markers" && layer.type !== "route") return null;
2580
+ const p = layer.points[picked.group];
2581
+ const s = screen.get(layer.key)?.[picked.group];
2582
+ if (!p || !s || picked.index >= p.rows.length) return null;
2583
+ return {
2584
+ layer,
2585
+ frame: p.frame,
2586
+ row: p.rows[picked.index],
2587
+ color: p.colors[picked.index],
2588
+ radius: p.sizes[picked.index],
2589
+ px: s.px[picked.index],
2590
+ py: s.py[picked.index]
2591
+ };
2592
+ }
2593
+ var styles9 = StyleSheet9.create({
2594
+ fill: { flex: 1 },
2595
+ map: { overflow: "hidden", borderRadius: 4 },
2596
+ zoom: { position: "absolute", top: 6, left: 6, gap: 4 },
2597
+ button: {
2598
+ width: 28,
2599
+ height: 28,
2600
+ borderRadius: 4,
2601
+ borderWidth: StyleSheet9.hairlineWidth,
2602
+ alignItems: "center",
2603
+ justifyContent: "center"
2604
+ },
2605
+ buttonText: { fontSize: 16, fontWeight: "600", lineHeight: 18 },
2606
+ error: { position: "absolute", top: 6, left: 40, right: 6, fontSize: 11, paddingHorizontal: 6, paddingVertical: 3, borderRadius: 4 },
2607
+ attribution: { position: "absolute", right: 0, bottom: 0, fontSize: 9, paddingHorizontal: 4, paddingVertical: 1, opacity: 0.85, maxWidth: "100%" }
2608
+ });
2609
+
2610
+ // src/ui/panels/OtherPanels.tsx
2611
+ import { useMemo as useMemo5, useState as useState7 } from "react";
2612
+ import { Pressable as Pressable9, ScrollView as ScrollView4, StyleSheet as StyleSheet10, Text as Text10, View as View9 } from "react-native";
2613
+ import Svg7, { Path as Path7 } from "react-native-svg";
2614
+
2615
+ // src/ui/table.ts
2616
+ var DEFAULT_WIDTH = 120;
2617
+ function cellType(config) {
2618
+ const custom = config.custom ?? {};
2619
+ const type = custom.cellOptions?.type ?? custom.displayMode;
2620
+ if (type === "color-text" || type === "color-background" || type === "gauge") return type;
2621
+ if (type === "color-background-solid") return "color-background";
2622
+ if (type === "gradient-gauge" || type === "lcd-gauge" || type === "basic") return "gauge";
2623
+ return "auto";
2624
+ }
2625
+ function tableColumns(panel, frame, multipleFrames = false) {
2626
+ return frame.fields.flatMap((field, i) => {
2627
+ const raw = fieldDisplayName(field, frame, multipleFrames);
2628
+ const config = resolveFieldConfig(panel, field, frame, raw);
2629
+ const custom = config.custom ?? {};
2630
+ if (custom.hidden || custom.hideFrom?.viz) return [];
2631
+ const numeric = field.type === "number";
2632
+ const align = custom.align === "left" || custom.align === "center" || custom.align === "right" ? custom.align : numeric ? "right" : "left";
2633
+ const type = cellType(config);
2634
+ return [
2635
+ {
2636
+ key: `${i}/${field.name}`,
2637
+ field,
2638
+ name: config.displayName ?? raw,
2639
+ config,
2640
+ width: Math.max(Number(custom.width) || DEFAULT_WIDTH, Number(custom.minWidth) || 0),
2641
+ align,
2642
+ cellType: type,
2643
+ applyToRow: type === "color-background" && !!custom.cellOptions?.applyToRow,
2644
+ wrap: !!custom.cellOptions?.wrapText,
2645
+ extent: numeric ? extentOf(field.values) : void 0,
2646
+ reducers: footerReducers(panel, config, [field.name, config.displayName ?? raw])
2647
+ }
2648
+ ];
2649
+ });
2650
+ }
2651
+ function footerReducers(panel, config, names) {
2652
+ const own = config.custom?.footer?.reducers;
2653
+ if (own?.length) return own;
2654
+ const legacy = panel.options?.footer;
2655
+ if (!legacy?.show) return [];
2656
+ const reducer = legacy.reducer?.length ? legacy.reducer : ["sum"];
2657
+ if (legacy.countRows && reducer[0] === "count") return ["countAll"];
2658
+ const fields = Array.isArray(legacy.fields) ? legacy.fields : legacy.fields ? [legacy.fields] : [];
2659
+ return !fields.length || names.some((n) => fields.includes(n)) ? reducer : [];
2660
+ }
2661
+ function tableFooter(columns) {
2662
+ if (!columns.some((c) => c.reducers.length)) return null;
2663
+ let counted = false;
2664
+ return columns.map((c) => {
2665
+ const reducers = c.reducers.filter((r) => r !== "countAll" || !counted);
2666
+ const lines = reducers.flatMap((r) => {
2667
+ if (r === "countAll") {
2668
+ counted = true;
2669
+ return [{ label: "Count", text: String(c.field.values.length) }];
2670
+ }
2671
+ if (!isReducer(r)) return [];
2672
+ const label = REDUCER_LABELS[r];
2673
+ if (r === "count") return [{ label, text: String(c.field.values.length) }];
2674
+ if (c.field.type !== "number") {
2675
+ if (r === "distinctCount") return [{ label, text: String(new Set(c.field.values.filter((v) => v != null)).size) }];
2676
+ return [];
2677
+ }
2678
+ const value = reduce(c.field.values.map((v) => v == null ? null : Number(v)), r);
2679
+ const counts = r === "distinctCount" || r === "changeCount";
2680
+ return [{ label, text: counts ? String(value ?? 0) : formatValue(value, c.config) }];
2681
+ });
2682
+ return lines.length === 1 && lines[0].label !== "Count" ? [{ text: lines[0].text }] : lines;
2683
+ });
2684
+ }
2685
+ function extentOf(values) {
2686
+ let lo = Infinity;
2687
+ let hi = -Infinity;
2688
+ for (const v of values) {
2689
+ if (v == null) continue;
2690
+ const n = Number(v);
2691
+ if (!Number.isFinite(n)) continue;
2692
+ lo = Math.min(lo, n);
2693
+ hi = Math.max(hi, n);
2694
+ }
2695
+ return lo === Infinity ? void 0 : [lo, hi];
2696
+ }
2697
+ function cellDisplay(col, raw, fallbackColor) {
2698
+ const { config, field } = col;
2699
+ const mapped = mappedResult(raw, config);
2700
+ const num4 = field.type === "number" && raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null;
2701
+ const text = mapped?.text ?? (raw == null ? config.noValue ?? "" : field.type === "number" ? formatValue(num4, config) : field.type === "time" ? new Date(toMillis(raw)).toLocaleString() : String(raw));
2702
+ if (col.cellType === "auto") return { text };
2703
+ const mode = config.color?.mode;
2704
+ const named = mapped?.color ?? (mode === "fixed" ? config.color?.fixedColor : (!mode || mode === "thresholds") && num4 != null ? thresholdStep(num4, config)?.color : void 0);
2705
+ const color = named === "text" ? void 0 : mapped?.color ? resolveColor(mapped.color, fallbackColor) : num4 == null ? void 0 : valueColor(num4, config, fallbackColor, col.extent);
2706
+ if (col.cellType === "color-text") return { text, color };
2707
+ if (col.cellType === "color-background") return { text, background: color };
2708
+ const min = config.min ?? Math.min(0, col.extent?.[0] ?? 0);
2709
+ const max = config.max ?? col.extent?.[1] ?? 1;
2710
+ const gauge = num4 == null ? void 0 : Math.min(1, Math.max(0, (num4 - min) / (max - min || 1)));
2711
+ return { text, gauge, gaugeColor: color };
2712
+ }
2713
+ function contrastText(background, fallback) {
2714
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})([0-9a-f]{2})?$/i.exec(background);
2715
+ if (!m) return fallback;
2716
+ const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
2717
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
2718
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
2719
+ return lum > 0.55 ? "#111111" : "#ffffff";
2720
+ }
2721
+ function initialSort(panel, columns) {
2722
+ const first = panel.options?.sortBy?.[0];
2723
+ const col = first?.displayName != null ? columns.find((c) => c.name === first.displayName || c.field.name === first.displayName) : void 0;
2724
+ return col ? { key: col.key, desc: !!first.desc } : null;
2725
+ }
2726
+ function nextSort(current, key) {
2727
+ if (current?.key !== key) return { key, desc: false };
2728
+ return current.desc ? null : { key, desc: true };
2729
+ }
2730
+ function sortedRows(columns, length, sort) {
2731
+ const rows = Array.from({ length }, (_, i) => i);
2732
+ const col = sort && columns.find((c) => c.key === sort.key);
2733
+ if (!col) return rows;
2734
+ const { field } = col;
2735
+ const dir = sort.desc ? -1 : 1;
2736
+ const key = (v) => field.type === "time" ? toMillis(v) : field.type === "number" || field.type === "boolean" ? Number(v) : v;
2737
+ const empty = (v) => v == null || v === "" || typeof v === "number" && Number.isNaN(v);
2738
+ return rows.sort((a, b) => {
2739
+ const va = field.values[a];
2740
+ const vb = field.values[b];
2741
+ if (empty(va) || empty(vb)) return empty(va) === empty(vb) ? a - b : empty(va) ? 1 : -1;
2742
+ const ka = key(va);
2743
+ const kb = key(vb);
2744
+ const cmp = typeof ka === "number" && typeof kb === "number" ? ka - kb : compareText(String(ka), String(kb));
2745
+ return cmp * dir || a - b;
2746
+ });
2747
+ }
2748
+ var compareText = typeof Intl !== "undefined" && typeof Intl.Collator === "function" ? new Intl.Collator(void 0, { numeric: true, sensitivity: "base" }).compare : (a, b) => a < b ? -1 : a > b ? 1 : 0;
2749
+
2750
+ // src/ui/panels/OtherPanels.tsx
2751
+ import { jsx as jsx12, jsxs as jsxs10 } from "react/jsx-runtime";
2752
+ function PieChartPanel({ panel, frames }) {
2753
+ const theme = useDashTheme();
2754
+ const [size, onLayout] = useLayout();
2755
+ const values = useMemo5(
2756
+ () => reducedValues(panel, frames, theme.scheme).filter((v) => (v.value ?? 0) > 0),
2757
+ [panel, frames, theme.scheme]
2758
+ );
2759
+ if (!values.length) return /* @__PURE__ */ jsx12(NoData, {});
2760
+ const total = values.reduce((a, v) => a + (v.value ?? 0), 0);
2761
+ const r = Math.min(size.width, size.height) / 2 - 2;
2762
+ const inner = panel.options?.pieType === "pie" ? 0 : r * 0.62;
2763
+ const cx = size.width / 2;
2764
+ const cy = size.height / 2;
2765
+ const gap = values.length > 1 ? 0.02 : 0;
2766
+ const slices = [];
2767
+ let angle = -Math.PI / 2;
2768
+ for (const v of values) {
2769
+ const sweep = (v.value ?? 0) / total * Math.PI * 2;
2770
+ slices.push({ key: v.key, d: donutSlice(cx, cy, r, inner, angle + gap / 2, angle + sweep - gap / 2), color: v.color });
2771
+ angle += sweep;
2772
+ }
2773
+ return /* @__PURE__ */ jsxs10(View9, { style: styles10.fill, children: [
2774
+ /* @__PURE__ */ jsx12(View9, { style: styles10.fill, onLayout, children: r > 0 && /* @__PURE__ */ jsx12(Svg7, { width: size.width, height: size.height, children: slices.map((s) => /* @__PURE__ */ jsx12(Path7, { d: s.d, fill: s.color }, s.key)) }) }),
2775
+ /* @__PURE__ */ jsx12(
2776
+ Legend,
2777
+ {
2778
+ items: values.map((v) => ({
2779
+ key: v.key,
2780
+ name: v.name,
2781
+ color: v.color,
2782
+ value: `${v.text} (${Math.round((v.value ?? 0) / total * 100)}%)`
2783
+ }))
2784
+ }
2785
+ )
2786
+ ] });
2787
+ }
2788
+ function donutSlice(cx, cy, r, inner, a0, a1) {
2789
+ const large = a1 - a0 > Math.PI ? 1 : 0;
2790
+ const p = (rad, a) => `${cx + rad * Math.cos(a)},${cy + rad * Math.sin(a)}`;
2791
+ if (a1 - a0 >= Math.PI * 2 - 1e-3) a1 = a0 + Math.PI * 2 - 1e-3;
2792
+ if (inner <= 0) return `M${cx},${cy}L${p(r, a0)}A${r},${r} 0 ${large} 1 ${p(r, a1)}Z`;
2793
+ return `M${p(r, a0)}A${r},${r} 0 ${large} 1 ${p(r, a1)}L${p(inner, a1)}A${inner},${inner} 0 ${large} 0 ${p(inner, a0)}Z`;
2794
+ }
2795
+ function TablePanel({ panel, frames }) {
2796
+ const theme = useDashTheme();
2797
+ const { resolve, openLinks } = usePanelLinks(panel);
2798
+ const frame = frames[0];
2799
+ const columns = useMemo5(() => frame ? tableColumns(panel, frame, frames.length > 1) : [], [panel, frame, frames.length]);
2800
+ const [tapped, setSort] = useState7();
2801
+ const sort = tapped === void 0 ? initialSort(panel, columns) : tapped;
2802
+ const order = useMemo5(() => sortedRows(columns, frame ? frameLength(frame) : 0, sort), [columns, frame, sort]);
2803
+ if (!frame || !frameLength(frame)) return /* @__PURE__ */ jsx12(NoData, {});
2804
+ const shown = order.slice(0, 500);
2805
+ const rowColumn = columns.find((c) => c.applyToRow);
2806
+ const footer = tableFooter(columns);
2807
+ return /* @__PURE__ */ jsx12(ScrollView4, { horizontal: true, children: /* @__PURE__ */ jsxs10(View9, { style: styles10.fill, children: [
2808
+ /* @__PURE__ */ jsxs10(ScrollView4, { nestedScrollEnabled: true, style: styles10.fill, children: [
2809
+ /* @__PURE__ */ jsx12(View9, { style: [styles10.tr, { borderBottomColor: theme.border }], children: columns.map((c) => {
2810
+ const active = sort?.key === c.key;
2811
+ return /* @__PURE__ */ jsx12(
2812
+ Pressable9,
2813
+ {
2814
+ onPress: () => setSort(nextSort(sort, c.key)),
2815
+ accessibilityRole: "button",
2816
+ accessibilityLabel: `Sort by ${c.name}`,
2817
+ accessibilityState: { selected: active },
2818
+ style: { width: c.width },
2819
+ children: /* @__PURE__ */ jsxs10(Text10, { style: [styles10.th, { color: active ? theme.text : theme.textSecondary, textAlign: c.align }], numberOfLines: 2, children: [
2820
+ c.name,
2821
+ active ? sort.desc ? " \u2193" : " \u2191" : ""
2822
+ ] })
2823
+ },
2824
+ c.key
2825
+ );
2826
+ }) }),
2827
+ shown.map((i) => {
2828
+ const rowBg = rowColumn ? cellDisplay(rowColumn, rowColumn.field.values[i], theme.accent).background : void 0;
2829
+ return /* @__PURE__ */ jsx12(View9, { style: [styles10.tr, { borderBottomColor: theme.grid }, rowBg ? { backgroundColor: rowBg } : null], children: columns.map((c) => {
2830
+ const d = cellDisplay(c, c.field.values[i], theme.accent);
2831
+ const bg = d.background ?? rowBg;
2832
+ const linked = !!c.config.links?.length;
2833
+ const color = d.color ?? (bg ? contrastText(bg, theme.text) : linked ? theme.accent : theme.text);
2834
+ const cellStyle = [styles10.td, { width: c.width }, d.background ? { backgroundColor: d.background } : null];
2835
+ return /* @__PURE__ */ jsxs10(
2836
+ Pressable9,
2837
+ {
2838
+ disabled: !linked,
2839
+ onPress: () => openLinks(
2840
+ resolve(c.config.links, { frame, row: i, field: c.field, fieldName: c.name, value: c.field.values[i], text: d.text }),
2841
+ `${c.name}: ${d.text}`
2842
+ ),
2843
+ accessibilityRole: linked ? "link" : void 0,
2844
+ style: ({ pressed }) => [cellStyle, pressed && { opacity: 0.6 }],
2845
+ children: [
2846
+ d.gauge != null && /* @__PURE__ */ jsx12(View9, { style: [styles10.gaugeTrack, { backgroundColor: theme.grid }], children: /* @__PURE__ */ jsx12(View9, { style: [styles10.gaugeFill, { width: `${d.gauge * 100}%`, backgroundColor: d.gaugeColor ?? theme.accent }] }) }),
2847
+ /* @__PURE__ */ jsx12(Text10, { style: [styles10.cellText, { color, textAlign: c.align }, c.field.type === "number" && styles10.num], numberOfLines: c.wrap ? void 0 : 1, children: d.text })
2848
+ ]
2849
+ },
2850
+ c.key
2851
+ );
2852
+ }) }, i);
2853
+ })
2854
+ ] }),
2855
+ footer && /* @__PURE__ */ jsx12(View9, { style: [styles10.tr, styles10.footer, { borderTopColor: theme.border }], children: columns.map((c, ci) => /* @__PURE__ */ jsx12(View9, { style: [styles10.td, { width: c.width }], children: footer[ci].map((line, li) => /* @__PURE__ */ jsxs10(Text10, { style: [styles10.cellText, styles10.footerText, { color: theme.text, textAlign: c.align }], numberOfLines: 1, children: [
2856
+ line.label ? /* @__PURE__ */ jsx12(Text10, { style: { color: theme.textMuted, fontWeight: "400" }, children: `${line.label} ` }) : null,
2857
+ line.text
2858
+ ] }, li)) }, c.key)) })
2859
+ ] }) });
2860
+ }
2861
+ function TextPanel({ panel }) {
2862
+ const theme = useDashTheme();
2863
+ const raw = panel.options?.content;
2864
+ const content = typeof raw === "string" ? raw : "";
2865
+ const text = panel.options?.mode === "html" ? content.replace(/<[^>]+>/g, "") : content;
2866
+ return /* @__PURE__ */ jsx12(ScrollView4, { children: text.split(/\n{2,}/).map((block, i) => {
2867
+ const heading = /^#{1,6}\s+/.test(block);
2868
+ return /* @__PURE__ */ jsx12(Text10, { style: [styles10.para, { color: heading ? theme.text : theme.textSecondary }, heading && styles10.heading], children: block.replace(/^#{1,6}\s+/, "").replace(/\*\*(.+?)\*\*/g, "$1").replace(/\[(.+?)\]\(.+?\)/g, "$1") }, i);
2869
+ }) });
2870
+ }
2871
+ function BarChartPanel({ panel, frames, width }) {
2872
+ const theme = useDashTheme();
2873
+ const [plot, onPlotLayout] = useLayout();
2874
+ const values = useMemo5(() => reducedValues(panel, frames, theme.scheme), [panel, frames, theme.scheme]);
2875
+ const frame = frames[0];
2876
+ const category = frame && barCategory(panel, frame);
2877
+ if (!frame || !values.length) return /* @__PURE__ */ jsx12(NoData, {});
2878
+ const xField = panel.options?.xField;
2879
+ if (xField && !category) return /* @__PURE__ */ jsx12(NoData, { message: `No field named \u201C${String(xField)}\u201D` });
2880
+ const allNumeric = frame.fields.filter((f) => f.type === "number");
2881
+ const at = (f) => values[allNumeric.indexOf(f)];
2882
+ const numeric = category ? allNumeric.filter((f) => f !== category) : [];
2883
+ if (category && !numeric.length) return /* @__PURE__ */ jsx12(NoData, { message: `No number fields to draw besides \u201C${category.name}\u201D` });
2884
+ const fields = category ? numeric.map((f) => ({ key: f.name, name: at(f)?.name ?? f.name, color: at(f)?.color ?? theme.accent, config: at(f)?.config ?? {}, values: f.values.map(num2) })) : [{ key: "reduced", name: "", color: theme.accent, config: values[0].config, values: values.map((v) => v.value) }];
2885
+ const labels = category ? categoryLabels(category) : values.map((v) => v.name);
2886
+ const colorAt = (fi, i) => category ? fields[fi].color : values[i].color;
2887
+ const axes = barAxes(
2888
+ fields.map((f) => f.config),
2889
+ fields.map((f) => f.values),
2890
+ plot.height < 100 ? 2 : 4
2891
+ );
2892
+ const axisOf = (fi) => axes.find((a) => a.fields.includes(fi));
2893
+ const left = axes.find((a) => a.side === "left" && a.show);
2894
+ const right = axes.find((a) => a.side === "right" && a.show);
2895
+ const gridAxis = left ?? right;
2896
+ const plotW = width - (left ? AXIS_W : 0) - (right ? AXIS_W : 0);
2897
+ const every = Math.max(1, Math.ceil(labels.length / Math.max(1, Math.floor(plotW / 44))));
2898
+ const axisColumn = (axis) => /* @__PURE__ */ jsx12(View9, { style: [styles10.axis, axis.side === "left" ? styles10.axisLeft : styles10.axisRight], children: plot.height > 0 && axis.ticks.map((t) => /* @__PURE__ */ jsx12(
2899
+ Text10,
2900
+ {
2901
+ style: [styles10.tick, { color: theme.textMuted, top: plot.height * (1 - barFraction(axis, t)) - 7 }, axis.side === "left" ? styles10.tickLeft : styles10.tickRight],
2902
+ numberOfLines: 1,
2903
+ children: formatValue(t, { ...axis.config, decimals: tickDecimals(axis.ticks) })
2904
+ },
2905
+ t
2906
+ )) });
2907
+ return /* @__PURE__ */ jsxs10(View9, { style: styles10.fill, children: [
2908
+ (left?.label || right?.label) && /* @__PURE__ */ jsxs10(View9, { style: styles10.axisLabels, children: [
2909
+ /* @__PURE__ */ jsx12(Text10, { style: [styles10.axisLabel, { color: theme.textMuted }], children: left?.label ?? "" }),
2910
+ /* @__PURE__ */ jsx12(Text10, { style: [styles10.axisLabel, { color: theme.textMuted }], children: right?.label ?? "" })
2911
+ ] }),
2912
+ /* @__PURE__ */ jsxs10(View9, { style: styles10.barRow, children: [
2913
+ left && axisColumn(left),
2914
+ /* @__PURE__ */ jsxs10(View9, { style: styles10.fill, onLayout: onPlotLayout, children: [
2915
+ gridAxis && plot.height > 0 && gridAxis.ticks.map((t) => /* @__PURE__ */ jsx12(View9, { style: [styles10.gridLine, { backgroundColor: theme.grid, top: plot.height * (1 - barFraction(gridAxis, t)) }] }, t)),
2916
+ /* @__PURE__ */ jsx12(View9, { style: styles10.barchart, children: labels.map((_, i) => /* @__PURE__ */ jsx12(View9, { style: styles10.barStack, children: fields.map((f, fi) => {
2917
+ const axis = axisOf(fi);
2918
+ const base = barFraction(axis, Math.min(Math.max(0, axis.bottom), axis.top));
2919
+ const end = barFraction(axis, f.values[i] ?? 0);
2920
+ return /* @__PURE__ */ jsx12(View9, { style: styles10.barSlot, children: /* @__PURE__ */ jsx12(
2921
+ View9,
2922
+ {
2923
+ style: [
2924
+ styles10.bar,
2925
+ end < base && styles10.barDown,
2926
+ { bottom: `${Math.min(base, end) * 100}%`, height: `${Math.abs(end - base) * 100}%`, backgroundColor: colorAt(fi, i) }
2927
+ ]
2928
+ }
2929
+ ) }, fi);
2930
+ }) }, i)) })
2931
+ ] }),
2932
+ right && axisColumn(right)
2933
+ ] }),
2934
+ /* @__PURE__ */ jsx12(View9, { style: [styles10.barLabels, { marginLeft: left ? AXIS_W : 0, marginRight: right ? AXIS_W : 0 }], children: labels.map((label, i) => /* @__PURE__ */ jsx12(Text10, { style: [styles10.barLabel, { color: theme.textMuted }], numberOfLines: 1, children: i % every === 0 ? label : " " }, i)) }),
2935
+ category && fields.length > 1 && /* @__PURE__ */ jsx12(Legend, { items: fields })
2936
+ ] });
2937
+ }
2938
+ var AXIS_W = 40;
2939
+ function num2(v) {
2940
+ if (v == null) return null;
2941
+ const n = Number(v);
2942
+ return Number.isFinite(n) ? n : null;
2943
+ }
2944
+ function UnsupportedPanel({ panel }) {
2945
+ return /* @__PURE__ */ jsx12(NoData, { message: `"${panel.type}" panels aren't supported yet` });
2946
+ }
2947
+ var styles10 = StyleSheet10.create({
2948
+ fill: { flex: 1 },
2949
+ tr: { flexDirection: "row", borderBottomWidth: StyleSheet10.hairlineWidth },
2950
+ th: { paddingVertical: 6, paddingHorizontal: 6, fontSize: 12, fontWeight: "600" },
2951
+ td: { paddingVertical: 6, paddingHorizontal: 6, justifyContent: "center" },
2952
+ cellText: { fontSize: 12 },
2953
+ footer: { borderBottomWidth: 0, borderTopWidth: StyleSheet10.hairlineWidth },
2954
+ footerText: { fontWeight: "600", fontVariant: ["tabular-nums"] },
2955
+ gaugeTrack: { position: "absolute", left: 6, right: 6, bottom: 3, height: 3, borderRadius: 2, overflow: "hidden" },
2956
+ gaugeFill: { height: "100%", borderRadius: 2 },
2957
+ num: { textAlign: "right", fontVariant: ["tabular-nums"] },
2958
+ para: { fontSize: 14, lineHeight: 20, marginBottom: 8 },
2959
+ heading: { fontSize: 16, fontWeight: "600" },
2960
+ // Room for half of the top tick label, which is centred on the plot's top edge.
2961
+ barRow: { flex: 1, flexDirection: "row", paddingTop: 7 },
2962
+ barchart: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0, flexDirection: "row", alignItems: "flex-end", gap: 2 },
2963
+ barStack: { flex: 1, height: "100%", flexDirection: "row", alignItems: "flex-end", justifyContent: "center", gap: 2 },
2964
+ barSlot: { flex: 1, maxWidth: 24, height: "100%" },
2965
+ bar: { position: "absolute", left: 0, right: 0, borderTopLeftRadius: 4, borderTopRightRadius: 4 },
2966
+ barDown: { borderTopLeftRadius: 0, borderTopRightRadius: 0, borderBottomLeftRadius: 4, borderBottomRightRadius: 4 },
2967
+ barLabels: { flexDirection: "row", gap: 2 },
2968
+ barLabel: { flex: 1, fontSize: 10, marginTop: 4, textAlign: "center" },
2969
+ gridLine: { position: "absolute", left: 0, right: 0, height: StyleSheet10.hairlineWidth },
2970
+ axis: { width: AXIS_W },
2971
+ axisLeft: { paddingRight: 6 },
2972
+ axisRight: { paddingLeft: 6 },
2973
+ tick: { position: "absolute", fontSize: 10, lineHeight: 14 },
2974
+ tickLeft: { right: 6, textAlign: "right" },
2975
+ tickRight: { left: 6 },
2976
+ axisLabels: { flexDirection: "row", justifyContent: "space-between", marginBottom: 2 },
2977
+ axisLabel: { fontSize: 10 }
2978
+ });
2979
+
2980
+ // src/ui/panels/TimeSeriesPanel.tsx
2981
+ import { useId, useMemo as useMemo6, useRef as useRef3, useState as useState8 } from "react";
2982
+ import { Pressable as Pressable10, StyleSheet as StyleSheet11, Text as Text11, View as View10 } from "react-native";
2983
+ import Svg8, { Circle, ClipPath, Defs, G, Line, Path as Path8, Rect, Text as SvgText3 } from "react-native-svg";
2984
+ import { jsx as jsx13, jsxs as jsxs11 } from "react/jsx-runtime";
2985
+ var BASE_PAD = { top: 8, right: 8, bottom: 20, left: 44 };
2986
+ var BAR_MAX = 24;
2987
+ function TimeSeriesPanel({ panel, frames }) {
2988
+ const theme = useDashTheme();
2989
+ const { range: range3, setRawRange, pinned, setPinned } = useDashboard();
2990
+ const { resolve, openLinks } = usePanelLinks(panel);
2991
+ const [size, onLayout] = useLayout();
2992
+ const [hoverX, setHoverX] = useState8(null);
2993
+ const [preview, setPreview] = useState8(null);
2994
+ const [xZoom, setXZoom] = useState8(null);
2995
+ const pinch = useRef3(null);
2996
+ const originX = useRef3(0);
2997
+ const id = useId();
2998
+ const clipId = `plot${id.replace(/[^a-zA-Z0-9]/g, "")}`;
2999
+ const [touching, setTouching] = useState8(false);
3000
+ const numericX = panel.type === "trend";
3001
+ const { series, xConfig } = useMemo6(
3002
+ () => numericX ? styledXYSeries(panel, frames, theme.scheme) : { series: styledSeries(panel, frames, theme.scheme), xConfig: {} },
3003
+ [numericX, panel, frames, theme.scheme]
3004
+ );
3005
+ if (!series.length || series.every((s) => s.values.every((v) => v == null))) return /* @__PURE__ */ jsx13(NoData, {});
3006
+ const style = (s) => s.config.custom?.drawStyle ?? (panel.type === "graph" && panel.bars ? "bars" : "line");
3007
+ const anyBars = series.some((s) => style(s) === "bars");
3008
+ const anyFill = series.some((s) => (s.config.custom?.fillOpacity ?? 0) > 0);
3009
+ const yTitle = series.map((s) => axisTitle(s.config)).find(Boolean);
3010
+ const xTitle = numericX ? axisTitle(xConfig) : void 0;
3011
+ const PAD = {
3012
+ ...BASE_PAD,
3013
+ left: BASE_PAD.left + (yTitle ? AXIS_TITLE_SPACE : 0),
3014
+ bottom: BASE_PAD.bottom + (xTitle ? AXIS_TITLE_SPACE : 0)
3015
+ };
3016
+ const plotW = Math.max(0, size.width - PAD.left - PAD.right);
3017
+ const plotH = Math.max(0, size.height - PAD.top - PAD.bottom);
3018
+ const [dMin, dMax] = yDomain(series, anyBars || anyFill);
3019
+ const ticks = niceTicks(dMin, dMax, plotH < 100 ? 2 : 4);
3020
+ const yMin = series[0].config.min ?? ticks[0];
3021
+ const yMax = series[0].config.max ?? ticks[ticks.length - 1];
3022
+ const extent = numericX ? xExtent(series) : null;
3023
+ const shown = preview ?? (numericX ? xZoom : null);
3024
+ const [xFrom, xTo] = shown ? [shown.from, shown.to] : extent ?? [range3.from, range3.to];
3025
+ const x = linearScale(xFrom, xTo, PAD.left, PAD.left + plotW);
3026
+ const y = linearScale(yMin, yMax, PAD.top + plotH, PAD.top);
3027
+ const span = xTo - xFrom;
3028
+ const xTicks = numericX ? numberTicks(xFrom, xTo, plotW) : timeTicks(xFrom, xTo, plotW);
3029
+ const xLabel = (t) => numericX ? formatValue(t, { ...xConfig, decimals: tickDecimals(xTicks) }) : formatTimeTick(t, span);
3030
+ const unitConfig = series[0].config;
3031
+ const barSeries = series.filter((s) => style(s) === "bars");
3032
+ const pointsCount = Math.max(...series.map((s) => s.times.length));
3033
+ const slot = plotW / Math.max(pointsCount, 1);
3034
+ const groupW = Math.min(slot * 0.8, BAR_MAX * barSeries.length);
3035
+ const barW = Math.max(2, groupW / Math.max(barSeries.length, 1) - (barSeries.length > 1 ? 2 : 0));
3036
+ const canPinch = plotW > 0;
3037
+ const twoFingers = (e) => canPinch && (e.nativeEvent.touches?.length ?? 0) >= 2;
3038
+ const onPinchMove = (e) => {
3039
+ const touches = e.nativeEvent.touches ?? [];
3040
+ if (touches.length < 2) return;
3041
+ const [a, b] = touches;
3042
+ const dist = Math.max(Math.hypot(a.pageX - b.pageX, a.pageY - b.pageY), 1);
3043
+ const frac = ((a.pageX + b.pageX) / 2 - originX.current - PAD.left) / plotW;
3044
+ if (!pinch.current) pinch.current = { start: { from: xFrom, to: xTo }, dist, frac };
3045
+ const p = pinch.current;
3046
+ const limits = extent ? { minSpan: (extent[1] - extent[0]) / 1e3, maxSpan: extent[1] - extent[0], minFrom: extent[0], maxTo: extent[1] } : { maxTo: Math.max(Date.now(), p.start.to) };
3047
+ setPreview(zoomRange(p.start, dist / p.dist, p.frac, frac, limits));
3048
+ };
3049
+ const onPinchEnd = (commit) => {
3050
+ if (commit && pinch.current && preview) {
3051
+ if (!extent) setRawRange({ from: formatLocalDateTime(preview.from), to: formatLocalDateTime(preview.to) });
3052
+ else setXZoom(preview.to - preview.from >= extent[1] - extent[0] ? null : preview);
3053
+ }
3054
+ pinch.current = null;
3055
+ setPreview(null);
3056
+ };
3057
+ const hover = hoverX == null || !touching && pinned !== id ? null : nearest(series, xFrom + (hoverX - PAD.left) / (plotW || 1) * span);
3058
+ const hoverLinks = hover ? mergeLinks(
3059
+ hover.rows.flatMap(
3060
+ (r) => r.value == null || !r.series.config.links?.length ? [] : [{ name: r.name, links: resolve(r.series.config.links, linkData(r, frames, numericX ? String(panel.options?.xField ?? "") : void 0)) }]
3061
+ )
3062
+ ) : [];
3063
+ const isPinned = !!hover && pinned === id;
3064
+ return /* @__PURE__ */ jsxs11(View10, { style: styles11.fill, children: [
3065
+ /* @__PURE__ */ jsx13(
3066
+ View10,
3067
+ {
3068
+ style: styles11.fill,
3069
+ onStartShouldSetResponderCapture: twoFingers,
3070
+ onMoveShouldSetResponderCapture: twoFingers,
3071
+ onResponderTerminationRequest: () => false,
3072
+ onResponderGrant: (e) => {
3073
+ originX.current = e.nativeEvent.pageX - e.nativeEvent.locationX;
3074
+ setHoverX(null);
3075
+ return true;
3076
+ },
3077
+ onResponderMove: onPinchMove,
3078
+ onResponderRelease: () => onPinchEnd(true),
3079
+ onResponderTerminate: () => onPinchEnd(false),
3080
+ children: /* @__PURE__ */ jsxs11(
3081
+ View10,
3082
+ {
3083
+ style: styles11.fill,
3084
+ onLayout,
3085
+ onStartShouldSetResponder: () => true,
3086
+ onResponderGrant: (e) => {
3087
+ originX.current = e.nativeEvent.pageX - e.nativeEvent.locationX;
3088
+ setTouching(true);
3089
+ setPinned(null);
3090
+ setHoverX(e.nativeEvent.locationX);
3091
+ },
3092
+ onResponderMove: (e) => setHoverX(e.nativeEvent.locationX),
3093
+ onResponderRelease: () => {
3094
+ setTouching(false);
3095
+ if (hoverLinks.length) setPinned(id);
3096
+ else setHoverX(null);
3097
+ },
3098
+ onResponderTerminate: () => {
3099
+ setTouching(false);
3100
+ setHoverX(null);
3101
+ },
3102
+ children: [
3103
+ size.width > 0 && /* @__PURE__ */ jsxs11(Svg8, { width: size.width, height: size.height, children: [
3104
+ ticks.map((t) => /* @__PURE__ */ jsxs11(G, { children: [
3105
+ /* @__PURE__ */ jsx13(Line, { x1: PAD.left, x2: PAD.left + plotW, y1: y(t), y2: y(t), stroke: theme.grid, strokeWidth: 1 }),
3106
+ /* @__PURE__ */ jsx13(SvgText3, { x: PAD.left - 6, y: y(t) + 3, fontSize: 10, fill: theme.textMuted, textAnchor: "end", children: formatValue(t, { ...unitConfig, decimals: tickDecimals(ticks) }) })
3107
+ ] }, t)),
3108
+ xTicks.map((t) => /* @__PURE__ */ jsx13(
3109
+ SvgText3,
3110
+ {
3111
+ x: x(t),
3112
+ y: PAD.top + plotH + 15,
3113
+ fontSize: 10,
3114
+ fill: theme.textMuted,
3115
+ textAnchor: x(t) - PAD.left < 20 ? "start" : PAD.left + plotW - x(t) < 20 ? "end" : "middle",
3116
+ children: xLabel(t)
3117
+ },
3118
+ t
3119
+ )),
3120
+ /* @__PURE__ */ jsx13(AxisTitles, { x: xTitle, y: yTitle, plot: { left: PAD.left, top: PAD.top, width: plotW, height: plotH }, height: size.height }),
3121
+ /* @__PURE__ */ jsx13(Defs, { children: /* @__PURE__ */ jsx13(ClipPath, { id: clipId, children: /* @__PURE__ */ jsx13(Rect, { x: PAD.left - 6, y: 0, width: plotW + 12, height: size.height }) }) }),
3122
+ /* @__PURE__ */ jsxs11(G, { clipPath: `url(#${clipId})`, children: [
3123
+ barSeries.map(
3124
+ (s, si) => s.times.map((t, i) => {
3125
+ const v = s.values[i];
3126
+ if (v == null || t < xFrom || t > xTo) return null;
3127
+ const left = x(t) - groupW / 2 + si * (groupW / barSeries.length);
3128
+ return /* @__PURE__ */ jsx13(Path8, { d: barPath(left, barW, y(Math.max(v, 0)), y(Math.min(v, 0)), v >= 0), fill: s.color }, `${s.key}-${i}`);
3129
+ })
3130
+ ),
3131
+ series.filter((s) => style(s) !== "bars").map((s) => {
3132
+ const fill = (s.config.custom?.fillOpacity ?? 0) / 100;
3133
+ const showPoints = style(s) === "points" || s.config.custom?.showPoints === "always" || s.config.custom?.showPoints !== "never" && s.times.length <= plotW / 14;
3134
+ const segs = segments(s, x, y, s.config.custom?.lineInterpolation === "stepAfter");
3135
+ return /* @__PURE__ */ jsxs11(G, { children: [
3136
+ fill > 0 && segs.map((seg, i) => /* @__PURE__ */ jsx13(Path8, { d: `${seg.d}L${seg.lastX},${y(Math.max(yMin, 0))}L${seg.firstX},${y(Math.max(yMin, 0))}Z`, fill: s.color, opacity: fill }, `f${i}`)),
3137
+ style(s) !== "points" && segs.map((seg, i) => /* @__PURE__ */ jsx13(Path8, { d: seg.d, stroke: s.color, strokeWidth: s.config.custom?.lineWidth ?? 2, fill: "none", strokeLinejoin: "round", strokeLinecap: "round" }, `l${i}`)),
3138
+ showPoints && s.times.map(
3139
+ (t, i) => s.values[i] == null ? null : /* @__PURE__ */ jsx13(Circle, { cx: x(t), cy: y(s.values[i]), r: 4, fill: s.color, stroke: theme.surface, strokeWidth: 2 }, i)
3140
+ )
3141
+ ] }, s.key);
3142
+ }),
3143
+ hover && /* @__PURE__ */ jsxs11(G, { children: [
3144
+ /* @__PURE__ */ jsx13(Line, { x1: x(hover.time), x2: x(hover.time), y1: PAD.top, y2: PAD.top + plotH, stroke: theme.textMuted, strokeWidth: 1 }),
3145
+ hover.rows.map(
3146
+ (r) => r.value == null ? null : /* @__PURE__ */ jsx13(Circle, { cx: x(r.time), cy: y(r.value), r: 5, fill: r.color, stroke: theme.surface, strokeWidth: 2 }, r.key)
3147
+ )
3148
+ ] })
3149
+ ] })
3150
+ ] }),
3151
+ xZoom && !preview && /* @__PURE__ */ jsx13(
3152
+ Pressable10,
3153
+ {
3154
+ onPress: () => setXZoom(null),
3155
+ accessibilityRole: "button",
3156
+ hitSlop: 8,
3157
+ style: ({ pressed }) => [styles11.reset, { backgroundColor: theme.surface, borderColor: theme.border }, pressed && { opacity: 0.7 }],
3158
+ children: /* @__PURE__ */ jsx13(Text11, { style: [styles11.resetText, { color: theme.accent }], children: "Reset zoom" })
3159
+ }
3160
+ ),
3161
+ hover && /* @__PURE__ */ jsxs11(
3162
+ View10,
3163
+ {
3164
+ pointerEvents: isPinned ? "auto" : "none",
3165
+ onStartShouldSetResponder: () => isPinned,
3166
+ style: [
3167
+ styles11.tooltip,
3168
+ { backgroundColor: theme.surface, borderColor: theme.border },
3169
+ x(hover.time) > size.width / 2 ? { right: size.width - x(hover.time) + 8 } : { left: x(hover.time) + 8 }
3170
+ ],
3171
+ children: [
3172
+ /* @__PURE__ */ jsx13(Text11, { style: [styles11.tooltipTime, { color: theme.textMuted }], children: numericX ? formatValue(hover.time, xConfig) : formatTooltipTime(hover.time) }),
3173
+ hover.rows.map((r) => /* @__PURE__ */ jsxs11(View10, { style: styles11.tooltipRow, children: [
3174
+ /* @__PURE__ */ jsx13(View10, { style: [styles11.swatch, { backgroundColor: r.color }] }),
3175
+ /* @__PURE__ */ jsx13(Text11, { style: [styles11.tooltipName, { color: theme.textSecondary }], numberOfLines: 1, children: r.name }),
3176
+ /* @__PURE__ */ jsx13(Text11, { style: [styles11.tooltipValue, { color: theme.text }], children: formatValue(r.value, r.config) })
3177
+ ] }, r.key)),
3178
+ isPinned && /* @__PURE__ */ jsx13(TooltipLinks, { links: hoverLinks, onOpen: (l) => openLinks([l]) })
3179
+ ]
3180
+ }
3181
+ )
3182
+ ]
3183
+ }
3184
+ )
3185
+ }
3186
+ ),
3187
+ showLegend(panel, series.length) && /* @__PURE__ */ jsx13(Legend, { items: series })
3188
+ ] });
3189
+ }
3190
+ function segments(s, x, y, step = false) {
3191
+ const out = [];
3192
+ let d = "";
3193
+ let firstX = 0;
3194
+ let lastX = 0;
3195
+ let lastY = 0;
3196
+ s.times.forEach((t, i) => {
3197
+ const v = s.values[i];
3198
+ if (v == null) {
3199
+ if (d) out.push({ d, firstX, lastX });
3200
+ d = "";
3201
+ return;
3202
+ }
3203
+ const px = x(t);
3204
+ const py = y(v);
3205
+ if (!d) firstX = px;
3206
+ d += !d ? `M${px},${py}` : step ? `L${px},${lastY}L${px},${py}` : `L${px},${py}`;
3207
+ lastX = px;
3208
+ lastY = py;
3209
+ });
3210
+ if (d) out.push({ d, firstX, lastX });
3211
+ return out;
3212
+ }
3213
+ function barPath(left, w, top, bottom, up) {
3214
+ const h = bottom - top;
3215
+ const r = Math.min(4, w / 2, h);
3216
+ const right = left + w;
3217
+ if (up) {
3218
+ return `M${left},${bottom}V${top + r}Q${left},${top} ${left + r},${top}H${right - r}Q${right},${top} ${right},${top + r}V${bottom}Z`;
3219
+ }
3220
+ return `M${left},${top}V${bottom - r}Q${left},${bottom} ${left + r},${bottom}H${right - r}Q${right},${bottom} ${right},${bottom - r}V${top}Z`;
3221
+ }
3222
+ function timeTicks(from, to, width) {
3223
+ const n = width < 220 ? 2 : width < 400 ? 3 : 5;
3224
+ return Array.from({ length: n }, (_, i) => from + (to - from) * i / (n - 1));
3225
+ }
3226
+ function numberTicks(from, to, width) {
3227
+ const ticks = niceTicks(from, to, width < 220 ? 2 : width < 400 ? 3 : 5).filter((t) => t >= from && t <= to);
3228
+ return ticks.length ? ticks : [from, to];
3229
+ }
3230
+ function xExtent(series) {
3231
+ let min = Infinity;
3232
+ let max = -Infinity;
3233
+ for (const s of series) {
3234
+ if (!s.times.length) continue;
3235
+ min = Math.min(min, s.times[0]);
3236
+ max = Math.max(max, s.times[s.times.length - 1]);
3237
+ }
3238
+ return min === Infinity ? [0, 1] : min === max ? [min - 1, max + 1] : [min, max];
3239
+ }
3240
+ function nearest(series, t) {
3241
+ let best = null;
3242
+ for (const s of series) {
3243
+ for (const st of s.times) if (best == null || Math.abs(st - t) < Math.abs(best - t)) best = st;
3244
+ }
3245
+ if (best == null) return null;
3246
+ const time = best;
3247
+ return {
3248
+ time,
3249
+ rows: series.map((s) => {
3250
+ const i = s.times.indexOf(time);
3251
+ return { key: s.key, name: s.name, color: s.color, config: s.config, time, value: i >= 0 ? s.values[i] : null, series: s, index: i };
3252
+ })
3253
+ };
3254
+ }
3255
+ function linkData(r, frames, xField) {
3256
+ const frame = frames.find((f) => f.fields.includes(r.series.field));
3257
+ let row;
3258
+ if (frame && xField === void 0) {
3259
+ row = r.index;
3260
+ } else if (frame) {
3261
+ const xf = frame.fields.find((f) => f.name === xField) ?? numberFields(frame)[0];
3262
+ const at = xf?.values.findIndex((v, k) => Number(v) === r.time && Number(r.series.field.values[k]) === r.value);
3263
+ row = at != null && at >= 0 ? at : void 0;
3264
+ }
3265
+ return {
3266
+ frame,
3267
+ row,
3268
+ field: r.series.field,
3269
+ fieldName: r.name,
3270
+ seriesName: r.name,
3271
+ value: r.value,
3272
+ text: formatValue(r.value, r.config),
3273
+ time: xField === void 0 ? r.time : void 0
3274
+ };
3275
+ }
3276
+ var styles11 = StyleSheet11.create({
3277
+ fill: { flex: 1 },
3278
+ tooltip: {
3279
+ position: "absolute",
3280
+ top: 4,
3281
+ paddingHorizontal: 8,
3282
+ paddingVertical: 6,
3283
+ borderRadius: 6,
3284
+ borderWidth: StyleSheet11.hairlineWidth,
3285
+ maxWidth: 220,
3286
+ shadowColor: "#000",
3287
+ shadowOpacity: 0.12,
3288
+ shadowRadius: 6,
3289
+ shadowOffset: { width: 0, height: 2 },
3290
+ elevation: 3
3291
+ },
3292
+ reset: { position: "absolute", top: 4, right: 8, paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6, borderWidth: StyleSheet11.hairlineWidth },
3293
+ resetText: { fontSize: 11, fontWeight: "600" },
3294
+ tooltipTime: { fontSize: 11, marginBottom: 3 },
3295
+ tooltipRow: { flexDirection: "row", alignItems: "center", gap: 6 },
3296
+ swatch: { width: 10, height: 3, borderRadius: 2 },
3297
+ tooltipName: { fontSize: 12, flexShrink: 1 },
3298
+ tooltipValue: { fontSize: 12, fontWeight: "600", marginLeft: "auto", paddingLeft: 8 }
3299
+ });
3300
+
3301
+ // src/ui/panels/XYChartPanel.tsx
3302
+ import { useId as useId2, useMemo as useMemo7, useState as useState9 } from "react";
3303
+ import { StyleSheet as StyleSheet12, View as View11 } from "react-native";
3304
+ import Svg9, { Circle as Circle2, G as G2, Line as Line2, Path as Path9, Text as SvgText4 } from "react-native-svg";
3305
+
3306
+ // src/ui/xychart.ts
3307
+ var byName = (name) => name ? { matcher: { id: "byName", options: name } } : void 0;
3308
+ function mappings(panel) {
3309
+ const o = panel.options ?? {};
3310
+ if (o.seriesMapping != null || o.dims != null) {
3311
+ const frame = (i) => typeof i === "number" ? { matcher: { id: "byIndex", options: i } } : void 0;
3312
+ if (o.seriesMapping === "manual") {
3313
+ const series = (o.series ?? []).map((s) => ({
3314
+ frame: frame(s.frame),
3315
+ x: byName(s.x),
3316
+ y: byName(s.y),
3317
+ color: byName(s.pointColor?.field),
3318
+ size: byName(s.pointSize?.field),
3319
+ sizeRange: s.pointSize,
3320
+ name: { fixed: s.name }
3321
+ }));
3322
+ return { manual: true, series, exclude: [] };
3323
+ }
3324
+ return { manual: false, series: [{ frame: frame(o.dims?.frame), x: byName(o.dims?.x) }], exclude: o.dims?.exclude ?? [] };
3325
+ }
3326
+ return { manual: o.mapping === "manual", series: o.series ?? [], exclude: [] };
3327
+ }
3328
+ var isNumeric = (f) => f.type === "number" || f.type === "time";
3329
+ function xySeries(panel, frames, scheme) {
3330
+ const { manual, series: maps, exclude } = mappings(panel);
3331
+ const multiple = frames.length > 1;
3332
+ const out = [];
3333
+ const config = (field, frame) => resolveFieldConfig(panel, field, frame, fieldDisplayName(field, frame, multiple));
3334
+ const find = (pick, frame, fields = frame.fields) => pick ? fields.filter((f) => fieldMatches(pick.matcher, f, frame, fieldDisplayName(f, frame, multiple))) : [];
3335
+ for (const [mi, m] of (maps.length ? maps : [{}]).entries()) {
3336
+ const matcher = m.frame?.matcher;
3337
+ const chosen = matcher?.id === "byIndex" ? frames.filter((_, i) => i === matcher.options) : frames;
3338
+ for (const frame of chosen) {
3339
+ const numeric = frame.fields.filter(isNumeric);
3340
+ const xField = find(m.x, frame, numeric)[0] ?? numeric[0];
3341
+ if (!xField) continue;
3342
+ const colorField = find(m.color, frame, numeric)[0];
3343
+ const sizeField = find(m.size, frame, numeric)[0];
3344
+ const used = /* @__PURE__ */ new Set([xField, colorField, sizeField]);
3345
+ const yFields = m.y ? find(m.y, frame, numeric).filter((f) => f !== xField) : manual ? [] : numeric.filter((f) => !used.has(f) && !exclude.includes(f.name));
3346
+ for (const yField of yFields) {
3347
+ const yConfig = config(yField, frame);
3348
+ if (yConfig.custom?.hideFrom?.viz && !manual) continue;
3349
+ const xConfig = config(xField, frame);
3350
+ const color = seriesColor(out.length, scheme, yConfig);
3351
+ const base = yConfig.color?.mode === "thresholds" ? valueColor(null, yConfig, color) : color;
3352
+ const rows = [];
3353
+ const xs = [];
3354
+ const ys = [];
3355
+ yField.values.forEach((yv, i) => {
3356
+ const xv = xField.values[i];
3357
+ if (xv == null || yv == null) return;
3358
+ const xn = xField.type === "time" ? toMillis(xv) : Number(xv);
3359
+ const yn = yField.type === "time" ? toMillis(yv) : Number(yv);
3360
+ if (!Number.isFinite(xn) || !Number.isFinite(yn)) return;
3361
+ rows.push(i);
3362
+ xs.push(xn);
3363
+ ys.push(yn);
3364
+ });
3365
+ const pointSize = yConfig.custom?.pointSize;
3366
+ const fixedSize = m.sizeRange?.fixed ?? pointSize?.fixed ?? 5;
3367
+ let colors = rows.map(() => base);
3368
+ if (colorField) {
3369
+ const cConfig = config(colorField, frame);
3370
+ const values = rows.map((i) => num3(colorField.values[i]));
3371
+ const extent = range2(values);
3372
+ colors = values.map((v) => valueColor(v, cConfig, base, extent));
3373
+ }
3374
+ let sizes = rows.map(() => fixedSize);
3375
+ if (sizeField) {
3376
+ const values = rows.map((i) => num3(sizeField.values[i]));
3377
+ const [lo, hi] = range2(values) ?? [0, 1];
3378
+ const [min, max] = [m.sizeRange?.min ?? pointSize?.min ?? 5, m.sizeRange?.max ?? pointSize?.max ?? 20];
3379
+ sizes = values.map((v) => v == null ? min : min + (v - lo) / (hi - lo || 1) * (max - min));
3380
+ }
3381
+ const fixedName = m.name?.fixed;
3382
+ const yName = yConfig.displayName ?? fieldDisplayName(yField, frame, multiple);
3383
+ out.push({
3384
+ key: `${mi}/${frames.indexOf(frame)}/${yField.name}`,
3385
+ name: fixedName ? yFields.length > 1 ? `${fixedName} ${yName}` : fixedName : yName,
3386
+ color: base,
3387
+ frame,
3388
+ xField,
3389
+ yField,
3390
+ xConfig,
3391
+ yConfig,
3392
+ rows,
3393
+ xs,
3394
+ ys,
3395
+ colors,
3396
+ sizes,
3397
+ show: yConfig.custom?.show ?? "points",
3398
+ lineWidth: yConfig.custom?.lineWidth ?? 1
3399
+ });
3400
+ }
3401
+ }
3402
+ }
3403
+ return out;
3404
+ }
3405
+ function num3(v) {
3406
+ if (v == null) return null;
3407
+ const n = Number(v);
3408
+ return Number.isFinite(n) ? n : null;
3409
+ }
3410
+ function range2(values) {
3411
+ let lo = Infinity;
3412
+ let hi = -Infinity;
3413
+ for (const v of values) {
3414
+ if (v == null) continue;
3415
+ lo = Math.min(lo, v);
3416
+ hi = Math.max(hi, v);
3417
+ }
3418
+ return lo === Infinity ? void 0 : [lo, hi];
3419
+ }
3420
+ function xyDomain(values, config) {
3421
+ let lo = Infinity;
3422
+ let hi = -Infinity;
3423
+ for (const vs of values) {
3424
+ for (const v of vs) {
3425
+ lo = Math.min(lo, v);
3426
+ hi = Math.max(hi, v);
3427
+ }
3428
+ }
3429
+ if (lo === Infinity) return [config.min ?? 0, config.max ?? 1];
3430
+ const pad = (hi - lo || Math.abs(hi) || 1) * 0.05;
3431
+ return [config.min ?? lo - pad, config.max ?? hi + pad];
3432
+ }
3433
+
3434
+ // src/ui/panels/XYChartPanel.tsx
3435
+ import { jsx as jsx14, jsxs as jsxs12 } from "react/jsx-runtime";
3436
+ var AXIS = { left: 44, bottom: 20 };
3437
+ var EDGE = 8;
3438
+ var HIT_PX2 = 32;
3439
+ function XYChartPanel({ panel, frames }) {
3440
+ const theme = useDashTheme();
3441
+ const [size, onLayout] = useLayout();
3442
+ const [touch, setTouch] = useState9(null);
3443
+ const [touching, setTouching] = useState9(false);
3444
+ const id = useId2();
3445
+ const { pinned, setPinned } = useDashboard();
3446
+ const { resolve, openLinks } = usePanelLinks(panel);
3447
+ const series = useMemo7(() => xySeries(panel, frames, theme.scheme), [panel, frames, theme.scheme]);
3448
+ const first = series[0];
3449
+ const showX = first?.xConfig.custom?.axisPlacement !== "hidden";
3450
+ const showY = first?.yConfig.custom?.axisPlacement !== "hidden";
3451
+ const xTitle = showX ? axisTitle(first?.xConfig) : void 0;
3452
+ const yTitle = showY ? axisTitle(first?.yConfig) : void 0;
3453
+ const pad = {
3454
+ top: EDGE,
3455
+ right: EDGE,
3456
+ bottom: (showX ? AXIS.bottom : EDGE) + (xTitle ? AXIS_TITLE_SPACE : 0),
3457
+ left: (showY ? AXIS.left : EDGE) + (yTitle ? AXIS_TITLE_SPACE : 0)
3458
+ };
3459
+ const plotW = Math.max(0, size.width - pad.left - pad.right);
3460
+ const plotH = Math.max(0, size.height - pad.top - pad.bottom);
3461
+ const layout = useMemo7(() => {
3462
+ if (!first) return null;
3463
+ const [x0, x1] = xyDomain(series.map((s) => s.xs), first.xConfig);
3464
+ const [y0, y1] = xyDomain(series.map((s) => s.ys), first.yConfig);
3465
+ const x = linearScale(x0, x1, pad.left, pad.left + plotW);
3466
+ const y = linearScale(y0, y1, pad.top + plotH, pad.top);
3467
+ const points = series.map((s) => ({ px: s.xs.map(x), py: s.ys.map(y) }));
3468
+ return { x, y, x0, x1, y0, y1, points, paths: series.map((s, i) => drawSeries(s, points[i].px, points[i].py)) };
3469
+ }, [series, first, pad.left, pad.top, plotW, plotH]);
3470
+ if (!first || !layout || series.every((s) => !s.rows.length)) return /* @__PURE__ */ jsx14(NoData, {});
3471
+ const xTicks = showX ? axisTicks(layout.x0, layout.x1, plotW < 220 ? 2 : plotW < 400 ? 3 : 5) : [];
3472
+ const yTicks = showY ? axisTicks(layout.y0, layout.y1, plotH < 100 ? 2 : 4) : [];
3473
+ const gridX = first.xConfig.custom?.axisGridShow !== false;
3474
+ const gridY = first.yConfig.custom?.axisGridShow !== false;
3475
+ const hover = touch && (touching || pinned === id) ? nearestPoint(series, layout.points, touch) : null;
3476
+ const hoverLinks = hover ? rowLinks(panel, hover.series.frame, hover.series.rows[hover.index], frames.length > 1, resolve) : [];
3477
+ const isPinned = !!hover && pinned === id;
3478
+ const legendItems = series.filter((s) => !s.yConfig.custom?.hideFrom?.legend);
3479
+ return /* @__PURE__ */ jsxs12(View11, { style: styles12.fill, children: [
3480
+ /* @__PURE__ */ jsxs12(
3481
+ View11,
3482
+ {
3483
+ style: styles12.fill,
3484
+ onLayout,
3485
+ onStartShouldSetResponder: () => true,
3486
+ onResponderGrant: (e) => {
3487
+ setTouching(true);
3488
+ setPinned(null);
3489
+ setTouch({ x: e.nativeEvent.locationX, y: e.nativeEvent.locationY });
3490
+ },
3491
+ onResponderMove: (e) => setTouch({ x: e.nativeEvent.locationX, y: e.nativeEvent.locationY }),
3492
+ onResponderRelease: () => {
3493
+ setTouching(false);
3494
+ if (hoverLinks.length) setPinned(id);
3495
+ else setTouch(null);
3496
+ },
3497
+ onResponderTerminate: () => {
3498
+ setTouching(false);
3499
+ setTouch(null);
3500
+ },
3501
+ children: [
3502
+ size.width > 0 && /* @__PURE__ */ jsxs12(Svg9, { width: size.width, height: size.height, children: [
3503
+ yTicks.map((t) => /* @__PURE__ */ jsxs12(G2, { children: [
3504
+ gridY && /* @__PURE__ */ jsx14(Line2, { x1: pad.left, x2: pad.left + plotW, y1: layout.y(t), y2: layout.y(t), stroke: theme.grid, strokeWidth: 1 }),
3505
+ /* @__PURE__ */ jsx14(SvgText4, { x: pad.left - 6, y: layout.y(t) + 3, fontSize: 10, fill: theme.textMuted, textAnchor: "end", children: formatValue(t, { ...first.yConfig, decimals: first.yConfig.decimals ?? tickDecimals(yTicks) }) })
3506
+ ] }, `y${t}`)),
3507
+ xTicks.map((t) => /* @__PURE__ */ jsxs12(G2, { children: [
3508
+ gridX && /* @__PURE__ */ jsx14(Line2, { x1: layout.x(t), x2: layout.x(t), y1: pad.top, y2: pad.top + plotH, stroke: theme.grid, strokeWidth: 1 }),
3509
+ /* @__PURE__ */ jsx14(
3510
+ SvgText4,
3511
+ {
3512
+ x: layout.x(t),
3513
+ y: pad.top + plotH + 15,
3514
+ fontSize: 10,
3515
+ fill: theme.textMuted,
3516
+ textAnchor: layout.x(t) - pad.left < 20 ? "start" : pad.left + plotW - layout.x(t) < 20 ? "end" : "middle",
3517
+ children: formatValue(t, { ...first.xConfig, decimals: first.xConfig.decimals ?? tickDecimals(xTicks) })
3518
+ }
3519
+ )
3520
+ ] }, `x${t}`)),
3521
+ /* @__PURE__ */ jsx14(AxisTitles, { x: xTitle, y: yTitle, plot: { left: pad.left, top: pad.top, width: plotW, height: plotH }, height: size.height }),
3522
+ series.map((s, si) => /* @__PURE__ */ jsxs12(G2, { children: [
3523
+ layout.paths[si].line && /* @__PURE__ */ jsx14(Path9, { d: layout.paths[si].line, stroke: s.color, strokeWidth: s.lineWidth, fill: "none", strokeLinejoin: "round" }),
3524
+ layout.paths[si].dots.map(([color, d]) => /* @__PURE__ */ jsx14(Path9, { d, fill: color }, color))
3525
+ ] }, s.key)),
3526
+ hover && /* @__PURE__ */ jsx14(
3527
+ Circle2,
3528
+ {
3529
+ cx: hover.px,
3530
+ cy: hover.py,
3531
+ r: Math.max(hover.series.sizes[hover.index] / 2 + 2, 5),
3532
+ fill: hover.series.colors[hover.index],
3533
+ stroke: theme.text,
3534
+ strokeWidth: 2
3535
+ }
3536
+ )
3537
+ ] }),
3538
+ hover && /* @__PURE__ */ jsx14(
3539
+ RowTooltip,
3540
+ {
3541
+ at: { x: hover.px, y: hover.py },
3542
+ size,
3543
+ color: hover.series.colors[hover.index],
3544
+ title: hover.series.name,
3545
+ rows: rowTooltipItems(panel, hover.series.frame, hover.series.rows[hover.index], frames.length > 1),
3546
+ links: isPinned ? hoverLinks : void 0,
3547
+ onOpenLink: (l) => openLinks([l])
3548
+ }
3549
+ )
3550
+ ]
3551
+ }
3552
+ ),
3553
+ showLegend(panel, legendItems.length) && /* @__PURE__ */ jsx14(Legend, { items: legendItems })
3554
+ ] });
3555
+ }
3556
+ function drawSeries(s, px, py) {
3557
+ const line = s.show === "points" ? void 0 : px.map((x, i) => `${i ? "L" : "M"}${x},${py[i]}`).join("");
3558
+ if (s.show === "lines") return { line, dots: [] };
3559
+ const byColor = /* @__PURE__ */ new Map();
3560
+ px.forEach((x, i) => {
3561
+ const r = s.sizes[i] / 2;
3562
+ const color = s.colors[i];
3563
+ const parts = byColor.get(color) ?? byColor.set(color, []).get(color);
3564
+ parts.push(`M${x - r},${py[i]}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0`);
3565
+ });
3566
+ return { line, dots: [...byColor].map(([color, parts]) => [color, parts.join("")]) };
3567
+ }
3568
+ function axisTicks(from, to, count) {
3569
+ const ticks = niceTicks(from, to, count).filter((t) => t >= from && t <= to);
3570
+ return ticks.length ? ticks : [from, to];
3571
+ }
3572
+ function nearestPoint(series, points, at) {
3573
+ let best = null;
3574
+ let bestD = HIT_PX2 * HIT_PX2;
3575
+ series.forEach((s, si) => {
3576
+ const { px, py } = points[si];
3577
+ for (let i = 0; i < px.length; i++) {
3578
+ const d = (px[i] - at.x) ** 2 + (py[i] - at.y) ** 2;
3579
+ if (d < bestD) {
3580
+ bestD = d;
3581
+ best = { series: s, index: i, px: px[i], py: py[i] };
3582
+ }
3583
+ }
3584
+ });
3585
+ return best;
3586
+ }
3587
+ var styles12 = StyleSheet12.create({
3588
+ fill: { flex: 1 }
3589
+ });
3590
+
3591
+ // src/ui/panels/registry.ts
3592
+ var registry = {
3593
+ timeseries: TimeSeriesPanel,
3594
+ graph: TimeSeriesPanel,
3595
+ trend: TimeSeriesPanel,
3596
+ xychart: XYChartPanel,
3597
+ stat: StatPanel,
3598
+ singlestat: StatPanel,
3599
+ gauge: GaugePanel,
3600
+ bargauge: BarGaugePanel,
3601
+ piechart: PieChartPanel,
3602
+ barchart: BarChartPanel,
3603
+ table: TablePanel,
3604
+ text: TextPanel,
3605
+ geomap: GeomapPanel
3606
+ };
3607
+ function registerPanel(type, component) {
3608
+ registry[type] = component;
3609
+ }
3610
+ function panelComponent(type) {
3611
+ return registry[type] ?? UnsupportedPanel;
3612
+ }
3613
+
3614
+ // src/ui/DashboardView.tsx
3615
+ import { jsx as jsx15, jsxs as jsxs13 } from "react/jsx-runtime";
3616
+ var GAP = 8;
3617
+ var SIDE = 12;
3618
+ var TITLE_H = 28;
3619
+ var TABLET_WIDTH = 700;
3620
+ var MIN_PANEL_H = 160;
3621
+ function DashboardView({ mode = "auto", header, footer, refreshable }) {
3622
+ const theme = useDashTheme();
3623
+ const { dashboard, refresh, variables, variableInfo: variableInfo2, setPinned } = useDashboard();
3624
+ const [measured, onLayout] = useLayout();
3625
+ const window = useWindowDimensions();
3626
+ const insets = useSafeAreaInsets4();
3627
+ const width = (measured.width || window.width) - insets.left - insets.right;
3628
+ const layoutMode = mode === "auto" ? width >= TABLET_WIDTH ? "grid" : "phone" : mode;
3629
+ const sections = useMemo8(
3630
+ () => layoutDashboard(dashboard, layoutMode, { values: variables, info: variableInfo2 }),
3631
+ [dashboard, layoutMode, variables, variableInfo2]
3632
+ );
3633
+ const [toggled, setToggled] = useState10({});
3634
+ const { seen, viewportH, onScroll, onViewportLayout, onSectionLayout } = useSeenSections(window.height);
3635
+ const maxPanelH = Math.max(MIN_PANEL_H, viewportH - SIDE * 2);
3636
+ const contentW = width - SIDE * 2;
3637
+ const canRefresh = refreshable ?? dashboard.panels.some((p) => panelHasQueries(p) || p.panels?.some(panelHasQueries));
3638
+ return /* @__PURE__ */ jsxs13(View12, { style: [styles13.fill, { backgroundColor: theme.background }], onLayout, children: [
3639
+ width > 0 && /* @__PURE__ */ jsxs13(
3640
+ ScrollView5,
3641
+ {
3642
+ onScroll,
3643
+ onScrollBeginDrag: () => setPinned(null),
3644
+ onLayout: onViewportLayout,
3645
+ scrollEventThrottle: 100,
3646
+ contentContainerStyle: [styles13.content, { paddingLeft: SIDE + insets.left, paddingRight: SIDE + insets.right }],
3647
+ keyboardShouldPersistTaps: "handled",
3648
+ refreshControl: canRefresh ? /* @__PURE__ */ jsx15(RefreshControl, { refreshing: false, onRefresh: refresh }) : void 0,
3649
+ children: [
3650
+ header,
3651
+ sections.map((section) => {
3652
+ const collapsed = toggled[section.key] ?? section.collapsed;
3653
+ return /* @__PURE__ */ jsxs13(View12, { style: styles13.section, onLayout: (e) => onSectionLayout(section.key, e), children: [
3654
+ section.row && /* @__PURE__ */ jsxs13(
3655
+ Pressable11,
3656
+ {
3657
+ onPress: () => setToggled((t) => ({ ...t, [section.key]: !collapsed })),
3658
+ style: styles13.rowHeader,
3659
+ accessibilityRole: "button",
3660
+ accessibilityState: { expanded: !collapsed },
3661
+ children: [
3662
+ /* @__PURE__ */ jsx15(Text12, { style: [styles13.chevron, { color: theme.textMuted }], children: collapsed ? "\u25B8" : "\u25BE" }),
3663
+ /* @__PURE__ */ jsx15(Text12, { style: [styles13.rowTitle, { color: theme.text }], numberOfLines: 2, children: interpolate(section.row.title ?? "", { values: variables, info: variableInfo2, scoped: section.row.scopedVars, timezone: dashboard.timezone }) })
3664
+ ]
3665
+ }
3666
+ ),
3667
+ !collapsed && section.rows.map((row, ri) => /* @__PURE__ */ jsx15(View12, { style: styles13.row, children: row.cells.map((cell) => {
3668
+ const w = (contentW + GAP) * (cell.span / GRID_COLUMNS) - GAP;
3669
+ return /* @__PURE__ */ jsx15(PanelCard, { panel: cell.panel, width: w, height: Math.min(gridUnitsToPx(row.h), maxPanelH), deferred: !seen.has(section.key) }, cell.key);
3670
+ }) }, ri))
3671
+ ] }, section.key);
3672
+ })
3673
+ ]
3674
+ }
3675
+ ),
3676
+ footer
3677
+ ] });
3678
+ }
3679
+ function useSeenSections(viewportHeight) {
3680
+ const [seen, setSeen] = useState10(/* @__PURE__ */ new Set());
3681
+ const view = useRef4({ y: 0, h: viewportHeight });
3682
+ const [viewportH, setViewportH] = useState10(viewportHeight);
3683
+ const positions = useRef4(/* @__PURE__ */ new Map());
3684
+ const reveal = useCallback3(() => {
3685
+ const { y, h } = view.current;
3686
+ setSeen((prev) => {
3687
+ let next = null;
3688
+ for (const [key, p] of positions.current) {
3689
+ if (!prev.has(key) && p.y < y + 2 * h && p.y + p.h > y - h) (next ??= new Set(prev)).add(key);
3690
+ }
3691
+ return next ?? prev;
3692
+ });
3693
+ }, []);
3694
+ const onScroll = useCallback3(
3695
+ (e) => {
3696
+ view.current = { y: e.nativeEvent.contentOffset.y, h: e.nativeEvent.layoutMeasurement.height };
3697
+ reveal();
3698
+ },
3699
+ [reveal]
3700
+ );
3701
+ const onViewportLayout = useCallback3(
3702
+ (e) => {
3703
+ const h = e.nativeEvent.layout.height;
3704
+ view.current = { ...view.current, h };
3705
+ setViewportH(h);
3706
+ reveal();
3707
+ },
3708
+ [reveal]
3709
+ );
3710
+ const onSectionLayout = useCallback3(
3711
+ (key, e) => {
3712
+ const { y, height } = e.nativeEvent.layout;
3713
+ positions.current.set(key, { y, h: height });
3714
+ reveal();
3715
+ },
3716
+ [reveal]
3717
+ );
3718
+ return { seen, viewportH, onScroll, onViewportLayout, onSectionLayout };
3719
+ }
3720
+ function PanelCard(props) {
3721
+ const { panel, width, height } = props;
3722
+ return /* @__PURE__ */ jsx15(RenderBoundary, { resetKeys: [panel, width, height], fallback: (error) => /* @__PURE__ */ jsx15(PanelError, { panel, width, height, error }), children: /* @__PURE__ */ jsx15(PanelCardContent, { ...props }) });
3723
+ }
3724
+ function PanelError({ panel, width, height, error }) {
3725
+ const theme = useDashTheme();
3726
+ return /* @__PURE__ */ jsxs13(View12, { style: [styles13.card, { width, height, backgroundColor: theme.surface, borderColor: theme.danger }], accessibilityRole: "alert", children: [
3727
+ !!panel.title && /* @__PURE__ */ jsx15(Text12, { style: [styles13.title, styles13.errorTitle, { color: theme.text }], numberOfLines: 1, children: panel.title }),
3728
+ /* @__PURE__ */ jsx15(Text12, { style: [styles13.errorText, { color: theme.danger }], children: "This panel couldn\u2019t be shown." }),
3729
+ /* @__PURE__ */ jsx15(Text12, { style: [styles13.errorText, { color: theme.textMuted }], numberOfLines: 3, children: error.message })
3730
+ ] });
3731
+ }
3732
+ function PanelCardContent({ panel, width, height, deferred }) {
3733
+ const theme = useDashTheme();
3734
+ const { dashboard, variables, variableInfo: variableInfo2 } = useDashboard();
3735
+ const { resolve, openLinks } = usePanelLinks(panel);
3736
+ const input = isInputPanel(panel);
3737
+ const form = useContext4(InputFormContext);
3738
+ const problem = input ? form?.problem?.(panel.options.metric) : void 0;
3739
+ const hasLinks = !!panel.links?.length;
3740
+ const hasTitle = !!panel.title || hasLinks || !!problem;
3741
+ const title = panel.title ? interpolate(panel.title, { values: variables, info: variableInfo2, scoped: panel.scopedVars, timezone: dashboard.timezone }) : "";
3742
+ return /* @__PURE__ */ jsxs13(View12, { style: [styles13.card, { width, height, backgroundColor: theme.surface, borderColor: theme.border }], children: [
3743
+ hasTitle && /* @__PURE__ */ jsxs13(View12, { style: styles13.titleRow, children: [
3744
+ /* @__PURE__ */ jsx15(Text12, { style: [styles13.title, { color: theme.text }], numberOfLines: 1, children: title }),
3745
+ !!problem && /* @__PURE__ */ jsx15(Text12, { style: [styles13.problem, { color: theme.danger }], numberOfLines: 1, accessibilityRole: "alert", children: problem }),
3746
+ hasLinks && /* @__PURE__ */ jsx15(
3747
+ Pressable11,
3748
+ {
3749
+ onPress: () => openLinks(resolve(panel.links), title || void 0),
3750
+ accessibilityRole: "button",
3751
+ accessibilityLabel: panel.links.length === 1 ? panel.links[0].title || "Open link" : "Panel links",
3752
+ hitSlop: 10,
3753
+ style: ({ pressed }) => [styles13.titleLink, pressed && { opacity: 0.6 }],
3754
+ children: /* @__PURE__ */ jsx15(LinkIcon, { color: theme.textMuted })
3755
+ }
3756
+ )
3757
+ ] }),
3758
+ /* @__PURE__ */ jsx15(View12, { style: styles13.body, children: deferred && !input ? null : input ? /* @__PURE__ */ jsx15(InputPanelBody, { panel }) : /* @__PURE__ */ jsx15(DataPanelBody, { panel, width: width - 24, height: height - (hasTitle ? TITLE_H : 0) - 16 }) })
3759
+ ] });
3760
+ }
3761
+ function DataPanelBody({ panel, width, height }) {
3762
+ const theme = useDashTheme();
3763
+ const needsData = panelHasQueries(panel);
3764
+ const data = usePanelData(panel, width, needsData);
3765
+ const Component2 = panelComponent(panel.type);
3766
+ if (needsData && data.error) {
3767
+ return /* @__PURE__ */ jsx15(View12, { style: styles13.center, children: /* @__PURE__ */ jsx15(Text12, { style: [styles13.error, { color: theme.danger }], numberOfLines: 4, children: data.error }) });
3768
+ }
3769
+ if (needsData && data.loading && !data.frames.length) {
3770
+ return /* @__PURE__ */ jsx15(View12, { style: styles13.center, children: /* @__PURE__ */ jsx15(ActivityIndicator, { color: theme.textMuted }) });
3771
+ }
3772
+ return /* @__PURE__ */ jsx15(Component2, { panel, frames: data.frames, width, height });
3773
+ }
3774
+ var styles13 = StyleSheet13.create({
3775
+ fill: { flex: 1 },
3776
+ content: { padding: SIDE, paddingBottom: 32, gap: GAP },
3777
+ section: { gap: GAP },
3778
+ rowHeader: { flexDirection: "row", alignItems: "center", gap: 6, paddingVertical: 6 },
3779
+ chevron: { fontSize: 14, width: 14 },
3780
+ rowTitle: { fontSize: 15, fontWeight: "600" },
3781
+ row: { flexDirection: "row", gap: GAP },
3782
+ card: { borderRadius: 10, borderWidth: StyleSheet13.hairlineWidth, paddingHorizontal: 12, paddingVertical: 8, overflow: "hidden" },
3783
+ titleRow: { flexDirection: "row", alignItems: "flex-start", gap: 8, height: TITLE_H - 8, marginBottom: 8 },
3784
+ title: { flex: 1, fontSize: 13, fontWeight: "600" },
3785
+ titleLink: { paddingTop: 1 },
3786
+ problem: { fontSize: 12, fontWeight: "600", flexShrink: 1 },
3787
+ body: { flex: 1 },
3788
+ errorTitle: { flex: 0, marginBottom: 6 },
3789
+ errorText: { fontSize: 12, lineHeight: 17 },
3790
+ center: { flex: 1, alignItems: "center", justifyContent: "center", padding: 8 },
3791
+ error: { fontSize: 12, textAlign: "center" }
3792
+ });
3793
+
3794
+ // src/ui/inputs/InputForm.tsx
3795
+ import { useCallback as useCallback4, useEffect as useEffect4, useMemo as useMemo9, useState as useState11 } from "react";
3796
+ import { Pressable as Pressable12, StyleSheet as StyleSheet14, Text as Text13, View as View13 } from "react-native";
3797
+ import { jsx as jsx16, jsxs as jsxs14 } from "react/jsx-runtime";
3798
+ var NO_CHOICES = {};
3799
+ var NO_DEFAULTS = {};
3800
+ function savedValues(panels, entries) {
3801
+ const values = {};
3802
+ for (const p of panels) {
3803
+ const mine = entries.filter((e) => e.metric === p.options.metric);
3804
+ values[p.options.metric] = p.options.multi ? mine.length ? mine.map((e) => e.text ?? e.value) : null : entryToInputValue(p, mine[0]);
3805
+ }
3806
+ return values;
3807
+ }
3808
+ function InputForm({ dashboard, store, onSaved, choices = NO_CHOICES, header, timestamp, defaults: given = NO_DEFAULTS, beforeSave, editing }) {
3809
+ const theme = useDashTheme();
3810
+ const panels = useMemo9(() => inputPanels(dashboard), [dashboard]);
3811
+ const saved = useMemo9(() => editing ? savedValues(panels, editing) : NO_DEFAULTS, [panels, editing]);
3812
+ const [defaults, setDefaults] = useState11({});
3813
+ const [edits, setEdits] = useState11({});
3814
+ const [offsetMs, setOffsetMs] = useState11(0);
3815
+ const [status, setStatus] = useState11(null);
3816
+ const [checked, setChecked] = useState11(false);
3817
+ useEffect4(() => {
3818
+ let run = 0;
3819
+ const load = async () => {
3820
+ const mine = ++run;
3821
+ const next = {};
3822
+ for (const p of panels) {
3823
+ const d = p.options.default;
3824
+ if (d === "last") next[p.options.metric] = entryToInputValue(p, await store.latest(p.options.metric));
3825
+ else if (d !== void 0) next[p.options.metric] = d;
3826
+ }
3827
+ if (mine === run) setDefaults(next);
3828
+ };
3829
+ load();
3830
+ const unsubscribe = store.subscribe(load);
3831
+ return () => {
3832
+ run = -1;
3833
+ unsubscribe();
3834
+ };
3835
+ }, [panels, store]);
3836
+ const state = useMemo9(() => {
3837
+ const value = (m) => m in edits ? edits[m] : m in saved ? saved[m] : m in given ? given[m] : defaults[m] ?? null;
3838
+ return {
3839
+ value,
3840
+ setValue: (m, v) => {
3841
+ setStatus(null);
3842
+ setEdits((e) => ({ ...e, [m]: v }));
3843
+ },
3844
+ isDirty: (m) => m in edits,
3845
+ store,
3846
+ choices,
3847
+ problem: (m) => {
3848
+ const p = panels.find((x) => x.options.metric === m);
3849
+ return p && (checked || m in edits) ? inputProblem(p, value(m)) : void 0;
3850
+ }
3851
+ };
3852
+ }, [edits, saved, defaults, given, store, choices, panels, checked]);
3853
+ const dirty = Object.keys(edits).length;
3854
+ const save = useCallback4(async () => {
3855
+ const problems = panels.flatMap((p) => {
3856
+ const problem = inputProblem(p, state.value(p.options.metric));
3857
+ return problem ? [`${p.title || p.options.metric}: ${problem.toLowerCase()}`] : [];
3858
+ });
3859
+ if (problems.length) {
3860
+ setChecked(true);
3861
+ setStatus(problems.length === 1 ? `Can\u2019t save. ${problems[0]}` : `Can\u2019t save: ${problems.length} fields need fixing`);
3862
+ return;
3863
+ }
3864
+ const ts = editing?.[0]?.ts ?? (header !== void 0 ? timestamp?.() ?? Date.now() : Date.now() + offsetMs);
3865
+ const entries = panels.filter((p) => editing || p.options.metric in edits || p.options.record === "always").flatMap((p) => toEntries(p, state.value(p.options.metric), ts));
3866
+ if (!entries.length) return;
3867
+ const extra = beforeSave ? await beforeSave(ts) : [];
3868
+ if (!extra) return;
3869
+ const added = editing ? await replace(store, editing.map((e) => e.id), [...entries, ...extra]) : await store.add([...entries, ...extra]);
3870
+ setEdits({});
3871
+ setChecked(false);
3872
+ setOffsetMs(0);
3873
+ setStatus(`Saved ${added.length} ${added.length === 1 ? "value" : "values"}`);
3874
+ onSaved?.(added.length, added);
3875
+ }, [panels, edits, state, offsetMs, store, onSaved, header, timestamp, beforeSave, editing]);
3876
+ return /* @__PURE__ */ jsx16(InputFormContext.Provider, { value: state, children: /* @__PURE__ */ jsx16(DashboardProvider, { dashboard, children: /* @__PURE__ */ jsx16(
3877
+ DashboardView,
3878
+ {
3879
+ header: header !== void 0 ? header : /* @__PURE__ */ jsx16(TimestampPicker, { offsetMs, onChange: setOffsetMs }),
3880
+ footer: /* @__PURE__ */ jsxs14(View13, { style: [styles14.footer, { backgroundColor: theme.surface, borderTopColor: theme.border }], children: [
3881
+ /* @__PURE__ */ jsx16(Text13, { style: [styles14.status, { color: status?.startsWith("Can\u2019t") ? theme.danger : theme.textSecondary }], children: status ?? (dirty ? `${dirty} unsaved ${dirty === 1 ? "change" : "changes"}` : "Nothing to save") }),
3882
+ dirty > 0 && /* @__PURE__ */ jsx16(
3883
+ Pressable12,
3884
+ {
3885
+ onPress: () => {
3886
+ setEdits({});
3887
+ setChecked(false);
3888
+ setStatus(null);
3889
+ },
3890
+ style: styles14.secondary,
3891
+ accessibilityRole: "button",
3892
+ children: /* @__PURE__ */ jsx16(Text13, { style: { color: theme.textSecondary, fontWeight: "500" }, children: "Discard" })
3893
+ }
3894
+ ),
3895
+ /* @__PURE__ */ jsx16(
3896
+ Pressable12,
3897
+ {
3898
+ onPress: save,
3899
+ disabled: !dirty,
3900
+ accessibilityRole: "button",
3901
+ style: ({ pressed }) => [styles14.save, { backgroundColor: theme.accent, opacity: !dirty ? 0.4 : pressed ? 0.8 : 1 }],
3902
+ children: /* @__PURE__ */ jsx16(Text13, { style: styles14.saveText, children: "Save" })
3903
+ }
3904
+ )
3905
+ ] })
3906
+ }
3907
+ ) }) });
3908
+ }
3909
+ async function replace(store, ids, entries) {
3910
+ if (store.replace) return store.replace(ids, entries);
3911
+ for (const id of ids) await store.remove(id);
3912
+ return store.add(entries);
3913
+ }
3914
+ var HOUR = 36e5;
3915
+ function TimestampPicker({ offsetMs, onChange }) {
3916
+ const theme = useDashTheme();
3917
+ const [now, setNow] = useState11(() => Date.now());
3918
+ useEffect4(() => {
3919
+ const id = setInterval(() => setNow(Date.now()), 3e4);
3920
+ return () => clearInterval(id);
3921
+ }, []);
3922
+ const when = new Date(now + offsetMs);
3923
+ const step = (ms) => () => onChange(Math.min(0, offsetMs + ms));
3924
+ return /* @__PURE__ */ jsxs14(View13, { style: [styles14.when, { backgroundColor: theme.surface, borderColor: theme.border }], children: [
3925
+ /* @__PURE__ */ jsxs14(View13, { style: { flex: 1 }, children: [
3926
+ /* @__PURE__ */ jsx16(Text13, { style: [styles14.whenLabel, { color: theme.textMuted }], children: "Recording for" }),
3927
+ /* @__PURE__ */ jsx16(Text13, { style: [styles14.whenValue, { color: theme.text }], children: offsetMs === 0 ? "Now" : when.toLocaleString(void 0, { weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) })
3928
+ ] }),
3929
+ [
3930
+ ["\u22121d", -24 * HOUR],
3931
+ ["\u22121h", -HOUR],
3932
+ ["+1h", HOUR]
3933
+ ].map(([label, ms]) => /* @__PURE__ */ jsx16(Pressable12, { onPress: step(ms), style: [styles14.stepBtn, { borderColor: theme.border }], accessibilityRole: "button", children: /* @__PURE__ */ jsx16(Text13, { style: { color: theme.text, fontSize: 13 }, children: label }) }, label)),
3934
+ offsetMs !== 0 && /* @__PURE__ */ jsx16(Pressable12, { onPress: () => onChange(0), style: [styles14.stepBtn, { borderColor: theme.accent }], accessibilityRole: "button", children: /* @__PURE__ */ jsx16(Text13, { style: { color: theme.accent, fontSize: 13, fontWeight: "600" }, children: "Now" }) })
3935
+ ] });
3936
+ }
3937
+ var styles14 = StyleSheet14.create({
3938
+ footer: { flexDirection: "row", alignItems: "center", gap: 12, paddingHorizontal: 16, paddingVertical: 10, borderTopWidth: StyleSheet14.hairlineWidth },
3939
+ status: { flex: 1, fontSize: 13 },
3940
+ secondary: { paddingHorizontal: 8, paddingVertical: 10 },
3941
+ save: { paddingHorizontal: 22, paddingVertical: 10, borderRadius: 8 },
3942
+ saveText: { color: "#fff", fontWeight: "600", fontSize: 15 },
3943
+ when: { flexDirection: "row", alignItems: "center", gap: 6, padding: 12, borderRadius: 10, borderWidth: StyleSheet14.hairlineWidth },
3944
+ whenLabel: { fontSize: 11 },
3945
+ whenValue: { fontSize: 15, fontWeight: "600" },
3946
+ stepBtn: { paddingHorizontal: 10, paddingVertical: 6, borderRadius: 6, borderWidth: 1 }
3947
+ });
3948
+ export {
3949
+ ALL,
3950
+ BUNDLE_ACCEPT,
3951
+ BUNDLE_TYPE,
3952
+ CANVAS_GAP,
3953
+ CANVAS_ROW_HEADER,
3954
+ Calendar,
3955
+ Chip,
3956
+ ConfigLoader,
3957
+ DASHBOARD_DS,
3958
+ DEFAULT_GAZETTEER,
3959
+ DashThemeProvider,
3960
+ DashboardProvider,
3961
+ DashboardToolbar,
3962
+ DashboardView,
3963
+ EDITABLE_VARIABLE_TYPES,
3964
+ GRID_COLUMNS,
3965
+ GrafanaClient,
3966
+ GrafanaDataSource,
3967
+ GrafanaError,
3968
+ HttpConfigFiles,
3969
+ INPUT_OPTION_KEYS,
3970
+ INPUT_TYPES,
3971
+ InputForm,
3972
+ InputFormContext,
3973
+ LOCAL_DATASOURCE_TYPE,
3974
+ Legend,
3975
+ LocalDataSource,
3976
+ MANIFEST_VERSION,
3977
+ MAPPING_TYPES,
3978
+ MemoryEntryStore,
3979
+ NAMED_COLORS,
3980
+ NoData,
3981
+ OPTION_CATEGORIES,
3982
+ OVERRIDE_MATCHERS,
3983
+ PANEL_TYPES,
3984
+ PanelCard,
3985
+ REDUCER_LABELS,
3986
+ REFRESH_CHOICES,
3987
+ RELATIVE_RANGES,
3988
+ RenderBoundary,
3989
+ SERIES_PALETTE,
3990
+ SPECIAL_MATCHES,
3991
+ SaveConflictError,
3992
+ TIME_PRESETS,
3993
+ UNIT_CHOICES,
3994
+ addTime,
3995
+ appSchema,
3996
+ applyDashboardLink,
3997
+ applyJsonEdits,
3998
+ applyTransformations,
3999
+ assembleBundle,
4000
+ assembleFromResponse,
4001
+ buildFrames,
4002
+ bundleFromFiles,
4003
+ bundleRoot,
4004
+ calculateInterval,
4005
+ checkFiles,
4006
+ cleanDashboard,
4007
+ cleanPanelOptions,
4008
+ darkTheme,
4009
+ dashboardSchema,
4010
+ dashboardSchemaIssues,
4011
+ dashboardSourceIds,
4012
+ defaultFetchJson,
4013
+ describeRange,
4014
+ diffJson,
4015
+ documentIdFor,
4016
+ documentUses,
4017
+ dropTarget,
4018
+ duplicatePanel,
4019
+ entriesSavedWith,
4020
+ entryToInputValue,
4021
+ expandRow,
4022
+ fetchBundle,
4023
+ fetchJsonWithToken,
4024
+ fieldDisplayName,
4025
+ fieldMatches,
4026
+ formatClock,
4027
+ formatDisplay,
4028
+ formatDuration,
4029
+ formatJsonText,
4030
+ formatLocalDateTime,
4031
+ formatValue,
4032
+ frameLength,
4033
+ framesToOptions,
4034
+ fromWire,
4035
+ getPath,
4036
+ gridUnitsToPx,
4037
+ initialVariableValues,
4038
+ inputPanels,
4039
+ inputProblem,
4040
+ insertPanel,
4041
+ interpolate,
4042
+ interpolateDeep,
4043
+ isBundleResponse,
4044
+ isEditableVariableType,
4045
+ isInputPanel,
4046
+ isInputType,
4047
+ isLocalDatasource,
4048
+ isReducer,
4049
+ isRow,
4050
+ isSqlDatasource,
4051
+ layoutCanvas,
4052
+ layoutDashboard,
4053
+ lightTheme,
4054
+ lineColumn,
4055
+ loadGazetteer,
4056
+ locate,
4057
+ manifestSchemaIssues,
4058
+ mappedResult,
4059
+ mappingProblem,
4060
+ mappingRow,
4061
+ mappingRows,
4062
+ metricChanges,
4063
+ movePanel,
4064
+ newDocument,
4065
+ newPanel,
4066
+ newVariable,
4067
+ nextPanelId,
4068
+ normalizeRef,
4069
+ numberFields,
4070
+ optionValue,
4071
+ overrideProperties,
4072
+ panelEdits,
4073
+ panelHasQueries,
4074
+ panelKey,
4075
+ panelOptions,
4076
+ panelOverrides,
4077
+ panelSize,
4078
+ panelSpan,
4079
+ parseClockDigits,
4080
+ parseDashboardLink,
4081
+ parseDuration,
4082
+ parseGazetteer,
4083
+ parseJsonText,
4084
+ parseLocalDateTime,
4085
+ parseRange,
4086
+ parseTime,
4087
+ pointerToPath,
4088
+ prepareDashboard,
4089
+ queryPanel,
4090
+ queryParam,
4091
+ readConfigFiles,
4092
+ readingOrder,
4093
+ reduce,
4094
+ refineOptions,
4095
+ refreshedVariables,
4096
+ registerPanel,
4097
+ removeDocumentFromManifest,
4098
+ removePanel,
4099
+ renameDocumentInManifest,
4100
+ renameVariableInPanels,
4101
+ repack,
4102
+ repeatOptions,
4103
+ resizePanel,
4104
+ resolveColor,
4105
+ resolveFieldConfig,
4106
+ resolveLinks,
4107
+ resolveTimezone,
4108
+ resolveUrl,
4109
+ resolveVariables,
4110
+ rowsToMappings,
4111
+ sampleEntries,
4112
+ screenDocuments,
4113
+ screenOfType,
4114
+ selectValue,
4115
+ seriesColor,
4116
+ setHiddenOnPhones,
4117
+ setJsonValue,
4118
+ setOption,
4119
+ setOptionValue,
4120
+ setOverrides,
4121
+ splitPath,
4122
+ startOf,
4123
+ stringifyCompact,
4124
+ tabIdFor,
4125
+ textSuggestions,
4126
+ thresholdStep,
4127
+ timeExprError,
4128
+ timeField,
4129
+ toEntries,
4130
+ toMillis,
4131
+ toSeries,
4132
+ toXYSeries,
4133
+ uniqueNames,
4134
+ useDashTheme,
4135
+ useDashboard,
4136
+ useInputForm,
4137
+ usePanelData,
4138
+ validateBundle,
4139
+ validateDashboard,
4140
+ validateManifest,
4141
+ valueColor,
4142
+ valueText,
4143
+ variableDependents,
4144
+ variableInfo,
4145
+ variableNameError,
4146
+ variableOptions,
4147
+ variableOrder,
4148
+ variableReferences,
4149
+ variableUses,
4150
+ variableWithCurrent,
4151
+ variableWithFlags,
4152
+ variableWithQuery,
4153
+ variableWithType,
4154
+ visibleVariables,
4155
+ zoomRange
4156
+ };