@surfaces-ui/components 0.0.0-stage → 0.2.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 (264) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +48 -2
  4. package/dist/appComponents.d.ts +86 -0
  5. package/dist/appComponents.js +555 -0
  6. package/dist/appComponents.js.map +1 -0
  7. package/dist/chart/BulletGraph.d.ts +44 -0
  8. package/dist/chart/BulletGraph.js +40 -0
  9. package/dist/chart/BulletGraph.js.map +1 -0
  10. package/dist/chart/Chart.d.ts +177 -0
  11. package/dist/chart/Chart.js +279 -0
  12. package/dist/chart/Chart.js.map +1 -0
  13. package/dist/chart/Sparkline.d.ts +35 -0
  14. package/dist/chart/Sparkline.js +37 -0
  15. package/dist/chart/Sparkline.js.map +1 -0
  16. package/dist/chart/advice.d.ts +28 -0
  17. package/dist/chart/advice.js +39 -0
  18. package/dist/chart/advice.js.map +1 -0
  19. package/dist/chart/option.d.ts +90 -0
  20. package/dist/chart/option.js +252 -0
  21. package/dist/chart/option.js.map +1 -0
  22. package/dist/controls/Combobox.d.ts +39 -0
  23. package/dist/controls/Combobox.js +75 -0
  24. package/dist/controls/Combobox.js.map +1 -0
  25. package/dist/controls/ConfirmDialog.d.ts +35 -0
  26. package/dist/controls/ConfirmDialog.js +84 -0
  27. package/dist/controls/ConfirmDialog.js.map +1 -0
  28. package/dist/controls/ItemControls.d.ts +115 -0
  29. package/dist/controls/ItemControls.js +109 -0
  30. package/dist/controls/ItemControls.js.map +1 -0
  31. package/dist/controls/Popover.d.ts +31 -0
  32. package/dist/controls/Popover.js +114 -0
  33. package/dist/controls/Popover.js.map +1 -0
  34. package/dist/controls/ResizeHandle.d.ts +48 -0
  35. package/dist/controls/ResizeHandle.js +91 -0
  36. package/dist/controls/ResizeHandle.js.map +1 -0
  37. package/dist/controls/SegmentedControl.d.ts +27 -0
  38. package/dist/controls/SegmentedControl.js +17 -0
  39. package/dist/controls/SegmentedControl.js.map +1 -0
  40. package/dist/controls/StatusBadge.d.ts +17 -0
  41. package/dist/controls/StatusBadge.js +10 -0
  42. package/dist/controls/StatusBadge.js.map +1 -0
  43. package/dist/controls/context.d.ts +17 -0
  44. package/dist/controls/context.js +2 -0
  45. package/dist/controls/context.js.map +1 -0
  46. package/dist/controls/placement.d.ts +43 -0
  47. package/dist/controls/placement.js +19 -0
  48. package/dist/controls/placement.js.map +1 -0
  49. package/dist/controls/resize.d.ts +23 -0
  50. package/dist/controls/resize.js +49 -0
  51. package/dist/controls/resize.js.map +1 -0
  52. package/dist/data/DataSourceProvider.d.ts +11 -0
  53. package/dist/data/DataSourceProvider.js +21 -0
  54. package/dist/data/DataSourceProvider.js.map +1 -0
  55. package/dist/data/export.d.ts +33 -0
  56. package/dist/data/export.js +77 -0
  57. package/dist/data/export.js.map +1 -0
  58. package/dist/data/format.d.ts +44 -0
  59. package/dist/data/format.js +127 -0
  60. package/dist/data/format.js.map +1 -0
  61. package/dist/data/messages.d.ts +13 -0
  62. package/dist/data/messages.js +2 -0
  63. package/dist/data/messages.js.map +1 -0
  64. package/dist/data/useRowWindow.d.ts +70 -0
  65. package/dist/data/useRowWindow.js +175 -0
  66. package/dist/data/useRowWindow.js.map +1 -0
  67. package/dist/discovery/AskData.d.ts +22 -0
  68. package/dist/discovery/AskData.js +48 -0
  69. package/dist/discovery/AskData.js.map +1 -0
  70. package/dist/discovery/ContextBuilder.d.ts +49 -0
  71. package/dist/discovery/ContextBuilder.js +167 -0
  72. package/dist/discovery/ContextBuilder.js.map +1 -0
  73. package/dist/discovery/DataSearch.d.ts +27 -0
  74. package/dist/discovery/DataSearch.js +73 -0
  75. package/dist/discovery/DataSearch.js.map +1 -0
  76. package/dist/discovery/ObjectDetail.d.ts +38 -0
  77. package/dist/discovery/ObjectDetail.js +129 -0
  78. package/dist/discovery/ObjectDetail.js.map +1 -0
  79. package/dist/discovery/RelationshipGraph.d.ts +19 -0
  80. package/dist/discovery/RelationshipGraph.js +64 -0
  81. package/dist/discovery/RelationshipGraph.js.map +1 -0
  82. package/dist/discovery/shared.d.ts +38 -0
  83. package/dist/discovery/shared.js +64 -0
  84. package/dist/discovery/shared.js.map +1 -0
  85. package/dist/editor/SqlEditor.d.ts +41 -0
  86. package/dist/editor/SqlEditor.js +181 -0
  87. package/dist/editor/SqlEditor.js.map +1 -0
  88. package/dist/explore/Explorer.d.ts +110 -0
  89. package/dist/explore/Explorer.js +471 -0
  90. package/dist/explore/Explorer.js.map +1 -0
  91. package/dist/explore/ModelLineage.d.ts +22 -0
  92. package/dist/explore/ModelLineage.js +70 -0
  93. package/dist/explore/ModelLineage.js.map +1 -0
  94. package/dist/explore/ReportBuilder.d.ts +39 -0
  95. package/dist/explore/ReportBuilder.js +98 -0
  96. package/dist/explore/ReportBuilder.js.map +1 -0
  97. package/dist/explore/SemanticModelEditor.d.ts +60 -0
  98. package/dist/explore/SemanticModelEditor.js +220 -0
  99. package/dist/explore/SemanticModelEditor.js.map +1 -0
  100. package/dist/explore/SemanticRows.d.ts +42 -0
  101. package/dist/explore/SemanticRows.js +117 -0
  102. package/dist/explore/SemanticRows.js.map +1 -0
  103. package/dist/explore/SemanticsProvider.d.ts +31 -0
  104. package/dist/explore/SemanticsProvider.js +72 -0
  105. package/dist/explore/SemanticsProvider.js.map +1 -0
  106. package/dist/explore/model.d.ts +151 -0
  107. package/dist/explore/model.js +344 -0
  108. package/dist/explore/model.js.map +1 -0
  109. package/dist/explore/report.d.ts +60 -0
  110. package/dist/explore/report.js +92 -0
  111. package/dist/explore/report.js.map +1 -0
  112. package/dist/explore/semantic-proposal.d.ts +44 -0
  113. package/dist/explore/semantic-proposal.js +67 -0
  114. package/dist/explore/semantic-proposal.js.map +1 -0
  115. package/dist/explore/semantic.d.ts +44 -0
  116. package/dist/explore/semantic.js +154 -0
  117. package/dist/explore/semantic.js.map +1 -0
  118. package/dist/files/FileBrowser.d.ts +42 -0
  119. package/dist/files/FileBrowser.js +314 -0
  120. package/dist/files/FileBrowser.js.map +1 -0
  121. package/dist/files/files.d.ts +65 -0
  122. package/dist/files/files.js +165 -0
  123. package/dist/files/files.js.map +1 -0
  124. package/dist/filter/FilterBar.d.ts +49 -0
  125. package/dist/filter/FilterBar.js +153 -0
  126. package/dist/filter/FilterBar.js.map +1 -0
  127. package/dist/filter/QueryFilters.d.ts +25 -0
  128. package/dist/filter/QueryFilters.js +58 -0
  129. package/dist/filter/QueryFilters.js.map +1 -0
  130. package/dist/form/Form.d.ts +76 -0
  131. package/dist/form/Form.js +131 -0
  132. package/dist/form/Form.js.map +1 -0
  133. package/dist/graph/NodeGraph.d.ts +30 -0
  134. package/dist/graph/NodeGraph.js +86 -0
  135. package/dist/graph/NodeGraph.js.map +1 -0
  136. package/dist/graph/model.d.ts +68 -0
  137. package/dist/graph/model.js +122 -0
  138. package/dist/graph/model.js.map +1 -0
  139. package/dist/grid/DataGrid.d.ts +98 -0
  140. package/dist/grid/DataGrid.js +399 -0
  141. package/dist/grid/DataGrid.js.map +1 -0
  142. package/dist/index.d.ts +84 -0
  143. package/dist/index.js +86 -0
  144. package/dist/index.js.map +1 -0
  145. package/dist/locale/SurfacesText.d.ts +17 -0
  146. package/dist/locale/SurfacesText.js +17 -0
  147. package/dist/locale/SurfacesText.js.map +1 -0
  148. package/dist/locale/locale.d.ts +305 -0
  149. package/dist/locale/locale.js +359 -0
  150. package/dist/locale/locale.js.map +1 -0
  151. package/dist/menu/ContextMenu.d.ts +31 -0
  152. package/dist/menu/ContextMenu.js +95 -0
  153. package/dist/menu/ContextMenu.js.map +1 -0
  154. package/dist/metric/Metric.d.ts +33 -0
  155. package/dist/metric/Metric.js +63 -0
  156. package/dist/metric/Metric.js.map +1 -0
  157. package/dist/metric/useMeasure.d.ts +23 -0
  158. package/dist/metric/useMeasure.js +43 -0
  159. package/dist/metric/useMeasure.js.map +1 -0
  160. package/dist/model/ModelDiagram.d.ts +142 -0
  161. package/dist/model/ModelDiagram.js +699 -0
  162. package/dist/model/ModelDiagram.js.map +1 -0
  163. package/dist/panzoom/usePanZoom.d.ts +117 -0
  164. package/dist/panzoom/usePanZoom.js +313 -0
  165. package/dist/panzoom/usePanZoom.js.map +1 -0
  166. package/dist/pipeline/DatasetReview.d.ts +48 -0
  167. package/dist/pipeline/DatasetReview.js +157 -0
  168. package/dist/pipeline/DatasetReview.js.map +1 -0
  169. package/dist/pipeline/IngestWizard.d.ts +51 -0
  170. package/dist/pipeline/IngestWizard.js +79 -0
  171. package/dist/pipeline/IngestWizard.js.map +1 -0
  172. package/dist/pipeline/Pipeline.d.ts +171 -0
  173. package/dist/pipeline/Pipeline.js +203 -0
  174. package/dist/pipeline/Pipeline.js.map +1 -0
  175. package/dist/pipeline/PipelineView.d.ts +63 -0
  176. package/dist/pipeline/PipelineView.js +239 -0
  177. package/dist/pipeline/PipelineView.js.map +1 -0
  178. package/dist/pivot/PivotTable.d.ts +94 -0
  179. package/dist/pivot/PivotTable.js +171 -0
  180. package/dist/pivot/PivotTable.js.map +1 -0
  181. package/dist/plan/QueryPlan.d.ts +29 -0
  182. package/dist/plan/QueryPlan.js +79 -0
  183. package/dist/plan/QueryPlan.js.map +1 -0
  184. package/dist/result/QueryResult.d.ts +51 -0
  185. package/dist/result/QueryResult.js +255 -0
  186. package/dist/result/QueryResult.js.map +1 -0
  187. package/dist/review/ActionReceipt.d.ts +52 -0
  188. package/dist/review/ActionReceipt.js +32 -0
  189. package/dist/review/ActionReceipt.js.map +1 -0
  190. package/dist/review/PiiReview.d.ts +37 -0
  191. package/dist/review/PiiReview.js +29 -0
  192. package/dist/review/PiiReview.js.map +1 -0
  193. package/dist/review/PlanReview.d.ts +42 -0
  194. package/dist/review/PlanReview.js +37 -0
  195. package/dist/review/PlanReview.js.map +1 -0
  196. package/dist/review/StepFlow.d.ts +25 -0
  197. package/dist/review/StepFlow.js +21 -0
  198. package/dist/review/StepFlow.js.map +1 -0
  199. package/dist/review/pii.d.ts +21 -0
  200. package/dist/review/pii.js +67 -0
  201. package/dist/review/pii.js.map +1 -0
  202. package/dist/rows/RowList.d.ts +41 -0
  203. package/dist/rows/RowList.js +71 -0
  204. package/dist/rows/RowList.js.map +1 -0
  205. package/dist/schema/ObjectBrowser.d.ts +78 -0
  206. package/dist/schema/ObjectBrowser.js +467 -0
  207. package/dist/schema/ObjectBrowser.js.map +1 -0
  208. package/dist/schema/ObjectInfo.d.ts +25 -0
  209. package/dist/schema/ObjectInfo.js +69 -0
  210. package/dist/schema/ObjectInfo.js.map +1 -0
  211. package/dist/schema/SchemaExplorer.d.ts +32 -0
  212. package/dist/schema/SchemaExplorer.js +175 -0
  213. package/dist/schema/SchemaExplorer.js.map +1 -0
  214. package/dist/schema/refs.d.ts +32 -0
  215. package/dist/schema/refs.js +65 -0
  216. package/dist/schema/refs.js.map +1 -0
  217. package/dist/site/Site.d.ts +191 -0
  218. package/dist/site/Site.js +138 -0
  219. package/dist/site/Site.js.map +1 -0
  220. package/dist/source/ConnectionBuilder.d.ts +54 -0
  221. package/dist/source/ConnectionBuilder.js +115 -0
  222. package/dist/source/ConnectionBuilder.js.map +1 -0
  223. package/dist/source/SourceList.d.ts +17 -0
  224. package/dist/source/SourceList.js +71 -0
  225. package/dist/source/SourceList.js.map +1 -0
  226. package/dist/styles.css +9882 -0
  227. package/dist/styles.layer.css +9886 -0
  228. package/dist/table/DataTable.d.ts +72 -0
  229. package/dist/table/DataTable.js +68 -0
  230. package/dist/table/DataTable.js.map +1 -0
  231. package/dist/table/Pagination.d.ts +20 -0
  232. package/dist/table/Pagination.js +16 -0
  233. package/dist/table/Pagination.js.map +1 -0
  234. package/dist/table/SelectionBar.d.ts +43 -0
  235. package/dist/table/SelectionBar.js +18 -0
  236. package/dist/table/SelectionBar.js.map +1 -0
  237. package/dist/text/Markdown.d.ts +71 -0
  238. package/dist/text/Markdown.js +187 -0
  239. package/dist/text/Markdown.js.map +1 -0
  240. package/dist/text/highlight.d.ts +23 -0
  241. package/dist/text/highlight.js +196 -0
  242. package/dist/text/highlight.js.map +1 -0
  243. package/dist/theme/ThemePicker.d.ts +16 -0
  244. package/dist/theme/ThemePicker.js +49 -0
  245. package/dist/theme/ThemePicker.js.map +1 -0
  246. package/dist/theme/ThemeProvider.d.ts +43 -0
  247. package/dist/theme/ThemeProvider.js +107 -0
  248. package/dist/theme/ThemeProvider.js.map +1 -0
  249. package/dist/workspace/NavBar.d.ts +23 -0
  250. package/dist/workspace/NavBar.js +171 -0
  251. package/dist/workspace/NavBar.js.map +1 -0
  252. package/dist/workspace/SideNav.d.ts +61 -0
  253. package/dist/workspace/SideNav.js +149 -0
  254. package/dist/workspace/SideNav.js.map +1 -0
  255. package/dist/workspace/Workspace.d.ts +50 -0
  256. package/dist/workspace/Workspace.js +243 -0
  257. package/dist/workspace/Workspace.js.map +1 -0
  258. package/dist/workspace/icons.d.ts +34 -0
  259. package/dist/workspace/icons.js +37 -0
  260. package/dist/workspace/icons.js.map +1 -0
  261. package/dist/workspace/layout.d.ts +74 -0
  262. package/dist/workspace/layout.js +276 -0
  263. package/dist/workspace/layout.js.map +1 -0
  264. package/package.json +85 -3
