@altertable/data-app-react 0.0.0-stage → 0.71.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 (169) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -2
  3. package/THIRD_PARTY_NOTICES +18 -0
  4. package/dist/chunks/index-1nbjx0se.js +17022 -0
  5. package/dist/chunks/index-1nbjx0se.js.map +120 -0
  6. package/dist/index.js +2888 -0
  7. package/dist/index.js.map +23 -0
  8. package/dist/types/actions.d.ts +53 -0
  9. package/dist/types/annotations/AnnotationBar.d.ts +30 -0
  10. package/dist/types/annotations/AnnotationControls.d.ts +10 -0
  11. package/dist/types/annotations/AnnotationEditor.d.ts +16 -0
  12. package/dist/types/annotations/AnnotationMarkers.d.ts +19 -0
  13. package/dist/types/annotations/AnnotationSelectionLayer.d.ts +12 -0
  14. package/dist/types/annotations/AnnotationTarget.d.ts +9 -0
  15. package/dist/types/annotations/AnnotationTooltip.d.ts +9 -0
  16. package/dist/types/annotations/AnnotationTrigger.d.ts +10 -0
  17. package/dist/types/annotations/annotation-editor-state.d.ts +58 -0
  18. package/dist/types/annotations/annotation-screenshot.d.ts +4 -0
  19. package/dist/types/annotations/annotation-targets.d.ts +34 -0
  20. package/dist/types/annotations/getAnnotationProps.d.ts +17 -0
  21. package/dist/types/annotations/styles.d.ts +3 -0
  22. package/dist/types/annotations/useAnnotationGeometry.d.ts +22 -0
  23. package/dist/types/annotations/useDataAppAnnotations.d.ts +22 -0
  24. package/dist/types/app-context.d.ts +3 -0
  25. package/dist/types/bindings.d.ts +169 -0
  26. package/dist/types/content.d.ts +36 -0
  27. package/dist/types/date-formatting.d.ts +12 -0
  28. package/dist/types/details.d.ts +46 -0
  29. package/dist/types/exploration.d.ts +44 -0
  30. package/dist/types/hooks.d.ts +114 -0
  31. package/dist/types/index.d.ts +78 -0
  32. package/dist/types/injectStyles.d.ts +7 -0
  33. package/dist/types/mount.d.ts +13 -0
  34. package/dist/types/search-suggestions.d.ts +8 -0
  35. package/dist/types/source-owner.d.ts +2 -0
  36. package/dist/types/style-contract.d.ts +88 -0
  37. package/dist/types/style-validation.d.ts +2 -0
  38. package/dist/types/styles.d.ts +8 -0
  39. package/dist/types/ui/AboutData.d.ts +73 -0
  40. package/dist/types/ui/AltertableLogo.d.ts +3 -0
  41. package/dist/types/ui/AppFooter.d.ts +6 -0
  42. package/dist/types/ui/AppHeader.d.ts +10 -0
  43. package/dist/types/ui/AppLayout.d.ts +10 -0
  44. package/dist/types/ui/AppScope.d.ts +7 -0
  45. package/dist/types/ui/AppToolbar.d.ts +30 -0
  46. package/dist/types/ui/AreaChart.d.ts +7 -0
  47. package/dist/types/ui/BarChart.d.ts +6 -0
  48. package/dist/types/ui/Breakdown.d.ts +13 -0
  49. package/dist/types/ui/Button.d.ts +12 -0
  50. package/dist/types/ui/ChartLegend.d.ts +32 -0
  51. package/dist/types/ui/Checkbox.d.ts +21 -0
  52. package/dist/types/ui/CheckboxGroup.d.ts +7 -0
  53. package/dist/types/ui/ChoicePicker.d.ts +39 -0
  54. package/dist/types/ui/Comparison.d.ts +14 -0
  55. package/dist/types/ui/ComposedChart.d.ts +41 -0
  56. package/dist/types/ui/ComposedChartLegend.d.ts +9 -0
  57. package/dist/types/ui/ContentSkeleton.d.ts +7 -0
  58. package/dist/types/ui/DataApp.d.ts +24 -0
  59. package/dist/types/ui/DataAppFrame.d.ts +52 -0
  60. package/dist/types/ui/DataBoundary.d.ts +14 -0
  61. package/dist/types/ui/DataSection.d.ts +14 -0
  62. package/dist/types/ui/DataSectionBoundary.d.ts +30 -0
  63. package/dist/types/ui/DataTable.d.ts +29 -0
  64. package/dist/types/ui/DataValue.d.ts +9 -0
  65. package/dist/types/ui/DataViewToast.d.ts +11 -0
  66. package/dist/types/ui/DataWidget.d.ts +37 -0
  67. package/dist/types/ui/DateDisplay.d.ts +9 -0
  68. package/dist/types/ui/DateRangePicker.d.ts +30 -0
  69. package/dist/types/ui/DateTimeTooltip.d.ts +10 -0
  70. package/dist/types/ui/DimensionPicker.d.ts +14 -0
  71. package/dist/types/ui/EmptyState.d.ts +6 -0
  72. package/dist/types/ui/ExplorationActionControl.d.ts +60 -0
  73. package/dist/types/ui/ExportControl.d.ts +4 -0
  74. package/dist/types/ui/FilterActions.d.ts +10 -0
  75. package/dist/types/ui/FilterBar.d.ts +3 -0
  76. package/dist/types/ui/FunnelChart.d.ts +20 -0
  77. package/dist/types/ui/GettingStarted.d.ts +6 -0
  78. package/dist/types/ui/GlossaryDefinition.d.ts +7 -0
  79. package/dist/types/ui/GlossaryExplanation.d.ts +16 -0
  80. package/dist/types/ui/GradientScroll.d.ts +23 -0
  81. package/dist/types/ui/Grid.d.ts +12 -0
  82. package/dist/types/ui/GridItem.d.ts +7 -0
  83. package/dist/types/ui/HelpPopover.d.ts +21 -0
  84. package/dist/types/ui/IconButton.d.ts +19 -0
  85. package/dist/types/ui/InspectionContext.d.ts +12 -0
  86. package/dist/types/ui/InspectionProvider.d.ts +29 -0
  87. package/dist/types/ui/JourneyChart.d.ts +10 -0
  88. package/dist/types/ui/Kbd.d.ts +7 -0
  89. package/dist/types/ui/LineChart.d.ts +7 -0
  90. package/dist/types/ui/LiveControl.d.ts +10 -0
  91. package/dist/types/ui/Menu.d.ts +13 -0
  92. package/dist/types/ui/MetricWidget.d.ts +51 -0
  93. package/dist/types/ui/NumberField.d.ts +27 -0
  94. package/dist/types/ui/NumberFilterPicker.d.ts +11 -0
  95. package/dist/types/ui/PeriodSummary.d.ts +17 -0
  96. package/dist/types/ui/PickerField.d.ts +23 -0
  97. package/dist/types/ui/PieChart.d.ts +11 -0
  98. package/dist/types/ui/PopoverSurface.d.ts +5 -0
  99. package/dist/types/ui/PresentStory.d.ts +30 -0
  100. package/dist/types/ui/QueryList.d.ts +14 -0
  101. package/dist/types/ui/RadioGroup.d.ts +18 -0
  102. package/dist/types/ui/Ranking.d.ts +13 -0
  103. package/dist/types/ui/RefreshControl.d.ts +9 -0
  104. package/dist/types/ui/RequestHint.d.ts +20 -0
  105. package/dist/types/ui/RetentionChart.d.ts +27 -0
  106. package/dist/types/ui/ScatterChart.d.ts +17 -0
  107. package/dist/types/ui/SearchField.d.ts +23 -0
  108. package/dist/types/ui/SearchInput.d.ts +10 -0
  109. package/dist/types/ui/SearchMatch.d.ts +6 -0
  110. package/dist/types/ui/SearchTypeahead.d.ts +15 -0
  111. package/dist/types/ui/SectionHeading.d.ts +8 -0
  112. package/dist/types/ui/Select.d.ts +22 -0
  113. package/dist/types/ui/SelectionMark.d.ts +5 -0
  114. package/dist/types/ui/Sheet.d.ts +21 -0
  115. package/dist/types/ui/Skeleton.d.ts +8 -0
  116. package/dist/types/ui/Stack.d.ts +7 -0
  117. package/dist/types/ui/StaticDataApp.d.ts +4 -0
  118. package/dist/types/ui/StatusPanel.d.ts +10 -0
  119. package/dist/types/ui/TableWidget.d.ts +67 -0
  120. package/dist/types/ui/Tabs.d.ts +10 -0
  121. package/dist/types/ui/TextContent.d.ts +4 -0
  122. package/dist/types/ui/TextWidget.d.ts +20 -0
  123. package/dist/types/ui/ThemeSelector.d.ts +12 -0
  124. package/dist/types/ui/Toast.d.ts +8 -0
  125. package/dist/types/ui/Tooltip.d.ts +23 -0
  126. package/dist/types/ui/TooltipSurface.d.ts +3 -0
  127. package/dist/types/ui/TrendChart.d.ts +5 -0
  128. package/dist/types/ui/UpdatedAt.d.ts +9 -0
  129. package/dist/types/ui/VariableBar.d.ts +6 -0
  130. package/dist/types/ui/VisualizationWidget.d.ts +43 -0
  131. package/dist/types/ui/WidgetDisclosure.d.ts +6 -0
  132. package/dist/types/ui/WidgetEvidence.d.ts +12 -0
  133. package/dist/types/ui/WidgetViewTabs.d.ts +16 -0
  134. package/dist/types/ui/chart-data.d.ts +36 -0
  135. package/dist/types/ui/chart-date-axis.d.ts +15 -0
  136. package/dist/types/ui/chart-interaction.d.ts +27 -0
  137. package/dist/types/ui/chart-primitives.d.ts +22 -0
  138. package/dist/types/ui/chart-time.d.ts +19 -0
  139. package/dist/types/ui/chartColor.d.ts +2 -0
  140. package/dist/types/ui/classNames.d.ts +1 -0
  141. package/dist/types/ui/csv-export.d.ts +19 -0
  142. package/dist/types/ui/data-context.d.ts +76 -0
  143. package/dist/types/ui/data-identifiers.d.ts +32 -0
  144. package/dist/types/ui/icons.d.ts +49 -0
  145. package/dist/types/ui/index.d.ts +111 -0
  146. package/dist/types/ui/journey-flow.d.ts +49 -0
  147. package/dist/types/ui/keyboard.d.ts +6 -0
  148. package/dist/types/ui/metric-comparison.d.ts +30 -0
  149. package/dist/types/ui/metric.d.ts +11 -0
  150. package/dist/types/ui/presentation.d.ts +25 -0
  151. package/dist/types/ui/search.d.ts +6 -0
  152. package/dist/types/ui/searchItems.d.ts +36 -0
  153. package/dist/types/ui/shortcuts.d.ts +45 -0
  154. package/dist/types/ui/story.d.ts +20 -0
  155. package/dist/types/ui/time-interval.d.ts +96 -0
  156. package/dist/types/ui/use-chart-scroll-to-end.d.ts +2 -0
  157. package/dist/types/ui/useAppAppearance.d.ts +3 -0
  158. package/dist/types/ui/useDataAppPresentation.d.ts +3 -0
  159. package/dist/types/ui/useSvgId.d.ts +2 -0
  160. package/dist/types/ui/variables.d.ts +36 -0
  161. package/dist/types/ui/widget-views.d.ts +3 -0
  162. package/dist/types/view-control-bar.d.ts +18 -0
  163. package/dist/types/view-controls.d.ts +20 -0
  164. package/dist/types/view-runtime.d.ts +34 -0
  165. package/dist/types/view.d.ts +87 -0
  166. package/dist/types/widgets.d.ts +90 -0
  167. package/dist/ui/index.js +3520 -0
  168. package/dist/ui/index.js.map +36 -0
  169. package/package.json +65 -4
