@altertable/data-app-react 0.78.0 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,16 +1,232 @@
1
- import { $t as Button, B as AnnotationTooltip, C as ContentSkeleton, Ct as resolveActions, D as DataAppFrame, Dt as DetailView, E as Notice, Et as DetailRoutes, G as getViewDefinition, H as createDataHooks, Jt as shortcuts, K as useDeclaredResult, Nt as mountDataApp, O as TextContent, Ot as useDetailNavigation, Qt as EmptyState, R as IconButton, S as withWidgetBoundary, T as DataValue$1, Tt as DetailContent, U as AppViewResultsContext, Ut as Tooltip, Vt as Sheet, W as assertAppFilters, Wt as TooltipProvider, Xt as useInspectionDefaults, Yt as InspectionContext, Zt as AppIcon, _t as datasetTable, a as TextWidget$1, an as injectDataAppStyles, at as Skeleton, bt as DateDisplay, d as MetricWidget$1, dt as SearchSuggestionsContext, f as VisualizationWidget$1, gt as RegisteredBinding, h as ExplorationActionControl, ht as MetricRecords, i as chartColor, in as useDataApp, jt as ownedSource, k as Stack, kt as DataSectionBoundary, m as comparisonChange, mt as sectionContent, n as createDataContext, nn as DateFormattingContext, nt as DateTimeRangePicker, o as TableWidget$1, on as injectStyles, p as metricComparison, qt as Kbd, rn as useDateFormatting, rt as Select, t as SectionHeading, tn as classNames, vt as exportDatasets, w as getAnnotationProps, wt as breakdownState, xt as DateTimeTooltip, yt as registeredEvidence, z as useDataAppAnnotations } from "./chunks/SectionHeading-BKvi7HVv.js";
2
- import { getDataAppTransport, navigateNewTab, navigateNewWindowOrTab } from "@altertable/data-app/client";
3
- import { KEY_SEPARATOR, fixedUnitMilliseconds, invariant } from "@altertable/data-app/internal";
4
- import { useCallback, useContext, useEffect, useEffectEvent, useImperativeHandle, useReducer, useRef, useState } from "react";
1
+ import { $t as Kbd, At as errorPresentation, C as DataAppFrame, Ct as resolveActions, D as TextContent, Dt as DetailView, E as useAppAppearance, Et as DetailRoutes, Ft as mountDataApp, G as useDeclaredResult, Gt as Sheet, H as AppViewResultsContext, Ht as TabPanels, Jt as subscribeSearch, L as IconButton, Lt as SegmentedTab, Nt as ownedSource, O as Stack, Ot as useDetailNavigation, R as useDataAppAnnotations, Rt as SegmentedTabList, S as LoadingStatus, T as useDataAppPresentation, Tt as DetailContent, U as assertAppFilters, Ut as Tabs, V as createDataHooks, Vt as TabPanel, W as getViewDefinition, Xt as TooltipProvider, Yt as Tooltip, _ as ContentSkeleton, _t as datasetTable, a as DataTable, an as Button, at as Skeleton, b as Notice, bt as DateDisplay, cn as DateFormattingContext, dn as injectDataAppStyles, dt as SearchSuggestionsContext, en as shortcuts, fn as injectStyles, g as withWidgetBoundary, gt as RegisteredBinding, h as DataWidget, ht as MetricRecords, i as chartColor, in as EmptyState, jt as StatusPanel, kt as DataSectionBoundary, l as ExplorationActionControl, ln as useDateFormatting, mt as sectionContent, n as createDataContext, nn as useInspectionDefaults, nt as Select, o as DataTableEmptyRow, pt as searchItems, qt as searchParams, rn as AppIcon, rt as dateTimeRangeLabel, sn as classNames, t as SectionHeading, tn as InspectionContext, tt as DateTimeRangePicker, un as useDataApp, v as ContentSkeletonBody, vt as exportDatasets, w as useDataAppTransport, wt as breakdownState, x as WidgetFrameContext, xt as DateTimeTooltip, y as getAnnotationProps, yt as registeredEvidence, z as AnnotationTooltip } from "./chunks/SectionHeading-DR8RX7YZ.js";
2
+ import { appDiagnostics, getDataAppTransport, navigateNewTab, navigateNewWindowOrTab } from "@altertable/data-app/client";
3
+ import { KEY_SEPARATOR, appUrlKeys, fixedUnitMilliseconds, invariant, readWidgetCaptureRequest, readWidgetId, reportWidgetCapture } from "@altertable/data-app/internal";
4
+ import { Component, Suspense, useCallback, useContext, useEffect, useEffectEvent, useId, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
5
5
  import { autoUpdate, flip, offset, shift, useFloating, useMergeRefs } from "@floating-ui/react";
6
6
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
7
  import { Eye, EyeOff, GripVertical, LoaderCircle, Minus, Trash2, X } from "lucide-react";
8
- import { formatCount, formatDateRange, formatDateTime, formatMetric, formatPercent, parseDateTime } from "@altertable/data-app/format";
8
+ import { formatCount, formatDateRange, formatDateTime, formatMetric, formatPercent, parseDateTime, pluralize } from "@altertable/data-app/format";
9
9
  import { parseDataAppAnnotationDraft, parseExternalUrl } from "@altertable/data-app/contract";
10
10
  import { createPortal } from "react-dom";
11
+ //#region src/ui/FocusedWidget.tsx
12
+ function readThemeOverride() {
13
+ const [theme, ...rest] = searchParams().getAll(appUrlKeys.theme);
14
+ if (rest.length === 0 && (theme === "light" || theme === "dark")) return theme;
15
+ }
16
+ function currentSearch() {
17
+ return searchParams().toString();
18
+ }
19
+ function FocusedWidgetSurface({ capture, ...props }) {
20
+ const transport = useDataAppTransport();
21
+ const subscribe = useCallback((listener) => transport?.subscribe(listener) ?? (() => {}), [transport]);
22
+ const search = useSyncExternalStore(subscribeSearch, currentSearch, () => "");
23
+ const request = useSyncExternalStore(subscribe, () => readWidgetCaptureRequest(transport?.snapshot(), search), () => void 0);
24
+ const { state } = capture;
25
+ const widgetId = "widgetId" in capture ? capture.widgetId : void 0;
26
+ useLayoutEffect(() => {
27
+ if (!request) return;
28
+ transport?.[reportWidgetCapture]?.(request, widgetId === void 0 ? { state: "invalid-target" } : {
29
+ state,
30
+ widgetId
31
+ });
32
+ }, [
33
+ transport,
34
+ request,
35
+ state,
36
+ widgetId
37
+ ]);
38
+ return /* @__PURE__ */ jsx("main", {
39
+ ...props,
40
+ className: "altertable-focused-widget",
41
+ "data-widget-state": state,
42
+ "data-focused-widget": widgetId
43
+ });
44
+ }
45
+ function useFocusedTarget(registry) {
46
+ const id = useSyncExternalStore(subscribeSearch, () => readWidgetId(searchParams()), () => void 0);
47
+ if (!registry || id === void 0) return null;
48
+ if (id === null) return {
49
+ kind: "invalid",
50
+ reason: "Provide one valid widget ID in the URL."
51
+ };
52
+ const widget = registry.get(id);
53
+ return widget ? {
54
+ kind: "widget",
55
+ widget
56
+ } : {
57
+ kind: "invalid",
58
+ reason: `No widget is registered as “${id}”.`
59
+ };
60
+ }
61
+ function FocusedWidget({ target }) {
62
+ const identity = useId();
63
+ const app = useDataApp();
64
+ const transport = useDataAppTransport();
65
+ const presentation = useDataAppPresentation(transport);
66
+ const theme = useSyncExternalStore(subscribeSearch, readThemeOverride, () => void 0);
67
+ const search = useSyncExternalStore(subscribeSearch, currentSearch, () => "");
68
+ useAppAppearance(app.appearance, theme ?? presentation?.theme);
69
+ if (target.kind === "invalid") return /* @__PURE__ */ jsx(FocusedWidgetSurface, {
70
+ capture: { state: "invalid-target" },
71
+ children: /* @__PURE__ */ jsx(StatusPanel, {
72
+ status: "error",
73
+ title: "Widget unavailable",
74
+ description: target.reason
75
+ })
76
+ });
77
+ const { widget } = target;
78
+ return /* @__PURE__ */ jsx(WidgetFrameContext, {
79
+ value: false,
80
+ children: /* @__PURE__ */ jsx(FocusedRenderBoundary, {
81
+ id: widget.id,
82
+ identity,
83
+ resetKey: search,
84
+ children: /* @__PURE__ */ jsx(FocusedWidgetResult, { widget })
85
+ })
86
+ });
87
+ }
88
+ var FocusedRenderBoundary = class extends Component {
89
+ state = {
90
+ failed: false,
91
+ resetKey: this.props.resetKey
92
+ };
93
+ static getDerivedStateFromProps(props, state) {
94
+ return props.resetKey === state.resetKey ? null : {
95
+ failed: false,
96
+ resetKey: props.resetKey
97
+ };
98
+ }
99
+ static getDerivedStateFromError() {
100
+ return { failed: true };
101
+ }
102
+ componentDidCatch(error) {
103
+ appDiagnostics.record("render", this.props.id, error, this.props.identity);
104
+ }
105
+ componentDidUpdate(_, previous) {
106
+ if (previous.failed && !this.state.failed) appDiagnostics.clear("render", this.props.id, this.props.identity);
107
+ }
108
+ componentWillUnmount() {
109
+ appDiagnostics.clear("render", this.props.id, this.props.identity);
110
+ }
111
+ render() {
112
+ return this.state.failed ? /* @__PURE__ */ jsx(FocusedWidgetSurface, {
113
+ capture: {
114
+ state: "error",
115
+ widgetId: this.props.id
116
+ },
117
+ children: /* @__PURE__ */ jsx(StatusPanel, {
118
+ status: "error",
119
+ title: "This widget couldn’t render"
120
+ })
121
+ }) : this.props.children;
122
+ }
123
+ };
124
+ function FocusedWidgetResult({ widget }) {
125
+ const section = sectionContent(widget.content);
126
+ const result = useDeclaredResult(section.view);
127
+ const view = result.view;
128
+ const { kind } = view;
129
+ const data = result.snapshot?.data;
130
+ const input = result.snapshot?.input;
131
+ const element = useRef(null);
132
+ const drawing = useMemo(() => kind === "ready" ? {
133
+ widget,
134
+ data,
135
+ input
136
+ } : void 0, [
137
+ kind,
138
+ data,
139
+ input,
140
+ widget
141
+ ]);
142
+ const [outcome, setOutcome] = useState();
143
+ const drawn = drawing && outcome?.drawing === drawing ? outcome.state : void 0;
144
+ const requestError = kind === "error" || kind === "stale-error" ? errorPresentation(view.error) : void 0;
145
+ let state = "loading";
146
+ if (requestError) state = "error";
147
+ else if (kind === "empty") state = "empty";
148
+ else if (drawn) state = drawn;
149
+ return /* @__PURE__ */ jsx(FocusedWidgetSurface, {
150
+ ref: element,
151
+ capture: {
152
+ state,
153
+ widgetId: widget.id
154
+ },
155
+ "aria-busy": state === "loading",
156
+ inert: true,
157
+ children: requestError ? /* @__PURE__ */ jsx(StatusPanel, {
158
+ status: "error",
159
+ title: requestError.title,
160
+ description: requestError.description
161
+ }) : kind === "empty" ? /* @__PURE__ */ jsx(EmptyState, { ...result.emptyFallback }) : drawn === "error" ? /* @__PURE__ */ jsx(StatusPanel, {
162
+ status: "error",
163
+ title: "This widget couldn’t finish rendering"
164
+ }) : /* @__PURE__ */ jsxs(Suspense, {
165
+ fallback: /* @__PURE__ */ jsx(WidgetLoading, { reset: setOutcome }),
166
+ children: [
167
+ /* @__PURE__ */ jsx(DateFormattingContext, {
168
+ value: { timeZone: result.timeZone },
169
+ children: /* @__PURE__ */ jsx(WidgetContent, { render: () => kind === "ready" ? section.children(view.data, view.input) : section.loadingFallback })
170
+ }),
171
+ state === "loading" && /* @__PURE__ */ jsx(LoadingStatus, { label: "Loading widget" }),
172
+ drawing && /* @__PURE__ */ jsx(DrawingObserver, {
173
+ element,
174
+ drawing,
175
+ settle: setOutcome
176
+ })
177
+ ]
178
+ })
179
+ });
180
+ }
181
+ function WidgetLoading({ reset }) {
182
+ useLayoutEffect(() => reset(void 0), [reset]);
183
+ return /* @__PURE__ */ jsx(LoadingStatus, { label: "Loading widget" });
184
+ }
185
+ function WidgetContent({ render }) {
186
+ return render();
187
+ }
188
+ /** Settles a drawing once custom rendering, fonts, and the next frame are done. */
189
+ function DrawingObserver({ element, drawing, settle }) {
190
+ useLayoutEffect(() => {
191
+ const abort = new AbortController();
192
+ const { signal } = abort;
193
+ async function wait() {
194
+ await Promise.resolve();
195
+ if (signal.aborted || !element.current) return;
196
+ await drawing.widget.waitForReady?.(element.current, signal);
197
+ if (signal.aborted) return;
198
+ await document.fonts.ready;
199
+ if (signal.aborted) return;
200
+ await new Promise((resolve) => requestAnimationFrame(() => resolve()));
201
+ }
202
+ wait().then(() => {
203
+ if (!signal.aborted) settle({
204
+ drawing,
205
+ state: "ready"
206
+ });
207
+ }, () => {
208
+ if (!signal.aborted) settle({
209
+ drawing,
210
+ state: "error"
211
+ });
212
+ });
213
+ return () => abort.abort();
214
+ }, [
215
+ element,
216
+ drawing,
217
+ settle
218
+ ]);
219
+ return null;
220
+ }
221
+ //#endregion
11
222
  //#region src/ui/DataApp.tsx
12
- /** Executes the primary view and its summary views, and owns controls, inspection, exports, and stories. */
13
223
  function DataApp(props) {
224
+ const target = useFocusedTarget((props.view && getViewDefinition(props.view).clientFilters)?.widgets);
225
+ if (target) return /* @__PURE__ */ jsx(FocusedWidget, { target }, target.kind === "widget" ? target.widget.id : void 0);
226
+ if (!props.view) return /* @__PURE__ */ jsx(DataAppFrame, { ...props });
227
+ return /* @__PURE__ */ jsx(ViewDataApp, { ...props });
228
+ }
229
+ function ViewDataApp(props) {
14
230
  const { summaryViews = [], ...appProps } = props;
15
231
  const { clientFilters } = getViewDefinition(props.view);
16
232
  return /* @__PURE__ */ jsx(AppFilterControls, {
@@ -85,6 +301,7 @@ function PrimaryDataApp(props) {
85
301
  ...controls,
86
302
  queries: allResults.flatMap(({ queries }) => queries ?? []),
87
303
  refreshing: allResults.some(({ refreshing }) => refreshing),
304
+ viewRefreshing: primary.refreshing,
88
305
  refetch() {
89
306
  for (const { refetch } of allResults) refetch();
90
307
  },
@@ -123,7 +340,10 @@ function PrimaryDataApp(props) {
123
340
  value: {
124
341
  primaryView: view,
125
342
  clientFilters,
126
- results: new Map(results).set(view, result)
343
+ results: new Map(results).set(view, {
344
+ ...result,
345
+ refreshing: primary.refreshing
346
+ })
127
347
  },
128
348
  children: /* @__PURE__ */ jsx(DetailRoutes, {
129
349
  details,
@@ -168,6 +388,478 @@ function GridItem({ children, span = 1, className, ...props }) {
168
388
  });
169
389
  }
170
390
  //#endregion
391
+ //#region src/ui/DataValue.tsx
392
+ /** Bind inline content to displayed data. Keep static wording outside this span. */
393
+ function DataValue$1({ reading, loadingFallback, children, ...props }) {
394
+ return /* @__PURE__ */ jsx("span", {
395
+ ...props,
396
+ "aria-busy": reading.loading || props["aria-busy"],
397
+ children: reading.loading ? loadingFallback : children(reading.value)
398
+ });
399
+ }
400
+ //#endregion
401
+ //#region src/ui/metric-comparison.ts
402
+ /** Label a comparison from the input that produced the displayed result. Null means the
403
+ * requested previous period has no comparable value; zero remains a measured value. */
404
+ function dateTimeMetricComparison(displayedInput, values, options = {}) {
405
+ if (!displayedInput.comparison) return void 0;
406
+ function label(range) {
407
+ return dateTimeRangeLabel(range, options);
408
+ }
409
+ return {
410
+ current: {
411
+ value: values.current,
412
+ formattedValue: formatMetric(values.current, values.format),
413
+ periodLabel: label(displayedInput.range)
414
+ },
415
+ previous: {
416
+ value: values.previous,
417
+ formattedValue: values.previous === null ? "Not available" : formatMetric(values.previous, values.format),
418
+ periodLabel: label(displayedInput.comparison)
419
+ },
420
+ favorableDirection: values.favorableDirection
421
+ };
422
+ }
423
+ /** A zero or missing baseline has no meaningful relative percentage. */
424
+ function comparisonChange({ current, previous, favorableDirection }) {
425
+ const percent = previous?.value ? (current.value - previous.value) / Math.abs(previous.value) * 100 : null;
426
+ const direction = percent === null || Math.abs(percent) < .05 ? "flat" : percent > 0 ? "up" : "down";
427
+ return {
428
+ percent,
429
+ direction,
430
+ tone: direction === "flat" || !favorableDirection ? "neutral" : direction === favorableDirection ? "good" : "bad",
431
+ icon: direction === "up" ? "trendUp" : direction === "down" ? "trendDown" : "trendFlat"
432
+ };
433
+ }
434
+ //#endregion
435
+ //#region src/ui/metric.ts
436
+ function metricComparison(metric, reading, options = {}) {
437
+ if (reading.loading || !reading.value.period) return void 0;
438
+ return dateTimeMetricComparison(reading.value.period, {
439
+ current: reading.value.current,
440
+ previous: reading.value.previous ?? null,
441
+ format: metric.format,
442
+ favorableDirection: metric.favorableDirection
443
+ }, options);
444
+ }
445
+ //#endregion
446
+ //#region src/ui/widget-views.ts
447
+ function validateWidgetViews(views, selected) {
448
+ const ids = new Set(views.map((view) => view.id));
449
+ invariant(views.length > 0 && ids.size === views.length && views.every((view) => !!view.id.trim()), "Widget tab IDs must be nonempty and unique.");
450
+ invariant(ids.has(selected), `Unknown widget tab: ${selected}.`);
451
+ }
452
+ //#endregion
453
+ //#region src/ui/WidgetViewTabs.tsx
454
+ function WidgetViewTabs({ label, views, selectedKey, onSelectionChange, className, ...props }) {
455
+ validateWidgetViews(views, selectedKey);
456
+ return /* @__PURE__ */ jsx("div", {
457
+ ...props,
458
+ className: classNames("altertable-widget-view-tabs", className),
459
+ children: /* @__PURE__ */ jsxs(Tabs, {
460
+ selectedKey,
461
+ onSelectionChange: (key) => onSelectionChange(String(key)),
462
+ children: [/* @__PURE__ */ jsx(SegmentedTabList, {
463
+ "aria-label": label,
464
+ children: views.map((view) => /* @__PURE__ */ jsx(SegmentedTab, {
465
+ id: view.id,
466
+ children: view.label
467
+ }, view.id))
468
+ }), /* @__PURE__ */ jsx(TabPanels, { children: views.map((view) => /* @__PURE__ */ jsx(TabPanel, {
469
+ id: view.id,
470
+ children: view.isEmpty ? /* @__PURE__ */ jsx(EmptyState, { ...view.emptyFallback }) : view.content
471
+ }, view.id)) })]
472
+ })
473
+ });
474
+ }
475
+ //#endregion
476
+ //#region src/ui/VisualizationWidget.tsx
477
+ /** Compose an unframed visual with the shared heading and inspection. */
478
+ function VisualizationWidget$1(props) {
479
+ if ("views" in props && props.views) return /* @__PURE__ */ jsx(VisualizationWidgetWithViews, { ...props });
480
+ if ("reading" in props) {
481
+ const { reading, children, isEmpty, emptyFallback, skeleton, footer, ...shell } = props;
482
+ return /* @__PURE__ */ jsx(DataWidget, {
483
+ ...shell,
484
+ reading,
485
+ isEmpty,
486
+ emptyFallback,
487
+ skeleton,
488
+ footer,
489
+ children: (data) => /* @__PURE__ */ jsx("div", {
490
+ className: "altertable-visualization-widget-content",
491
+ children: children(data)
492
+ })
493
+ });
494
+ }
495
+ const { visual, loading = false, loadingContent, footer, ...shell } = props;
496
+ if (loading) return /* @__PURE__ */ jsx(DataWidget, {
497
+ ...shell,
498
+ footer,
499
+ "aria-busy": true,
500
+ children: /* @__PURE__ */ jsx("div", {
501
+ className: "altertable-visualization-widget-content",
502
+ children: loadingContent ?? /* @__PURE__ */ jsx(ContentSkeletonBody, { variant: "panel" })
503
+ })
504
+ });
505
+ return /* @__PURE__ */ jsx(DataWidget, {
506
+ ...shell,
507
+ footer,
508
+ children: /* @__PURE__ */ jsx("div", {
509
+ className: "altertable-visualization-widget-content",
510
+ children: visual
511
+ })
512
+ });
513
+ }
514
+ function VisualizationWidgetWithViews({ reading, views, viewLabel, initialView, isEmpty, emptyFallback, skeleton, footer, ...shell }) {
515
+ const [selected, setSelected] = useState(initialView ?? views[0]?.id ?? "");
516
+ validateWidgetViews(views, selected);
517
+ return /* @__PURE__ */ jsx(DataWidget, {
518
+ ...shell,
519
+ reading,
520
+ isEmpty,
521
+ emptyFallback,
522
+ skeleton,
523
+ footer,
524
+ children: (data) => /* @__PURE__ */ jsx("div", {
525
+ className: "altertable-visualization-widget-content",
526
+ children: /* @__PURE__ */ jsx(WidgetViewTabs, {
527
+ label: viewLabel,
528
+ views: views.map((view) => ({
529
+ id: view.id,
530
+ label: view.label,
531
+ content: view.render(data),
532
+ isEmpty: false,
533
+ emptyFallback
534
+ })),
535
+ selectedKey: selected,
536
+ onSelectionChange: setSelected
537
+ })
538
+ })
539
+ });
540
+ }
541
+ //#endregion
542
+ //#region src/ui/MetricWidget.tsx
543
+ function MetricWidget$1(props) {
544
+ const dateFormatting = useDateFormatting();
545
+ if ("metric" in props) {
546
+ const { metric, reading, ...rest } = props;
547
+ if (reading.loading) return /* @__PURE__ */ jsx(MetricWidgetContent$1, {
548
+ ...rest,
549
+ label: metric.label,
550
+ evidence: metric.evidence,
551
+ loading: true
552
+ });
553
+ return /* @__PURE__ */ jsx(MetricWidgetContent$1, {
554
+ ...rest,
555
+ label: metric.label,
556
+ value: reading.value.current,
557
+ format: metric.format,
558
+ evidence: metric.evidence,
559
+ comparison: metricComparison(metric, reading, dateFormatting)
560
+ });
561
+ }
562
+ return /* @__PURE__ */ jsx(MetricWidgetContent$1, { ...props });
563
+ }
564
+ function MetricWidgetContent$1({ label, annotationId, value, content, format, loading = false, description, comparison, evidence, records, action, status, visual, className, ...props }) {
565
+ return /* @__PURE__ */ jsx(VisualizationWidget$1, {
566
+ ...props,
567
+ className: classNames("altertable-metric-widget", className),
568
+ title: label,
569
+ annotationId,
570
+ evidence,
571
+ records,
572
+ "aria-busy": loading || props["aria-busy"],
573
+ action,
574
+ status,
575
+ visual: /* @__PURE__ */ jsx(MetricVisual, {
576
+ loading,
577
+ value,
578
+ content,
579
+ format,
580
+ comparison,
581
+ description,
582
+ visual
583
+ })
584
+ });
585
+ }
586
+ function MetricVisual({ loading, value, content, format, comparison, description, visual }) {
587
+ const shownValue = format ? formatMetric(value, format) : content;
588
+ const change = comparison ? comparisonChange(comparison) : null;
589
+ const shownTrend = change?.percent != null ? /* @__PURE__ */ jsxs("span", {
590
+ className: "altertable-metric-change",
591
+ "data-tone": change.tone,
592
+ children: [
593
+ /* @__PURE__ */ jsx(AppIcon, {
594
+ name: change.icon,
595
+ size: 14
596
+ }),
597
+ Math.abs(change.percent).toFixed(1),
598
+ "% vs",
599
+ " ",
600
+ comparison?.previous?.periodLabel?.toLowerCase() ?? "previous period"
601
+ ]
602
+ }) : comparison?.previous?.value === null ? /* @__PURE__ */ jsx("span", {
603
+ className: "altertable-metric-change",
604
+ "data-tone": "neutral",
605
+ children: "Previous period unavailable"
606
+ }) : null;
607
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
608
+ /* @__PURE__ */ jsxs("div", {
609
+ className: "altertable-metric-reading",
610
+ children: [/* @__PURE__ */ jsx("strong", {
611
+ className: "altertable-metric-value",
612
+ "data-unavailable": shownValue === "—" || void 0,
613
+ children: loading ? /* @__PURE__ */ jsx(Skeleton, { className: "altertable-metric-loading-value" }) : shownValue
614
+ }), shownTrend && /* @__PURE__ */ jsx("span", {
615
+ className: "altertable-metric-trend",
616
+ children: shownTrend
617
+ })]
618
+ }),
619
+ description && /* @__PURE__ */ jsx("small", {
620
+ className: "altertable-metric-description",
621
+ children: description
622
+ }),
623
+ visual && /* @__PURE__ */ jsx("div", {
624
+ className: "altertable-metric-visual",
625
+ children: visual
626
+ })
627
+ ] });
628
+ }
629
+ //#endregion
630
+ //#region src/ui/TableWidget.tsx
631
+ function TableWidget$1(props) {
632
+ const { pagination, limit, columns } = props;
633
+ invariant(!pagination || Number.isSafeInteger(pagination.pageSize) && pagination.pageSize >= 1, "TableWidget pagination.pageSize must be a positive integer.");
634
+ invariant(limit === void 0 || Number.isSafeInteger(limit) && limit >= 1, "TableWidget limit must be a positive integer.");
635
+ const columnIds = columns.map((column) => column.id);
636
+ invariant(columnIds.length > 0 && columnIds.every((id) => !!id.trim()) && new Set(columnIds).size === columnIds.length, "TableWidget column IDs must be nonempty and unique.");
637
+ if (props.reading) {
638
+ const { reading, skeletonRows, ...rest } = props;
639
+ return /* @__PURE__ */ jsx(TableWidgetContent$1, {
640
+ ...rest,
641
+ rows: reading.loading ? [] : reading.value,
642
+ loading: reading.loading,
643
+ skeletonRows
644
+ });
645
+ }
646
+ return /* @__PURE__ */ jsx(TableWidgetContent$1, { ...props });
647
+ }
648
+ function TableWidgetContent$1({ title, count, showCount = true, onClearFilters, description, columns, rows, rowKey, action, evidence, search, limit, pagination, emptyFallback, noMatchesFallback, loading = false, skeletonRows, ...props }) {
649
+ const keys = rows.map(rowKey);
650
+ invariant(keys.every((key) => typeof key === "string" ? !!key.trim() : Number.isFinite(key)) && new Set(keys.map(String)).size === keys.length, "TableWidget row keys must be nonempty and unique.");
651
+ const rowKeys = JSON.stringify(keys);
652
+ const pageSize = pagination === false || limit !== void 0 ? null : pagination?.pageSize ?? 10;
653
+ const [pageState, setPageState] = useState({
654
+ page: 0,
655
+ rowKeys,
656
+ searchValue: search?.value,
657
+ pageSize
658
+ });
659
+ if (pageState.rowKeys !== rowKeys || pageState.searchValue !== search?.value || pageState.pageSize !== pageSize) setPageState({
660
+ page: 0,
661
+ rowKeys,
662
+ searchValue: search?.value,
663
+ pageSize
664
+ });
665
+ const hits = search ? searchItems(rows, search.value, {
666
+ attributes: search.attributes,
667
+ mode: search.mode,
668
+ fuzzyThreshold: search.fuzzyThreshold
669
+ }) : rows.map((item) => ({
670
+ item,
671
+ score: 0,
672
+ matches: {}
673
+ }));
674
+ const pageCount = pageSize ? Math.max(1, Math.ceil(hits.length / pageSize)) : 1;
675
+ const page = Math.min(pageState.page, pageCount - 1);
676
+ const start = pageSize ? page * pageSize : 0;
677
+ const visible = hits.slice(start, pageSize ? start + pageSize : Math.max(0, limit ?? hits.length));
678
+ const pager = pageSize && pageCount > 1 && /* @__PURE__ */ jsxs("nav", {
679
+ className: "altertable-table-pagination",
680
+ "aria-label": "Table pages",
681
+ children: [/* @__PURE__ */ jsxs("span", {
682
+ className: "altertable-table-pagination-range",
683
+ children: [
684
+ formatCount(start + 1),
685
+ "–",
686
+ formatCount(start + visible.length),
687
+ " of",
688
+ " ",
689
+ formatCount(hits.length),
690
+ " ",
691
+ pluralize(hits.length, "result")
692
+ ]
693
+ }), /* @__PURE__ */ jsxs("span", {
694
+ className: "altertable-table-pagination-controls",
695
+ children: [
696
+ /* @__PURE__ */ jsxs("span", { children: [
697
+ "Page ",
698
+ page + 1,
699
+ " of ",
700
+ pageCount
701
+ ] }),
702
+ /* @__PURE__ */ jsx(Tooltip, {
703
+ content: "Previous page",
704
+ children: /* @__PURE__ */ jsx(Button, {
705
+ size: "icon-compact",
706
+ "aria-label": "Previous page",
707
+ disabled: page === 0,
708
+ onClick: () => setPageState({
709
+ page: page - 1,
710
+ rowKeys,
711
+ searchValue: search?.value,
712
+ pageSize
713
+ }),
714
+ children: /* @__PURE__ */ jsx(AppIcon, {
715
+ name: "previousMonth",
716
+ size: 16
717
+ })
718
+ })
719
+ }),
720
+ /* @__PURE__ */ jsx(Tooltip, {
721
+ content: "Next page",
722
+ children: /* @__PURE__ */ jsx(Button, {
723
+ size: "icon-compact",
724
+ "aria-label": "Next page",
725
+ disabled: page >= pageCount - 1,
726
+ onClick: () => setPageState({
727
+ page: page + 1,
728
+ rowKeys,
729
+ searchValue: search?.value,
730
+ pageSize
731
+ }),
732
+ children: /* @__PURE__ */ jsx(AppIcon, {
733
+ name: "nextMonth",
734
+ size: 16
735
+ })
736
+ })
737
+ })
738
+ ]
739
+ })]
740
+ });
741
+ return /* @__PURE__ */ jsx(VisualizationWidget$1, {
742
+ ...props,
743
+ className: classNames("altertable-table-widget", props.className),
744
+ title,
745
+ count: loading || !showCount ? void 0 : count ?? hits.length,
746
+ description,
747
+ action,
748
+ evidence,
749
+ "aria-busy": loading || props["aria-busy"],
750
+ footer: pager,
751
+ visual: /* @__PURE__ */ jsx("div", {
752
+ className: "altertable-table-widget-content",
753
+ children: /* @__PURE__ */ jsx(TableWidgetTable, {
754
+ columns,
755
+ visible,
756
+ rowKey,
757
+ rowCount: rows.length,
758
+ matchCount: hits.length,
759
+ search,
760
+ emptyFallback,
761
+ noMatchesFallback,
762
+ onClearFilters,
763
+ loading,
764
+ skeletonRows: skeletonRows ?? limit ?? (pagination ? pagination.pageSize : void 0) ?? 5
765
+ })
766
+ })
767
+ });
768
+ }
769
+ /** Each page or inspection mount owns its input and recovery focus. */
770
+ function TableWidgetTable({ columns, visible, rowKey, rowCount, matchCount, search, emptyFallback, noMatchesFallback, onClearFilters, loading, skeletonRows }) {
771
+ const tableRef = useRef(null);
772
+ const searchInputRef = useRef(null);
773
+ const searchRef = useMergeRefs([searchInputRef, search?.inputProps?.ref]);
774
+ const searchable = search && {
775
+ label: search.label,
776
+ placeholder: search.placeholder,
777
+ value: search.value,
778
+ onChange: search.onChange,
779
+ resetValue: search.resetValue,
780
+ inputProps: {
781
+ ...search.inputProps,
782
+ ref: searchRef
783
+ },
784
+ itemCount: rowCount
785
+ };
786
+ const searchHasNoMatches = rowCount > 0 && matchCount === 0 && !!search;
787
+ const canClearSearch = searchHasNoMatches && search && search.value !== (search.resetValue ?? "");
788
+ function clearSearch() {
789
+ search?.onChange(search.resetValue ?? "");
790
+ requestAnimationFrame(() => (searchInputRef.current ?? tableRef.current)?.focus());
791
+ }
792
+ function clearFilters() {
793
+ onClearFilters?.();
794
+ tableRef.current?.focus();
795
+ }
796
+ const emptyContent = searchHasNoMatches || rowCount === 0 && !!onClearFilters ? noMatchesFallback ?? {
797
+ title: "No matching results",
798
+ description: searchHasNoMatches ? "Try a different search." : "Try different filters."
799
+ } : emptyFallback;
800
+ const recovery = canClearSearch ? /* @__PURE__ */ jsx(Button, {
801
+ onClick: clearSearch,
802
+ children: "Clear search"
803
+ }) : rowCount === 0 && onClearFilters ? /* @__PURE__ */ jsx(Button, {
804
+ onClick: clearFilters,
805
+ children: "Clear filters"
806
+ }) : void 0;
807
+ const emptyAction = recovery ? /* @__PURE__ */ jsxs(Fragment$1, { children: [emptyContent.action, recovery] }) : emptyContent.action;
808
+ return /* @__PURE__ */ jsxs(DataTable, {
809
+ ref: tableRef,
810
+ tabIndex: -1,
811
+ searchable: loading ? void 0 : searchable,
812
+ "aria-busy": loading || void 0,
813
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: columns.map((column) => /* @__PURE__ */ jsx("th", {
814
+ scope: "col",
815
+ "data-type": column.type,
816
+ children: column.header
817
+ }, column.id)) }) }), /* @__PURE__ */ jsx("tbody", {
818
+ "aria-hidden": loading || void 0,
819
+ children: loading ? Array.from({ length: Math.min(100, Math.max(0, Math.trunc(skeletonRows) || 0)) }, (_, row) => /* @__PURE__ */ jsx("tr", { children: columns.map((column) => /* @__PURE__ */ jsx("td", {
820
+ "data-type": column.type,
821
+ children: /* @__PURE__ */ jsx(Skeleton, { style: {
822
+ width: "70%",
823
+ height: "1lh"
824
+ } })
825
+ }, column.id)) }, row)) : visible.length === 0 ? /* @__PURE__ */ jsx(DataTableEmptyRow, {
826
+ colSpan: columns.length,
827
+ ...emptyContent,
828
+ action: emptyAction
829
+ }) : visible.map((hit) => /* @__PURE__ */ jsx("tr", { children: columns.map((column, index) => index === 0 ? /* @__PURE__ */ jsx("th", {
830
+ scope: "row",
831
+ "data-type": column.type,
832
+ children: column.cell(hit.item, hit)
833
+ }, column.id) : /* @__PURE__ */ jsx("td", {
834
+ "data-type": column.type,
835
+ children: column.cell(hit.item, hit)
836
+ }, column.id)) }, rowKey(hit.item)))
837
+ })]
838
+ });
839
+ }
840
+ //#endregion
841
+ //#region src/ui/TextWidget.tsx
842
+ function TextWidget$1(props) {
843
+ const content = props.reading ? props.reading.loading ? null : props.children(props.reading.value) : props.children;
844
+ const { reading, children: _, className, ...shell } = props;
845
+ const loading = reading?.loading === true;
846
+ return /* @__PURE__ */ jsx(DataWidget, {
847
+ ...shell,
848
+ className: classNames("altertable-text-widget", className),
849
+ evidence: shell.evidence,
850
+ "aria-busy": loading || shell["aria-busy"],
851
+ children: /* @__PURE__ */ jsx(TextContent, { children: loading ? /* @__PURE__ */ jsxs("div", {
852
+ className: "altertable-text-widget-skeleton",
853
+ "aria-hidden": "true",
854
+ children: [
855
+ /* @__PURE__ */ jsx(Skeleton, {}),
856
+ /* @__PURE__ */ jsx(Skeleton, {}),
857
+ /* @__PURE__ */ jsx(Skeleton, {})
858
+ ]
859
+ }) : content })
860
+ });
861
+ }
862
+ //#endregion
171
863
  //#region src/widgets.tsx
172
864
  function MetricWidgetContent({ metric, source, records, actions, action, ...presentation }) {
173
865
  const navigation = useDetailNavigation();