@@ -0,0 +1,344 @@
1
+ import { measureExpressionProblem, measureNames, parseMeasureExpression } from "@surfaces-ui/data";
2
+ import { SortDirection } from "@surfaces-ui/proto";
3
+ import { DataType } from "apache-arrow";
4
+ import { AGGREGATE_FUNCTIONS, TIME_GRAINS } from "../chart/Chart.js";
5
+ import { canTurnSideways } from "../chart/option.js";
6
+ import { filtersFromSpec } from "@surfaces-ui/data";
7
+ import { isNumeric } from "../data/format.js";
8
+ import { numberFormat } from "../locale/locale.js";
9
+ const CHART_TYPES = ["bar", "line", "area"];
10
+ /** The chart settings with anything that cannot apply left out: unknown types, and measures not on the shelf. */
11
+ export function normalizeChartSettings(chart, values) {
12
+ if (!chart || typeof chart !== "object")
13
+ return undefined;
14
+ const measures = Object.fromEntries(Object.entries(chart.measures ?? {})
15
+ .filter(([id]) => values.includes(id))
16
+ .map(([id, style]) => [
17
+ id,
18
+ {
19
+ ...(style?.type && CHART_TYPES.includes(style.type) ? { type: style.type } : {}),
20
+ ...(style?.axis === "right" ? { axis: "right" } : {}),
21
+ },
22
+ ])
23
+ .filter(([, style]) => Object.keys(style).length > 0));
24
+ const out = {
25
+ ...(chart.type && CHART_TYPES.includes(chart.type) ? { type: chart.type } : {}),
26
+ ...(chart.swap ? { swap: true } : {}),
27
+ ...(Object.keys(measures).length > 0 ? { measures } : {}),
28
+ };
29
+ return Object.keys(out).length > 0 ? out : undefined;
30
+ }
31
+ /** A measure's style on the chart, changed; an empty style clears it. */
32
+ export function setMeasureStyle(state, id, style) {
33
+ const measures = { ...(state.chart?.measures ?? {}), [id]: { ...(state.chart?.measures?.[id] ?? {}), ...style } };
34
+ return { ...state, chart: normalizeChartSettings({ ...state.chart, measures }, state.values) };
35
+ }
36
+ /** The chart settings changed: its type, or whether it is turned on its side. */
37
+ export function setChartSettings(state, change) {
38
+ return { ...state, chart: normalizeChartSettings({ ...state.chart, ...change }, state.values) };
39
+ }
40
+ export const emptyExplore = { fields: [], rows: [], values: [], filters: [] };
41
+ const ID = /^[A-Za-z][A-Za-z0-9_]*$/;
42
+ const MONEY = /(amount|price|cost|revenue|sales|total|refund|paid|charge|fee|balance|margin|spend|value)/i;
43
+ const KEY = /(^id$|_id$|_key$|_no$|_number$|^sku$|code$)/i;
44
+ /**
45
+ * A number whose name says it adds up: money taken or spent, a count, a
46
+ * quantity, time spent, energy used. Any other number is read as a reading
47
+ * (a temperature, a speed, a price, a score, a level, a 0 or 1), which is
48
+ * averaged: summing a reading over many rows gives a number nobody means.
49
+ */
50
+ const ADDS_UP = /(amount|cost|revenue|sales|total|refund|paid|charge|fee|spend|income|profit|count|qty|quantity|units|orders|items|hours|minutes|seconds|days|kwh|mwh|energy|volume|clicks|views|visits|sessions|downloads|bytes|calls|tickets|^n_|^num_)/i;
51
+ /** A pill id from a label, unlike any already taken: "Refund rate" becomes refund_rate. */
52
+ export function pillId(label, taken = []) {
53
+ const have = new Set(taken);
54
+ const base = label
55
+ .toLowerCase()
56
+ .replace(/[^a-z0-9]+/g, "_")
57
+ .replace(/^_+|_+$/g, "")
58
+ .replace(/^(\d)/, "n$1")
59
+ .slice(0, 40) || "field";
60
+ let id = base;
61
+ for (let n = 2; have.has(id); n++)
62
+ id = `${base}_${n}`;
63
+ return id;
64
+ }
65
+ const words = (column) => column.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase());
66
+ /**
67
+ * Pills generated from a query's columns: text, true/false and dates become
68
+ * attributes (a date by month), numbers become metrics (summed when their
69
+ * name says they add up, averaged otherwise), and a
70
+ * column that names things (an id, a code) becomes an attribute with a
71
+ * count of its distinct values. There is always a count of rows. This is a
72
+ * reading of names and types only; nothing is looked up in the data.
73
+ */
74
+ export function pillsFromFields(fields, by = "the columns") {
75
+ const pills = [];
76
+ const taken = () => pills.map((p) => p.id);
77
+ for (const field of fields) {
78
+ const { name, type } = field;
79
+ if (DataType.isList(type) || DataType.isStruct(type) || DataType.isMap(type) || DataType.isBinary(type))
80
+ continue;
81
+ if (DataType.isTimestamp(type) || DataType.isDate(type)) {
82
+ pills.push({ id: pillId(name, taken()), kind: "attribute", label: `${words(name)} (month)`, column: name, grain: "month", by });
83
+ }
84
+ else if (isNumeric(type) && !KEY.test(name)) {
85
+ const sums = ADDS_UP.test(name);
86
+ pills.push({ id: pillId(name, taken()), kind: "metric", label: sums ? words(name) : `Average ${words(name).toLowerCase()}`, column: name, aggregate: sums ? "sum" : "avg", format: MONEY.test(name) ? "currency" : sums ? "compact" : "number", by });
87
+ }
88
+ else {
89
+ pills.push({ id: pillId(name, taken()), kind: "attribute", label: words(name), column: name, by });
90
+ if (KEY.test(name))
91
+ pills.push({ id: pillId(`${name}_count`, taken()), kind: "metric", label: `Distinct ${words(name).toLowerCase()}`, column: name, aggregate: "count_distinct", format: "compact", by });
92
+ }
93
+ }
94
+ pills.push({ id: pillId("rows", taken()), kind: "metric", label: "Rows", aggregate: "count", format: "compact", by });
95
+ return pills;
96
+ }
97
+ /**
98
+ * Calculations worth offering from the metrics there are: each summed
99
+ * metric per row (an average that follows the filters), a margin when there
100
+ * is something sold and something it cost, and one money metric as a share
101
+ * of another. They are suggestions from names, labelled as such, and a
102
+ * person keeps, edits or removes them.
103
+ */
104
+ export function suggestDerived(pills, by = "suggested from the columns") {
105
+ const out = [];
106
+ const taken = () => [...pills, ...out].map((p) => p.id);
107
+ const has = (expression) => [...pills, ...out].some((p) => p.kind === "derived" && p.expression?.replace(/\s+/g, "") === expression.replace(/\s+/g, ""));
108
+ const add = (label, expression, format, description) => {
109
+ if (!has(expression))
110
+ out.push({ id: pillId(label, taken()), kind: "derived", label, expression, format, description, by });
111
+ };
112
+ const sums = pills.filter((p) => p.kind === "metric" && p.aggregate === "sum");
113
+ const rows = pills.find((p) => p.kind === "metric" && p.aggregate === "count" && !p.column);
114
+ if (rows)
115
+ for (const metric of sums.slice(0, 3))
116
+ add(`${metric.label} per row`, `${metric.id} / ${rows.id}`, metric.format === "currency" ? "currency" : "number", `${metric.label} divided by the number of rows.`);
117
+ const sold = sums.find((p) => /(revenue|sales|amount|price|total)/i.test(p.column ?? ""));
118
+ const cost = sums.find((p) => /cost/i.test(p.column ?? ""));
119
+ if (sold && cost && sold !== cost)
120
+ add("Margin", `(${sold.id} - ${cost.id}) / ${sold.id}`, "percent", `What is left of ${sold.label.toLowerCase()} after ${cost.label.toLowerCase()}, as a share.`);
121
+ const money = sums.filter((p) => p.format === "currency");
122
+ const part = money.find((p) => /(refund|discount|fee|tax|return)/i.test(p.column ?? ""));
123
+ const whole = money.find((p) => p !== part && /(revenue|sales|amount|total|price)/i.test(p.column ?? ""));
124
+ if (part && whole)
125
+ add(`${part.label} share of ${whole.label.toLowerCase()}`, `${part.id} / ${whole.id}`, "percent", `${part.label} divided by ${whole.label.toLowerCase()}.`);
126
+ return out;
127
+ }
128
+ /** Why a pill cannot be used, or undefined when it can. `columns`, when given, are the query's own. */
129
+ export function pillProblem(pill, all, columns) {
130
+ if (!ID.test(pill.id))
131
+ return "Its name in calculations must start with a letter and use only letters, digits and underscores.";
132
+ if (all.filter((p) => p.id === pill.id).length > 1)
133
+ return `Another field is already called "${pill.id}".`;
134
+ if (!pill.label.trim())
135
+ return "It needs a label.";
136
+ const known = (column) => !columns || (column !== undefined && columns.includes(column));
137
+ if (pill.kind === "attribute")
138
+ return !pill.column ? "An attribute needs a column." : known(pill.column) ? undefined : `There is no column "${pill.column}" in this query.`;
139
+ if (pill.kind === "metric") {
140
+ if (!pill.aggregate)
141
+ return "A metric needs a way to summarise: sum, average, count.";
142
+ if (!pill.column)
143
+ return pill.aggregate === "count" ? undefined : "Only a count can do without a column.";
144
+ return known(pill.column) ? undefined : `There is no column "${pill.column}" in this query.`;
145
+ }
146
+ // A calculation is over metrics only, so one can never depend on itself.
147
+ return measureExpressionProblem(pill.expression ?? "", all.filter((p) => p.kind === "metric").map((p) => p.id));
148
+ }
149
+ /** The state with anything that cannot be drawn taken off the shelves: ids that are not fields, an attribute among the values. */
150
+ export function normalizeExplore(state) {
151
+ const kind = new Map(state.fields.map((p) => [p.id, p.kind]));
152
+ const rows = [...new Set(state.rows)].filter((id) => kind.get(id) === "attribute").slice(0, 3);
153
+ const split = state.split && kind.get(state.split) === "attribute" && !rows.includes(state.split) ? state.split : undefined;
154
+ const values = [...new Set(state.values)].filter((id) => kind.get(id) === "metric" || kind.get(id) === "derived").slice(0, 6);
155
+ const chart = normalizeChartSettings(state.chart, values);
156
+ return { fields: state.fields, rows, ...(split ? { split } : {}), values, filters: state.filters, ...(state.view ? { view: state.view } : {}), ...(chart ? { chart } : {}) };
157
+ }
158
+ /** Where a pill goes when it is simply chosen: an attribute breaks the view down, a metric is measured. */
159
+ export function addToShelf(state, id, shelf, at) {
160
+ const pill = state.fields.find((p) => p.id === id);
161
+ if (!pill)
162
+ return state;
163
+ const target = shelf ?? (pill.kind === "attribute" ? "rows" : "values");
164
+ // At a place among the others (counted without this pill), or at the end.
165
+ const insert = (list) => {
166
+ const others = list.filter((item) => item !== id);
167
+ const place = at === undefined ? others.length : Math.max(0, Math.min(others.length, at));
168
+ return [...others.slice(0, place), id, ...others.slice(place)];
169
+ };
170
+ if (target === "split")
171
+ return normalizeExplore({ ...state, rows: state.rows.filter((r) => r !== id), split: id });
172
+ if (target === "rows")
173
+ return normalizeExplore({ ...state, rows: insert(state.rows), ...(state.split === id ? { split: undefined } : {}) });
174
+ return normalizeExplore({ ...state, values: insert(state.values) });
175
+ }
176
+ /** A pill moved one place earlier (-1) or later (1) on its shelf: the first breakdown is the x axis, the first measure the first series. At an end, nothing changes. */
177
+ export function movePill(state, id, by) {
178
+ const shelf = state.rows.includes(id) ? "rows" : state.values.includes(id) ? "values" : undefined;
179
+ if (!shelf)
180
+ return state;
181
+ const from = state[shelf].indexOf(id);
182
+ const to = from + by;
183
+ if (to < 0 || to >= state[shelf].length)
184
+ return state;
185
+ return addToShelf(state, id, shelf, to);
186
+ }
187
+ export function removeFromShelf(state, id, shelf) {
188
+ if (shelf === "split")
189
+ return { ...state, split: undefined };
190
+ return { ...state, [shelf]: state[shelf].filter((item) => item !== id) };
191
+ }
192
+ /** A pill changed, added (when its id is new) or, with `undefined`, removed, along with what that does to the shelves and to calculations that named it. */
193
+ export function setPill(state, id, next) {
194
+ const exists = state.fields.some((p) => p.id === id);
195
+ let fields = next ? (exists ? state.fields.map((p) => (p.id === id ? next : p)) : [...state.fields, next]) : state.fields.filter((p) => p.id !== id);
196
+ const renamed = next && next.id !== id ? next.id : undefined;
197
+ if (renamed) {
198
+ // Calculations follow a rename.
199
+ fields = fields.map((p) => (p.kind === "derived" && p.expression ? { ...p, expression: p.expression.replace(new RegExp(`\\b${id}\\b`, "g"), renamed) } : p));
200
+ }
201
+ const swap = (item) => (item === id ? renamed : item);
202
+ const keep = (list) => list.map((item) => (item === id ? (next ? (renamed ?? id) : undefined) : item)).filter((item) => item !== undefined);
203
+ return normalizeExplore({ ...state, fields, rows: keep(state.rows), values: keep(state.values), split: state.split === id ? (next ? (swap(id) ?? id) : undefined) : state.split });
204
+ }
205
+ const pillOf = (state, id) => state.fields.find((p) => p.id === id);
206
+ /** The metrics a set of values needs summarised: the metrics themselves and those their calculations name. */
207
+ function metricsNeeded(state) {
208
+ const ids = [];
209
+ for (const id of state.values) {
210
+ const pill = pillOf(state, id);
211
+ if (pill?.kind === "metric")
212
+ ids.push(id);
213
+ if (pill?.kind === "derived") {
214
+ try {
215
+ ids.push(...measureNames(parseMeasureExpression(pill.expression ?? "")));
216
+ }
217
+ catch {
218
+ // Reported where the pill is shown.
219
+ }
220
+ }
221
+ }
222
+ return [...new Set(ids)].map((id) => pillOf(state, id)).filter((p) => p?.kind === "metric");
223
+ }
224
+ /**
225
+ * The query for the table of what is on the shelves: one row per
226
+ * combination of the attributes, a column per metric and calculation, all
227
+ * worked out by the engine. Sorted by time when the first attribute is a
228
+ * date, by the first value otherwise, so a row limit keeps the largest.
229
+ */
230
+ export function exploreQuery(state, sql, limit = 200, now) {
231
+ const attributes = [...state.rows, ...(state.split ? [state.split] : [])].map((id) => pillOf(state, id)).filter((p) => p?.kind === "attribute");
232
+ const plain = attributes.filter((p) => !p.grain);
233
+ const timed = attributes.filter((p) => p.grain);
234
+ const derived = state.values.map((id) => pillOf(state, id)).filter((p) => p?.kind === "derived");
235
+ const first = attributes[0];
236
+ return {
237
+ baseSql: sql,
238
+ filters: filtersFromSpec(state.filters, now),
239
+ groupBy: plain.map((p) => p.column),
240
+ buckets: timed.map((p) => ({ column: p.column, alias: p.id, by: { case: "grain", value: TIME_GRAINS[p.grain] } })),
241
+ aggregates: metricsNeeded(state).map((p) => ({ function: AGGREGATE_FUNCTIONS[p.aggregate ?? "count"], column: p.column ?? "", alias: p.id })),
242
+ derived: derived.map((p) => ({ alias: p.id, expression: p.expression ?? "" })),
243
+ sorts: first?.grain ? [{ column: first.id, direction: SortDirection.ASC }] : state.values[0] ? [{ column: state.values[0], direction: SortDirection.DESC }] : [],
244
+ page: { limit },
245
+ };
246
+ }
247
+ /** The name a pill's values come back under in `exploreQuery`'s result. */
248
+ export const pillColumn = (pill) => (pill.kind === "attribute" && !pill.grain ? pill.column : pill.id);
249
+ /** Why the bars cannot be turned on their side now, or undefined when they can. */
250
+ export function swapProblem(state) {
251
+ const chart = exploreChart({ ...state, chart: { ...state.chart, swap: false } });
252
+ if (!chart)
253
+ return "There is no chart to turn yet.";
254
+ if (!canTurnSideways(chart.type, chart.y))
255
+ return "Only bars on one scale can be turned on their side.";
256
+ return undefined;
257
+ }
258
+ /**
259
+ * The chart for what is on the shelves, or undefined when there is nothing
260
+ * to draw one from (no attribute, or no value). A date is a line over time;
261
+ * categories are bars, largest first. The split becomes the series, with
262
+ * each measure for each of its values; a second attribute does when one
263
+ * value is shown.
264
+ */
265
+ export function exploreChart(state) {
266
+ const rows = state.rows.map((id) => pillOf(state, id)).filter((p) => p?.kind === "attribute");
267
+ const values = state.values.map((id) => pillOf(state, id)).filter((p) => !!p && p.kind !== "attribute");
268
+ const x = rows[0];
269
+ if (!x || values.length === 0)
270
+ return undefined;
271
+ const split = (state.split ? pillOf(state, state.split) : rows[1]) ?? undefined;
272
+ const type = state.chart?.type ?? (x.grain ? "line" : "bar");
273
+ // A second scale needs a measure on each; all of them on the right is one scale, drawn on the left.
274
+ const right = new Set(values.filter((p) => state.chart?.measures?.[p.id]?.axis === "right").map((p) => p.id));
275
+ if (right.size === values.length)
276
+ right.clear();
277
+ const style = (pill) => {
278
+ const own = state.chart?.measures?.[pill.id]?.type;
279
+ return { ...(own && own !== type ? { type: own } : {}), ...(right.has(pill.id) ? { axis: "right" } : {}) };
280
+ };
281
+ const y = values.map((pill) => {
282
+ if (pill.kind === "metric")
283
+ return { ...(pill.column ? { column: pill.column } : {}), aggregate: pill.aggregate ?? "count", label: pill.label, ...style(pill) };
284
+ let names = [];
285
+ try {
286
+ names = measureNames(parseMeasureExpression(pill.expression ?? ""));
287
+ }
288
+ catch {
289
+ // The chart reports a calculation it cannot read.
290
+ }
291
+ const terms = Object.fromEntries(names
292
+ .map((name) => pillOf(state, name))
293
+ .filter((p) => p?.kind === "metric")
294
+ .map((p) => [p.id, { ...(p.column ? { column: p.column } : {}), aggregate: p.aggregate ?? "count" }]));
295
+ return { expression: pill.expression ?? "", terms, label: pill.label, ...style(pill) };
296
+ });
297
+ const left = values.filter((p) => !right.has(p.id));
298
+ const onRight = values.filter((p) => right.has(p.id));
299
+ const sideways = !!state.chart?.swap && canTurnSideways(type, y);
300
+ return {
301
+ type,
302
+ x: x.column,
303
+ ...(x.grain ? { xGrain: x.grain } : {}),
304
+ // The split makes the series, one per value and measure ("North · Revenue") when there are several measures;
305
+ // a second attribute on the rows splits only one measure, so more on the rows never multiplies the lines unasked.
306
+ ...(split?.column && !split.grain && (state.split || values.length === 1) ? { splitBy: split.column } : {}),
307
+ y,
308
+ xTitle: x.label,
309
+ // With two scales each is named, so a reader knows which line is read against which.
310
+ ...(onRight.length > 0 ? { yTitle: left.map((p) => p.label).join(", "), yRightTitle: onRight.map((p) => p.label).join(", ") } : {}),
311
+ // An axis writes one format; measures in different ones keep plain numbers.
312
+ ...(left[0]?.format && left.every((p) => p.format === left[0].format) ? { yFormat: left[0].format } : {}),
313
+ ...(sideways ? { horizontal: true } : {}),
314
+ };
315
+ }
316
+ /** A number as a pill's format writes it. */
317
+ export function pillNumber(value, format) {
318
+ if (value == null)
319
+ return "–";
320
+ const n = typeof value === "bigint" ? Number(value) : Number(value);
321
+ if (!Number.isFinite(n))
322
+ return String(value);
323
+ if (format === "percent")
324
+ return numberFormat({ style: "percent", maximumFractionDigits: 1 }).format(n);
325
+ if (format === "currency")
326
+ return numberFormat({ style: "currency", currency: "USD", notation: Math.abs(n) >= 100_000 ? "compact" : "standard", maximumFractionDigits: Math.abs(n) >= 100_000 ? 1 : 2 }).format(n);
327
+ if (format === "compact")
328
+ return numberFormat({ notation: "compact", maximumFractionDigits: 1 }).format(n);
329
+ return numberFormat({ maximumFractionDigits: 2 }).format(n);
330
+ }
331
+ /**
332
+ * A first view to start from, so there is something drawn before anyone
333
+ * presses a pill: the first category (not an id, not a date) broken down
334
+ * by the first measure (not a count of ids). A date stands in when there is
335
+ * no category, and a count of rows when there is no measure.
336
+ */
337
+ export function suggestedView(fields) {
338
+ const attributes = fields.filter((p) => p.kind === "attribute");
339
+ const by = attributes.find((p) => !p.grain && !KEY.test(p.column ?? "")) ?? attributes.find((p) => p.grain);
340
+ const metrics = fields.filter((p) => p.kind === "metric");
341
+ const measure = metrics.find((p) => p.column && p.aggregate !== "count_distinct") ?? metrics.find((p) => !p.column) ?? metrics[0];
342
+ return by && measure ? { rows: [by.id], values: [measure.id] } : { rows: [], values: [] };
343
+ }
344
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/explore/model.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AACnG,OAAO,EAAE,aAAa,EAAwB,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAc,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAA2D,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9H,OAAO,EAAkB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAmB,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAuEnD,MAAM,WAAW,GAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/D,iHAAiH;AACjH,MAAM,UAAU,sBAAsB,CAAC,KAAuC,EAAE,MAAgB;IAC9F,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC1D,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAC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C,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AAC5F,CAAC","sourcesContent":["import type { MessageInitShape } from \"@bufbuild/protobuf\";\nimport { measureExpressionProblem, measureNames, parseMeasureExpression } from \"@surfaces-ui/data\";\nimport { SortDirection, type ViewQuerySchema } from \"@surfaces-ui/proto\";\nimport { DataType, type Field } from \"apache-arrow\";\nimport { AGGREGATE_FUNCTIONS, type ChartAggregate, type ChartGrain, type ChartMeasure, TIME_GRAINS } from \"../chart/Chart.js\";\nimport { type ChartType, canTurnSideways } from \"../chart/option.js\";\nimport { type FilterSpec, filtersFromSpec } from \"@surfaces-ui/data\";\nimport { isNumeric } from \"../data/format.js\";\nimport { numberFormat } from \"../locale/locale.js\";\n\nexport type PillKind = \"attribute\" | \"metric\" | \"derived\";\nexport type PillFormat = \"number\" | \"compact\" | \"currency\" | \"percent\";\nexport type PillAggregate = Exclude<ChartAggregate, \"percentile\">;\n\n/**\n * A field as a pill: something a person or an agent can put on a shelf.\n * An attribute is a column to break down by, a metric is a column\n * summarised, and a derived metric is arithmetic over metrics. Pills are\n * plain data and nothing about them is fixed in advance: they are generated\n * from a query's columns, suggested, written by an agent, or made and\n * edited by hand.\n */\nexport interface Pill {\n /** Its name in calculations: letters, digits and underscores, starting with a letter. Unique in the list. */\n id: string;\n kind: PillKind;\n label: string;\n /** Attributes and metrics: the column. A metric without one counts rows. */\n column?: string;\n /** A date or time attribute: the size of its buckets. */\n grain?: ChartGrain;\n /** Metrics: how the column is summarised. */\n aggregate?: PillAggregate;\n /** Derived metrics: arithmetic over metric ids, e.g. `refunded / revenue`. */\n expression?: string;\n format?: PillFormat;\n description?: string;\n /** Who made it: \"the columns\" when it was generated from them, a model's name, or \"you\". Always shown. */\n by?: string;\n /**\n * The semantic model it comes from, when it is that model's field as the\n * model defines it. A pill changed by hand loses this until it is added\n * to the model again.\n */\n model?: string;\n}\n\n/** What is on the shelves. Plain JSON, so a page, a URL or an agent can hold and set it. */\n/** How a view's measures are drawn. A measure's own type or axis wins over the chart's. */\nexport type ExploreChartType = \"bar\" | \"line\" | \"area\";\nexport interface ExploreMeasureStyle {\n /** Draw this measure as bars, a line or an area, whatever the rest are. */\n type?: ExploreChartType;\n /** \"right\" puts this measure on a second scale at the right; for two measures of different sizes. */\n axis?: \"left\" | \"right\";\n}\nexport interface ExploreChartSettings {\n /** How measures are drawn unless one says otherwise. Defaults to a line over time and bars otherwise. */\n type?: ExploreChartType;\n /** Turn bars on their side: the breakdown down the left, the measure along the bottom. Bars on one scale only. */\n swap?: boolean;\n /** Per measure, by pill id. */\n measures?: Record<string, ExploreMeasureStyle>;\n}\n\nexport interface ExploreState {\n fields: Pill[];\n /** Attributes to break down by, by pill id. The first is the x axis. */\n rows: string[];\n /** An attribute whose values become separate series. */\n split?: string;\n /** Metrics and derived metrics to show, by pill id. */\n values: string[];\n filters: FilterSpec[];\n view?: \"chart\" | \"table\";\n /** How the chart draws the shelves. Left out, the chart is chosen from what is on them. */\n chart?: ExploreChartSettings;\n}\n\nconst CHART_TYPES: readonly string[] = [\"bar\", \"line\", \"area\"];\n\n/** The chart settings with anything that cannot apply left out: unknown types, and measures not on the shelf. */\nexport function normalizeChartSettings(chart: ExploreChartSettings | undefined, values: string[]): ExploreChartSettings | undefined {\n if (!chart || typeof chart !== \"object\") return undefined;\n const measures = Object.fromEntries(\n Object.entries(chart.measures ?? {})\n .filter(([id]) => values.includes(id))\n .map(([id, style]): [string, ExploreMeasureStyle] => [\n id,\n {\n ...(style?.type && CHART_TYPES.includes(style.type) ? { type: style.type } : {}),\n ...(style?.axis === \"right\" ? { axis: \"right\" as const } : {}),\n },\n ])\n .filter(([, style]) => Object.keys(style).length > 0),\n );\n const out: ExploreChartSettings = {\n ...(chart.type && CHART_TYPES.includes(chart.type) ? { type: chart.type } : {}),\n ...(chart.swap ? { swap: true } : {}),\n ...(Object.keys(measures).length > 0 ? { measures } : {}),\n };\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** A measure's style on the chart, changed; an empty style clears it. */\nexport function setMeasureStyle(state: ExploreState, id: string, style: ExploreMeasureStyle): ExploreState {\n const measures = { ...(state.chart?.measures ?? {}), [id]: { ...(state.chart?.measures?.[id] ?? {}), ...style } };\n return { ...state, chart: normalizeChartSettings({ ...state.chart, measures }, state.values) };\n}\n\n/** The chart settings changed: its type, or whether it is turned on its side. */\nexport function setChartSettings(state: ExploreState, change: Omit<ExploreChartSettings, \"measures\">): ExploreState {\n return { ...state, chart: normalizeChartSettings({ ...state.chart, ...change }, state.values) };\n}\n\nexport const emptyExplore: ExploreState = { fields: [], rows: [], values: [], filters: [] };\n\nconst ID = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst MONEY = /(amount|price|cost|revenue|sales|total|refund|paid|charge|fee|balance|margin|spend|value)/i;\nconst KEY = /(^id$|_id$|_key$|_no$|_number$|^sku$|code$)/i;\n/**\n * A number whose name says it adds up: money taken or spent, a count, a\n * quantity, time spent, energy used. Any other number is read as a reading\n * (a temperature, a speed, a price, a score, a level, a 0 or 1), which is\n * averaged: summing a reading over many rows gives a number nobody means.\n */\nconst ADDS_UP = /(amount|cost|revenue|sales|total|refund|paid|charge|fee|spend|income|profit|count|qty|quantity|units|orders|items|hours|minutes|seconds|days|kwh|mwh|energy|volume|clicks|views|visits|sessions|downloads|bytes|calls|tickets|^n_|^num_)/i;\n\n/** A pill id from a label, unlike any already taken: \"Refund rate\" becomes refund_rate. */\nexport function pillId(label: string, taken: Iterable<string> = []): string {\n const have = new Set(taken);\n const base =\n label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .replace(/^(\\d)/, \"n$1\")\n .slice(0, 40) || \"field\";\n let id = base;\n for (let n = 2; have.has(id); n++) id = `${base}_${n}`;\n return id;\n}\n\nconst words = (column: string) => column.replace(/_/g, \" \").replace(/^\\w/, (c) => c.toUpperCase());\n\n/**\n * Pills generated from a query's columns: text, true/false and dates become\n * attributes (a date by month), numbers become metrics (summed when their\n * name says they add up, averaged otherwise), and a\n * column that names things (an id, a code) becomes an attribute with a\n * count of its distinct values. There is always a count of rows. This is a\n * reading of names and types only; nothing is looked up in the data.\n */\nexport function pillsFromFields(fields: Pick<Field, \"name\" | \"type\">[], by = \"the columns\"): Pill[] {\n const pills: Pill[] = [];\n const taken = () => pills.map((p) => p.id);\n for (const field of fields) {\n const { name, type } = field;\n if (DataType.isList(type) || DataType.isStruct(type) || DataType.isMap(type) || DataType.isBinary(type)) continue;\n if (DataType.isTimestamp(type) || DataType.isDate(type)) {\n pills.push({ id: pillId(name, taken()), kind: \"attribute\", label: `${words(name)} (month)`, column: name, grain: \"month\", by });\n } else if (isNumeric(type) && !KEY.test(name)) {\n const sums = ADDS_UP.test(name);\n pills.push({ id: pillId(name, taken()), kind: \"metric\", label: sums ? words(name) : `Average ${words(name).toLowerCase()}`, column: name, aggregate: sums ? \"sum\" : \"avg\", format: MONEY.test(name) ? \"currency\" : sums ? \"compact\" : \"number\", by });\n } else {\n pills.push({ id: pillId(name, taken()), kind: \"attribute\", label: words(name), column: name, by });\n if (KEY.test(name)) pills.push({ id: pillId(`${name}_count`, taken()), kind: \"metric\", label: `Distinct ${words(name).toLowerCase()}`, column: name, aggregate: \"count_distinct\", format: \"compact\", by });\n }\n }\n pills.push({ id: pillId(\"rows\", taken()), kind: \"metric\", label: \"Rows\", aggregate: \"count\", format: \"compact\", by });\n return pills;\n}\n\n/**\n * Calculations worth offering from the metrics there are: each summed\n * metric per row (an average that follows the filters), a margin when there\n * is something sold and something it cost, and one money metric as a share\n * of another. They are suggestions from names, labelled as such, and a\n * person keeps, edits or removes them.\n */\nexport function suggestDerived(pills: Pill[], by = \"suggested from the columns\"): Pill[] {\n const out: Pill[] = [];\n const taken = () => [...pills, ...out].map((p) => p.id);\n const has = (expression: string) => [...pills, ...out].some((p) => p.kind === \"derived\" && p.expression?.replace(/\\s+/g, \"\") === expression.replace(/\\s+/g, \"\"));\n const add = (label: string, expression: string, format: PillFormat, description: string) => {\n if (!has(expression)) out.push({ id: pillId(label, taken()), kind: \"derived\", label, expression, format, description, by });\n };\n const sums = pills.filter((p) => p.kind === \"metric\" && p.aggregate === \"sum\");\n const rows = pills.find((p) => p.kind === \"metric\" && p.aggregate === \"count\" && !p.column);\n if (rows) for (const metric of sums.slice(0, 3)) add(`${metric.label} per row`, `${metric.id} / ${rows.id}`, metric.format === \"currency\" ? \"currency\" : \"number\", `${metric.label} divided by the number of rows.`);\n const sold = sums.find((p) => /(revenue|sales|amount|price|total)/i.test(p.column ?? \"\"));\n const cost = sums.find((p) => /cost/i.test(p.column ?? \"\"));\n if (sold && cost && sold !== cost) add(\"Margin\", `(${sold.id} - ${cost.id}) / ${sold.id}`, \"percent\", `What is left of ${sold.label.toLowerCase()} after ${cost.label.toLowerCase()}, as a share.`);\n const money = sums.filter((p) => p.format === \"currency\");\n const part = money.find((p) => /(refund|discount|fee|tax|return)/i.test(p.column ?? \"\"));\n const whole = money.find((p) => p !== part && /(revenue|sales|amount|total|price)/i.test(p.column ?? \"\"));\n if (part && whole) add(`${part.label} share of ${whole.label.toLowerCase()}`, `${part.id} / ${whole.id}`, \"percent\", `${part.label} divided by ${whole.label.toLowerCase()}.`);\n return out;\n}\n\n/** Why a pill cannot be used, or undefined when it can. `columns`, when given, are the query's own. */\nexport function pillProblem(pill: Pill, all: Pill[], columns?: string[]): string | undefined {\n if (!ID.test(pill.id)) return \"Its name in calculations must start with a letter and use only letters, digits and underscores.\";\n if (all.filter((p) => p.id === pill.id).length > 1) return `Another field is already called \"${pill.id}\".`;\n if (!pill.label.trim()) return \"It needs a label.\";\n const known = (column: string | undefined) => !columns || (column !== undefined && columns.includes(column));\n if (pill.kind === \"attribute\") return !pill.column ? \"An attribute needs a column.\" : known(pill.column) ? undefined : `There is no column \"${pill.column}\" in this query.`;\n if (pill.kind === \"metric\") {\n if (!pill.aggregate) return \"A metric needs a way to summarise: sum, average, count.\";\n if (!pill.column) return pill.aggregate === \"count\" ? undefined : \"Only a count can do without a column.\";\n return known(pill.column) ? undefined : `There is no column \"${pill.column}\" in this query.`;\n }\n // A calculation is over metrics only, so one can never depend on itself.\n return measureExpressionProblem(pill.expression ?? \"\", all.filter((p) => p.kind === \"metric\").map((p) => p.id));\n}\n\n/** The state with anything that cannot be drawn taken off the shelves: ids that are not fields, an attribute among the values. */\nexport function normalizeExplore(state: ExploreState): ExploreState {\n const kind = new Map(state.fields.map((p) => [p.id, p.kind]));\n const rows = [...new Set(state.rows)].filter((id) => kind.get(id) === \"attribute\").slice(0, 3);\n const split = state.split && kind.get(state.split) === \"attribute\" && !rows.includes(state.split) ? state.split : undefined;\n const values = [...new Set(state.values)].filter((id) => kind.get(id) === \"metric\" || kind.get(id) === \"derived\").slice(0, 6);\n const chart = normalizeChartSettings(state.chart, values);\n return { fields: state.fields, rows, ...(split ? { split } : {}), values, filters: state.filters, ...(state.view ? { view: state.view } : {}), ...(chart ? { chart } : {}) };\n}\n\n/** Where a pill goes when it is simply chosen: an attribute breaks the view down, a metric is measured. */\nexport function addToShelf(state: ExploreState, id: string, shelf?: \"rows\" | \"split\" | \"values\", at?: number): ExploreState {\n const pill = state.fields.find((p) => p.id === id);\n if (!pill) return state;\n const target = shelf ?? (pill.kind === \"attribute\" ? \"rows\" : \"values\");\n // At a place among the others (counted without this pill), or at the end.\n const insert = (list: string[]) => {\n const others = list.filter((item) => item !== id);\n const place = at === undefined ? others.length : Math.max(0, Math.min(others.length, at));\n return [...others.slice(0, place), id, ...others.slice(place)];\n };\n if (target === \"split\") return normalizeExplore({ ...state, rows: state.rows.filter((r) => r !== id), split: id });\n if (target === \"rows\") return normalizeExplore({ ...state, rows: insert(state.rows), ...(state.split === id ? { split: undefined } : {}) });\n return normalizeExplore({ ...state, values: insert(state.values) });\n}\n\n/** A pill moved one place earlier (-1) or later (1) on its shelf: the first breakdown is the x axis, the first measure the first series. At an end, nothing changes. */\nexport function movePill(state: ExploreState, id: string, by: -1 | 1): ExploreState {\n const shelf = state.rows.includes(id) ? \"rows\" : state.values.includes(id) ? \"values\" : undefined;\n if (!shelf) return state;\n const from = state[shelf].indexOf(id);\n const to = from + by;\n if (to < 0 || to >= state[shelf].length) return state;\n return addToShelf(state, id, shelf, to);\n}\n\nexport function removeFromShelf(state: ExploreState, id: string, shelf: \"rows\" | \"split\" | \"values\"): ExploreState {\n if (shelf === \"split\") return { ...state, split: undefined };\n return { ...state, [shelf]: state[shelf].filter((item) => item !== id) };\n}\n\n/** A pill changed, added (when its id is new) or, with `undefined`, removed, along with what that does to the shelves and to calculations that named it. */\nexport function setPill(state: ExploreState, id: string, next: Pill | undefined): ExploreState {\n const exists = state.fields.some((p) => p.id === id);\n let fields = next ? (exists ? state.fields.map((p) => (p.id === id ? next : p)) : [...state.fields, next]) : state.fields.filter((p) => p.id !== id);\n const renamed = next && next.id !== id ? next.id : undefined;\n if (renamed) {\n // Calculations follow a rename.\n fields = fields.map((p) => (p.kind === \"derived\" && p.expression ? { ...p, expression: p.expression.replace(new RegExp(`\\\\b${id}\\\\b`, \"g\"), renamed) } : p));\n }\n const swap = (item: string) => (item === id ? renamed : item);\n const keep = (list: string[]) => list.map((item) => (item === id ? (next ? (renamed ?? id) : undefined) : item)).filter((item): item is string => item !== undefined);\n return normalizeExplore({ ...state, fields, rows: keep(state.rows), values: keep(state.values), split: state.split === id ? (next ? (swap(id) ?? id) : undefined) : state.split });\n}\n\nconst pillOf = (state: ExploreState, id: string) => state.fields.find((p) => p.id === id);\n\n/** The metrics a set of values needs summarised: the metrics themselves and those their calculations name. */\nfunction metricsNeeded(state: ExploreState): Pill[] {\n const ids: string[] = [];\n for (const id of state.values) {\n const pill = pillOf(state, id);\n if (pill?.kind === \"metric\") ids.push(id);\n if (pill?.kind === \"derived\") {\n try {\n ids.push(...measureNames(parseMeasureExpression(pill.expression ?? \"\")));\n } catch {\n // Reported where the pill is shown.\n }\n }\n }\n return [...new Set(ids)].map((id) => pillOf(state, id)).filter((p): p is Pill => p?.kind === \"metric\");\n}\n\n/**\n * The query for the table of what is on the shelves: one row per\n * combination of the attributes, a column per metric and calculation, all\n * worked out by the engine. Sorted by time when the first attribute is a\n * date, by the first value otherwise, so a row limit keeps the largest.\n */\nexport function exploreQuery(state: ExploreState, sql: string, limit = 200, now?: Date): MessageInitShape<typeof ViewQuerySchema> {\n const attributes = [...state.rows, ...(state.split ? [state.split] : [])].map((id) => pillOf(state, id)).filter((p): p is Pill => p?.kind === \"attribute\");\n const plain = attributes.filter((p) => !p.grain);\n const timed = attributes.filter((p) => p.grain);\n const derived = state.values.map((id) => pillOf(state, id)).filter((p): p is Pill => p?.kind === \"derived\");\n const first = attributes[0];\n return {\n baseSql: sql,\n filters: filtersFromSpec(state.filters, now),\n groupBy: plain.map((p) => p.column!),\n buckets: timed.map((p) => ({ column: p.column!, alias: p.id, by: { case: \"grain\" as const, value: TIME_GRAINS[p.grain!] } })),\n aggregates: metricsNeeded(state).map((p) => ({ function: AGGREGATE_FUNCTIONS[p.aggregate ?? \"count\"], column: p.column ?? \"\", alias: p.id })),\n derived: derived.map((p) => ({ alias: p.id, expression: p.expression ?? \"\" })),\n sorts: first?.grain ? [{ column: first.id, direction: SortDirection.ASC }] : state.values[0] ? [{ column: state.values[0], direction: SortDirection.DESC }] : [],\n page: { limit },\n };\n}\n\n/** The name a pill's values come back under in `exploreQuery`'s result. */\nexport const pillColumn = (pill: Pill): string => (pill.kind === \"attribute\" && !pill.grain ? pill.column! : pill.id);\n\nexport interface ExploreChart {\n type: ChartType;\n x: string;\n xGrain?: ChartGrain;\n splitBy?: string;\n y: ChartMeasure[];\n xTitle: string;\n /** The measures on each scale, named, when there are two scales. */\n yTitle?: string;\n yRightTitle?: string;\n /** The left scale's format, when its measures share one: the axis writes it. */\n yFormat?: PillFormat;\n /** Bars on their side. Set only when the settings ask for it and the chart is bars on one scale. */\n horizontal?: boolean;\n}\n\n/** Why the bars cannot be turned on their side now, or undefined when they can. */\nexport function swapProblem(state: ExploreState): string | undefined {\n const chart = exploreChart({ ...state, chart: { ...state.chart, swap: false } });\n if (!chart) return \"There is no chart to turn yet.\";\n if (!canTurnSideways(chart.type, chart.y)) return \"Only bars on one scale can be turned on their side.\";\n return undefined;\n}\n\n/**\n * The chart for what is on the shelves, or undefined when there is nothing\n * to draw one from (no attribute, or no value). A date is a line over time;\n * categories are bars, largest first. The split becomes the series, with\n * each measure for each of its values; a second attribute does when one\n * value is shown.\n */\nexport function exploreChart(state: ExploreState): ExploreChart | undefined {\n const rows = state.rows.map((id) => pillOf(state, id)).filter((p): p is Pill => p?.kind === \"attribute\");\n const values = state.values.map((id) => pillOf(state, id)).filter((p): p is Pill => !!p && p.kind !== \"attribute\");\n const x = rows[0];\n if (!x || values.length === 0) return undefined;\n const split = (state.split ? pillOf(state, state.split) : rows[1]) ?? undefined;\n const type: ExploreChartType = state.chart?.type ?? (x.grain ? \"line\" : \"bar\");\n // A second scale needs a measure on each; all of them on the right is one scale, drawn on the left.\n const right = new Set(values.filter((p) => state.chart?.measures?.[p.id]?.axis === \"right\").map((p) => p.id));\n if (right.size === values.length) right.clear();\n const style = (pill: Pill): Pick<ChartMeasure, \"type\" | \"axis\"> => {\n const own = state.chart?.measures?.[pill.id]?.type;\n return { ...(own && own !== type ? { type: own } : {}), ...(right.has(pill.id) ? { axis: \"right\" as const } : {}) };\n };\n const y = values.map((pill): ChartMeasure => {\n if (pill.kind === \"metric\") return { ...(pill.column ? { column: pill.column } : {}), aggregate: pill.aggregate ?? \"count\", label: pill.label, ...style(pill) };\n let names: string[] = [];\n try {\n names = measureNames(parseMeasureExpression(pill.expression ?? \"\"));\n } catch {\n // The chart reports a calculation it cannot read.\n }\n const terms = Object.fromEntries(\n names\n .map((name) => pillOf(state, name))\n .filter((p): p is Pill => p?.kind === \"metric\")\n .map((p) => [p.id, { ...(p.column ? { column: p.column } : {}), aggregate: p.aggregate ?? (\"count\" as const) }]),\n );\n return { expression: pill.expression ?? \"\", terms, label: pill.label, ...style(pill) };\n });\n const left = values.filter((p) => !right.has(p.id));\n const onRight = values.filter((p) => right.has(p.id));\n const sideways = !!state.chart?.swap && canTurnSideways(type, y);\n return {\n type,\n x: x.column!,\n ...(x.grain ? { xGrain: x.grain } : {}),\n // The split makes the series, one per value and measure (\"North · Revenue\") when there are several measures;\n // a second attribute on the rows splits only one measure, so more on the rows never multiplies the lines unasked.\n ...(split?.column && !split.grain && (state.split || values.length === 1) ? { splitBy: split.column } : {}),\n y,\n xTitle: x.label,\n // With two scales each is named, so a reader knows which line is read against which.\n ...(onRight.length > 0 ? { yTitle: left.map((p) => p.label).join(\", \"), yRightTitle: onRight.map((p) => p.label).join(\", \") } : {}),\n // An axis writes one format; measures in different ones keep plain numbers.\n ...(left[0]?.format && left.every((p) => p.format === left[0]!.format) ? { yFormat: left[0].format } : {}),\n ...(sideways ? { horizontal: true } : {}),\n };\n}\n\n/** A number as a pill's format writes it. */\nexport function pillNumber(value: unknown, format: PillFormat | undefined): string {\n if (value == null) return \"–\";\n const n = typeof value === \"bigint\" ? Number(value) : Number(value);\n if (!Number.isFinite(n)) return String(value);\n if (format === \"percent\") return numberFormat({ style: \"percent\", maximumFractionDigits: 1 }).format(n);\n if (format === \"currency\") return numberFormat({ style: \"currency\", currency: \"USD\", notation: Math.abs(n) >= 100_000 ? \"compact\" : \"standard\", maximumFractionDigits: Math.abs(n) >= 100_000 ? 1 : 2 }).format(n);\n if (format === \"compact\") return numberFormat({ notation: \"compact\", maximumFractionDigits: 1 }).format(n);\n return numberFormat({ maximumFractionDigits: 2 }).format(n);\n}\n\n/**\n * A first view to start from, so there is something drawn before anyone\n * presses a pill: the first category (not an id, not a date) broken down\n * by the first measure (not a count of ids). A date stands in when there is\n * no category, and a count of rows when there is no measure.\n */\nexport function suggestedView(fields: Pill[]): Pick<ExploreState, \"rows\" | \"values\"> {\n const attributes = fields.filter((p) => p.kind === \"attribute\");\n const by = attributes.find((p) => !p.grain && !KEY.test(p.column ?? \"\")) ?? attributes.find((p) => p.grain);\n const metrics = fields.filter((p) => p.kind === \"metric\");\n const measure = metrics.find((p) => p.column && p.aggregate !== \"count_distinct\") ?? metrics.find((p) => !p.column) ?? metrics[0];\n return by && measure ? { rows: [by.id], values: [measure.id] } : { rows: [], values: [] };\n}\n"]}
@@ -0,0 +1,60 @@
1
+ import type { FilterSpec } from "@surfaces-ui/data";
2
+ import { type ExploreChartSettings, type ExploreState, type Pill } from "./model.js";
3
+ /** One view on a report: what is on its shelves, drawn from the report's pills and filters. */
4
+ export interface ReportTile {
5
+ id: string;
6
+ /** Shown above the tile. Left out, the shelves are read out: "Refund rate by Category". */
7
+ title?: string;
8
+ rows: string[];
9
+ split?: string;
10
+ values: string[];
11
+ view?: "chart" | "table";
12
+ /** How its chart is drawn: type, axes swapped, each measure's own type and scale. */
13
+ chart?: ExploreChartSettings;
14
+ /** How many of the report's three columns it takes. Defaults to 1; headline numbers take the row. */
15
+ span?: 1 | 2 | 3;
16
+ }
17
+ /**
18
+ * A report: pills defined once, filters shared by every view, and the views
19
+ * themselves as tiles. This is the whole of a dashboard as plain JSON, so
20
+ * it can be saved, reviewed, sent to an agent and written by one.
21
+ */
22
+ export interface ReportState {
23
+ title?: string;
24
+ /** The report's fields. Every tile and the builder use these, so a metric means the same thing everywhere on it. */
25
+ fields: Pill[];
26
+ /** Filters every tile follows. */
27
+ filters: FilterSpec[];
28
+ tiles: ReportTile[];
29
+ /** What is on the builder's shelves: the tile being made, or the one being changed. */
30
+ draft?: Pick<ReportTile, "rows" | "split" | "values" | "view" | "chart">;
31
+ /** The tile the draft will replace, when one is being changed. */
32
+ editing?: string;
33
+ }
34
+ export declare const emptyReport: ReportState;
35
+ export declare const MAX_TILES = 24;
36
+ /** A tile's shelves as an explorer state over the report's pills and filters. */
37
+ export declare function tileState(report: ReportState, tile: Pick<ReportTile, "rows" | "split" | "values" | "view" | "chart">): ExploreState;
38
+ /** The builder's own state: the draft over the report's pills and filters. */
39
+ export declare function draftState(report: ReportState): ExploreState;
40
+ /** The report after the builder changed: its pills and filters are the report's, the shelves are the draft. */
41
+ export declare function withDraft(report: ReportState, state: ExploreState): ReportState;
42
+ /**
43
+ * Keeps the draft as a tile: a new one at the end, or in place of the tile
44
+ * being changed. A draft with nothing to measure is not kept. The shelves
45
+ * are left as they are, so the next tile starts from this one.
46
+ */
47
+ export declare function keepDraft(report: ReportState, title?: string): ReportState;
48
+ /** Opens a tile in the builder, to change it. */
49
+ export declare function editTile(report: ReportState, id: string): ReportState;
50
+ export declare function removeTile(report: ReportState, id: string): ReportState;
51
+ /** Moves a tile one place earlier (-1) or later (1). At an end, nothing changes. */
52
+ export declare function moveTile(report: ReportState, id: string, by: -1 | 1): ReportState;
53
+ export declare function setTile(report: ReportState, id: string, change: Partial<Pick<ReportTile, "title" | "span" | "view">>): ReportState;
54
+ /**
55
+ * A report with nothing that cannot be drawn: tiles that name pills that are
56
+ * gone lose them, a tile left with nothing to measure is dropped, and ids
57
+ * are made unlike each other. Whatever its source (a saved page, an agent),
58
+ * a report goes through this before it is shown.
59
+ */
60
+ export declare function normalizeReport(report: ReportState): ReportState;
@@ -0,0 +1,92 @@
1
+ import { normalizeExplore } from "./model.js";
2
+ export const emptyReport = { fields: [], filters: [], tiles: [] };
3
+ export const MAX_TILES = 24;
4
+ /** A tile's shelves as an explorer state over the report's pills and filters. */
5
+ export function tileState(report, tile) {
6
+ return normalizeExplore({ fields: report.fields, rows: tile.rows, ...(tile.split ? { split: tile.split } : {}), values: tile.values, filters: report.filters, ...(tile.view ? { view: tile.view } : {}), ...(tile.chart ? { chart: tile.chart } : {}) });
7
+ }
8
+ /** The builder's own state: the draft over the report's pills and filters. */
9
+ export function draftState(report) {
10
+ // Not normalised here: a draft can name pills that are generated only once the columns are known.
11
+ const draft = report.draft ?? { rows: [], values: [] };
12
+ return { fields: report.fields, rows: draft.rows, ...(draft.split ? { split: draft.split } : {}), values: draft.values, filters: report.filters, ...(draft.view ? { view: draft.view } : {}), ...(draft.chart ? { chart: draft.chart } : {}) };
13
+ }
14
+ /** The report after the builder changed: its pills and filters are the report's, the shelves are the draft. */
15
+ export function withDraft(report, state) {
16
+ return { ...report, fields: state.fields, filters: state.filters, draft: { rows: state.rows, ...(state.split ? { split: state.split } : {}), values: state.values, ...(state.view ? { view: state.view } : {}), ...(state.chart ? { chart: state.chart } : {}) } };
17
+ }
18
+ const nextId = (tiles) => {
19
+ for (let n = tiles.length + 1;; n++)
20
+ if (!tiles.some((t) => t.id === `tile-${n}`))
21
+ return `tile-${n}`;
22
+ };
23
+ /**
24
+ * Keeps the draft as a tile: a new one at the end, or in place of the tile
25
+ * being changed. A draft with nothing to measure is not kept. The shelves
26
+ * are left as they are, so the next tile starts from this one.
27
+ */
28
+ export function keepDraft(report, title) {
29
+ const draft = report.draft;
30
+ const state = draft ? tileState(report, draft) : undefined;
31
+ if (!draft || !state || state.values.length === 0)
32
+ return report;
33
+ const shelves = { rows: state.rows, ...(state.split ? { split: state.split } : {}), values: state.values, ...(draft.view ? { view: draft.view } : {}), chart: state.chart };
34
+ if (report.editing && report.tiles.some((t) => t.id === report.editing)) {
35
+ return { ...report, tiles: report.tiles.map((t) => (t.id === report.editing ? { ...t, ...shelves, ...(shelves.split ? {} : { split: undefined }), ...(title !== undefined ? { title: title || undefined } : {}) } : t)), editing: undefined };
36
+ }
37
+ if (report.tiles.length >= MAX_TILES)
38
+ return report;
39
+ // Headline numbers read best across the top of the row.
40
+ const span = state.rows.length === 0 ? 3 : 1;
41
+ const { chart, ...rest } = shelves;
42
+ return { ...report, tiles: [...report.tiles, { id: nextId(report.tiles), ...(title ? { title } : {}), ...rest, ...(chart ? { chart } : {}), span }] };
43
+ }
44
+ /** Opens a tile in the builder, to change it. */
45
+ export function editTile(report, id) {
46
+ const tile = report.tiles.find((t) => t.id === id);
47
+ if (!tile)
48
+ return report;
49
+ return { ...report, editing: id, draft: { rows: tile.rows, ...(tile.split ? { split: tile.split } : {}), values: tile.values, ...(tile.view ? { view: tile.view } : {}), ...(tile.chart ? { chart: tile.chart } : {}) } };
50
+ }
51
+ export function removeTile(report, id) {
52
+ return { ...report, tiles: report.tiles.filter((t) => t.id !== id), ...(report.editing === id ? { editing: undefined } : {}) };
53
+ }
54
+ /** Moves a tile one place earlier (-1) or later (1). At an end, nothing changes. */
55
+ export function moveTile(report, id, by) {
56
+ const from = report.tiles.findIndex((t) => t.id === id);
57
+ const to = from + by;
58
+ if (from < 0 || to < 0 || to >= report.tiles.length)
59
+ return report;
60
+ const tiles = [...report.tiles];
61
+ [tiles[from], tiles[to]] = [tiles[to], tiles[from]];
62
+ return { ...report, tiles };
63
+ }
64
+ export function setTile(report, id, change) {
65
+ return { ...report, tiles: report.tiles.map((t) => (t.id === id ? { ...t, ...change } : t)) };
66
+ }
67
+ /**
68
+ * A report with nothing that cannot be drawn: tiles that name pills that are
69
+ * gone lose them, a tile left with nothing to measure is dropped, and ids
70
+ * are made unlike each other. Whatever its source (a saved page, an agent),
71
+ * a report goes through this before it is shown.
72
+ */
73
+ export function normalizeReport(report) {
74
+ // Before the pills exist (they are generated once the columns are known) there is nothing to check tiles against.
75
+ if (report.fields.length === 0)
76
+ return report;
77
+ const seen = new Set();
78
+ const tiles = [];
79
+ for (const tile of report.tiles.slice(0, MAX_TILES)) {
80
+ const state = tileState(report, tile);
81
+ if (state.values.length === 0)
82
+ continue;
83
+ let id = tile.id || nextId(tiles);
84
+ if (seen.has(id))
85
+ id = nextId(tiles);
86
+ seen.add(id);
87
+ const span = tile.span === 2 || tile.span === 3 ? tile.span : 1;
88
+ tiles.push({ id, ...(tile.title ? { title: tile.title } : {}), rows: state.rows, ...(state.split ? { split: state.split } : {}), values: state.values, ...(tile.view ? { view: tile.view } : {}), ...(state.chart ? { chart: state.chart } : {}), span });
89
+ }
90
+ return { ...report, tiles, ...(report.editing && !tiles.some((t) => t.id === report.editing) ? { editing: undefined } : {}) };
91
+ }
92
+ //# sourceMappingURL=report.js.map