@altertable/data-app-react 0.76.0 → 0.77.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,22 +1,111 @@
1
- import { $t as Button, At as resolveActions, C as ContentSkeleton, Ct as DetailContent, D as TextContent, Dt as DataSectionBoundary, E as DataAppFrame, Et as useDetailNavigation, H as PrimaryViewContext, J as dateTimeRangeVariable, Jt as shortcuts, K as choiceVariable, L as IconButton, Nt as mountDataApp, O as Stack, Qt as EmptyState, R as useDataAppAnnotations, S as withWidgetBoundary, T as DataValue$1, Tt as DetailView, U as useDeclaredResult, Ut as Tooltip, V as createDataHooks, Vt as Sheet, Wt as TooltipProvider, X as searchVariable, Xt as useInspectionDefaults, Y as multiChoiceVariable, Yt as InspectionContext, Zt as AppIcon, _t as datasetTable, a as TextWidget$1, an as injectDataAppStyles, at as DateTimeRangePicker, bt as DateDisplay, ct as Skeleton, 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 breakdownState, kt as ownedSource, m as comparisonChange, mt as sectionContent, n as createDataContext, nn as DateFormattingContext, o as TableWidget$1, on as injectStyles, ot as Select, p as metricComparison, q as dateTimeRangePresets, qt as Kbd, rn as useDateFormatting, t as SectionHeading, tn as classNames, vt as exportDatasets, w as getAnnotationProps, wt as DetailRoutes, xt as DateTimeTooltip, yt as registeredEvidence, z as AnnotationTooltip } from "./chunks/SectionHeading-DLVTKa91.js";
1
+ import { At as ownedSource, Bt as Sheet, C as ContentSkeleton, Ct as breakdownState, D as TextContent, Dt as useDetailNavigation, E as DataAppFrame, Et as DetailView, G as useDeclaredResult, H as AppViewResultsContext, Ht as Tooltip, Jt as InspectionContext, Kt as Kbd, L as IconButton, Mt as mountDataApp, O as Stack, Ot as DataSectionBoundary, Qt as Button, R as useDataAppAnnotations, S as withWidgetBoundary, St as resolveActions, T as DataValue$1, Tt as DetailRoutes, U as assertAppFilters, Ut as TooltipProvider, V as createDataHooks, W as getViewDefinition, Xt as AppIcon, Yt as useInspectionDefaults, Zt as EmptyState, _t as exportDatasets, a as TextWidget$1, an as injectStyles, bt as DateTimeTooltip, d as MetricWidget$1, en as classNames, f as VisualizationWidget$1, gt as datasetTable, h as ExplorationActionControl, ht as RegisteredBinding, i as chartColor, in as injectDataAppStyles, it as Skeleton, m as comparisonChange, mt as MetricRecords, n as createDataContext, nn as useDateFormatting, nt as Select, o as TableWidget$1, p as metricComparison, pt as sectionContent, qt as shortcuts, rn as useDataApp, t as SectionHeading, tn as DateFormattingContext, tt as DateTimeRangePicker, ut as SearchSuggestionsContext, vt as registeredEvidence, w as getAnnotationProps, wt as DetailContent, yt as DateDisplay, z as AnnotationTooltip } from "./chunks/SectionHeading-Bz5RIXit.js";
2
2
  import { getDataAppTransport, navigateNewTab, navigateNewWindowOrTab } from "@altertable/data-app/client";
3
3
  import { KEY_SEPARATOR, fixedUnitMilliseconds, invariant } from "@altertable/data-app/internal";
4
- import { useContext, useEffect, useEffectEvent, useImperativeHandle, useReducer, useRef, useState } from "react";
4
+ import { useCallback, useContext, useEffect, useEffectEvent, useImperativeHandle, useReducer, useRef, useState } 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 { parseDataAppAnnotationDraft, parseExternalUrl } from "@altertable/data-app/contract";
9
8
  import { formatCount, formatDateRange, formatDateTime, formatMetric, formatPercent, parseDateTime } from "@altertable/data-app/format";
9
+ import { parseDataAppAnnotationDraft, parseExternalUrl } from "@altertable/data-app/contract";
10
10
  import { createPortal } from "react-dom";
11
11
  //#region src/ui/DataApp.tsx