@@ -0,0 +1,3520 @@
1
+ import {
2
+ injectDataAppStyles2,
3
+ useDateFormatting2,
4
+ AppIcon2,
5
+ classNames,
6
+ Button2,
7
+ PressButton,
8
+ TooltipSurface,
9
+ TooltipProvider2,
10
+ Tooltip2,
11
+ GradientScroll2,
12
+ Sheet2,
13
+ TabPanels2,
14
+ TabList2,
15
+ Tab2,
16
+ TabPanel2,
17
+ Tabs2,
18
+ useViewTab2,
19
+ AboutData2,
20
+ DataAppProvider2,
21
+ useDeclaredResult,
22
+ HelpPopover2,
23
+ DateDisplay2,
24
+ useAppVariables2,
25
+ SearchField2,
26
+ SearchMatch2,
27
+ matchSearchText2,
28
+ searchItems2,
29
+ SearchTypeahead2,
30
+ Select2,
31
+ FilterActions2,
32
+ VariableBar2,
33
+ NumberField2,
34
+ NumberRangeField2,
35
+ NumberFilterPicker2,
36
+ ChoicePicker2,
37
+ CheckboxGroupContext,
38
+ Checkbox2,
39
+ DateRangePicker2,
40
+ FilterBar2,
41
+ DimensionPicker2,
42
+ createDataHooks2,
43
+ isPlainKeyEvent2,
44
+ MenuTrigger2,
45
+ MenuSection2,
46
+ MenuPopover2,
47
+ Menu2,
48
+ MenuItem2,
49
+ MenuSeparator2,
50
+ LiveControl2,
51
+ PresentStory2,
52
+ DataAppFrame,
53
+ ExplorationActionControl2,
54
+ ExplorationActionMenu,
55
+ useChartActions,
56
+ openExplorationMenu,
57
+ explorationMenuEvents,
58
+ getPrimaryExplorationAction,
59
+ DataWidget2,
60
+ VisualizationWidget2,
61
+ MetricWidget2,
62
+ DataTable2,
63
+ DataTableShare2,
64
+ DataTableEmptyRow2,
65
+ DataTableTimestamp2,
66
+ TableWidget2,
67
+ TextWidget2,
68
+ DataValue2,
69
+ chartBarFill,
70
+ createDataContext2,
71
+ SectionHeading2
72
+ } from "../chunks/index-1nbjx0se.js";
73
+ // packages/data-app-react/src/ui/GettingStarted.tsx
74
+ import { createDataClient } from "@altertable/data-app/client";
75
+
76
+ // packages/data-app-react/src/ui/StaticDataApp.tsx
77
+ import { jsx } from "react/jsx-runtime";
78
+ function DataApp(props) {
79
+ return /* @__PURE__ */ jsx(DataAppFrame, {
80
+ ...props
81
+ });
82
+ }
83
+
84
+ // packages/data-app-react/src/ui/GettingStarted.tsx
85
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
86
+ var connectionContext = createDataContext2({})({
87
+ description: "Connection setup",
88
+ glossary: {}
89
+ });
90
+ var client = /* @__PURE__ */ createDataClient();
91
+ var { defineDataView } = /* @__PURE__ */ createDataHooks2(client);
92
+ var connectionView = defineDataView({
93
+ dataContext: connectionContext,
94
+ operation: "connection",
95
+ describeInput: () => "the connection",
96
+ isEmpty: () => false,
97
+ emptyFallback: { title: "No connection" }
98
+ });
99
+ function GettingStarted({ dataContext }) {
100
+ const connection = useDeclaredResult(connectionView);
101
+ const state = connection.view.kind === "error" || connection.view.kind === "stale-error" ? "error" : connection.refreshing || !connection.snapshot ? "checking" : "connected";
102
+ return /* @__PURE__ */ jsxs(DataApp, {
103
+ dataContext,
104
+ description: "Check your lakehouse connection, then build a view around a real question.",
105
+ queries: connection.queries,
106
+ toolbarActions: /* @__PURE__ */ jsx2(Button2, {
107
+ disabled: connection.refreshing,
108
+ onClick: () => connection.refetch(),
109
+ children: "Check connection"
110
+ }),
111
+ children: [
112
+ /* @__PURE__ */ jsxs("section", {
113
+ className: "starter-connection",
114
+ "data-state": state,
115
+ role: state === "error" ? "alert" : "status",
116
+ children: [
117
+ /* @__PURE__ */ jsx2("div", {
118
+ className: "starter-connection-icon",
119
+ children: /* @__PURE__ */ jsx2(AppIcon2, {
120
+ name: state === "connected" ? "check" : state === "error" ? "error" : "loading",
121
+ size: 24
122
+ })
123
+ }),
124
+ /* @__PURE__ */ jsxs("div", {
125
+ className: "starter-connection-copy",
126
+ children: [
127
+ /* @__PURE__ */ jsx2("span", {
128
+ className: "starter-eyebrow",
129
+ children: "Lakehouse connection"
130
+ }),
131
+ /* @__PURE__ */ jsx2("h2", {
132
+ children: state === "connected" ? "Connected" : state === "error" ? "Connection not verified" : "Checking connection…"
133
+ }),
134
+ /* @__PURE__ */ jsx2("p", {
135
+ children: state === "connected" ? "A query completed successfully using this app’s current profile. You’re ready to build your first view." : state === "error" ? connection.snapshot ? "An earlier query succeeded, but the latest check failed. Check the profile and try again." : "The query could not complete. Check the profile and lakehouse access, then try again." : "Running a lightweight query with this app’s current profile."
136
+ }),
137
+ state === "connected" && /* @__PURE__ */ jsx2("small", {
138
+ children: "This check does not verify access to every dataset."
139
+ })
140
+ ]
141
+ }),
142
+ state === "error" && /* @__PURE__ */ jsx2(Button2, {
143
+ onClick: () => connection.refetch(),
144
+ children: "Try again"
145
+ })
146
+ ]
147
+ }),
148
+ /* @__PURE__ */ jsxs("section", {
149
+ className: "starter-next",
150
+ "aria-labelledby": "starter-next-title",
151
+ children: [
152
+ /* @__PURE__ */ jsxs("div", {
153
+ className: "starter-next-heading",
154
+ children: [
155
+ /* @__PURE__ */ jsx2("span", {
156
+ className: "starter-eyebrow",
157
+ children: "Next steps"
158
+ }),
159
+ /* @__PURE__ */ jsx2("h2", {
160
+ id: "starter-next-title",
161
+ children: "Turn this starter into a useful app"
162
+ }),
163
+ /* @__PURE__ */ jsx2("p", {
164
+ children: "Start with one question your readers need answered."
165
+ })
166
+ ]
167
+ }),
168
+ /* @__PURE__ */ jsxs("ol", {
169
+ className: "starter-steps",
170
+ children: [
171
+ /* @__PURE__ */ jsxs("li", {
172
+ children: [
173
+ /* @__PURE__ */ jsx2("strong", {
174
+ children: "Choose a question"
175
+ }),
176
+ /* @__PURE__ */ jsx2("p", {
177
+ children: "Decide what someone should learn or do after opening this app."
178
+ })
179
+ ]
180
+ }),
181
+ /* @__PURE__ */ jsxs("li", {
182
+ children: [
183
+ /* @__PURE__ */ jsx2("strong", {
184
+ children: "Find the right data"
185
+ }),
186
+ /* @__PURE__ */ jsx2("p", {
187
+ children: "Inspect the relevant catalogs, tables, and columns before writing the query."
188
+ })
189
+ ]
190
+ }),
191
+ /* @__PURE__ */ jsxs("li", {
192
+ children: [
193
+ /* @__PURE__ */ jsx2("strong", {
194
+ children: "Build the first view"
195
+ }),
196
+ /* @__PURE__ */ jsxs("p", {
197
+ children: [
198
+ "Replace the connection check in ",
199
+ /* @__PURE__ */ jsx2("code", {
200
+ children: "src/operations.ts"
201
+ }),
202
+ ", then render its result in ",
203
+ /* @__PURE__ */ jsx2("code", {
204
+ children: "src/App.tsx"
205
+ }),
206
+ "."
207
+ ]
208
+ })
209
+ ]
210
+ })
211
+ ]
212
+ })
213
+ ]
214
+ })
215
+ ]
216
+ });
217
+ }
218
+ // packages/data-app-react/src/ui/GlossaryExplanation.tsx
219
+ import { jsx as jsx3 } from "react/jsx-runtime";
220
+ function GlossaryExplanation({
221
+ entry,
222
+ empty,
223
+ title,
224
+ description,
225
+ visual,
226
+ queries,
227
+ dataContext,
228
+ className,
229
+ ...props
230
+ }) {
231
+ return /* @__PURE__ */ jsx3(AboutData2, {
232
+ ...props,
233
+ shortcut: false,
234
+ iconOnly: true,
235
+ variant: "ghost",
236
+ title: title ?? entry.term,
237
+ description,
238
+ visual,
239
+ references: { kind: "entries", entries: [entry] },
240
+ empty,
241
+ dataContext,
242
+ queries,
243
+ className: className ?? "altertable-inspect-trigger",
244
+ tooltip: "Explore this term",
245
+ "aria-label": props["aria-label"] ?? `Explore ${entry.term}`,
246
+ children: /* @__PURE__ */ jsx3(AppIcon2, {
247
+ name: "openDetails"
248
+ })
249
+ });
250
+ }
251
+ // packages/data-app-react/src/ui/GlossaryDefinition.tsx
252
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
253
+ function GlossaryDefinition({
254
+ entry,
255
+ children
256
+ }) {
257
+ return /* @__PURE__ */ jsxs2(HelpPopover2, {
258
+ trigger: children ?? entry.term,
259
+ triggerLabel: `Explain ${entry.term}`,
260
+ label: entry.term,
261
+ triggerProps: {
262
+ className: "altertable-glossary-definition-trigger",
263
+ "data-atbl-control": "help"
264
+ },
265
+ panelProps: { className: "altertable-glossary-definition-popover" },
266
+ children: [
267
+ /* @__PURE__ */ jsx4("strong", {
268
+ children: entry.term
269
+ }),
270
+ /* @__PURE__ */ jsx4("div", {
271
+ children: entry.definition
272
+ })
273
+ ]
274
+ });
275
+ }
276
+ // packages/data-app-react/src/ui/TrendChart.tsx
277
+ import { formatNumber as formatNumber3 } from "@altertable/data-app/format";
278
+
279
+ // packages/data-app-react/src/ui/use-chart-scroll-to-end.ts
280
+ import { useLayoutEffect, useRef } from "react";
281
+ function useChartScrollToEnd(items) {
282
+ const scrollport = useRef(null);
283
+ useLayoutEffect(() => {
284
+ const element = scrollport.current;
285
+ if (element)
286
+ element.scrollLeft = element.scrollWidth - element.clientWidth;
287
+ }, [items]);
288
+ return scrollport;
289
+ }
290
+
291
+ // packages/data-app-react/src/ui/TrendChart.tsx
292
+ import {
293
+ Fragment as Fragment2,
294
+ useRef as useRef3,
295
+ useState as useState3
296
+ } from "react";
297
+ import {
298
+ AreaChart as RechartsAreaChart,
299
+ LineChart as RechartsLineChart,
300
+ ReferenceLine
301
+ } from "recharts";
302
+
303
+ // packages/data-app-react/src/ui/chart-date-axis.tsx
304
+ import {
305
+ createContext,
306
+ useCallback,
307
+ useContext,
308
+ useEffect,
309
+ useMemo,
310
+ useState
311
+ } from "react";
312
+ import { XAxis, usePlotArea } from "recharts";
313
+
314
+ // packages/data-app-react/src/ui/time-interval.ts
315
+ /*!
316
+ * TypeScript port of d3-time 3.1.0 (ISC), https://github.com/d3/d3-time/tree/v3.1.0
317
+ * Numeric tick-step helpers adapted from d3-array 3.2.4 (ISC).
318
+ *
319
+ * Copyright 2010-2022 Mike Bostock (d3-time)
320
+ * Copyright 2010-2023 Mike Bostock (d3-array tick-step helpers)
321
+ *
322
+ * Permission to use, copy, modify, and/or distribute this software for any purpose
323
+ * with or without fee is hereby granted, provided that the above copyright notice
324
+ * and this permission notice appear in all copies.
325
+ *
326
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
327
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
328
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
329
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
330
+ * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
331
+ * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
332
+ * THIS SOFTWARE.
333
+ */
334
+ function timeInterval(floor, offset, count, field) {
335
+ function interval(value) {
336
+ const date = arguments.length === 0 ? new Date : new Date(+value);
337
+ floor(date);
338
+ return date;
339
+ }
340
+ interval.floor = (value) => {
341
+ const date = new Date(+value);
342
+ floor(date);
343
+ return date;
344
+ };
345
+ interval.ceil = (value) => {
346
+ const date = new Date(+value - 1);
347
+ floor(date);
348
+ offset(date, 1);
349
+ floor(date);
350
+ return date;
351
+ };
352
+ interval.round = (value) => {
353
+ const before = interval(value);
354
+ const after = interval.ceil(value);
355
+ return +value - +before < +after - +value ? before : after;
356
+ };
357
+ interval.offset = (value, step) => {
358
+ const date = new Date(+value);
359
+ offset(date, step == null ? 1 : Math.floor(step));
360
+ return date;
361
+ };
362
+ interval.range = (start, stop, step) => {
363
+ const range = [];
364
+ const date = interval.ceil(start);
365
+ const stride = step == null ? 1 : Math.floor(step);
366
+ if (!(+date < +stop) || !(stride > 0))
367
+ return range;
368
+ let previous;
369
+ do {
370
+ previous = new Date(+date);
371
+ range.push(previous);
372
+ offset(date, stride);
373
+ floor(date);
374
+ } while (+previous < +date && +date < +stop);
375
+ return range;
376
+ };
377
+ interval.filter = (test) => timeInterval((date) => {
378
+ if (!Number.isNaN(+date)) {
379
+ floor(date);
380
+ while (!test(date)) {
381
+ date.setTime(+date - 1);
382
+ floor(date);
383
+ }
384
+ }
385
+ }, (date, step) => {
386
+ if (!Number.isNaN(+date)) {
387
+ const direction = step < 0 ? -1 : 1;
388
+ for (let remaining = Math.abs(step);remaining > 0; --remaining) {
389
+ do {
390
+ offset(date, direction);
391
+ } while (!test(date));
392
+ }
393
+ }
394
+ });
395
+ if (count) {
396
+ interval.count = (start, end) => {
397
+ countStart.setTime(+start);
398
+ countEnd.setTime(+end);
399
+ floor(countStart);
400
+ floor(countEnd);
401
+ return Math.floor(count(countStart, countEnd));
402
+ };
403
+ interval.every = (step) => {
404
+ step = Math.floor(step);
405
+ if (!Number.isFinite(step) || !(step > 0))
406
+ return null;
407
+ if (step === 1)
408
+ return interval;
409
+ return interval.filter(field ? (date) => field(date) % step === 0 : (date) => interval.count(0, date) % step === 0);
410
+ };
411
+ }
412
+ return interval;
413
+ }
414
+ var countStart = new Date;
415
+ var countEnd = new Date;
416
+ var durationSecond = 1000;
417
+ var durationMinute = durationSecond * 60;
418
+ var durationHour = durationMinute * 60;
419
+ var durationDay = durationHour * 24;
420
+ var durationWeek = durationDay * 7;
421
+ var durationMonth = durationDay * 30;
422
+ var durationYear = durationDay * 365;
423
+ var millisecond = timeInterval(() => {}, (date, step) => {
424
+ date.setTime(+date + step);
425
+ }, (start, end) => {
426
+ return +end - +start;
427
+ });
428
+ millisecond.every = (k) => {
429
+ k = Math.floor(k);
430
+ if (!isFinite(k) || !(k > 0))
431
+ return null;
432
+ if (!(k > 1))
433
+ return millisecond;
434
+ return timeInterval((date) => {
435
+ date.setTime(Math.floor(+date / k) * k);
436
+ }, (date, step) => {
437
+ date.setTime(+date + step * k);
438
+ }, (start, end) => {
439
+ return (+end - +start) / k;
440
+ });
441
+ };
442
+ var milliseconds = millisecond.range;
443
+ var second = timeInterval((date) => {
444
+ date.setTime(+date - date.getMilliseconds());
445
+ }, (date, step) => {
446
+ date.setTime(+date + step * durationSecond);
447
+ }, (start, end) => {
448
+ return (+end - +start) / durationSecond;
449
+ }, (date) => {
450
+ return date.getUTCSeconds();
451
+ });
452
+ var seconds = second.range;
453
+ var timeMinute = timeInterval((date) => {
454
+ date.setTime(+date - date.getMilliseconds() - date.getSeconds() * durationSecond);
455
+ }, (date, step) => {
456
+ date.setTime(+date + step * durationMinute);
457
+ }, (start, end) => {
458
+ return (+end - +start) / durationMinute;
459
+ }, (date) => {
460
+ return date.getMinutes();
461
+ });
462
+ var timeMinutes = timeMinute.range;
463
+ var utcMinute = timeInterval((date) => {
464
+ date.setUTCSeconds(0, 0);
465
+ }, (date, step) => {
466
+ date.setTime(+date + step * durationMinute);
467
+ }, (start, end) => {
468
+ return (+end - +start) / durationMinute;
469
+ }, (date) => {
470
+ return date.getUTCMinutes();
471
+ });
472
+ var utcMinutes = utcMinute.range;
473
+ var timeHour = timeInterval((date) => {
474
+ date.setTime(+date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);
475
+ }, (date, step) => {
476
+ date.setTime(+date + step * durationHour);
477
+ }, (start, end) => {
478
+ return (+end - +start) / durationHour;
479
+ }, (date) => {
480
+ return date.getHours();
481
+ });
482
+ var timeHours = timeHour.range;
483
+ var utcHour = timeInterval((date) => {
484
+ date.setUTCMinutes(0, 0, 0);
485
+ }, (date, step) => {
486
+ date.setTime(+date + step * durationHour);
487
+ }, (start, end) => {
488
+ return (+end - +start) / durationHour;
489
+ }, (date) => {
490
+ return date.getUTCHours();
491
+ });
492
+ var utcHours = utcHour.range;
493
+ var timeDay = timeInterval((date) => date.setHours(0, 0, 0, 0), (date, step) => date.setDate(date.getDate() + step), (start, end) => (+end - +start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay, (date) => date.getDate() - 1);
494
+ var timeDays = timeDay.range;
495
+ var utcDay = timeInterval((date) => {
496
+ date.setUTCHours(0, 0, 0, 0);
497
+ }, (date, step) => {
498
+ date.setUTCDate(date.getUTCDate() + step);
499
+ }, (start, end) => {
500
+ return (+end - +start) / durationDay;
501
+ }, (date) => {
502
+ return date.getUTCDate() - 1;
503
+ });
504
+ var utcDays = utcDay.range;
505
+ var unixDay = timeInterval((date) => {
506
+ date.setUTCHours(0, 0, 0, 0);
507
+ }, (date, step) => {
508
+ date.setUTCDate(date.getUTCDate() + step);
509
+ }, (start, end) => {
510
+ return (+end - +start) / durationDay;
511
+ }, (date) => {
512
+ return Math.floor(+date / durationDay);
513
+ });
514
+ var unixDays = unixDay.range;
515
+ function timeWeekday(i) {
516
+ return timeInterval((date) => {
517
+ date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
518
+ date.setHours(0, 0, 0, 0);
519
+ }, (date, step) => {
520
+ date.setDate(date.getDate() + step * 7);
521
+ }, (start, end) => {
522
+ return (+end - +start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
523
+ });
524
+ }
525
+ var timeSunday = timeWeekday(0);
526
+ var timeMonday = timeWeekday(1);
527
+ var timeTuesday = timeWeekday(2);
528
+ var timeWednesday = timeWeekday(3);
529
+ var timeThursday = timeWeekday(4);
530
+ var timeFriday = timeWeekday(5);
531
+ var timeSaturday = timeWeekday(6);
532
+ var timeSundays = timeSunday.range;
533
+ var timeMondays = timeMonday.range;
534
+ var timeTuesdays = timeTuesday.range;
535
+ var timeWednesdays = timeWednesday.range;
536
+ var timeThursdays = timeThursday.range;
537
+ var timeFridays = timeFriday.range;
538
+ var timeSaturdays = timeSaturday.range;
539
+ function utcWeekday(i) {
540
+ return timeInterval((date) => {
541
+ date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
542
+ date.setUTCHours(0, 0, 0, 0);
543
+ }, (date, step) => {
544
+ date.setUTCDate(date.getUTCDate() + step * 7);
545
+ }, (start, end) => {
546
+ return (+end - +start) / durationWeek;
547
+ });
548
+ }
549
+ var utcSunday = utcWeekday(0);
550
+ var utcMonday = utcWeekday(1);
551
+ var utcTuesday = utcWeekday(2);
552
+ var utcWednesday = utcWeekday(3);
553
+ var utcThursday = utcWeekday(4);
554
+ var utcFriday = utcWeekday(5);
555
+ var utcSaturday = utcWeekday(6);
556
+ var utcSundays = utcSunday.range;
557
+ var utcMondays = utcMonday.range;
558
+ var utcTuesdays = utcTuesday.range;
559
+ var utcWednesdays = utcWednesday.range;
560
+ var utcThursdays = utcThursday.range;
561
+ var utcFridays = utcFriday.range;
562
+ var utcSaturdays = utcSaturday.range;
563
+ var timeMonth = timeInterval((date) => {
564
+ date.setDate(1);
565
+ date.setHours(0, 0, 0, 0);
566
+ }, (date, step) => {
567
+ date.setMonth(date.getMonth() + step);
568
+ }, (start, end) => {
569
+ return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
570
+ }, (date) => {
571
+ return date.getMonth();
572
+ });
573
+ var timeMonths = timeMonth.range;
574
+ var utcMonth = timeInterval((date) => {
575
+ date.setUTCDate(1);
576
+ date.setUTCHours(0, 0, 0, 0);
577
+ }, (date, step) => {
578
+ date.setUTCMonth(date.getUTCMonth() + step);
579
+ }, (start, end) => {
580
+ return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
581
+ }, (date) => {
582
+ return date.getUTCMonth();
583
+ });
584
+ var utcMonths = utcMonth.range;
585
+ var timeYear = timeInterval((date) => {
586
+ date.setMonth(0, 1);
587
+ date.setHours(0, 0, 0, 0);
588
+ }, (date, step) => {
589
+ date.setFullYear(date.getFullYear() + step);
590
+ }, (start, end) => {
591
+ return end.getFullYear() - start.getFullYear();
592
+ }, (date) => {
593
+ return date.getFullYear();
594
+ });
595
+ timeYear.every = (k) => {
596
+ return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {
597
+ date.setFullYear(Math.floor(date.getFullYear() / k) * k);
598
+ date.setMonth(0, 1);
599
+ date.setHours(0, 0, 0, 0);
600
+ }, (date, step) => {
601
+ date.setFullYear(date.getFullYear() + step * k);
602
+ });
603
+ };
604
+ var timeYears = timeYear.range;
605
+ var utcYear = timeInterval((date) => {
606
+ date.setUTCMonth(0, 1);
607
+ date.setUTCHours(0, 0, 0, 0);
608
+ }, (date, step) => {
609
+ date.setUTCFullYear(date.getUTCFullYear() + step);
610
+ }, (start, end) => {
611
+ return end.getUTCFullYear() - start.getUTCFullYear();
612
+ }, (date) => {
613
+ return date.getUTCFullYear();
614
+ });
615
+ utcYear.every = (k) => {
616
+ return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {
617
+ date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
618
+ date.setUTCMonth(0, 1);
619
+ date.setUTCHours(0, 0, 0, 0);
620
+ }, (date, step) => {
621
+ date.setUTCFullYear(date.getUTCFullYear() + step * k);
622
+ });
623
+ };
624
+ var utcYears = utcYear.range;
625
+ var e10 = Math.sqrt(50);
626
+ var e5 = Math.sqrt(10);
627
+ var e2 = Math.sqrt(2);
628
+ function tickSpec(start, stop, count) {
629
+ const step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
630
+ let i1, i2, inc;
631
+ if (power < 0) {
632
+ inc = Math.pow(10, -power) / factor;
633
+ i1 = Math.round(start * inc);
634
+ i2 = Math.round(stop * inc);
635
+ if (i1 / inc < start)
636
+ ++i1;
637
+ if (i2 / inc > stop)
638
+ --i2;
639
+ inc = -inc;
640
+ } else {
641
+ inc = Math.pow(10, power) * factor;
642
+ i1 = Math.round(start / inc);
643
+ i2 = Math.round(stop / inc);
644
+ if (i1 * inc < start)
645
+ ++i1;
646
+ if (i2 * inc > stop)
647
+ --i2;
648
+ }
649
+ if (i2 < i1 && 0.5 <= count && count < 2)
650
+ return tickSpec(start, stop, count * 2);
651
+ return [i1, i2, inc];
652
+ }
653
+ function tickIncrement(start, stop, count) {
654
+ return tickSpec(start, stop, count)[2];
655
+ }
656
+ function tickStep(start, stop, count) {
657
+ const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);
658
+ return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
659
+ }
660
+ function ticker(year, month, week, day, hour, minute) {
661
+ const tickIntervals = [
662
+ [second, 1, durationSecond],
663
+ [second, 5, 5 * durationSecond],
664
+ [second, 15, 15 * durationSecond],
665
+ [second, 30, 30 * durationSecond],
666
+ [minute, 1, durationMinute],
667
+ [minute, 5, 5 * durationMinute],
668
+ [minute, 15, 15 * durationMinute],
669
+ [minute, 30, 30 * durationMinute],
670
+ [hour, 1, durationHour],
671
+ [hour, 3, 3 * durationHour],
672
+ [hour, 6, 6 * durationHour],
673
+ [hour, 12, 12 * durationHour],
674
+ [day, 1, durationDay],
675
+ [day, 2, 2 * durationDay],
676
+ [week, 1, durationWeek],
677
+ [month, 1, durationMonth],
678
+ [month, 3, 3 * durationMonth],
679
+ [year, 1, durationYear]
680
+ ];
681
+ function ticks(start, stop, count) {
682
+ const reverse = +stop < +start;
683
+ if (reverse)
684
+ [start, stop] = [stop, start];
685
+ const interval = typeof count !== "number" ? count : tickInterval(start, stop, count);
686
+ const ticks = interval ? interval.range(start, +stop + 1) : [];
687
+ return reverse ? ticks.reverse() : ticks;
688
+ }
689
+ function tickInterval(start, stop, count) {
690
+ const target = Math.abs(+stop - +start) / count;
691
+ let low = 0;
692
+ let high = tickIntervals.length;
693
+ if (Number.isNaN(target))
694
+ low = high;
695
+ while (low < high) {
696
+ const middle = low + high >>> 1;
697
+ if (tickIntervals[middle][2] <= target)
698
+ low = middle + 1;
699
+ else
700
+ high = middle;
701
+ }
702
+ const i = low;
703
+ if (i === tickIntervals.length)
704
+ return year.every(tickStep(+start / durationYear, +stop / durationYear, count));
705
+ if (i === 0)
706
+ return millisecond.every(Math.max(tickStep(+start, +stop, count), 1));
707
+ const previous = tickIntervals[i - 1];
708
+ const next = tickIntervals[i];
709
+ const [t, step] = target / previous[2] < next[2] / target ? previous : next;
710
+ return t.every(step);
711
+ }
712
+ return [ticks, tickInterval];
713
+ }
714
+ var [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);
715
+ var [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);
716
+
717
+ // packages/data-app-react/src/ui/chart-time.ts
718
+ import {
719
+ formatDate,
720
+ formatDateTime,
721
+ parseDateTime
722
+ } from "@altertable/data-app/format";
723
+ var day = 86400000;
724
+ var calendarDatePattern = /^\d{4}-\d{2}-\d{2}$/;
725
+ function isCalendarDate(value) {
726
+ return typeof value === "string" && calendarDatePattern.test(value);
727
+ }
728
+ function chartTimestamp(value, numeric = false) {
729
+ if (isCalendarDate(value)) {
730
+ return parseDateTime(`${value}T00:00:00Z`)?.getTime() ?? null;
731
+ }
732
+ if (value instanceof Date || typeof value === "string" || numeric && typeof value === "number") {
733
+ return parseDateTime(value)?.getTime() ?? null;
734
+ }
735
+ return null;
736
+ }
737
+ function timeModel(values, numeric = false) {
738
+ const timestamps = new Set;
739
+ for (const value of values) {
740
+ const timestamp = chartTimestamp(value, numeric);
741
+ if (timestamp == null)
742
+ return null;
743
+ timestamps.add(timestamp);
744
+ }
745
+ const times = [...timestamps].sort((a, b) => a - b);
746
+ const start = times[0];
747
+ const end = times.at(-1);
748
+ if (start == null || end == null)
749
+ return null;
750
+ let minimumInterval = Infinity;
751
+ for (let index = 1;index < times.length; index++) {
752
+ minimumInterval = Math.min(minimumInterval, times[index] - times[index - 1]);
753
+ }
754
+ if (times.length === 1)
755
+ minimumInterval = day;
756
+ const dateOnly = values.every(isCalendarDate);
757
+ const seconds = times.some((value) => value % 60000 !== 0) || minimumInterval < 60000;
758
+ const milliseconds = times.some((value) => value % 1000 !== 0) || minimumInterval < 1000;
759
+ function tooltip(value) {
760
+ const time = chartTimestamp(value, true);
761
+ if (time == null)
762
+ return typeof value === "string" || typeof value === "number" ? String(value) : "";
763
+ if (dateOnly)
764
+ return formatDate(new Date(time).toISOString().slice(0, 10));
765
+ if (milliseconds) {
766
+ return new Intl.DateTimeFormat("en-US", {
767
+ timeZone: "UTC",
768
+ year: "numeric",
769
+ month: "short",
770
+ day: "numeric",
771
+ hour: "2-digit",
772
+ minute: "2-digit",
773
+ second: "2-digit",
774
+ fractionalSecondDigits: 3,
775
+ hourCycle: "h23"
776
+ }).format(time);
777
+ }
778
+ return formatDateTime(time, {
779
+ precision: seconds ? "second" : "minute",
780
+ timeZone: "UTC"
781
+ });
782
+ }
783
+ return {
784
+ start,
785
+ end,
786
+ times,
787
+ minimumInterval,
788
+ tooltip
789
+ };
790
+ }
791
+ function datePart(value, options) {
792
+ return new Intl.DateTimeFormat("en-US", {
793
+ ...options,
794
+ timeZone: "UTC"
795
+ }).format(value);
796
+ }
797
+ function timeTicks2(model, width) {
798
+ const { start, end } = model;
799
+ const firstDate = new Date(start);
800
+ const lastDate = new Date(end);
801
+ const spansYears = firstDate.getUTCFullYear() !== lastDate.getUTCFullYear();
802
+ const spansDates = firstDate.toISOString().slice(0, 10) !== lastDate.toISOString().slice(0, 10);
803
+ const count = Math.max(2, Math.min(12, Math.floor(width / 80), model.times.length));
804
+ let ticks = start === end ? [start] : utcTicks(new Date(start), new Date(end), Math.min(count, (end - start) / model.minimumInterval)).map(Number);
805
+ const step = ticks.length > 1 ? ticks[1] - ticks[0] : Math.max(end - start, model.minimumInterval);
806
+ const candidates = [...new Set([start, ...ticks, end])].sort((a, b) => a - b);
807
+ ticks = [start];
808
+ const gap = step < 1000 ? 110 : 80;
809
+ for (const value of candidates.slice(1)) {
810
+ if ((value - ticks.at(-1)) / (end - start) * width >= gap)
811
+ ticks.push(value);
812
+ }
813
+ if (end !== start && ticks.at(-1) !== end) {
814
+ if (ticks.length > 1 && (end - ticks.at(-1)) / (end - start) * width < gap)
815
+ ticks.pop();
816
+ ticks.push(end);
817
+ }
818
+ function label(value, index) {
819
+ const previous = index > 0 ? new Date(ticks[index - 1]) : undefined;
820
+ const date = new Date(value);
821
+ const yearChanged = !previous || previous.getUTCFullYear() !== date.getUTCFullYear();
822
+ const dateChanged = !previous || previous.toISOString().slice(0, 10) !== date.toISOString().slice(0, 10);
823
+ if (step >= 300 * day)
824
+ return { main: String(date.getUTCFullYear()), context: "" };
825
+ if (step >= 28 * day && (model.minimumInterval >= 28 * day || end - start >= 180 * day))
826
+ return {
827
+ main: datePart(value, { month: "short" }),
828
+ context: spansYears && yearChanged ? String(date.getUTCFullYear()) : ""
829
+ };
830
+ if (step >= day && !(model.minimumInterval < day && end - start <= 3 * day))
831
+ return {
832
+ main: datePart(value, { month: "short", day: "numeric" }),
833
+ context: spansYears && yearChanged ? String(date.getUTCFullYear()) : ""
834
+ };
835
+ return {
836
+ main: datePart(value, {
837
+ hour: "2-digit",
838
+ minute: "2-digit",
839
+ ...step < 60000 ? { second: "2-digit" } : {},
840
+ ...step < 1000 ? { fractionalSecondDigits: 3 } : {},
841
+ hourCycle: "h23"
842
+ }),
843
+ context: spansDates && dateChanged ? datePart(value, {
844
+ month: "short",
845
+ day: "numeric",
846
+ ...spansYears && yearChanged ? { year: "numeric" } : {}
847
+ }) : ""
848
+ };
849
+ }
850
+ return { ticks, label };
851
+ }
852
+
853
+ // packages/data-app-react/src/ui/chart-date-axis.tsx
854
+ import { formatNumber } from "@altertable/data-app/format";
855
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
856
+ var ChartDateAxesContext = createContext(null);
857
+ function ChartDateAxes({
858
+ data,
859
+ children
860
+ }) {
861
+ const [formatters, setFormatters] = useState(() => new Map);
862
+ const register = useCallback((id, formatter) => {
863
+ setFormatters((current) => new Map(current).set(id, formatter));
864
+ return () => setFormatters((current) => {
865
+ const next = new Map(current);
866
+ next.delete(id);
867
+ return next;
868
+ });
869
+ }, []);
870
+ return /* @__PURE__ */ jsx5(ChartDateAxesContext.Provider, {
871
+ value: { data, formatters, register },
872
+ children
873
+ });
874
+ }
875
+ function useDateAxisLabel(id = 0) {
876
+ return useContext(ChartDateAxesContext)?.formatters.get(id);
877
+ }
878
+ function field(row, key) {
879
+ if (row == null || typeof row !== "object")
880
+ return;
881
+ if (key in row)
882
+ return row[key];
883
+ return String(key).replace(/\[(\d+)\]/g, ".$1").split(".").reduce((value, part) => value != null && typeof value === "object" ? value[part] : undefined, row);
884
+ }
885
+ var xAxisDefaults = {
886
+ stroke: "var(--atbl-muted)",
887
+ tickFormatter: (value) => typeof value === "number" ? formatNumber(value) : String(value),
888
+ tickLine: false,
889
+ axisLine: { stroke: "var(--atbl-border)" },
890
+ tick: { fontSize: "var(--atbl-type-meta-size)" }
891
+ };
892
+ function ChartXAxis(props) {
893
+ const context = useContext(ChartDateAxesContext);
894
+ const plot = usePlotArea();
895
+ const data = context?.data;
896
+ const { dataKey, ...axisProps } = props;
897
+ const numeric = props.scale === "utc";
898
+ const enabled = numeric || props.type == null && props.scale == null && props.tickFormatter == null && props.ticks == null;
899
+ const model = useMemo(() => {
900
+ if (!enabled || !data?.length || dataKey == null)
901
+ return null;
902
+ return timeModel(data.map((row) => typeof dataKey === "function" ? dataKey(row) : field(row, dataKey)), numeric);
903
+ }, [data, dataKey, enabled, numeric]);
904
+ const register = context?.register;
905
+ const id = props.xAxisId ?? 0;
906
+ useEffect(() => model ? register?.(id, model.tooltip) : undefined, [register, id, model]);
907
+ if (!model || dataKey == null) {
908
+ return /* @__PURE__ */ jsx5(XAxis, {
909
+ ...xAxisDefaults,
910
+ ...props
911
+ });
912
+ }
913
+ const automaticTicks = props.ticks == null && props.tickFormatter == null ? timeTicks2(model, plot?.width ?? 400) : null;
914
+ return /* @__PURE__ */ jsx5(XAxis, {
915
+ ...xAxisDefaults,
916
+ scale: "utc",
917
+ domain: model.start === model.end ? [
918
+ model.start - model.minimumInterval / 2,
919
+ model.end + model.minimumInterval / 2
920
+ ] : [model.start, model.end],
921
+ ticks: automaticTicks?.ticks,
922
+ interval: automaticTicks ? 0 : undefined,
923
+ height: 48,
924
+ tickFormatter: model.tooltip,
925
+ tick: automaticTicks ? ({ x, y, payload, index }) => {
926
+ const label = automaticTicks.label(Number(payload.value), index);
927
+ return /* @__PURE__ */ jsxs3("text", {
928
+ x,
929
+ y: Number(y) + 5,
930
+ fill: "var(--atbl-muted)",
931
+ fontSize: "var(--atbl-type-meta-size)",
932
+ textAnchor: index === 0 ? "start" : index === automaticTicks.ticks.length - 1 ? "end" : "middle",
933
+ children: [
934
+ /* @__PURE__ */ jsx5("tspan", {
935
+ x,
936
+ dy: "0.8em",
937
+ children: label.main
938
+ }),
939
+ label.context && /* @__PURE__ */ jsx5("tspan", {
940
+ x,
941
+ dy: "1.4em",
942
+ children: label.context
943
+ })
944
+ ]
945
+ });
946
+ } : xAxisDefaults.tick,
947
+ ...axisProps,
948
+ type: "number",
949
+ dataKey: (row) => chartTimestamp(typeof dataKey === "function" ? dataKey(row) : field(row, dataKey), numeric)
950
+ });
951
+ }
952
+
953
+ // packages/data-app-react/src/ui/chart-primitives.tsx
954
+ import { useContext as useContext3, useLayoutEffect as useLayoutEffect2 } from "react";
955
+ import { formatNumber as formatNumber2 } from "@altertable/data-app/format";
956
+
957
+ // packages/data-app-react/src/ui/chart-interaction.tsx
958
+ import {
959
+ createContext as createContext2,
960
+ useContext as useContext2,
961
+ useId,
962
+ useEffect as useEffect2
963
+ } from "react";
964
+ import { jsx as jsx6 } from "react/jsx-runtime";
965
+ var ChartInteractionContext = createContext2(null);
966
+ function isChartSeriesActive(interaction, seriesId) {
967
+ return !interaction?.isPointerInspection || interaction.seriesCount === 1 || interaction.activeSeriesId === seriesId;
968
+ }
969
+ function useChartSeries(id) {
970
+ const generatedId = useId();
971
+ const interaction = useContext2(ChartInteractionContext);
972
+ const seriesId = id ?? generatedId;
973
+ const registerSeries = interaction?.registerSeries;
974
+ useEffect2(() => registerSeries?.(seriesId), [registerSeries, seriesId]);
975
+ return {
976
+ id: seriesId,
977
+ active: isChartSeriesActive(interaction, seriesId)
978
+ };
979
+ }
980
+ function ChartSeries({
981
+ id,
982
+ children
983
+ }) {
984
+ const interaction = useContext2(ChartInteractionContext);
985
+ return /* @__PURE__ */ jsx6("g", {
986
+ onPointerOver: () => interaction?.setHoveredSeriesId(id),
987
+ onPointerDown: () => interaction?.setHoveredSeriesId(id),
988
+ children
989
+ });
990
+ }
991
+
992
+ // packages/data-app-react/src/ui/chart-primitives.tsx
993
+ import {
994
+ Area,
995
+ Dot,
996
+ Bar,
997
+ Line,
998
+ Scatter,
999
+ YAxis,
1000
+ CartesianGrid,
1001
+ Tooltip,
1002
+ DefaultTooltipContent
1003
+ } from "recharts";
1004
+
1005
+ // packages/data-app-react/src/ui/ChartLegend.tsx
1006
+ import {
1007
+ Children,
1008
+ useId as useId2,
1009
+ useEffect as useEffect3,
1010
+ useRef as useRef2,
1011
+ useState as useState2
1012
+ } from "react";
1013
+ import { jsx as jsx7, jsxs as jsxs4, Fragment } from "react/jsx-runtime";
1014
+ function ChartLegendRoot({
1015
+ children,
1016
+ layout = "horizontal",
1017
+ align = "start",
1018
+ maxVisibleItems,
1019
+ className,
1020
+ "aria-label": ariaLabel = "Chart legend",
1021
+ ...props
1022
+ }) {
1023
+ const [expanded, setExpanded] = useState2(false);
1024
+ const listId = useId2();
1025
+ const containerRef = useRef2(null);
1026
+ const [columns, setColumns] = useState2(2);
1027
+ useEffect3(() => {
1028
+ const container = containerRef.current;
1029
+ if (!container)
1030
+ return;
1031
+ function measure() {
1032
+ const list = containerRef.current?.firstElementChild;
1033
+ if (list) {
1034
+ setColumns(getComputedStyle(list).gridTemplateColumns.split(" ").length);
1035
+ }
1036
+ }
1037
+ const observer = new ResizeObserver(measure);
1038
+ observer.observe(container);
1039
+ measure();
1040
+ return () => observer.disconnect();
1041
+ }, [layout]);
1042
+ const items = Children.toArray(children);
1043
+ const rowCapacity = layout === "vertical" ? 6 : columns * (layout === "single-row" ? 1 : 2);
1044
+ const configuredLimit = typeof maxVisibleItems === "number" && Number.isFinite(maxVisibleItems) ? Math.max(1, Math.floor(maxVisibleItems)) : rowCapacity;
1045
+ const cappedLimit = Math.min(configuredLimit, rowCapacity);
1046
+ const limit = layout === "vertical" ? configuredLimit : cappedLimit >= columns ? Math.floor(cappedLimit / columns) * columns : cappedLimit;
1047
+ const visibleCount = items.length > limit ? limit - 1 : limit;
1048
+ const hiddenCount = Math.max(0, items.length - visibleCount);
1049
+ return /* @__PURE__ */ jsx7("div", {
1050
+ ref: containerRef,
1051
+ className: "altertable-chart-legend-container",
1052
+ children: /* @__PURE__ */ jsxs4("ul", {
1053
+ id: listId,
1054
+ ...props,
1055
+ "aria-label": ariaLabel,
1056
+ "data-layout": layout,
1057
+ "data-align": align,
1058
+ className: classNames("altertable-chart-legend", className),
1059
+ children: [
1060
+ expanded ? items : items.slice(0, visibleCount),
1061
+ hiddenCount > 0 && /* @__PURE__ */ jsx7("li", {
1062
+ className: "altertable-chart-legend-overflow",
1063
+ children: /* @__PURE__ */ jsx7("button", {
1064
+ type: "button",
1065
+ "data-atbl-control": "action",
1066
+ "data-atbl-focus": "ring",
1067
+ className: "altertable-chart-legend-action",
1068
+ "aria-expanded": expanded,
1069
+ "aria-controls": props.id ?? listId,
1070
+ onClick: () => setExpanded((value) => !value),
1071
+ children: expanded ? "Show fewer" : `+${hiddenCount} more`
1072
+ })
1073
+ })
1074
+ ]
1075
+ })
1076
+ });
1077
+ }
1078
+ function ChartLegendItem({
1079
+ inactive,
1080
+ className,
1081
+ ...props
1082
+ }) {
1083
+ return /* @__PURE__ */ jsx7("li", {
1084
+ ...props,
1085
+ "data-inactive": inactive || undefined,
1086
+ className: classNames("altertable-chart-legend-item", className)
1087
+ });
1088
+ }
1089
+ function ChartLegendMarker({
1090
+ kind,
1091
+ color = kind === "bar" ? chartBarFill : "var(--atbl-chart-1)",
1092
+ className,
1093
+ style,
1094
+ ...props
1095
+ }) {
1096
+ return /* @__PURE__ */ jsxs4("svg", {
1097
+ ...props,
1098
+ "aria-hidden": "true",
1099
+ focusable: "false",
1100
+ viewBox: kind === "square" ? "0 0 8 8" : "0 0 20 12",
1101
+ "data-kind": kind,
1102
+ className: classNames("altertable-chart-legend-marker", className),
1103
+ style: { color, ...style },
1104
+ children: [
1105
+ kind === "square" && /* @__PURE__ */ jsx7("rect", {
1106
+ width: "8",
1107
+ height: "8",
1108
+ fill: "currentColor"
1109
+ }),
1110
+ kind === "bar" && /* @__PURE__ */ jsx7("path", {
1111
+ d: "M6 11V3Q6 1 8 1H12Q14 1 14 3V11Z",
1112
+ fill: "currentColor"
1113
+ }),
1114
+ kind === "slice" && /* @__PURE__ */ jsx7("rect", {
1115
+ x: "5",
1116
+ y: "1",
1117
+ width: "10",
1118
+ height: "10",
1119
+ rx: "2",
1120
+ fill: "currentColor"
1121
+ }),
1122
+ kind === "point" && /* @__PURE__ */ jsx7("circle", {
1123
+ cx: "10",
1124
+ cy: "6",
1125
+ r: "3",
1126
+ fill: "currentColor"
1127
+ }),
1128
+ kind === "line" && /* @__PURE__ */ jsxs4(Fragment, {
1129
+ children: [
1130
+ /* @__PURE__ */ jsx7("path", {
1131
+ d: "M1 6H19",
1132
+ fill: "none",
1133
+ stroke: "currentColor",
1134
+ strokeWidth: "2",
1135
+ strokeLinecap: "round"
1136
+ }),
1137
+ /* @__PURE__ */ jsx7("circle", {
1138
+ cx: "10",
1139
+ cy: "6",
1140
+ r: "2.5",
1141
+ fill: "var(--atbl-surface)",
1142
+ stroke: "currentColor",
1143
+ strokeWidth: "2"
1144
+ })
1145
+ ]
1146
+ }),
1147
+ kind === "area" && /* @__PURE__ */ jsxs4(Fragment, {
1148
+ children: [
1149
+ /* @__PURE__ */ jsx7("path", {
1150
+ d: "M1 10L7 5L13 7L19 2V11H1Z",
1151
+ fill: "currentColor",
1152
+ fillOpacity: "0.14"
1153
+ }),
1154
+ /* @__PURE__ */ jsx7("path", {
1155
+ d: "M1 10L7 5L13 7L19 2",
1156
+ fill: "none",
1157
+ stroke: "currentColor",
1158
+ strokeWidth: "2",
1159
+ strokeLinejoin: "round",
1160
+ strokeLinecap: "round"
1161
+ })
1162
+ ]
1163
+ })
1164
+ ]
1165
+ });
1166
+ }
1167
+ function ChartLegendLabel({
1168
+ className,
1169
+ children,
1170
+ title,
1171
+ ...props
1172
+ }) {
1173
+ return /* @__PURE__ */ jsx7("span", {
1174
+ ...props,
1175
+ title: title ?? (typeof children === "string" ? children : undefined),
1176
+ className: classNames("altertable-chart-legend-label", className),
1177
+ children
1178
+ });
1179
+ }
1180
+ var ChartLegend = Object.assign(ChartLegendRoot, {
1181
+ Item: ChartLegendItem,
1182
+ Marker: ChartLegendMarker,
1183
+ Label: ChartLegendLabel
1184
+ });
1185
+
1186
+ // packages/data-app-react/src/ui/chart-primitives.tsx
1187
+ import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
1188
+ var seriesColor = "var(--atbl-chart-1)";
1189
+ function ChartDot({
1190
+ active = false,
1191
+ stroke = seriesColor,
1192
+ fill = active ? stroke : "var(--atbl-surface)",
1193
+ r = active ? 4.5 : 3,
1194
+ ...props
1195
+ }) {
1196
+ return /* @__PURE__ */ jsx8(Dot, {
1197
+ stroke,
1198
+ fill,
1199
+ r,
1200
+ strokeWidth: 2,
1201
+ ...props
1202
+ });
1203
+ }
1204
+ function NearestChartDot({
1205
+ seriesId,
1206
+ cx,
1207
+ cy,
1208
+ stroke
1209
+ }) {
1210
+ const interaction = useContext3(ChartInteractionContext);
1211
+ const registerPoint = interaction?.registerPoint;
1212
+ useLayoutEffect2(() => {
1213
+ if (cx == null || cy == null)
1214
+ return;
1215
+ return registerPoint?.(seriesId, cx, cy);
1216
+ }, [registerPoint, seriesId, cx, cy]);
1217
+ const active = isChartSeriesActive(interaction, seriesId);
1218
+ return active ? /* @__PURE__ */ jsx8(ChartDot, {
1219
+ cx,
1220
+ cy,
1221
+ stroke,
1222
+ active: true,
1223
+ style: { pointerEvents: "none" }
1224
+ }) : null;
1225
+ }
1226
+ function ChartBar(props) {
1227
+ const series = useChartSeries(props.id);
1228
+ return /* @__PURE__ */ jsx8(ChartSeries, {
1229
+ id: series.id,
1230
+ children: /* @__PURE__ */ jsx8(Bar, {
1231
+ fill: chartBarFill,
1232
+ radius: props.stackId == null ? [5, 5, 0, 0] : 0,
1233
+ maxBarSize: 30,
1234
+ activeBar: series.active ? { opacity: 0.75 } : false,
1235
+ isAnimationActive: false,
1236
+ ...props,
1237
+ id: series.id
1238
+ })
1239
+ });
1240
+ }
1241
+ function ChartLine({
1242
+ stroke = seriesColor,
1243
+ dot = false,
1244
+ activeDot,
1245
+ ...props
1246
+ }) {
1247
+ const series = useChartSeries(props.id);
1248
+ return /* @__PURE__ */ jsx8(ChartSeries, {
1249
+ id: series.id,
1250
+ children: /* @__PURE__ */ jsx8(Line, {
1251
+ type: "linear",
1252
+ stroke,
1253
+ strokeWidth: 2,
1254
+ strokeLinecap: "round",
1255
+ strokeLinejoin: "round",
1256
+ dot: dot === true ? ({ cx, cy }) => /* @__PURE__ */ jsx8(ChartDot, {
1257
+ cx,
1258
+ cy,
1259
+ stroke
1260
+ }) : dot,
1261
+ activeDot: activeDot === undefined || activeDot === true ? ({ cx, cy }) => /* @__PURE__ */ jsx8(NearestChartDot, {
1262
+ seriesId: series.id,
1263
+ cx,
1264
+ cy,
1265
+ stroke
1266
+ }) : activeDot,
1267
+ isAnimationActive: false,
1268
+ ...props,
1269
+ id: series.id
1270
+ })
1271
+ });
1272
+ }
1273
+ function ChartArea({
1274
+ stroke = seriesColor,
1275
+ dot = false,
1276
+ activeDot,
1277
+ ...props
1278
+ }) {
1279
+ const series = useChartSeries(props.id);
1280
+ return /* @__PURE__ */ jsx8(ChartSeries, {
1281
+ id: series.id,
1282
+ children: /* @__PURE__ */ jsx8(Area, {
1283
+ legendType: "square",
1284
+ type: "linear",
1285
+ stroke,
1286
+ strokeWidth: 2,
1287
+ strokeLinecap: "round",
1288
+ strokeLinejoin: "round",
1289
+ fill: stroke,
1290
+ fillOpacity: 0.14,
1291
+ dot: dot === true ? ({ cx, cy }) => /* @__PURE__ */ jsx8(ChartDot, {
1292
+ cx,
1293
+ cy,
1294
+ stroke
1295
+ }) : dot,
1296
+ activeDot: activeDot === undefined || activeDot === true ? ({ cx, cy }) => /* @__PURE__ */ jsx8(NearestChartDot, {
1297
+ seriesId: series.id,
1298
+ cx,
1299
+ cy,
1300
+ stroke
1301
+ }) : activeDot,
1302
+ isAnimationActive: false,
1303
+ ...props,
1304
+ id: series.id
1305
+ })
1306
+ });
1307
+ }
1308
+ function ChartScatter(props) {
1309
+ const series = useChartSeries(props.id);
1310
+ return /* @__PURE__ */ jsx8(ChartSeries, {
1311
+ id: series.id,
1312
+ children: /* @__PURE__ */ jsx8(Scatter, {
1313
+ fill: seriesColor,
1314
+ isAnimationActive: false,
1315
+ ...props,
1316
+ id: series.id
1317
+ })
1318
+ });
1319
+ }
1320
+ function ChartYAxis(props) {
1321
+ return /* @__PURE__ */ jsx8(YAxis, {
1322
+ stroke: "var(--atbl-muted)",
1323
+ tickFormatter: (value) => typeof value === "number" ? formatNumber2(value) : String(value),
1324
+ tickLine: false,
1325
+ axisLine: false,
1326
+ tick: { fontSize: "var(--atbl-type-meta-size)" },
1327
+ ...props
1328
+ });
1329
+ }
1330
+ function ChartGrid(props) {
1331
+ return /* @__PURE__ */ jsx8(CartesianGrid, {
1332
+ stroke: "var(--atbl-border)",
1333
+ vertical: false,
1334
+ ...props
1335
+ });
1336
+ }
1337
+ function ChartTooltipContent(props) {
1338
+ if (!props.active || !props.payload?.length)
1339
+ return null;
1340
+ return /* @__PURE__ */ jsx8(TooltipSurface, {
1341
+ "data-variant": "chart",
1342
+ role: "tooltip",
1343
+ children: /* @__PURE__ */ jsx8(DefaultTooltipContent, {
1344
+ ...props,
1345
+ separator: "",
1346
+ payload: props.payload?.map((entry) => ({
1347
+ ...entry,
1348
+ unit: undefined,
1349
+ formatter: (value, name, _item, index, payload) => {
1350
+ const formatter = entry.formatter ?? props.formatter;
1351
+ const formatted = formatter ? formatter(value, name, entry, index, props.payload ?? payload) : Array.isArray(value) ? value.map((item) => typeof item === "number" ? formatNumber2(item) : item).join(" ~ ") : typeof value === "number" ? formatNumber2(value) : value;
1352
+ if (formatted == null)
1353
+ return null;
1354
+ const [displayValue, displayName] = Array.isArray(formatted) ? formatted : [formatted, name];
1355
+ return [
1356
+ /* @__PURE__ */ jsxs5("span", {
1357
+ className: "altertable-chart-tooltip-row",
1358
+ children: [
1359
+ /* @__PURE__ */ jsx8(ChartLegend.Marker, {
1360
+ kind: "square",
1361
+ className: "altertable-chart-tooltip-marker",
1362
+ color: entry.color ?? entry.stroke ?? entry.fill ?? "var(--atbl-chart-1)"
1363
+ }),
1364
+ /* @__PURE__ */ jsxs5("span", {
1365
+ className: "altertable-chart-tooltip-reading",
1366
+ children: [
1367
+ displayName,
1368
+ displayName !== undefined && displayName !== "" ? props.separator ?? " : " : "",
1369
+ displayValue,
1370
+ entry.unit
1371
+ ]
1372
+ })
1373
+ ]
1374
+ }, entry.graphicalItemId),
1375
+ ""
1376
+ ];
1377
+ }
1378
+ })),
1379
+ contentStyle: {
1380
+ margin: 0,
1381
+ padding: 0,
1382
+ background: "transparent",
1383
+ border: 0,
1384
+ whiteSpace: "normal",
1385
+ ...props.contentStyle
1386
+ },
1387
+ labelStyle: {
1388
+ color: "var(--atbl-text)",
1389
+ fontSize: "var(--atbl-type-body-size)",
1390
+ fontWeight: 650,
1391
+ lineHeight: 1.2,
1392
+ ...props.labelStyle
1393
+ },
1394
+ itemStyle: {
1395
+ color: "var(--atbl-text)",
1396
+ paddingTop: 2,
1397
+ paddingBottom: 0,
1398
+ ...props.itemStyle
1399
+ }
1400
+ })
1401
+ });
1402
+ }
1403
+ function ChartTooltip(props) {
1404
+ const dateLabel = useDateAxisLabel(props.axisId);
1405
+ const interaction = useContext3(ChartInteractionContext);
1406
+ return /* @__PURE__ */ jsx8(Tooltip, {
1407
+ labelFormatter: dateLabel,
1408
+ content: (content) => /* @__PURE__ */ jsx8(ChartTooltipContent, {
1409
+ ...content,
1410
+ payload: interaction?.isPointerInspection && interaction.seriesCount !== 1 && props.shared !== true ? content.payload.filter((entry) => entry.graphicalItemId === interaction.activeSeriesId) : content.payload
1411
+ }),
1412
+ position: interaction?.isPointerInspection && interaction.activePoint ? { y: interaction.activePoint.y } : undefined,
1413
+ cursor: false,
1414
+ isAnimationActive: false,
1415
+ ...props
1416
+ });
1417
+ }
1418
+
1419
+ // packages/data-app-react/src/ui/chart-data.ts
1420
+ import { invariant } from "@altertable/data-app/internal";
1421
+ function validateChartIds(kind, items) {
1422
+ const ids = new Set;
1423
+ for (const item of items) {
1424
+ invariant(item.id.trim().length > 0, `${kind} chart IDs must be nonempty and unique: blank ID.`);
1425
+ invariant(!ids.has(item.id), `${kind} chart IDs must be nonempty and unique: duplicate "${item.id}".`);
1426
+ ids.add(item.id);
1427
+ }
1428
+ }
1429
+ function validateValueChartItems(kind, items) {
1430
+ validateChartIds(kind, items);
1431
+ for (const item of items) {
1432
+ invariant(Number.isFinite(item.value), `${kind} chart "${item.id}" requires finite values.`);
1433
+ invariant(kind !== "bar" && kind !== "pie" || item.value >= 0, `${kind} chart "${item.id}" requires nonnegative values.`);
1434
+ }
1435
+ }
1436
+ function validateScatterChartItems(items) {
1437
+ validateChartIds("scatter", items);
1438
+ for (const item of items) {
1439
+ invariant(Number.isFinite(item.x) && Number.isFinite(item.y), `scatter chart "${item.id}" requires finite values for x and y.`);
1440
+ }
1441
+ }
1442
+
1443
+ // packages/data-app-react/src/ui/TrendChart.tsx
1444
+ import { jsx as jsx9, jsxs as jsxs6, Fragment as Fragment3 } from "react/jsx-runtime";
1445
+ function TrendChart({
1446
+ items,
1447
+ unit,
1448
+ ariaLabel,
1449
+ formatValue = formatNumber3,
1450
+ kind,
1451
+ itemActions
1452
+ }) {
1453
+ validateValueChartItems(kind, items);
1454
+ const Plot = kind === "area" ? RechartsAreaChart : RechartsLineChart;
1455
+ const chartActions = useChartActions();
1456
+ const [activeIndex, setActiveIndex] = useState3();
1457
+ const scrollport = useChartScrollToEnd(items);
1458
+ const menuTriggers = useRef3(new Map);
1459
+ const magnitude = items.reduce((max, item) => Math.max(max, Math.abs(item.value)), 1);
1460
+ const low = items.reduce((min, item) => Math.min(min, item.value / magnitude), 0);
1461
+ const high = items.reduce((max, item) => Math.max(max, item.value / magnitude), 0);
1462
+ return /* @__PURE__ */ jsxs6("section", {
1463
+ className: "altertable-trend-chart",
1464
+ "aria-label": ariaLabel,
1465
+ children: [
1466
+ items.length === 0 && /* @__PURE__ */ jsx9("span", {
1467
+ children: "No data"
1468
+ }),
1469
+ items.length > 0 && /* @__PURE__ */ jsx9(Fragment3, {
1470
+ children: /* @__PURE__ */ jsx9("div", {
1471
+ className: "altertable-trend-scroll",
1472
+ ref: scrollport,
1473
+ children: /* @__PURE__ */ jsxs6("div", {
1474
+ className: "altertable-trend-plot",
1475
+ style: { minWidth: items.length * 40 },
1476
+ children: [
1477
+ /* @__PURE__ */ jsx9("div", {
1478
+ className: "altertable-chart-canvas",
1479
+ "aria-hidden": "true",
1480
+ children: /* @__PURE__ */ jsxs6(Plot, {
1481
+ data: items.map((item) => ({
1482
+ ...item,
1483
+ plotValue: item.value / magnitude
1484
+ })),
1485
+ responsive: true,
1486
+ width: "100%",
1487
+ height: 220,
1488
+ margin: { top: 12, right: 0, bottom: 12, left: 0 },
1489
+ accessibilityLayer: false,
1490
+ tabIndex: -1,
1491
+ children: [
1492
+ /* @__PURE__ */ jsx9(ChartXAxis, {
1493
+ hide: true,
1494
+ dataKey: "id",
1495
+ scale: "band"
1496
+ }),
1497
+ /* @__PURE__ */ jsx9(ChartYAxis, {
1498
+ hide: true,
1499
+ domain: [low, high === low ? low + 1 : high]
1500
+ }),
1501
+ /* @__PURE__ */ jsx9(ReferenceLine, {
1502
+ y: 0,
1503
+ stroke: "var(--atbl-border)"
1504
+ }),
1505
+ kind === "area" && /* @__PURE__ */ jsx9(ChartArea, {
1506
+ dataKey: "plotValue",
1507
+ stroke: "none",
1508
+ fill: "var(--atbl-chart-1)",
1509
+ dot: false,
1510
+ activeDot: false
1511
+ }),
1512
+ /* @__PURE__ */ jsx9(ChartLine, {
1513
+ dataKey: "plotValue",
1514
+ dot: ({ cx, cy, index }) => index === activeIndex ? /* @__PURE__ */ jsx9(ChartDot, {
1515
+ cx,
1516
+ cy,
1517
+ active: index === activeIndex
1518
+ }) : /* @__PURE__ */ jsx9("g", {}),
1519
+ activeDot: false
1520
+ })
1521
+ ]
1522
+ })
1523
+ }),
1524
+ /* @__PURE__ */ jsx9("div", {
1525
+ className: "altertable-trend-points",
1526
+ children: items.map((item, index) => {
1527
+ const declaredActions = itemActions?.(item) ?? [];
1528
+ const actions = chartActions.actions(declaredActions, item.label, `${formatValue(item.value)} ${unit}`);
1529
+ const action = getPrimaryExplorationAction(actions);
1530
+ const menuTrigger = {
1531
+ get current() {
1532
+ return menuTriggers.current.get(item.id) ?? null;
1533
+ }
1534
+ };
1535
+ return /* @__PURE__ */ jsx9(Fragment2, {
1536
+ children: /* @__PURE__ */ jsxs6("div", {
1537
+ className: "altertable-chart-item-actions",
1538
+ children: [
1539
+ /* @__PURE__ */ jsx9(Tooltip2, {
1540
+ variant: "chart",
1541
+ onOpenChange: (open) => setActiveIndex((current) => open ? index : current === index ? undefined : current),
1542
+ content: /* @__PURE__ */ jsxs6(Fragment3, {
1543
+ children: [
1544
+ /* @__PURE__ */ jsx9("strong", {
1545
+ children: item.label
1546
+ }),
1547
+ /* @__PURE__ */ jsxs6("span", {
1548
+ children: [
1549
+ formatValue(item.value),
1550
+ " ",
1551
+ unit
1552
+ ]
1553
+ })
1554
+ ]
1555
+ }),
1556
+ className: "altertable-chart-column",
1557
+ children: action ? /* @__PURE__ */ jsxs6("button", {
1558
+ "data-atbl-focus": "ring",
1559
+ "data-atbl-control": "action",
1560
+ type: "button",
1561
+ className: "altertable-trend-point",
1562
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}. ${action.label}`,
1563
+ ...explorationMenuEvents(menuTrigger),
1564
+ onClick: (event) => action.onSelect(event.currentTarget),
1565
+ children: [
1566
+ /* @__PURE__ */ jsx9("span", {
1567
+ className: "altertable-trend-hit"
1568
+ }),
1569
+ /* @__PURE__ */ jsx9("span", {
1570
+ className: "altertable-trend-label",
1571
+ children: item.label
1572
+ })
1573
+ ]
1574
+ }) : actions.length > 1 ? /* @__PURE__ */ jsxs6(MenuTrigger2, {
1575
+ children: [
1576
+ /* @__PURE__ */ jsxs6(PressButton, {
1577
+ ...explorationMenuEvents(menuTrigger),
1578
+ ref: (element) => {
1579
+ if (element)
1580
+ menuTriggers.current.set(item.id, element);
1581
+ else
1582
+ menuTriggers.current.delete(item.id);
1583
+ },
1584
+ className: "altertable-trend-point",
1585
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}. Actions`,
1586
+ children: [
1587
+ /* @__PURE__ */ jsx9("span", {
1588
+ className: "altertable-trend-hit"
1589
+ }),
1590
+ /* @__PURE__ */ jsx9("span", {
1591
+ className: "altertable-trend-label",
1592
+ children: item.label
1593
+ })
1594
+ ]
1595
+ }),
1596
+ /* @__PURE__ */ jsx9(ExplorationActionMenu, {
1597
+ actions,
1598
+ ariaLabel: `${item.label} actions`,
1599
+ triggerRef: menuTrigger
1600
+ })
1601
+ ]
1602
+ }) : /* @__PURE__ */ jsxs6("button", {
1603
+ "data-atbl-focus": "ring",
1604
+ "data-atbl-control": "default",
1605
+ type: "button",
1606
+ tabIndex: -1,
1607
+ className: "altertable-trend-point",
1608
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}`,
1609
+ children: [
1610
+ /* @__PURE__ */ jsx9("span", {
1611
+ className: "altertable-trend-hit"
1612
+ }),
1613
+ /* @__PURE__ */ jsx9("span", {
1614
+ className: "altertable-trend-label",
1615
+ children: item.label
1616
+ })
1617
+ ]
1618
+ })
1619
+ }),
1620
+ action && /* @__PURE__ */ jsx9(ExplorationActionControl2, {
1621
+ contextOnly: declaredActions.length === 1,
1622
+ indicator: "chevron",
1623
+ ref: (element) => {
1624
+ if (element)
1625
+ menuTriggers.current.set(item.id, element);
1626
+ else
1627
+ menuTriggers.current.delete(item.id);
1628
+ },
1629
+ actions,
1630
+ ariaLabel: `${item.label} actions`,
1631
+ hidePrimary: Boolean(action)
1632
+ })
1633
+ ]
1634
+ })
1635
+ }, item.id);
1636
+ })
1637
+ })
1638
+ ]
1639
+ })
1640
+ })
1641
+ }),
1642
+ chartActions.feedback
1643
+ ]
1644
+ });
1645
+ }
1646
+
1647
+ // packages/data-app-react/src/ui/LineChart.tsx
1648
+ import { jsx as jsx10 } from "react/jsx-runtime";
1649
+ function LineChart(props) {
1650
+ return /* @__PURE__ */ jsx10(TrendChart, {
1651
+ ...props,
1652
+ kind: "line"
1653
+ });
1654
+ }
1655
+ // packages/data-app-react/src/ui/AreaChart.tsx
1656
+ import { jsx as jsx11 } from "react/jsx-runtime";
1657
+ function AreaChart(props) {
1658
+ return /* @__PURE__ */ jsx11(TrendChart, {
1659
+ ...props,
1660
+ kind: "area"
1661
+ });
1662
+ }
1663
+ // packages/data-app-react/src/ui/PieChart.tsx
1664
+ import { useRef as useRef4, useState as useState4 } from "react";
1665
+ import { jsx as jsx12, jsxs as jsxs7, Fragment as Fragment4 } from "react/jsx-runtime";
1666
+ function PieChart({
1667
+ items,
1668
+ unit,
1669
+ ariaLabel,
1670
+ showLegend = true,
1671
+ formatValue = (value) => new Intl.NumberFormat().format(value),
1672
+ itemActions
1673
+ }) {
1674
+ validateValueChartItems("pie", items);
1675
+ const chartActions = useChartActions();
1676
+ const [previewId, setPreviewId] = useState4(null);
1677
+ const [plotOpen, setPlotOpen] = useState4(false);
1678
+ const [legendId, setLegendId] = useState4(null);
1679
+ const menuTriggers = useRef4(new Map);
1680
+ const plotMenuTriggers = useRef4(new Map);
1681
+ const maximum = items.reduce((max, item) => Math.max(max, item.value), 0);
1682
+ const total = maximum ? items.reduce((sum, item) => sum + item.value / maximum, 0) : 0;
1683
+ let cursor = -Math.PI / 2;
1684
+ const slices = [];
1685
+ for (const [index, item] of items.entries()) {
1686
+ let point = function(angle) {
1687
+ return `${110 + Math.cos(angle) * 100},${110 + Math.sin(angle) * 100}`;
1688
+ };
1689
+ const share = total ? item.value / maximum / total : 0;
1690
+ const start = cursor;
1691
+ cursor += share * Math.PI * 2;
1692
+ const middle = (start + cursor) / 2;
1693
+ slices.push({
1694
+ row: item,
1695
+ share,
1696
+ color: `var(--atbl-chart-${index % 8 + 1})`,
1697
+ path: `${share === 1 ? "M" : "M110,110 L"}${point(start)} A100,100 0 0 1 ${point(middle)} A100,100 0 0 1 ${point(cursor)} Z`
1698
+ });
1699
+ }
1700
+ function percent(share) {
1701
+ return new Intl.NumberFormat("en-US", {
1702
+ style: "percent",
1703
+ maximumFractionDigits: 1
1704
+ }).format(share);
1705
+ }
1706
+ function detail(slice) {
1707
+ const item = slice.row;
1708
+ return /* @__PURE__ */ jsxs7(Fragment4, {
1709
+ children: [
1710
+ /* @__PURE__ */ jsx12("strong", {
1711
+ children: item.label
1712
+ }),
1713
+ /* @__PURE__ */ jsxs7("span", {
1714
+ children: [
1715
+ formatValue(item.value),
1716
+ " ",
1717
+ unit,
1718
+ " · ",
1719
+ percent(slice.share)
1720
+ ]
1721
+ })
1722
+ ]
1723
+ });
1724
+ }
1725
+ function actionsFor(slice) {
1726
+ const item = slice.row;
1727
+ return chartActions.actions(itemActions?.(item) ?? [], item.label, `${formatValue(item.value)} ${unit} · ${percent(slice.share)}`);
1728
+ }
1729
+ const preview = slices.find((slice) => slice.row.id === previewId);
1730
+ return /* @__PURE__ */ jsxs7("section", {
1731
+ className: "altertable-pie-chart",
1732
+ "aria-label": ariaLabel,
1733
+ children: [
1734
+ items.length === 0 && /* @__PURE__ */ jsx12("span", {
1735
+ children: "No data"
1736
+ }),
1737
+ items.length > 0 && /* @__PURE__ */ jsxs7(Fragment4, {
1738
+ children: [
1739
+ /* @__PURE__ */ jsxs7("div", {
1740
+ className: "altertable-pie-plot",
1741
+ children: [
1742
+ /* @__PURE__ */ jsx12(Tooltip2, {
1743
+ variant: "chart",
1744
+ className: "altertable-pie-tooltip",
1745
+ onOpenChange: setPlotOpen,
1746
+ content: preview ? detail(preview) : null,
1747
+ children: /* @__PURE__ */ jsx12("svg", {
1748
+ viewBox: "0 0 220 220",
1749
+ "aria-hidden": itemActions ? undefined : true,
1750
+ "aria-label": itemActions ? ariaLabel : undefined,
1751
+ focusable: itemActions ? undefined : false,
1752
+ role: itemActions ? "group" : undefined,
1753
+ children: total === 0 ? /* @__PURE__ */ jsx12("circle", {
1754
+ cx: "110",
1755
+ cy: "110",
1756
+ r: "100",
1757
+ className: "altertable-pie-empty"
1758
+ }) : slices.filter((slice) => slice.share > 0).map((slice) => {
1759
+ const item = slice.row;
1760
+ const menuTrigger = {
1761
+ get current() {
1762
+ return menuTriggers.current.get(item.id) ?? plotMenuTriggers.current.get(item.id) ?? null;
1763
+ }
1764
+ };
1765
+ const action = getPrimaryExplorationAction(actionsFor(slice));
1766
+ const opensMenu = !action && (itemActions?.(item).length ?? 0) > 1;
1767
+ return /* @__PURE__ */ jsx12("path", {
1768
+ d: slice.path,
1769
+ fill: slice.color,
1770
+ className: "altertable-pie-slice",
1771
+ "data-active": item.id === (plotOpen && previewId ? previewId : showLegend ? legendId : null) || undefined,
1772
+ onPointerDown: (event) => {
1773
+ if (plotOpen && previewId !== item.id)
1774
+ event.preventDefault();
1775
+ setPreviewId(item.id);
1776
+ },
1777
+ onClick: (event) => {
1778
+ if (action)
1779
+ action.onSelect(event.currentTarget);
1780
+ else if (opensMenu)
1781
+ menuTrigger.current?.click();
1782
+ },
1783
+ onContextMenu: explorationMenuEvents(menuTrigger).onContextMenu,
1784
+ onKeyDown: (event) => {
1785
+ explorationMenuEvents(menuTrigger).onKeyDown(event);
1786
+ if ((action || opensMenu) && (event.key === "Enter" || event.key === " ")) {
1787
+ event.preventDefault();
1788
+ if (action)
1789
+ action.onSelect(event.currentTarget);
1790
+ else
1791
+ menuTrigger.current?.click();
1792
+ }
1793
+ },
1794
+ "aria-label": action ? `${item.label}: ${formatValue(item.value)} ${unit}. ${action.label}` : opensMenu ? `${item.label}: ${formatValue(item.value)} ${unit}. Actions` : undefined,
1795
+ role: action || opensMenu ? "button" : undefined,
1796
+ "data-atbl-control": action || opensMenu ? "action" : undefined,
1797
+ tabIndex: action || opensMenu ? 0 : undefined,
1798
+ onPointerEnter: (event) => {
1799
+ if (event.pointerType === "mouse")
1800
+ setPreviewId(item.id);
1801
+ },
1802
+ onPointerLeave: (event) => {
1803
+ if (event.pointerType === "mouse")
1804
+ setPreviewId(null);
1805
+ }
1806
+ }, item.id);
1807
+ })
1808
+ })
1809
+ }),
1810
+ slices.map((slice) => {
1811
+ const item = slice.row;
1812
+ const actions = actionsFor(slice);
1813
+ if (actions.length === 0)
1814
+ return null;
1815
+ return /* @__PURE__ */ jsx12("span", {
1816
+ className: "altertable-sr-only",
1817
+ children: /* @__PURE__ */ jsx12(ExplorationActionControl2, {
1818
+ ref: (element) => {
1819
+ if (element)
1820
+ plotMenuTriggers.current.set(item.id, element);
1821
+ else
1822
+ plotMenuTriggers.current.delete(item.id);
1823
+ },
1824
+ actions,
1825
+ ariaLabel: `${item.label} actions`,
1826
+ contextOnly: true,
1827
+ hidePrimary: true
1828
+ })
1829
+ }, item.id);
1830
+ }),
1831
+ total === 0 && /* @__PURE__ */ jsx12("span", {
1832
+ className: "altertable-pie-empty-label",
1833
+ children: "No nonzero values"
1834
+ })
1835
+ ]
1836
+ }),
1837
+ showLegend && /* @__PURE__ */ jsx12(ChartLegend, {
1838
+ layout: "vertical",
1839
+ "aria-label": `${ariaLabel} legend`,
1840
+ className: "altertable-pie-legend",
1841
+ children: slices.map((slice) => {
1842
+ const item = slice.row;
1843
+ const actions = actionsFor(slice);
1844
+ const menuTrigger = {
1845
+ get current() {
1846
+ return menuTriggers.current.get(item.id) ?? null;
1847
+ }
1848
+ };
1849
+ const label = `${item.label}: ${formatValue(item.value)} ${unit}, ${percent(slice.share)}${actions.length ? ". Actions" : ""}`;
1850
+ const contents = /* @__PURE__ */ jsxs7(Fragment4, {
1851
+ children: [
1852
+ /* @__PURE__ */ jsx12(ChartLegend.Marker, {
1853
+ kind: "square",
1854
+ color: slice.color
1855
+ }),
1856
+ /* @__PURE__ */ jsx12(ChartLegend.Label, {
1857
+ className: "altertable-pie-label",
1858
+ children: item.label
1859
+ }),
1860
+ actions.length > 0 && /* @__PURE__ */ jsx12(AppIcon2, {
1861
+ name: "moreActions",
1862
+ size: 14,
1863
+ className: "altertable-pie-menu-indicator"
1864
+ }),
1865
+ /* @__PURE__ */ jsx12("strong", {
1866
+ className: "altertable-pie-value",
1867
+ children: formatValue(item.value)
1868
+ }),
1869
+ /* @__PURE__ */ jsx12("span", {
1870
+ className: "altertable-pie-share",
1871
+ children: percent(slice.share)
1872
+ })
1873
+ ]
1874
+ });
1875
+ return /* @__PURE__ */ jsx12(ChartLegend.Item, {
1876
+ children: /* @__PURE__ */ jsx12(Tooltip2, {
1877
+ variant: "chart",
1878
+ content: detail(slice),
1879
+ onOpenChange: (open) => setLegendId((current) => open ? item.id : current === item.id ? null : current),
1880
+ children: actions.length ? /* @__PURE__ */ jsxs7(MenuTrigger2, {
1881
+ children: [
1882
+ /* @__PURE__ */ jsx12(PressButton, {
1883
+ ...explorationMenuEvents(menuTrigger),
1884
+ ref: (element) => {
1885
+ if (element)
1886
+ menuTriggers.current.set(item.id, element);
1887
+ else
1888
+ menuTriggers.current.delete(item.id);
1889
+ },
1890
+ "aria-label": label,
1891
+ children: contents
1892
+ }),
1893
+ /* @__PURE__ */ jsx12(ExplorationActionMenu, {
1894
+ actions,
1895
+ ariaLabel: item.label,
1896
+ triggerRef: menuTrigger,
1897
+ placement: "bottom start"
1898
+ })
1899
+ ]
1900
+ }) : /* @__PURE__ */ jsx12("button", {
1901
+ type: "button",
1902
+ "data-atbl-focus": "ring",
1903
+ "data-atbl-control": "default",
1904
+ tabIndex: -1,
1905
+ "aria-label": label,
1906
+ children: contents
1907
+ })
1908
+ })
1909
+ }, item.id);
1910
+ })
1911
+ })
1912
+ ]
1913
+ }),
1914
+ chartActions.feedback
1915
+ ]
1916
+ });
1917
+ }
1918
+ // packages/data-app-react/src/ui/ScatterChart.tsx
1919
+ import { jsx as jsx13, jsxs as jsxs8, Fragment as Fragment5 } from "react/jsx-runtime";
1920
+ function formatNumber4(value) {
1921
+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(value);
1922
+ }
1923
+ function scale(values) {
1924
+ const magnitude = values.reduce((max, value) => Math.max(max, Math.abs(value)), 1);
1925
+ const low = values.reduce((min, value) => Math.min(min, value / magnitude), 0);
1926
+ const high = values.reduce((max, value) => Math.max(max, value / magnitude), 0) || (low === 0 ? 1 : 0);
1927
+ const span = high - low;
1928
+ return {
1929
+ position(value) {
1930
+ return (value / magnitude - low) / span * 100;
1931
+ },
1932
+ ticks: [low, low + span / 2, high].map((value) => value * magnitude)
1933
+ };
1934
+ }
1935
+ function ScatterChart({
1936
+ items,
1937
+ xLabel,
1938
+ yLabel,
1939
+ xUnit,
1940
+ yUnit,
1941
+ ariaLabel,
1942
+ formatX = formatNumber4,
1943
+ formatY = formatNumber4
1944
+ }) {
1945
+ validateScatterChartItems(items);
1946
+ const xScale = scale(items.map((item) => item.x));
1947
+ const yScale = scale(items.map((item) => item.y));
1948
+ return /* @__PURE__ */ jsxs8("section", {
1949
+ className: "altertable-scatter-chart",
1950
+ "aria-label": ariaLabel,
1951
+ children: [
1952
+ items.length === 0 && /* @__PURE__ */ jsx13("span", {
1953
+ children: "No data"
1954
+ }),
1955
+ items.length > 0 && /* @__PURE__ */ jsxs8(Fragment5, {
1956
+ children: [
1957
+ /* @__PURE__ */ jsxs8("p", {
1958
+ className: "altertable-scatter-axis-title",
1959
+ children: [
1960
+ yLabel,
1961
+ yUnit && ` (${yUnit})`
1962
+ ]
1963
+ }),
1964
+ /* @__PURE__ */ jsx13("div", {
1965
+ className: "altertable-scatter-axes",
1966
+ children: /* @__PURE__ */ jsxs8("div", {
1967
+ className: "altertable-scatter-plot",
1968
+ children: [
1969
+ yScale.ticks.map((value, index) => /* @__PURE__ */ jsx13("div", {
1970
+ className: "altertable-scatter-gridline",
1971
+ style: { bottom: `${index * 50}%` },
1972
+ "aria-hidden": "true",
1973
+ children: /* @__PURE__ */ jsx13("span", {
1974
+ title: formatY(value),
1975
+ children: formatY(value)
1976
+ })
1977
+ }, index)),
1978
+ xScale.ticks.map((value, index) => /* @__PURE__ */ jsx13("span", {
1979
+ className: "altertable-scatter-x-tick",
1980
+ "data-edge": index,
1981
+ style: { left: `${index * 50}%` },
1982
+ "aria-hidden": "true",
1983
+ title: formatX(value),
1984
+ children: formatX(value)
1985
+ }, index)),
1986
+ items.map((item) => /* @__PURE__ */ jsx13(Tooltip2, {
1987
+ variant: "chart",
1988
+ content: /* @__PURE__ */ jsxs8(Fragment5, {
1989
+ children: [
1990
+ /* @__PURE__ */ jsx13("strong", {
1991
+ children: item.label
1992
+ }),
1993
+ /* @__PURE__ */ jsxs8("span", {
1994
+ children: [
1995
+ xLabel,
1996
+ ": ",
1997
+ formatX(item.x),
1998
+ " ",
1999
+ xUnit
2000
+ ]
2001
+ }),
2002
+ /* @__PURE__ */ jsxs8("span", {
2003
+ children: [
2004
+ yLabel,
2005
+ ": ",
2006
+ formatY(item.y),
2007
+ " ",
2008
+ yUnit
2009
+ ]
2010
+ })
2011
+ ]
2012
+ }),
2013
+ className: "altertable-scatter-tooltip",
2014
+ style: {
2015
+ left: `${xScale.position(item.x)}%`,
2016
+ bottom: `${yScale.position(item.y)}%`
2017
+ },
2018
+ children: /* @__PURE__ */ jsx13("button", {
2019
+ "data-atbl-focus": "ring",
2020
+ "data-atbl-control": "default",
2021
+ type: "button",
2022
+ tabIndex: -1,
2023
+ className: "altertable-scatter-point",
2024
+ "aria-label": `${item.label}: ${xLabel} ${formatX(item.x)} ${xUnit}, ${yLabel} ${formatY(item.y)} ${yUnit}`,
2025
+ children: /* @__PURE__ */ jsx13("span", {})
2026
+ })
2027
+ }, item.id))
2028
+ ]
2029
+ })
2030
+ }),
2031
+ /* @__PURE__ */ jsxs8("p", {
2032
+ className: "altertable-scatter-axis-title altertable-scatter-x-title",
2033
+ children: [
2034
+ xLabel,
2035
+ xUnit && ` (${xUnit})`
2036
+ ]
2037
+ })
2038
+ ]
2039
+ })
2040
+ ]
2041
+ });
2042
+ }
2043
+ // packages/data-app-react/src/ui/BarChart.tsx
2044
+ import { formatNumber as formatNumber5 } from "@altertable/data-app/format";
2045
+ import {
2046
+ Fragment as Fragment6,
2047
+ useRef as useRef5,
2048
+ useState as useState5
2049
+ } from "react";
2050
+ import { BarChart as RechartsBarChart, Cell } from "recharts";
2051
+ import { jsx as jsx14, jsxs as jsxs9, Fragment as Fragment7 } from "react/jsx-runtime";
2052
+ function BarChart({
2053
+ items,
2054
+ unit,
2055
+ ariaLabel,
2056
+ formatValue = formatNumber5,
2057
+ itemActions
2058
+ }) {
2059
+ validateValueChartItems("bar", items);
2060
+ const chartActions = useChartActions();
2061
+ const [activeId, setActiveId] = useState5();
2062
+ const scrollport = useChartScrollToEnd(items);
2063
+ const menuTriggers = useRef5(new Map);
2064
+ const maximum = items.reduce((max, item) => Math.max(max, item.value), 1);
2065
+ return /* @__PURE__ */ jsxs9("section", {
2066
+ className: "altertable-selectable-bars",
2067
+ "aria-label": ariaLabel,
2068
+ children: [
2069
+ items.length === 0 && /* @__PURE__ */ jsx14("span", {
2070
+ children: "No data"
2071
+ }),
2072
+ /* @__PURE__ */ jsx14("div", {
2073
+ className: "altertable-selectable-bars-scroll",
2074
+ ref: scrollport,
2075
+ children: /* @__PURE__ */ jsxs9("div", {
2076
+ className: "altertable-selectable-bars-plot",
2077
+ style: { minWidth: items.length * 45 },
2078
+ children: [
2079
+ /* @__PURE__ */ jsx14("div", {
2080
+ className: "altertable-chart-canvas",
2081
+ "aria-hidden": "true",
2082
+ children: /* @__PURE__ */ jsxs9(RechartsBarChart, {
2083
+ data: items.map((item) => ({
2084
+ ...item,
2085
+ plotValue: item.value / maximum
2086
+ })),
2087
+ responsive: true,
2088
+ width: "100%",
2089
+ height: 220,
2090
+ margin: { top: 0, right: 0, bottom: 0, left: 0 },
2091
+ accessibilityLayer: false,
2092
+ tabIndex: -1,
2093
+ barCategoryGap: "24%",
2094
+ children: [
2095
+ /* @__PURE__ */ jsx14(ChartXAxis, {
2096
+ hide: true,
2097
+ dataKey: "id",
2098
+ scale: "band"
2099
+ }),
2100
+ /* @__PURE__ */ jsx14(ChartYAxis, {
2101
+ hide: true,
2102
+ domain: [0, 1],
2103
+ allowDataOverflow: true
2104
+ }),
2105
+ /* @__PURE__ */ jsx14(ChartBar, {
2106
+ dataKey: "plotValue",
2107
+ minPointSize: (value) => (value ?? 0) > 0 ? 7 : 0,
2108
+ children: items.map((item) => /* @__PURE__ */ jsx14(Cell, {
2109
+ fill: chartBarFill,
2110
+ opacity: activeId === item.id ? 0.75 : 1
2111
+ }, item.id))
2112
+ })
2113
+ ]
2114
+ })
2115
+ }),
2116
+ /* @__PURE__ */ jsx14("div", {
2117
+ className: "altertable-selectable-bars-items",
2118
+ children: items.map((item) => {
2119
+ const actions = chartActions.actions(itemActions?.(item) ?? [], item.label, `${formatValue(item.value)} ${unit}`);
2120
+ const action = getPrimaryExplorationAction(actions);
2121
+ const menuTrigger = {
2122
+ get current() {
2123
+ return menuTriggers.current.get(item.id) ?? null;
2124
+ }
2125
+ };
2126
+ return /* @__PURE__ */ jsx14(Fragment6, {
2127
+ children: /* @__PURE__ */ jsxs9("div", {
2128
+ className: "altertable-chart-item-actions",
2129
+ children: [
2130
+ /* @__PURE__ */ jsx14(Tooltip2, {
2131
+ variant: "chart",
2132
+ onOpenChange: (open) => setActiveId((current) => open ? item.id : current === item.id ? undefined : current),
2133
+ content: /* @__PURE__ */ jsxs9(Fragment7, {
2134
+ children: [
2135
+ /* @__PURE__ */ jsx14("strong", {
2136
+ children: item.label
2137
+ }),
2138
+ /* @__PURE__ */ jsxs9("span", {
2139
+ children: [
2140
+ formatValue(item.value),
2141
+ " ",
2142
+ unit
2143
+ ]
2144
+ })
2145
+ ]
2146
+ }),
2147
+ className: "altertable-chart-column",
2148
+ children: action ? /* @__PURE__ */ jsx14("button", {
2149
+ "data-atbl-focus": "ring",
2150
+ "data-atbl-control": "action",
2151
+ type: "button",
2152
+ className: "altertable-selectable-bars-item",
2153
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}. ${action.label}`,
2154
+ ...explorationMenuEvents(menuTrigger),
2155
+ onClick: (event) => action.onSelect(event.currentTarget),
2156
+ children: /* @__PURE__ */ jsx14("span", {
2157
+ className: "altertable-selectable-bars-area"
2158
+ })
2159
+ }) : actions.length ? /* @__PURE__ */ jsx14("button", {
2160
+ type: "button",
2161
+ "data-atbl-focus": "ring",
2162
+ "data-atbl-control": "action",
2163
+ className: "altertable-selectable-bars-item",
2164
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}. Actions`,
2165
+ ...explorationMenuEvents(menuTrigger),
2166
+ onClick: (event) => openExplorationMenu(menuTrigger, event),
2167
+ children: /* @__PURE__ */ jsx14("span", {
2168
+ className: "altertable-selectable-bars-area"
2169
+ })
2170
+ }) : /* @__PURE__ */ jsx14("button", {
2171
+ "data-atbl-focus": "ring",
2172
+ "data-atbl-control": "default",
2173
+ type: "button",
2174
+ tabIndex: -1,
2175
+ className: "altertable-selectable-bars-item",
2176
+ "aria-label": `${item.label}: ${formatValue(item.value)} ${unit}`,
2177
+ children: /* @__PURE__ */ jsx14("span", {
2178
+ className: "altertable-selectable-bars-area"
2179
+ })
2180
+ })
2181
+ }),
2182
+ /* @__PURE__ */ jsx14("div", {
2183
+ className: "altertable-chart-item-label-row",
2184
+ children: actions.length ? /* @__PURE__ */ jsxs9(MenuTrigger2, {
2185
+ children: [
2186
+ /* @__PURE__ */ jsxs9(PressButton, {
2187
+ className: "altertable-selectable-bars-label",
2188
+ variant: "ghost",
2189
+ size: "compact",
2190
+ ...explorationMenuEvents(menuTrigger),
2191
+ ref: (element) => {
2192
+ if (element)
2193
+ menuTriggers.current.set(item.id, element);
2194
+ else
2195
+ menuTriggers.current.delete(item.id);
2196
+ },
2197
+ "aria-label": `${item.label}: Actions`,
2198
+ children: [
2199
+ item.label,
2200
+ /* @__PURE__ */ jsx14(AppIcon2, {
2201
+ name: "disclosure",
2202
+ size: 12
2203
+ })
2204
+ ]
2205
+ }),
2206
+ /* @__PURE__ */ jsx14(ExplorationActionMenu, {
2207
+ actions,
2208
+ ariaLabel: item.label,
2209
+ triggerRef: menuTrigger,
2210
+ placement: "bottom"
2211
+ })
2212
+ ]
2213
+ }) : /* @__PURE__ */ jsx14("span", {
2214
+ className: "altertable-selectable-bars-label",
2215
+ children: item.label
2216
+ })
2217
+ })
2218
+ ]
2219
+ })
2220
+ }, item.id);
2221
+ })
2222
+ })
2223
+ ]
2224
+ })
2225
+ }),
2226
+ chartActions.feedback
2227
+ ]
2228
+ });
2229
+ }
2230
+ // packages/data-app-react/src/ui/RadioGroup.tsx
2231
+ import {
2232
+ RadioGroup as AriaRadioGroup,
2233
+ Radio as AriaRadio,
2234
+ Label
2235
+ } from "react-aria-components";
2236
+ import {
2237
+ validateChoiceOptions
2238
+ } from "@altertable/data-app/internal";
2239
+ import { jsx as jsx15, jsxs as jsxs10, Fragment as Fragment8 } from "react/jsx-runtime";
2240
+ function RadioGroup({
2241
+ label,
2242
+ className,
2243
+ children,
2244
+ ...props
2245
+ }) {
2246
+ return /* @__PURE__ */ jsxs10(AriaRadioGroup, {
2247
+ ...props,
2248
+ className: classNames("altertable-radio-group", className),
2249
+ children: [
2250
+ /* @__PURE__ */ jsx15(Label, {
2251
+ className: "altertable-control-label",
2252
+ children: label
2253
+ }),
2254
+ children
2255
+ ]
2256
+ });
2257
+ }
2258
+ function Radio({ className, children, ...props }) {
2259
+ return /* @__PURE__ */ jsx15(AriaRadio, {
2260
+ ...props,
2261
+ "data-atbl-control": "action",
2262
+ "data-atbl-focus": "ring",
2263
+ className: classNames("altertable-radio", className),
2264
+ children: (state) => /* @__PURE__ */ jsxs10(Fragment8, {
2265
+ children: [
2266
+ /* @__PURE__ */ jsx15("span", {
2267
+ className: "altertable-radio-mark",
2268
+ "aria-hidden": "true"
2269
+ }),
2270
+ typeof children === "function" ? children(state) : children
2271
+ ]
2272
+ })
2273
+ });
2274
+ }
2275
+ function SegmentedControl({
2276
+ options,
2277
+ className,
2278
+ ...props
2279
+ }) {
2280
+ validateChoiceOptions(options);
2281
+ return /* @__PURE__ */ jsx15(RadioGroup, {
2282
+ ...props,
2283
+ orientation: "horizontal",
2284
+ className: classNames("altertable-segmented-control", className),
2285
+ children: /* @__PURE__ */ jsx15("div", {
2286
+ className: "altertable-segmented-options",
2287
+ children: options.map((option) => /* @__PURE__ */ jsx15(Radio, {
2288
+ value: option.id,
2289
+ "data-atbl-internal-surface": "option",
2290
+ children: option.label
2291
+ }, option.id))
2292
+ })
2293
+ });
2294
+ }
2295
+ // packages/data-app-react/src/ui/CheckboxGroup.tsx
2296
+ import { invariant as invariant2 } from "@altertable/data-app/internal";
2297
+ import { jsx as jsx16, jsxs as jsxs11 } from "react/jsx-runtime";
2298
+ function CheckboxGroup({
2299
+ label,
2300
+ values,
2301
+ onChange,
2302
+ className,
2303
+ children,
2304
+ disabled,
2305
+ ...props
2306
+ }) {
2307
+ invariant2(new Set(values).size === values.length, "Checkbox group values must be unique.");
2308
+ return /* @__PURE__ */ jsxs11("fieldset", {
2309
+ ...props,
2310
+ disabled,
2311
+ className: classNames("altertable-checkbox-group", className),
2312
+ children: [
2313
+ /* @__PURE__ */ jsx16("legend", {
2314
+ children: label
2315
+ }),
2316
+ /* @__PURE__ */ jsx16(CheckboxGroupContext, {
2317
+ value: {
2318
+ values,
2319
+ disabled,
2320
+ onChange(value, checked) {
2321
+ onChange(checked ? [...values.filter((item) => item !== value), value] : values.filter((item) => item !== value));
2322
+ }
2323
+ },
2324
+ children
2325
+ })
2326
+ ]
2327
+ });
2328
+ }
2329
+ // packages/data-app-react/src/ui/ComposedChart.tsx
2330
+ import {
2331
+ useState as useState7,
2332
+ useCallback as useCallback2
2333
+ } from "react";
2334
+
2335
+ // packages/data-app-react/src/ui/ComposedChartLegend.tsx
2336
+ import { KEY_SEPARATOR } from "@altertable/data-app/internal";
2337
+ import { useState as useState6 } from "react";
2338
+ import { Legend } from "recharts";
2339
+ import { jsx as jsx17, jsxs as jsxs12, Fragment as Fragment9 } from "react/jsx-runtime";
2340
+ var legendMarkerKinds = {
2341
+ square: "area",
2342
+ rect: "bar",
2343
+ line: "line",
2344
+ plainline: "line"
2345
+ };
2346
+ function createLegendItemKeys() {
2347
+ const identities = new WeakMap;
2348
+ let nextIdentity = 0;
2349
+ function identity(value) {
2350
+ let id = identities.get(value);
2351
+ if (id === undefined) {
2352
+ id = nextIdentity++;
2353
+ identities.set(value, id);
2354
+ }
2355
+ return id;
2356
+ }
2357
+ return (payload) => {
2358
+ const keys = payload.map((entry) => {
2359
+ const source = entry.payload;
2360
+ const id = source && typeof source === "object" && "id" in source ? source.id : undefined;
2361
+ if (typeof id === "string" || typeof id === "number")
2362
+ return ["series", typeof id, id].join(KEY_SEPARATOR);
2363
+ const key = entry.dataKey;
2364
+ if (typeof key === "string" || typeof key === "number")
2365
+ return ["data", typeof key, key].join(KEY_SEPARATOR);
2366
+ return ["object", identity(typeof key === "function" ? key : entry)].join(KEY_SEPARATOR);
2367
+ });
2368
+ const counts = new Map;
2369
+ for (const key of keys)
2370
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2371
+ return keys.map((key, index) => {
2372
+ if (counts.get(key) === 1)
2373
+ return key;
2374
+ const entry = payload[index];
2375
+ const source = entry.payload;
2376
+ return [
2377
+ key,
2378
+ "object",
2379
+ identity(source && typeof source === "object" ? source : entry)
2380
+ ].join(KEY_SEPARATOR);
2381
+ });
2382
+ };
2383
+ }
2384
+ function LegendContent({
2385
+ payload = [],
2386
+ maxVisibleItems,
2387
+ formatter,
2388
+ layout,
2389
+ align,
2390
+ labelStyle,
2391
+ iconType,
2392
+ iconSize = 8,
2393
+ inactiveColor = "var(--atbl-muted)",
2394
+ position,
2395
+ verticalAlign,
2396
+ onClick,
2397
+ onMouseEnter,
2398
+ onMouseLeave,
2399
+ "aria-label": ariaLabel
2400
+ }) {
2401
+ const [getItemKeys] = useState6(createLegendItemKeys);
2402
+ const itemKeys = getItemKeys(payload);
2403
+ if (!payload.some((entry) => entry.type !== "none"))
2404
+ return null;
2405
+ const vertical = layout === "vertical" || layout === "auto" && (position === "left" || position === "right");
2406
+ return /* @__PURE__ */ jsx17(ChartLegend, {
2407
+ "aria-label": ariaLabel,
2408
+ className: position === "top" || position == null && verticalAlign === "top" ? "altertable-composed-chart-legend-above" : position === "bottom" || position == null && verticalAlign !== "middle" && !vertical ? "altertable-composed-chart-legend-below" : undefined,
2409
+ maxVisibleItems,
2410
+ layout: vertical ? "vertical" : "horizontal",
2411
+ align: align === "right" ? "end" : align === "left" ? "start" : "center",
2412
+ children: payload.map((entry, index) => {
2413
+ if (entry.type === "none")
2414
+ return null;
2415
+ const type = iconType ?? entry.type;
2416
+ const kind = iconType ? legendMarkerKinds[type ?? "none"] ?? "point" : "square";
2417
+ const formatLabel = entry.formatter ?? formatter;
2418
+ const label = formatLabel ? formatLabel(entry.value, entry, index) : entry.value;
2419
+ const content = /* @__PURE__ */ jsxs12(Fragment9, {
2420
+ children: [
2421
+ type !== "none" && (entry.legendIcon ?? /* @__PURE__ */ jsx17(ChartLegend.Marker, {
2422
+ kind,
2423
+ color: entry.inactive ? inactiveColor : entry.color,
2424
+ style: {
2425
+ width: iconSize,
2426
+ height: kind === "square" ? iconSize : iconSize * 0.6
2427
+ }
2428
+ })),
2429
+ /* @__PURE__ */ jsx17(ChartLegend.Label, {
2430
+ style: labelStyle,
2431
+ children: label
2432
+ })
2433
+ ]
2434
+ });
2435
+ return /* @__PURE__ */ jsx17(ChartLegend.Item, {
2436
+ inactive: entry.inactive,
2437
+ onMouseEnter: onMouseEnter ? (event) => onMouseEnter(entry, index, event) : undefined,
2438
+ onMouseLeave: onMouseLeave ? (event) => onMouseLeave(entry, index, event) : undefined,
2439
+ children: onClick ? /* @__PURE__ */ jsx17("button", {
2440
+ type: "button",
2441
+ "data-atbl-control": "action",
2442
+ "data-atbl-focus": "ring",
2443
+ className: "altertable-chart-legend-action",
2444
+ onClick: (event) => onClick(entry, index, event),
2445
+ children: content
2446
+ }) : content
2447
+ }, itemKeys[index]);
2448
+ })
2449
+ });
2450
+ }
2451
+ function ComposedChartLegend({
2452
+ maxVisibleItems,
2453
+ ...props
2454
+ }) {
2455
+ return /* @__PURE__ */ jsx17(Legend, {
2456
+ iconSize: 8,
2457
+ inactiveColor: "var(--atbl-muted)",
2458
+ content: /* @__PURE__ */ jsx17(LegendContent, {
2459
+ maxVisibleItems
2460
+ }),
2461
+ ...props
2462
+ });
2463
+ }
2464
+
2465
+ // packages/data-app-react/src/ui/ComposedChart.tsx
2466
+ import {
2467
+ ComposedChart as RechartsComposedChart,
2468
+ ZAxis,
2469
+ ReferenceLine as ReferenceLine2,
2470
+ ReferenceArea,
2471
+ ReferenceDot,
2472
+ Brush,
2473
+ Cell as Cell2,
2474
+ Label as Label2,
2475
+ LabelList,
2476
+ ErrorBar
2477
+ } from "recharts";
2478
+ import { jsx as jsx18 } from "react/jsx-runtime";
2479
+ function findNearestSeriesId(hoveredSeriesId, points, position) {
2480
+ if (!position || hoveredSeriesId != null && !points.has(hoveredSeriesId))
2481
+ return hoveredSeriesId;
2482
+ let selected = hoveredSeriesId;
2483
+ let distance = Infinity;
2484
+ for (const [id, point] of points) {
2485
+ const candidate = Math.hypot(point.x - position.x, point.y - position.y);
2486
+ if (candidate < distance) {
2487
+ distance = candidate;
2488
+ selected = id;
2489
+ }
2490
+ }
2491
+ return selected;
2492
+ }
2493
+ function ComposedChartRoot({
2494
+ data,
2495
+ ariaLabel,
2496
+ width = "100%",
2497
+ height = 300,
2498
+ responsive = true,
2499
+ className,
2500
+ ...props
2501
+ }) {
2502
+ const [hasPointerFocus, setHasPointerFocus] = useState7(false);
2503
+ const [isPointerInspection, setIsPointerInspection] = useState7(false);
2504
+ const [hoveredSeriesId, setHoveredSeriesId] = useState7(null);
2505
+ const [pointerPosition, setPointerPosition] = useState7(null);
2506
+ const [points, setPoints] = useState7(() => new Map);
2507
+ const registerPoint = useCallback2((id, x, y) => {
2508
+ setPoints((current) => new Map(current).set(id, { x, y }));
2509
+ return () => setPoints((current) => {
2510
+ const next = new Map(current);
2511
+ next.delete(id);
2512
+ return next;
2513
+ });
2514
+ }, []);
2515
+ function trackPointer(event) {
2516
+ const svg = event.currentTarget.querySelector('svg[role="application"]');
2517
+ if (!(svg instanceof SVGSVGElement) || !(event.target instanceof Node) || !svg.contains(event.target)) {
2518
+ resetPointerInspection();
2519
+ return false;
2520
+ }
2521
+ setIsPointerInspection(true);
2522
+ if (hoveredSeriesId != null && !points.has(hoveredSeriesId)) {
2523
+ setPointerPosition(null);
2524
+ return true;
2525
+ }
2526
+ const matrix = svg.getScreenCTM();
2527
+ if (!matrix)
2528
+ return true;
2529
+ const point = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse());
2530
+ setPointerPosition({ x: point.x, y: point.y });
2531
+ return true;
2532
+ }
2533
+ function resetPointerInspection() {
2534
+ setIsPointerInspection(false);
2535
+ setHoveredSeriesId(null);
2536
+ setPointerPosition(null);
2537
+ }
2538
+ const activeSeriesId = findNearestSeriesId(hoveredSeriesId, points, pointerPosition);
2539
+ const [seriesIds, setSeriesIds] = useState7(() => new Set);
2540
+ const registerSeries = useCallback2((id) => {
2541
+ setSeriesIds((current) => new Set(current).add(id));
2542
+ return () => {
2543
+ setSeriesIds((current) => {
2544
+ const next = new Set(current);
2545
+ next.delete(id);
2546
+ return next;
2547
+ });
2548
+ };
2549
+ }, []);
2550
+ return /* @__PURE__ */ jsx18(ChartInteractionContext.Provider, {
2551
+ value: {
2552
+ isPointerInspection,
2553
+ activeSeriesId,
2554
+ activePoint: activeSeriesId == null ? undefined : points.get(activeSeriesId),
2555
+ registerPoint,
2556
+ setHoveredSeriesId,
2557
+ seriesCount: seriesIds.size,
2558
+ registerSeries
2559
+ },
2560
+ children: /* @__PURE__ */ jsx18("section", {
2561
+ className: classNames("altertable-composed-chart", className),
2562
+ "aria-label": ariaLabel,
2563
+ "data-atbl-internal-pointer-focus": hasPointerFocus || undefined,
2564
+ onPointerDownCapture: (event) => {
2565
+ setHasPointerFocus(trackPointer(event));
2566
+ },
2567
+ onPointerOverCapture: trackPointer,
2568
+ onPointerMoveCapture: trackPointer,
2569
+ onPointerLeave: (event) => {
2570
+ if (event.pointerType !== "touch") {
2571
+ resetPointerInspection();
2572
+ }
2573
+ },
2574
+ onKeyDownCapture: () => {
2575
+ setHasPointerFocus(false);
2576
+ resetPointerInspection();
2577
+ },
2578
+ onBlurCapture: (event) => {
2579
+ if (!event.currentTarget.contains(event.relatedTarget)) {
2580
+ setHasPointerFocus(false);
2581
+ resetPointerInspection();
2582
+ }
2583
+ },
2584
+ children: /* @__PURE__ */ jsx18(ChartDateAxes, {
2585
+ data,
2586
+ children: /* @__PURE__ */ jsx18(RechartsComposedChart, {
2587
+ "data-atbl-focus": "inset",
2588
+ ...props,
2589
+ data,
2590
+ width,
2591
+ height,
2592
+ responsive,
2593
+ "aria-label": ariaLabel
2594
+ })
2595
+ })
2596
+ })
2597
+ });
2598
+ }
2599
+ var ComposedChart = Object.assign(ComposedChartRoot, {
2600
+ Dot: ChartDot,
2601
+ Area: ChartArea,
2602
+ Bar: ChartBar,
2603
+ Line: ChartLine,
2604
+ Scatter: ChartScatter,
2605
+ XAxis: ChartXAxis,
2606
+ YAxis: ChartYAxis,
2607
+ ZAxis,
2608
+ CartesianGrid: ChartGrid,
2609
+ Tooltip: ChartTooltip,
2610
+ Legend: ComposedChartLegend,
2611
+ ReferenceLine: ReferenceLine2,
2612
+ ReferenceArea,
2613
+ ReferenceDot,
2614
+ Brush,
2615
+ Cell: Cell2,
2616
+ Label: Label2,
2617
+ LabelList,
2618
+ ErrorBar
2619
+ });
2620
+ // packages/data-app-react/src/ui/FunnelChart.tsx
2621
+ import { KEY_SEPARATOR as KEY_SEPARATOR2 } from "@altertable/data-app/internal";
2622
+ import { Fragment as Fragment10, useEffect as useEffect4, useRef as useRef6, useState as useState8 } from "react";
2623
+ import { invariant as invariant3 } from "@altertable/data-app/internal";
2624
+
2625
+ // packages/data-app-react/src/ui/useSvgId.ts
2626
+ import { useId as useId3 } from "react";
2627
+ var svgIdCharacterPattern = /[a-zA-Z0-9-]/;
2628
+ function useSvgId() {
2629
+ const id = useId3();
2630
+ const encodedId = Array.from(id, (character) => svgIdCharacterPattern.test(character) ? character : `_${character.codePointAt(0).toString(16)}_`).join("");
2631
+ return ["svg", encodedId].join("-");
2632
+ }
2633
+
2634
+ // packages/data-app-react/src/ui/FunnelChart.tsx
2635
+ import { formatNumber as formatNumber6, formatPercent } from "@altertable/data-app/format";
2636
+ import { jsx as jsx19, jsxs as jsxs13, Fragment as Fragment11 } from "react/jsx-runtime";
2637
+ function createFunnelModel(steps, series, chartId) {
2638
+ for (const [kind, items] of [
2639
+ ["funnel step", steps],
2640
+ ["funnel series", series]
2641
+ ]) {
2642
+ const ids = new Set;
2643
+ for (const item of items) {
2644
+ invariant3(item.id.trim().length > 0 && !ids.has(item.id), `${kind} chart IDs must be nonblank and unique.`);
2645
+ ids.add(item.id);
2646
+ }
2647
+ }
2648
+ for (const item of series) {
2649
+ invariant3(item.values.length === steps.length, "funnel chart counts must align with steps.");
2650
+ item.values.forEach((value, index) => {
2651
+ invariant3(Number.isFinite(value) && value >= 0, "funnel chart counts must be finite and nonnegative.");
2652
+ invariant3(index === 0 || value <= item.values[index - 1], "funnel chart counts must be nonincreasing.");
2653
+ });
2654
+ }
2655
+ const populations = series.map((item, index) => ({
2656
+ id: item.id,
2657
+ label: item.label,
2658
+ color: `var(--atbl-chart-${index % 8 + 1})`,
2659
+ hatchId: [chartId, "hatch", index].join("-")
2660
+ }));
2661
+ const rows = steps.map((step, index) => ({
2662
+ id: step.id,
2663
+ label: step.label,
2664
+ index,
2665
+ readings: new Map(series.map((item, seriesIndex) => {
2666
+ const first = item.values[0] ?? 0;
2667
+ const current = item.values[index];
2668
+ const previous = item.values[Math.max(0, index - 1)];
2669
+ const dropped = previous - current;
2670
+ const conversion = first > 0 ? current / first : null;
2671
+ const dropOff = first > 0 ? dropped / first : null;
2672
+ return [
2673
+ item.id,
2674
+ {
2675
+ population: populations[seriesIndex],
2676
+ current,
2677
+ previous,
2678
+ dropped,
2679
+ conversion,
2680
+ dropOff,
2681
+ conversionPercent: (conversion ?? 0) * 100,
2682
+ dropOffPercent: (dropOff ?? (index === 0 ? 1 : 0)) * 100
2683
+ }
2684
+ ];
2685
+ }))
2686
+ }));
2687
+ return { populations, rows };
2688
+ }
2689
+ function FunnelChart({
2690
+ steps,
2691
+ series,
2692
+ unit,
2693
+ ariaLabel,
2694
+ className,
2695
+ formatValue = formatNumber6
2696
+ }) {
2697
+ const chartId = useSvgId();
2698
+ const [highlighted, setHighlighted] = useState8(null);
2699
+ const clearTimer = useRef6(null);
2700
+ function cancelClear() {
2701
+ if (clearTimer.current !== null)
2702
+ clearTimeout(clearTimer.current);
2703
+ clearTimer.current = null;
2704
+ }
2705
+ useEffect4(() => cancelClear, []);
2706
+ function highlight(id, conversion, step) {
2707
+ cancelClear();
2708
+ setHighlighted({ id, conversion, step });
2709
+ }
2710
+ function clearHighlight() {
2711
+ cancelClear();
2712
+ setHighlighted(null);
2713
+ }
2714
+ function scheduleClear() {
2715
+ cancelClear();
2716
+ clearTimer.current = setTimeout(() => setHighlighted(null), 100);
2717
+ }
2718
+ const { populations, rows } = createFunnelModel(steps, series, chartId);
2719
+ return /* @__PURE__ */ jsx19("section", {
2720
+ className: classNames("altertable-funnel-chart", className),
2721
+ "aria-label": ariaLabel,
2722
+ onKeyDownCapture: clearHighlight,
2723
+ children: steps.length === 0 || series.length === 0 ? /* @__PURE__ */ jsx19("span", {
2724
+ children: "No data"
2725
+ }) : /* @__PURE__ */ jsxs13(Fragment11, {
2726
+ children: [
2727
+ /* @__PURE__ */ jsxs13("div", {
2728
+ className: "altertable-funnel-header",
2729
+ children: [
2730
+ /* @__PURE__ */ jsx19(ChartLegend, {
2731
+ "aria-label": "Funnel series",
2732
+ layout: "single-row",
2733
+ children: populations.map((item) => /* @__PURE__ */ jsxs13(ChartLegend.Item, {
2734
+ className: "altertable-funnel-summary-item",
2735
+ children: [
2736
+ /* @__PURE__ */ jsxs13("span", {
2737
+ className: "altertable-funnel-series-label",
2738
+ children: [
2739
+ /* @__PURE__ */ jsx19(ChartLegend.Marker, {
2740
+ kind: "square",
2741
+ color: item.color
2742
+ }),
2743
+ /* @__PURE__ */ jsx19(ChartLegend.Label, {
2744
+ children: item.label
2745
+ })
2746
+ ]
2747
+ }),
2748
+ /* @__PURE__ */ jsx19("strong", {
2749
+ className: "altertable-funnel-series-value",
2750
+ children: formatPercent(rows.at(-1)?.readings.get(item.id)?.conversion ?? null)
2751
+ })
2752
+ ]
2753
+ }, item.id))
2754
+ }),
2755
+ /* @__PURE__ */ jsxs13("p", {
2756
+ className: "altertable-funnel-path",
2757
+ children: [
2758
+ steps[0].label,
2759
+ " → ",
2760
+ steps.at(-1).label
2761
+ ]
2762
+ })
2763
+ ]
2764
+ }),
2765
+ /* @__PURE__ */ jsx19("div", {
2766
+ className: "altertable-funnel-scroll",
2767
+ children: /* @__PURE__ */ jsx19("div", {
2768
+ style: {
2769
+ minWidth: steps.length * Math.max(96, series.length * 40)
2770
+ },
2771
+ children: /* @__PURE__ */ jsxs13(ComposedChart, {
2772
+ data: rows,
2773
+ ariaLabel: `${ariaLabel} plot`,
2774
+ height: 300,
2775
+ barCategoryGap: "4%",
2776
+ barGap: 1,
2777
+ onMouseLeave: clearHighlight,
2778
+ children: [
2779
+ /* @__PURE__ */ jsx19(ComposedChart.CartesianGrid, {}),
2780
+ /* @__PURE__ */ jsx19(ComposedChart.XAxis, {
2781
+ dataKey: "label",
2782
+ interval: 0,
2783
+ height: 48
2784
+ }),
2785
+ /* @__PURE__ */ jsx19(ComposedChart.YAxis, {
2786
+ domain: [0, 100],
2787
+ width: 42,
2788
+ tickFormatter: (value) => formatPercent(value / 100)
2789
+ }),
2790
+ /* @__PURE__ */ jsx19("defs", {
2791
+ children: populations.map((item) => /* @__PURE__ */ jsxs13("pattern", {
2792
+ id: item.hatchId,
2793
+ patternUnits: "userSpaceOnUse",
2794
+ width: "6",
2795
+ height: "6",
2796
+ patternTransform: "rotate(45)",
2797
+ children: [
2798
+ /* @__PURE__ */ jsx19("rect", {
2799
+ width: "8",
2800
+ height: "8",
2801
+ fill: item.color,
2802
+ fillOpacity: 0.16
2803
+ }),
2804
+ /* @__PURE__ */ jsx19("line", {
2805
+ x1: "0",
2806
+ y1: "0",
2807
+ x2: "0",
2808
+ y2: "8",
2809
+ stroke: item.color,
2810
+ strokeOpacity: 0.4,
2811
+ strokeWidth: "2"
2812
+ })
2813
+ ]
2814
+ }, item.id))
2815
+ }),
2816
+ populations.map((item) => /* @__PURE__ */ jsxs13(Fragment10, {
2817
+ children: [
2818
+ /* @__PURE__ */ jsx19(ComposedChart.Bar, {
2819
+ dataKey: (row) => row.readings.get(item.id)?.conversionPercent ?? 0,
2820
+ name: item.label,
2821
+ stackId: item.id,
2822
+ fill: item.color,
2823
+ radius: 0,
2824
+ maxBarSize: undefined,
2825
+ activeBar: false,
2826
+ minPointSize: 0,
2827
+ opacity: !highlighted || highlighted.id === item.id ? 1 : 0.2,
2828
+ onMouseEnter: (bar) => highlight(item.id, true, bar.payload.index),
2829
+ onMouseLeave: scheduleClear,
2830
+ onClick: (bar) => highlight(item.id, true, bar.payload.index)
2831
+ }),
2832
+ /* @__PURE__ */ jsx19(ComposedChart.Bar, {
2833
+ dataKey: (row) => row.readings.get(item.id)?.dropOffPercent ?? 0,
2834
+ name: `${item.label} drop-off`,
2835
+ stackId: item.id,
2836
+ fill: `url(#${item.hatchId})`,
2837
+ opacity: !highlighted || highlighted.id === item.id ? 1 : 0.2,
2838
+ onMouseEnter: (bar) => highlight(item.id, false, bar.payload.index),
2839
+ onMouseLeave: scheduleClear,
2840
+ onClick: (bar) => highlight(item.id, false, bar.payload.index),
2841
+ radius: 0,
2842
+ maxBarSize: undefined,
2843
+ activeBar: false
2844
+ })
2845
+ ]
2846
+ }, item.id)),
2847
+ /* @__PURE__ */ jsx19(ComposedChart.Tooltip, {
2848
+ content: ({ active, activeIndex }) => {
2849
+ const row = activeIndex == null ? undefined : rows[Number(activeIndex)];
2850
+ if (!active || !row)
2851
+ return null;
2852
+ const tooltipItems = [...row.readings.values()].filter((value) => !highlighted || highlighted.step !== row.index || value.population.id === highlighted.id).flatMap((value) => {
2853
+ const item = value.population;
2854
+ const selected = highlighted?.step === row.index;
2855
+ const readings = selected ? [highlighted.conversion] : [true, false];
2856
+ return readings.map((conversion) => {
2857
+ const key = [
2858
+ item.id,
2859
+ conversion ? "conversion" : "drop-off"
2860
+ ].join(KEY_SEPARATOR2);
2861
+ return {
2862
+ name: item.label,
2863
+ graphicalItemId: key,
2864
+ dataKey: key,
2865
+ color: item.color,
2866
+ value: (conversion ? value.conversion : value.dropOff) ?? 0,
2867
+ formatter: () => /* @__PURE__ */ jsxs13(Fragment11, {
2868
+ children: [
2869
+ formatPercent(conversion ? value.conversion : value.dropOff),
2870
+ " ",
2871
+ conversion ? "conversion" : "drop-off",
2872
+ /* @__PURE__ */ jsxs13("span", {
2873
+ className: "altertable-funnel-tooltip-detail",
2874
+ children: [
2875
+ formatValue(conversion ? value.current : value.dropped),
2876
+ " ",
2877
+ "of ",
2878
+ formatValue(value.previous),
2879
+ " ",
2880
+ unit
2881
+ ]
2882
+ })
2883
+ ]
2884
+ })
2885
+ };
2886
+ });
2887
+ });
2888
+ return /* @__PURE__ */ jsx19(ChartTooltipContent, {
2889
+ active: true,
2890
+ label: row.label,
2891
+ payload: tooltipItems
2892
+ });
2893
+ }
2894
+ })
2895
+ ]
2896
+ })
2897
+ })
2898
+ }),
2899
+ /* @__PURE__ */ jsx19("ul", {
2900
+ className: "altertable-sr-only",
2901
+ children: rows.map((row) => /* @__PURE__ */ jsxs13("li", {
2902
+ children: [
2903
+ row.label,
2904
+ [...row.readings.values()].map((value) => /* @__PURE__ */ jsxs13("span", {
2905
+ children: [
2906
+ " ",
2907
+ "· ",
2908
+ value.population.label,
2909
+ ": ",
2910
+ formatValue(value.current),
2911
+ " ",
2912
+ unit,
2913
+ ", ",
2914
+ formatPercent(value.conversion),
2915
+ " conversion,",
2916
+ " ",
2917
+ formatValue(value.dropped),
2918
+ " dropped off"
2919
+ ]
2920
+ }, value.population.id))
2921
+ ]
2922
+ }, row.id))
2923
+ })
2924
+ ]
2925
+ })
2926
+ });
2927
+ }
2928
+ // packages/data-app-react/src/ui/RetentionChart.tsx
2929
+ import { Fragment as Fragment12 } from "react";
2930
+ import { invariant as invariant4 } from "@altertable/data-app/internal";
2931
+ import { formatNumber as formatNumber7, formatPercent as formatPercent2 } from "@altertable/data-app/format";
2932
+ import { jsx as jsx20, jsxs as jsxs14, Fragment as Fragment13 } from "react/jsx-runtime";
2933
+ function createRetentionModel(series, unit, formatValue) {
2934
+ const ids = new Set;
2935
+ const rowsByOffset = new Map;
2936
+ const cohorts = series.map((item, index) => {
2937
+ invariant4(item.id.trim().length > 0 && !ids.has(item.id), "retention series chart IDs must be nonblank and unique.");
2938
+ ids.add(item.id);
2939
+ invariant4(Number.isFinite(item.cohortSize) && item.cohortSize >= 0, "retention chart counts must be finite and nonnegative.");
2940
+ const seen = new Set;
2941
+ let previous;
2942
+ const readings = [...item.points].sort((a, b) => a.offset - b.offset).map((point) => {
2943
+ invariant4(Number.isSafeInteger(point.offset) && point.offset >= 0 && !seen.has(point.offset), "retention chart offsets must be unique nonnegative integers within each series.");
2944
+ seen.add(point.offset);
2945
+ invariant4(point.rate === null || Number.isFinite(point.rate) && point.rate >= 0 && point.rate <= 1, "retention chart rates must be finite fractions between 0 and 1, or null.");
2946
+ invariant4(point.rate === null === (point.retainedCount === null), "retention chart unobserved rates and counts must both be null.");
2947
+ if (point.retainedCount !== null) {
2948
+ invariant4(Number.isFinite(point.retainedCount) && point.retainedCount >= 0, "retention chart counts must be finite and nonnegative.");
2949
+ invariant4(point.retainedCount <= item.cohortSize, "retention chart retained counts cannot exceed cohort size.");
2950
+ }
2951
+ let row = rowsByOffset.get(point.offset);
2952
+ invariant4(!row || row.label === point.label, "retention chart labels must agree for the same offset.");
2953
+ if (!row) {
2954
+ row = {
2955
+ offset: point.offset,
2956
+ label: point.label,
2957
+ readings: new Map
2958
+ };
2959
+ rowsByOffset.set(point.offset, row);
2960
+ }
2961
+ const percent = point.rate === null ? null : point.rate * 100;
2962
+ const reading = {
2963
+ point,
2964
+ completePercent: point.incomplete ? null : percent,
2965
+ incompletePercent: point.incomplete ? percent : null,
2966
+ description: point.rate === null || point.retainedCount === null ? "Not observed" : `${formatPercent2(point.rate)} · ${formatValue(point.retainedCount)} / ${formatValue(item.cohortSize)} ${unit}${point.incomplete ? " · Incomplete period" : ""}`
2967
+ };
2968
+ if (point.incomplete && previous) {
2969
+ previous.incompletePercent = previous.completePercent ?? previous.incompletePercent;
2970
+ }
2971
+ row.readings.set(item.id, reading);
2972
+ previous = reading;
2973
+ return reading;
2974
+ });
2975
+ return {
2976
+ id: item.id,
2977
+ label: item.label,
2978
+ color: `var(--atbl-chart-${index % 8 + 1})`,
2979
+ readings
2980
+ };
2981
+ });
2982
+ const rows = [...rowsByOffset.values()].sort((a, b) => a.offset - b.offset);
2983
+ return { rows, rowsByOffset, cohorts };
2984
+ }
2985
+ function RetentionChart({
2986
+ series,
2987
+ unit,
2988
+ ariaLabel,
2989
+ className,
2990
+ formatValue = formatNumber7
2991
+ }) {
2992
+ const { rows, rowsByOffset, cohorts } = createRetentionModel(series, unit, formatValue);
2993
+ return /* @__PURE__ */ jsx20("section", {
2994
+ className: classNames("altertable-retention-chart", className),
2995
+ "aria-label": ariaLabel,
2996
+ children: rows.length === 0 ? /* @__PURE__ */ jsx20("span", {
2997
+ children: "No data"
2998
+ }) : /* @__PURE__ */ jsxs14(Fragment13, {
2999
+ children: [
3000
+ /* @__PURE__ */ jsxs14(ComposedChart, {
3001
+ data: rows,
3002
+ ariaLabel: `${ariaLabel} plot`,
3003
+ children: [
3004
+ /* @__PURE__ */ jsx20(ComposedChart.CartesianGrid, {}),
3005
+ /* @__PURE__ */ jsx20(ComposedChart.XAxis, {
3006
+ dataKey: "offset",
3007
+ type: "number",
3008
+ domain: [0, Math.max(1, rows.at(-1)?.offset ?? 0)],
3009
+ ticks: rows.map((row) => row.offset),
3010
+ tickFormatter: (value) => rowsByOffset.get(Number(value))?.label ?? ""
3011
+ }),
3012
+ /* @__PURE__ */ jsx20(ComposedChart.YAxis, {
3013
+ domain: [0, 100],
3014
+ width: 42,
3015
+ tickFormatter: (value) => `${value}%`
3016
+ }),
3017
+ cohorts.map((item) => /* @__PURE__ */ jsxs14(Fragment12, {
3018
+ children: [
3019
+ /* @__PURE__ */ jsx20(ComposedChart.Line, {
3020
+ dataKey: (row) => row.readings.get(item.id)?.completePercent ?? null,
3021
+ name: item.label,
3022
+ stroke: item.color,
3023
+ connectNulls: false
3024
+ }),
3025
+ /* @__PURE__ */ jsx20(ComposedChart.Line, {
3026
+ dataKey: (row) => row.readings.get(item.id)?.incompletePercent ?? null,
3027
+ name: item.label,
3028
+ stroke: item.color,
3029
+ strokeDasharray: "3 3",
3030
+ dot: false,
3031
+ activeDot: false,
3032
+ connectNulls: false
3033
+ })
3034
+ ]
3035
+ }, item.id)),
3036
+ /* @__PURE__ */ jsx20(ComposedChart.Tooltip, {
3037
+ filterNull: false,
3038
+ content: ({ active, label }) => {
3039
+ const row = typeof label === "number" ? rowsByOffset.get(label) : undefined;
3040
+ if (!active || !row)
3041
+ return null;
3042
+ return /* @__PURE__ */ jsxs14(TooltipSurface, {
3043
+ "data-variant": "chart",
3044
+ role: "tooltip",
3045
+ children: [
3046
+ /* @__PURE__ */ jsx20("strong", {
3047
+ children: row.label
3048
+ }),
3049
+ cohorts.map((item) => {
3050
+ const reading = row.readings.get(item.id);
3051
+ if (!reading)
3052
+ return null;
3053
+ return /* @__PURE__ */ jsxs14("span", {
3054
+ children: [
3055
+ item.label,
3056
+ ": ",
3057
+ reading.description
3058
+ ]
3059
+ }, item.id);
3060
+ })
3061
+ ]
3062
+ });
3063
+ }
3064
+ })
3065
+ ]
3066
+ }),
3067
+ /* @__PURE__ */ jsx20(ChartLegend, {
3068
+ "aria-label": `${ariaLabel} cohorts`,
3069
+ children: cohorts.map((item) => /* @__PURE__ */ jsxs14(ChartLegend.Item, {
3070
+ children: [
3071
+ /* @__PURE__ */ jsx20(ChartLegend.Marker, {
3072
+ kind: "square",
3073
+ color: item.color
3074
+ }),
3075
+ /* @__PURE__ */ jsx20(ChartLegend.Label, {
3076
+ children: item.label
3077
+ })
3078
+ ]
3079
+ }, item.id))
3080
+ }),
3081
+ /* @__PURE__ */ jsx20("ul", {
3082
+ className: "altertable-sr-only",
3083
+ "aria-label": `${ariaLabel} readings`,
3084
+ children: cohorts.map((item) => /* @__PURE__ */ jsxs14("li", {
3085
+ children: [
3086
+ item.label,
3087
+ item.readings.map((reading) => /* @__PURE__ */ jsxs14("span", {
3088
+ children: [
3089
+ " ",
3090
+ "· ",
3091
+ reading.point.label,
3092
+ ": ",
3093
+ reading.description
3094
+ ]
3095
+ }, reading.point.offset))
3096
+ ]
3097
+ }, item.id))
3098
+ })
3099
+ ]
3100
+ })
3101
+ });
3102
+ }
3103
+ // packages/data-app-react/src/ui/JourneyChart.tsx
3104
+ import { useLayoutEffect as useLayoutEffect3, useRef as useRef7, useState as useState9 } from "react";
3105
+ import { invariant as invariant5 } from "@altertable/data-app/internal";
3106
+ import { formatNumber as formatNumber8, formatPercent as formatPercent3 } from "@altertable/data-app/format";
3107
+
3108
+ // packages/data-app-react/src/ui/journey-flow.ts
3109
+ var journeyOutcomeLabels = {
3110
+ truncated: "More steps",
3111
+ "drop-off": "Drop-off",
3112
+ converted: "Converted",
3113
+ end: "End of path"
3114
+ };
3115
+ function journeyNodes(path) {
3116
+ const nodes = path.steps.map((step, depth) => ({
3117
+ key: JSON.stringify([depth, "event", step.event, step.property]),
3118
+ label: step.property === null ? step.event : `${step.event} · ${step.property}`,
3119
+ depth,
3120
+ outcome: "event"
3121
+ }));
3122
+ const outcome = path.truncated ? "truncated" : path.converted === false ? "drop-off" : path.converted === true ? "converted" : "end";
3123
+ nodes.push({
3124
+ key: JSON.stringify([nodes.length, outcome]),
3125
+ label: journeyOutcomeLabels[outcome],
3126
+ depth: nodes.length,
3127
+ outcome
3128
+ });
3129
+ return nodes;
3130
+ }
3131
+ function buildJourneyFlow(paths, expandedBranch) {
3132
+ const nodes = new Map;
3133
+ const links = new Map;
3134
+ for (const path of paths) {
3135
+ const fullSequence = journeyNodes(path);
3136
+ if (path.truncated)
3137
+ fullSequence.pop();
3138
+ const sequence = expandedBranch === undefined ? fullSequence : fullSequence.flatMap((node, index) => {
3139
+ const branchKeys = fullSequence.slice(0, index + 1).map((step) => step.key);
3140
+ const parentExpanded = index <= 1 || branchKeys.slice(0, index).every((key, depth) => expandedBranch[depth] === key);
3141
+ if (!parentExpanded)
3142
+ return [];
3143
+ return [
3144
+ {
3145
+ ...node,
3146
+ key: JSON.stringify(branchKeys),
3147
+ branchKeys,
3148
+ expandable: index >= 1 && index < fullSequence.length - 1,
3149
+ expanded: branchKeys.every((key, depth) => expandedBranch[depth] === key)
3150
+ }
3151
+ ];
3152
+ });
3153
+ sequence.forEach((node, index) => {
3154
+ const current = nodes.get(node.key) ?? {
3155
+ ...node,
3156
+ count: 0,
3157
+ pathKeys: []
3158
+ };
3159
+ current.count += path.count;
3160
+ if ("expandable" in node && node.expandable)
3161
+ current.expandable = true;
3162
+ current.pathKeys.push(path.id);
3163
+ nodes.set(node.key, current);
3164
+ const previous = sequence[index - 1];
3165
+ if (!previous)
3166
+ return;
3167
+ const key = JSON.stringify([previous.key, node.key]);
3168
+ const link = links.get(key) ?? {
3169
+ key,
3170
+ source: previous.key,
3171
+ target: node.key,
3172
+ count: 0,
3173
+ pathKeys: []
3174
+ };
3175
+ link.count += path.count;
3176
+ link.pathKeys.push(path.id);
3177
+ links.set(key, link);
3178
+ });
3179
+ }
3180
+ return { nodes: [...nodes.values()], links: [...links.values()] };
3181
+ }
3182
+ function limitJourneyFlow(graph, visibleEventsByDepth = {}) {
3183
+ const nodes = [];
3184
+ const replacements = new Map;
3185
+ for (const depth of new Set(graph.nodes.map((node) => node.depth))) {
3186
+ const column = graph.nodes.filter((node) => node.depth === depth).sort((a, b) => Number(Boolean(b.expanded)) - Number(Boolean(a.expanded)) || b.count - a.count || a.key.localeCompare(b.key));
3187
+ const events = column.filter((node) => node.outcome === "event");
3188
+ const outcomes = column.filter((node) => node.outcome !== "event");
3189
+ const limit = visibleEventsByDepth[depth] ?? 3;
3190
+ if (events.length <= limit) {
3191
+ nodes.push(...column);
3192
+ continue;
3193
+ }
3194
+ nodes.push(...events.slice(0, limit), ...outcomes);
3195
+ const hidden = events.slice(limit);
3196
+ const key = JSON.stringify(["other", depth]);
3197
+ hidden.forEach((node) => replacements.set(node.key, key));
3198
+ nodes.push({
3199
+ key,
3200
+ label: "More events",
3201
+ depth,
3202
+ outcome: "other",
3203
+ hiddenBranchCount: hidden.length,
3204
+ count: hidden.reduce((sum, node) => sum + node.count, 0),
3205
+ pathKeys: [...new Set(hidden.flatMap((node) => node.pathKeys))]
3206
+ });
3207
+ }
3208
+ const links = new Map;
3209
+ for (const link of graph.links) {
3210
+ const source = replacements.get(link.source) ?? link.source;
3211
+ const target = replacements.get(link.target) ?? link.target;
3212
+ const key = JSON.stringify([source, target]);
3213
+ const existing = links.get(key);
3214
+ if (existing) {
3215
+ existing.count += link.count;
3216
+ existing.pathKeys.push(...link.pathKeys);
3217
+ } else {
3218
+ links.set(key, {
3219
+ ...link,
3220
+ key,
3221
+ source,
3222
+ target,
3223
+ pathKeys: [...link.pathKeys]
3224
+ });
3225
+ }
3226
+ }
3227
+ return { nodes, links: [...links.values()] };
3228
+ }
3229
+
3230
+ // packages/data-app-react/src/ui/JourneyChart.tsx
3231
+ import { jsx as jsx21, jsxs as jsxs15 } from "react/jsx-runtime";
3232
+ function JourneyChart({
3233
+ paths,
3234
+ unit,
3235
+ ariaLabel,
3236
+ className,
3237
+ formatValue = formatNumber8
3238
+ }) {
3239
+ const ids = new Set;
3240
+ let total = 0;
3241
+ for (const path of paths) {
3242
+ invariant5(path.id.trim().length > 0 && !ids.has(path.id), "journey path chart IDs must be nonblank and unique.");
3243
+ ids.add(path.id);
3244
+ invariant5(Number.isFinite(path.count) && path.count >= 0, "journey chart counts must be finite and nonnegative.");
3245
+ total += path.count;
3246
+ invariant5(path.steps.length > 0 && path.steps.every((step) => step.event.trim().length > 0), "journey chart paths require nonblank events.");
3247
+ }
3248
+ invariant5(Number.isFinite(total), "journey chart total count must be finite.");
3249
+ return /* @__PURE__ */ jsx21("section", {
3250
+ className: classNames("altertable-journey-chart", className),
3251
+ "aria-label": ariaLabel,
3252
+ children: paths.length === 0 ? /* @__PURE__ */ jsx21("span", {
3253
+ children: "No data"
3254
+ }) : /* @__PURE__ */ jsx21(JourneyFlow, {
3255
+ paths,
3256
+ unit,
3257
+ formatValue
3258
+ }, JSON.stringify(paths))
3259
+ });
3260
+ }
3261
+ function JourneyFlow({
3262
+ paths,
3263
+ unit,
3264
+ formatValue
3265
+ }) {
3266
+ const [expandedBranch, setExpandedBranch] = useState9([]);
3267
+ const [visibleEventsByDepth, setVisibleEventsByDepth] = useState9({});
3268
+ const graph = limitJourneyFlow(buildJourneyFlow(paths, expandedBranch), visibleEventsByDepth);
3269
+ const scrollRef = useRef7(null);
3270
+ const pendingDepth = useRef7(null);
3271
+ const depthCount = Math.max(0, ...graph.nodes.map((node) => node.depth)) + 1;
3272
+ const startingCount = graph.nodes.filter((node) => node.depth === 0).reduce((sum, node) => sum + node.count, 0);
3273
+ function percent(count) {
3274
+ return formatPercent3(startingCount > 0 ? count / startingCount : null);
3275
+ }
3276
+ const nodeWidth = 176;
3277
+ const nodeHeight = 96;
3278
+ const barWidth = 16;
3279
+ const rowSpacing = nodeHeight + 80;
3280
+ const columnSpacing = nodeWidth + 112;
3281
+ const width = 34 + nodeWidth + (depthCount - 1) * columnSpacing;
3282
+ function columnX(depth) {
3283
+ return 10 + depth * columnSpacing;
3284
+ }
3285
+ useLayoutEffect3(() => {
3286
+ const depth = pendingDepth.current;
3287
+ const container = scrollRef.current;
3288
+ if (depth === null || !container || depth >= depthCount)
3289
+ return;
3290
+ pendingDepth.current = null;
3291
+ const left = columnX(depth);
3292
+ const right = left + nodeWidth + 24;
3293
+ const nextLeft = left < container.scrollLeft ? left - 24 : right > container.scrollLeft + container.clientWidth ? right - container.clientWidth : container.scrollLeft;
3294
+ if (nextLeft !== container.scrollLeft)
3295
+ container.scrollTo({
3296
+ left: Math.max(0, nextLeft),
3297
+ behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth"
3298
+ });
3299
+ });
3300
+ const columns = Array.from({ length: depthCount }, (_, depth) => graph.nodes.filter((node) => node.depth === depth).sort((a, b) => {
3301
+ function rank(node) {
3302
+ return node.outcome === "event" ? 0 : node.outcome === "other" ? 1 : 2;
3303
+ }
3304
+ return rank(a) - rank(b) || b.count - a.count || a.key.localeCompare(b.key);
3305
+ }));
3306
+ const positions = new Map;
3307
+ columns.forEach((column, depth) => {
3308
+ const parent = columns[depth - 1]?.find((node) => node.expanded);
3309
+ const parentY = parent ? positions.get(parent.key)?.y : undefined;
3310
+ const top = Math.max(104, (parentY ?? 104) - (column.length > 1 ? rowSpacing : 0));
3311
+ column.forEach((node, index) => positions.set(node.key, {
3312
+ node,
3313
+ x: columnX(depth),
3314
+ y: top + index * rowSpacing
3315
+ }));
3316
+ });
3317
+ const height = Math.max(280, ...[...positions.values()].map((position) => position.y + nodeHeight + 40));
3318
+ const outgoingOffsets = new Map;
3319
+ const incomingOffsets = new Map;
3320
+ const orderedLinks = [...graph.links].sort((a, b) => (positions.get(a.source)?.y ?? 0) - (positions.get(b.source)?.y ?? 0) || (positions.get(a.target)?.y ?? 0) - (positions.get(b.target)?.y ?? 0));
3321
+ const links = orderedLinks.flatMap((link) => {
3322
+ const source = positions.get(link.source);
3323
+ const target = positions.get(link.target);
3324
+ if (!source || !target || link.count <= 0 || startingCount <= 0)
3325
+ return [];
3326
+ const x0 = source.x + barWidth;
3327
+ const x1 = target.x;
3328
+ const mid = (x0 + x1) / 2;
3329
+ const sourceTop = source.y + (outgoingOffsets.get(link.source) ?? 0);
3330
+ const targetTop = target.y + (incomingOffsets.get(link.target) ?? 0);
3331
+ const thickness = link.count / startingCount * nodeHeight;
3332
+ outgoingOffsets.set(link.source, (outgoingOffsets.get(link.source) ?? 0) + thickness);
3333
+ incomingOffsets.set(link.target, (incomingOffsets.get(link.target) ?? 0) + thickness);
3334
+ return [
3335
+ {
3336
+ muted: target.node.outcome === "end" || target.node.outcome === "other",
3337
+ d: `M${x0},${sourceTop} C${mid},${sourceTop} ${mid},${targetTop} ${x1},${targetTop} L${x1},${targetTop + thickness} C${mid},${targetTop + thickness} ${mid},${sourceTop + thickness} ${x0},${sourceTop + thickness} Z`
3338
+ }
3339
+ ];
3340
+ });
3341
+ return /* @__PURE__ */ jsx21("div", {
3342
+ ref: scrollRef,
3343
+ className: "altertable-journey-scroll",
3344
+ children: /* @__PURE__ */ jsxs15("div", {
3345
+ className: "altertable-journey-plot",
3346
+ style: { minWidth: width, minHeight: height },
3347
+ children: [
3348
+ /* @__PURE__ */ jsxs15("svg", {
3349
+ width: "100%",
3350
+ height: "100%",
3351
+ "aria-hidden": "true",
3352
+ focusable: "false",
3353
+ children: [
3354
+ /* @__PURE__ */ jsx21("path", {
3355
+ d: links.filter((link) => !link.muted).map((link) => link.d).join(" "),
3356
+ fill: "color-mix(in srgb, var(--atbl-chart-5) 22%, var(--atbl-surface))"
3357
+ }),
3358
+ /* @__PURE__ */ jsx21("path", {
3359
+ d: links.filter((link) => link.muted).map((link) => link.d).join(" "),
3360
+ fill: "color-mix(in srgb, var(--atbl-muted) 22%, var(--atbl-surface))"
3361
+ })
3362
+ ]
3363
+ }),
3364
+ columns.map((column, depth) => /* @__PURE__ */ jsx21("span", {
3365
+ className: "altertable-journey-stage",
3366
+ style: { left: columnX(depth) },
3367
+ children: column.length > 0 && column.every((node) => node.outcome !== "event" && node.outcome !== "other") ? "Outcome" : `Step ${depth + 1}`
3368
+ }, depth)),
3369
+ [...positions.values()].map(({ node, x, y }) => /* @__PURE__ */ jsxs15("div", {
3370
+ className: "altertable-journey-node",
3371
+ style: {
3372
+ left: x,
3373
+ top: y,
3374
+ width: nodeWidth,
3375
+ height: startingCount > 0 ? node.count / startingCount * nodeHeight : 0
3376
+ },
3377
+ children: [
3378
+ /* @__PURE__ */ jsx21("div", {
3379
+ className: "altertable-journey-bar",
3380
+ "data-event": node.outcome === "event" || undefined,
3381
+ "aria-hidden": "true",
3382
+ style: { width: barWidth }
3383
+ }),
3384
+ /* @__PURE__ */ jsxs15("section", {
3385
+ "aria-label": `${node.label}, step ${node.depth + 1}, ${formatValue(node.count)} ${unit}`,
3386
+ className: "altertable-journey-label",
3387
+ children: [
3388
+ /* @__PURE__ */ jsx21("span", {
3389
+ className: "altertable-journey-name",
3390
+ title: node.label,
3391
+ children: node.label
3392
+ }),
3393
+ /* @__PURE__ */ jsxs15("span", {
3394
+ children: [
3395
+ formatValue(node.count),
3396
+ " ",
3397
+ unit,
3398
+ " · ",
3399
+ percent(node.count)
3400
+ ]
3401
+ }),
3402
+ node.hiddenBranchCount ? /* @__PURE__ */ jsxs15("span", {
3403
+ children: [
3404
+ node.hiddenBranchCount,
3405
+ " hidden",
3406
+ " ",
3407
+ node.hiddenBranchCount === 1 ? "event" : "events"
3408
+ ]
3409
+ }) : null
3410
+ ]
3411
+ }),
3412
+ node.expandable && /* @__PURE__ */ jsx21(Button2, {
3413
+ variant: "outline",
3414
+ size: "icon-compact",
3415
+ className: "altertable-journey-expand",
3416
+ "aria-label": `${node.expanded ? "Less" : "More"} after ${node.label}, step ${node.depth + 1}`,
3417
+ "aria-expanded": Boolean(node.expanded),
3418
+ onClick: () => {
3419
+ pendingDepth.current = node.expanded ? null : node.depth + 1;
3420
+ setVisibleEventsByDepth((limits) => Object.fromEntries(Object.entries(limits).filter(([depth]) => Number(depth) <= node.depth)));
3421
+ setExpandedBranch(node.expanded ? (node.branchKeys ?? []).slice(0, -1) : node.branchKeys ?? []);
3422
+ },
3423
+ children: node.expanded ? "−" : "›"
3424
+ }),
3425
+ node.outcome === "other" && /* @__PURE__ */ jsx21(Button2, {
3426
+ size: "compact",
3427
+ variant: "ghost",
3428
+ className: "altertable-journey-more",
3429
+ "aria-label": `Show more events at step ${node.depth + 1}`,
3430
+ onClick: () => setVisibleEventsByDepth((limits) => ({
3431
+ ...limits,
3432
+ [node.depth]: (limits[node.depth] ?? 3) + 3
3433
+ })),
3434
+ children: "Show more events"
3435
+ })
3436
+ ]
3437
+ }, node.key))
3438
+ ]
3439
+ })
3440
+ });
3441
+ }
3442
+ export {
3443
+ AboutData2 as AboutData,
3444
+ AppIcon2 as AppIcon,
3445
+ AreaChart,
3446
+ BarChart,
3447
+ ChartLegend,
3448
+ Checkbox2 as Checkbox,
3449
+ CheckboxGroup,
3450
+ ChoicePicker2 as ChoicePicker,
3451
+ ComposedChart,
3452
+ DataApp,
3453
+ DataAppProvider2 as DataAppProvider,
3454
+ DataTable2 as DataTable,
3455
+ DataTableEmptyRow2 as DataTableEmptyRow,
3456
+ DataTableShare2 as DataTableShare,
3457
+ DataTableTimestamp2 as DataTableTimestamp,
3458
+ DataValue2 as DataValue,
3459
+ DataWidget2 as DataWidget,
3460
+ DateDisplay2 as DateDisplay,
3461
+ DateRangePicker2 as DateRangePicker,
3462
+ DimensionPicker2 as DimensionPicker,
3463
+ ExplorationActionControl2 as ExplorationActionControl,
3464
+ FilterActions2 as FilterActions,
3465
+ FilterBar2 as FilterBar,
3466
+ FunnelChart,
3467
+ GettingStarted,
3468
+ GlossaryDefinition,
3469
+ GlossaryExplanation,
3470
+ GradientScroll2 as GradientScroll,
3471
+ HelpPopover2 as HelpPopover,
3472
+ JourneyChart,
3473
+ LineChart,
3474
+ LiveControl2 as LiveControl,
3475
+ Menu2 as Menu,
3476
+ PressButton as MenuButton,
3477
+ MenuItem2 as MenuItem,
3478
+ MenuPopover2 as MenuPopover,
3479
+ MenuSection2 as MenuSection,
3480
+ MenuSeparator2 as MenuSeparator,
3481
+ MenuTrigger2 as MenuTrigger,
3482
+ MetricWidget2 as MetricWidget,
3483
+ NumberField2 as NumberField,
3484
+ NumberFilterPicker2 as NumberFilterPicker,
3485
+ NumberRangeField2 as NumberRangeField,
3486
+ PieChart,
3487
+ PresentStory2 as PresentStory,
3488
+ Radio,
3489
+ RadioGroup,
3490
+ RetentionChart,
3491
+ ScatterChart,
3492
+ SearchField2 as SearchField,
3493
+ SearchMatch2 as SearchMatch,
3494
+ SearchTypeahead2 as SearchTypeahead,
3495
+ SectionHeading2 as SectionHeading,
3496
+ SegmentedControl,
3497
+ Select2 as Select,
3498
+ Sheet2 as Sheet,
3499
+ Tab2 as Tab,
3500
+ TabList2 as TabList,
3501
+ TabPanel2 as TabPanel,
3502
+ TabPanels2 as TabPanels,
3503
+ TableWidget2 as TableWidget,
3504
+ Tabs2 as Tabs,
3505
+ TextWidget2 as TextWidget,
3506
+ Tooltip2 as Tooltip,
3507
+ TooltipProvider2 as TooltipProvider,
3508
+ VariableBar2 as VariableBar,
3509
+ VisualizationWidget2 as VisualizationWidget,
3510
+ injectDataAppStyles2 as injectDataAppStyles,
3511
+ isPlainKeyEvent2 as isPlainKeyEvent,
3512
+ matchSearchText2 as matchSearchText,
3513
+ searchItems2 as searchItems,
3514
+ useAppVariables2 as useAppVariables,
3515
+ useDateFormatting2 as useDateFormatting,
3516
+ useSvgId,
3517
+ useViewTab2 as useViewTab
3518
+ };
3519
+
3520
+ //# debugId=78DA6D4614004F8064756E2164756E21