12
- /** Executes the primary view and owns its controls, inspection, exports, and stories. */
12
+ /** Executes the primary view and its summary views, and owns controls, inspection, exports, and stories. */
13
13
  function DataApp(props) {
14
- const { view, datasets, story, showSearchSuggestions = true, details = [], children, ...frame } = props;
15
- const app = useDataApp();
14
+ const { summaryViews = [], ...appProps } = props;
15
+ const { clientFilters } = getViewDefinition(props.view);
16
+ return /* @__PURE__ */ jsx(AppFilterControls, {
17
+ clientFilters,
18
+ children: (controls) => /* @__PURE__ */ jsx(SummaryResults, {
19
+ views: summaryViews,
20
+ results: [],
21
+ children: (summaries) => /* @__PURE__ */ jsx(PrimaryDataApp, {
22
+ ...appProps,
23
+ clientFilters,
24
+ controls,
25
+ summaries
26
+ })
27
+ })
28
+ });
29
+ }
30
+ /** Render the client's filter controls once for the whole app. */
31
+ function AppFilterControls({ clientFilters, children }) {
32
+ return children(clientFilters.useControls());
33
+ }
34
+ /** Subscribe to each summary view in order, one hook call per component. */
35
+ function SummaryResults(props) {
36
+ const view = props.views[props.results.length];
37
+ if (!view) return props.children(props.results);
38
+ return /* @__PURE__ */ jsx(SummaryViewResult, {
39
+ ...props,
40
+ view
41
+ });
42
+ }
43
+ function SummaryViewResult({ view, ...props }) {
16
44
  const result = useDeclaredResult(view);
17
- const source = ownedSource(view, result.snapshot ?? { loading: true });
45
+ return /* @__PURE__ */ jsx(SummaryResults, {
46
+ ...props,
47
+ results: [...props.results, {
48
+ view,
49
+ result
50
+ }]
51
+ });
52
+ }
53
+ function PrimaryDataApp(props) {
54
+ const { view, clientFilters, controls, summaries, datasets, story, showSearchSuggestions = true, details = [], children, ...frame } = props;
55
+ const app = useDataApp();
56
+ const primary = useDeclaredResult(view);
57
+ const results = new Map([[view, primary], ...summaries.map(({ view, result }) => [view, result])]);
58
+ const owners = [...results.keys()];
59
+ assertAppFilters(view, clientFilters);
60
+ for (const summary of summaries) {
61
+ invariant(summary.result.dataContext === primary.dataContext, "Summary views must share the app view’s data context.");
62
+ assertAppFilters(summary.view, clientFilters);
63
+ }
64
+ const datasetOwners = (datasets ?? []).map((dataset) => {
65
+ const owner = RegisteredBinding.owner(dataset);
66
+ invariant(owner && results.has(owner), "A toolbar dataset must belong to the app view or one of its summary views.");
67
+ return owner;
68
+ });
69
+ /** Read the owners' displayed snapshots, marked for their bindings, once each has loaded. */
70
+ function readDisplayed(sourceOwners, read) {
71
+ const snapshots = sourceOwners.map((owner) => results.get(owner)?.snapshot);
72
+ if (!snapshots.every(isDefined)) return { loading: true };
73
+ return {
74
+ loading: false,
75
+ value: read(snapshots.map((snapshot, index) => ownedSource(sourceOwners[index], snapshot)))
76
+ };
77
+ }
78
+ /** The owner's displayed snapshot, or its loading state, marked for its bindings. */
79
+ function sourceOf(owner) {
80
+ return ownedSource(owner, results.get(owner)?.snapshot ?? { loading: true });
81
+ }
82
+ const allResults = [...results.values()];
83
+ const result = {
84
+ ...primary,
85
+ ...controls,
86
+ queries: allResults.flatMap(({ queries }) => queries ?? []),
87
+ refreshing: allResults.some(({ refreshing }) => refreshing),
88
+ refetch() {
89
+ for (const { refetch } of allResults) refetch();
90
+ },
91
+ cancel() {
92
+ for (const { cancel } of allResults) cancel();
93
+ }
94
+ };
95
+ const storyReading = story && readDisplayed(owners, ([snapshot, ...summarySnapshots]) => story(snapshot, ...summarySnapshots).map((finding) => ({
96
+ ...finding,
97
+ evidence: registeredEvidence(finding.evidence, owners)
98
+ })));
99
+ const csvExport = datasets && readDisplayed([view, ...datasetOwners], ([snapshot, ...snapshots]) => exportDatasets({
100
+ tables: datasets.map((dataset, index) => ({
101
+ dataset,
102
+ snapshot: snapshots[index]
103
+ })),
104
+ scope: view.scope(snapshot),
105
+ appTitle: app.title
106
+ }));
18
107
  const suggestionGroups = showSearchSuggestions && frame.showSearch !== false && result.searchControls ? (datasets ?? []).flatMap((dataset, index) => {
19
- const reading = dataset.readSearchSuggestions(source);
108
+ const reading = dataset.readSearchSuggestions(sourceOf(datasetOwners[index]));
20
109
  if (!reading) return [];
21
110
  return [reading.loading ? [] : reading.value.map((item) => ({
22
111
  ...item,
@@ -30,10 +119,11 @@ function DataApp(props) {
30
119
  groups: suggestionGroups,
31
120
  busy: result.refreshing
32
121
  } : null,
33
- children: /* @__PURE__ */ jsx(PrimaryViewContext, {
122
+ children: /* @__PURE__ */ jsx(AppViewResultsContext, {
34
123
  value: {
35
- declaration: view,
36
- result
124
+ primaryView: view,
125
+ clientFilters,
126
+ results: new Map(results).set(view, result)
37
127
  },
38
128
  children: /* @__PURE__ */ jsx(DetailRoutes, {
39
129
  details,
@@ -41,11 +131,8 @@ function DataApp(props) {
41
131
  ...frame,
42
132
  request: result,
43
133
  dataContext: result.dataContext,
44
- story: story ? (snapshot) => story(ownedSource(view, snapshot)).map((finding) => ({
45
- ...finding,
46
- evidence: registeredEvidence(finding.evidence, view)
47
- })) : void 0,
48
- csvExport: datasets ? (snapshot) => exportDatasets(datasets, ownedSource(view, snapshot), view.scope(snapshot), app.title) : void 0,
134
+ story: storyReading,
135
+ csvExport,
49
136
  children
50
137
  })
51
138
  })
@@ -53,6 +140,9 @@ function DataApp(props) {
53
140
  })
54
141
  });
55
142
  }
143
+ function isDefined(value) {
144
+ return value !== void 0;
145
+ }
56
146
  //#endregion
57
147
  //#region src/ui/Grid.tsx
58
148
  /** Responsive layout for peer cards and panels. Cards keep their content height by default. */
@@ -142,7 +232,7 @@ function VisualizationWidgetContent({ dataset, source, title, actions, breakdown
142
232
  const action = state ? /* @__PURE__ */ jsx("div", {
143
233
  ref: controlRef,
144
234
  children: /* @__PURE__ */ jsx(Select, {
145
- label: state.variable.label ?? "Break down by",
235
+ label: state.filter.label ?? "Break down by",
146
236
  labelPlacement: "inline",
147
237
  icon: "breakdown",
148
238
  size: "compact",
@@ -369,33 +459,72 @@ function ComparisonContent({ label, current, previous, favorableDirection, empha
369
459
  });
370
460
  }
371
461
  //#endregion
462
+ //#region src/ui/useHasNearedViewport.ts
463
+ /** Start requests slightly before a section scrolls into view so it is ready on arrival. */
464
+ const PREFETCH_MARGIN = "200px 0px";
465
+ /** Track whether an element has come within the prefetch margin of the viewport.
466
+ * The answer latches to true: a section that has loaded keeps following its filters. */
467
+ function useHasNearedViewport() {
468
+ const [hasNeared, setHasNeared] = useState(() => typeof IntersectionObserver === "undefined");
469
+ return [useCallback((element) => {
470
+ if (!element || hasNeared) return;
471
+ const observer = new IntersectionObserver((entries) => {
472
+ if (entries.some((entry) => entry.isIntersecting)) setHasNeared(true);
473
+ }, { rootMargin: PREFETCH_MARGIN });
474
+ observer.observe(element);
475
+ return () => observer.disconnect();
476
+ }, [hasNeared]), hasNeared];
477
+ }
478
+ //#endregion
372
479
  //#region src/ui/DataSection.tsx
480
+ /** Sections of views that `<DataApp>` runs share its results; every other section
481
+ * requests its own view once it nears the viewport. */
373
482
  function DataSection({ content, ...presentation }) {
374
- const primary = useContext(PrimaryViewContext);
483
+ const app = useContext(AppViewResultsContext);
375
484
  const { view, ...section } = sectionContent(content);
376
- if (primary?.declaration === view) {
377
- const result = primary.result;
378
- return /* @__PURE__ */ jsx(DataSectionBoundary, {
485
+ const appResult = app?.results.get(view);
486
+ if (!appResult) {
487
+ if (app) assertAppFilters(view, app.clientFilters);
488
+ return /* @__PURE__ */ jsx(LazySection, {
489
+ view,
379
490
  ...section,
380
- ...presentation,
381
- result,
382
- notice: "none"
491
+ ...presentation
383
492
  });
384
493
  }
385
- return /* @__PURE__ */ jsx(IndependentSection, {
386
- view,
494
+ if (view === app?.primaryView) return /* @__PURE__ */ jsx(DataSectionBoundary, {
387
495
  ...section,
388
- ...presentation
496
+ ...presentation,
497
+ result: appResult,
498
+ notice: "none"
499
+ });
500
+ return /* @__PURE__ */ jsx(StandaloneSection, {
501
+ ...section,
502
+ ...presentation,
503
+ result: appResult
389
504
  });
390
505
  }
391
- function IndependentSection({ view, ...props }) {
392
- const result = useDeclaredResult(view);
393
- const defaults = useInspectionDefaults();
394
- const section = /* @__PURE__ */ jsx(DataSectionBoundary, {
506
+ /** Requests its view only once the section nears the viewport,
507
+ * so each widget's query runs when a reader can see it. */
508
+ function LazySection({ view, ref, ...props }) {
509
+ const [observeViewport, hasNearedViewport] = useHasNearedViewport();
510
+ const result = useDeclaredResult(view, { enabled: hasNearedViewport });
511
+ const sectionRef = useCallback((element) => {
512
+ assignRef(ref, element);
513
+ const stopObserving = observeViewport(element);
514
+ return () => {
515
+ stopObserving?.();
516
+ assignRef(ref, null);
517
+ };
518
+ }, [ref, observeViewport]);
519
+ return /* @__PURE__ */ jsx(StandaloneSection, {
395
520
  ...props,
396
- result,
397
- notice: "inline"
521
+ ref: sectionRef,
522
+ result
398
523
  });
524
+ }
525
+ /** Reports its own request state inline and inspects its own queries. */
526
+ function StandaloneSection({ result, ...props }) {
527
+ const defaults = useInspectionDefaults();
399
528
  return /* @__PURE__ */ jsx(DateFormattingContext, {
400
529
  value: { timeZone: result.timeZone },
401
530
  children: /* @__PURE__ */ jsx(InspectionContext, {
@@ -404,10 +533,18 @@ function IndependentSection({ view, ...props }) {
404
533
  dataContext: result.dataContext,
405
534
  queries: result.queries
406
535
  },
407
- children: section
536
+ children: /* @__PURE__ */ jsx(DataSectionBoundary, {
537
+ ...props,
538
+ result,
539
+ notice: "inline"
540
+ })
408
541
  })
409
542
  });
410
543
  }
544
+ function assignRef(ref, value) {
545
+ if (typeof ref === "function") ref(value);
546
+ else if (ref) ref.current = value;
547
+ }
411
548
  //#endregion
412
549
  //#region src/ui/UpdatedAt.tsx
413
550
  function UpdatedAt({ timestamp, locale, label = "Updated", children, triggerProps, ...props }) {
@@ -469,7 +606,7 @@ function reportingPeriodText(period, options = {}) {
469
606
  const start = new Date(end.getTime() - period.amount * (period.unit === "hour" ? fixedUnitMilliseconds.HOUR : fixedUnitMilliseconds.DAY));
470
607
  return `${label(period, options)}, ${formatDateTime(start, options)} to ${formatDateTime(end, options)} in ${options.timeZone ?? "UTC"}`;
471
608
  }
472
- /** Read-only period context for the variable bar, including exact bounds for assistive technology. */
609
+ /** Read-only period context for the control bar, including exact bounds for assistive technology. */
473
610
  function PeriodSummary({ period, comparison, className }) {
474
611
  const options = useDateFormatting();
475
612
  const comparisonText = comparison ? comparisonLabel(period, comparison, options) : null;
@@ -1097,6 +1234,6 @@ function injectDataAppAnnotationStyles(options = {}) {
1097
1234
  });
1098
1235
  }
1099
1236
  //#endregion
1100
- export { AnnotationBar, AnnotationTarget, Breakdown, Button, Comparison, DataApp, DataSection, DataValue, DateDisplay, DateTimeRangePicker, DateTimeTooltip, DetailContent, DetailView, EmptyState, ExternalLink, Grid, GridItem, IconButton, MetricWidget, PeriodSummary, Ranking, SectionHeading, Skeleton, Stack, TableWidget, TextContent, TextWidget, Tooltip, TooltipProvider, UpdatedAt, VisualizationWidget, chartColor, choiceVariable, createDataContext, createDataHooks, dateTimeRangePresets, dateTimeRangeVariable, defineDataIdentifiers, injectDataAppAnnotationStyles, injectDataAppStyles, mountDataApp, multiChoiceVariable, searchVariable, useDataAppAnnotations, useDateFormatting, useDetailNavigation };
1237
+ export { AnnotationBar, AnnotationTarget, Breakdown, Button, Comparison, DataApp, DataSection, DataValue, DateDisplay, DateTimeRangePicker, DateTimeTooltip, DetailContent, DetailView, EmptyState, ExternalLink, Grid, GridItem, IconButton, MetricWidget, PeriodSummary, Ranking, SectionHeading, Skeleton, Stack, TableWidget, TextContent, TextWidget, Tooltip, TooltipProvider, UpdatedAt, VisualizationWidget, chartColor, createDataContext, createDataHooks, defineDataIdentifiers, injectDataAppAnnotationStyles, injectDataAppStyles, mountDataApp, useDataAppAnnotations, useDateFormatting, useDetailNavigation };
1101
1238
 
1102
1239
  //# sourceMappingURL=index.js.map