derive-dashboards 0.1.1 → 0.3.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 (202) hide show
  1. package/README.md +5 -3
  2. package/dist/cache.mjs +2 -1
  3. package/dist/cli/add.mjs +130 -0
  4. package/dist/cli/cli.mjs +14 -12
  5. package/dist/cli/config.mjs +12 -1
  6. package/dist/cli/doctor.mjs +162 -0
  7. package/dist/cli/init.mjs +3 -2
  8. package/dist/cli/json.mjs +21 -0
  9. package/dist/cli/layers.mjs +33 -0
  10. package/dist/core/document/display.d.mts +63 -0
  11. package/dist/core/document/display.mjs +139 -0
  12. package/dist/core/document/layout.mjs +1 -1
  13. package/dist/core/document/view-layout.d.mts +14 -0
  14. package/dist/core/document/view-layout.mjs +157 -0
  15. package/dist/core/engine/filter.mjs +2 -2
  16. package/dist/core/engine/leaf.mjs +9 -4
  17. package/dist/core/engine/members.mjs +1 -1
  18. package/dist/core/engine/version.d.mts +5 -4
  19. package/dist/core/engine/version.mjs +5 -4
  20. package/dist/core/error/codes.d.mts +4 -1
  21. package/dist/core/error/codes.mjs +4 -1
  22. package/dist/core/index.d.mts +12 -8
  23. package/dist/core/index.mjs +11 -7
  24. package/dist/core/model/member.mjs +5 -2
  25. package/dist/core/model/types.d.mts +13 -13
  26. package/dist/core/model/validate/drill.mjs +6 -15
  27. package/dist/core/model/validate/fields.mjs +130 -0
  28. package/dist/core/model/validate/index.mjs +11 -3
  29. package/dist/core/model/validate/known-members.mjs +133 -0
  30. package/dist/core/model/validate/known-nested.mjs +85 -0
  31. package/dist/core/model/validate/known.mjs +94 -0
  32. package/dist/core/model/validate/members.mjs +7 -4
  33. package/dist/core/model/validate/source.mjs +8 -1
  34. package/dist/core/policy/bind-query.d.mts +12 -0
  35. package/dist/core/policy/bind-query.mjs +53 -0
  36. package/dist/core/query/alias.mjs +11 -1
  37. package/dist/core/query/drill/selection.d.mts +7 -2
  38. package/dist/core/query/drill/selection.mjs +18 -15
  39. package/dist/core/query/filter.d.mts +6 -0
  40. package/dist/core/query/picks.d.mts +8 -2
  41. package/dist/core/query/picks.mjs +11 -4
  42. package/dist/core/query/segments.mjs +2 -1
  43. package/dist/core/result/columns.d.mts +10 -1
  44. package/dist/core/result/columns.mjs +27 -5
  45. package/dist/core/result/time-axis.d.mts +23 -0
  46. package/dist/core/result/time-axis.mjs +72 -0
  47. package/dist/core/result/types.d.mts +36 -1
  48. package/dist/core/schema/aliases.d.mts +7 -0
  49. package/dist/core/schema/aliases.mjs +77 -0
  50. package/dist/core/schema/answer-parts.mjs +23 -1
  51. package/dist/core/schema/answers.d.mts +204 -0
  52. package/dist/core/schema/answers.mjs +2 -0
  53. package/dist/core/schema/index.d.mts +3 -2
  54. package/dist/core/schema/index.mjs +3 -2
  55. package/dist/core/schema/query.d.mts +81 -0
  56. package/dist/core/schema/query.mjs +9 -5
  57. package/dist/core/schema/tools.d.mts +2 -0
  58. package/dist/core/schema/tools.mjs +27 -1
  59. package/dist/core/time/bucket.mjs +8 -2
  60. package/dist/core/types/api.d.mts +7 -1
  61. package/dist/core/types/api.mjs +1 -1
  62. package/dist/dashboards.mjs +4 -0
  63. package/dist/drill-change.mjs +1 -1
  64. package/dist/drill-seal.mjs +1 -0
  65. package/dist/editing.mjs +2 -2
  66. package/dist/endpoints/dashboards.mjs +17 -2
  67. package/dist/endpoints/index.d.mts +15 -2
  68. package/dist/endpoints/meta.mjs +10 -1
  69. package/dist/execute.mjs +32 -17
  70. package/dist/handler.mjs +5 -1
  71. package/dist/index.mjs +6 -1
  72. package/dist/llms.txt +22 -0
  73. package/dist/mcp/format.mjs +42 -8
  74. package/dist/mcp/query.mjs +34 -4
  75. package/dist/postgres-store.mjs +1 -0
  76. package/dist/react/Canvas.mjs +28 -5
  77. package/dist/react/Cell.mjs +2 -1
  78. package/dist/react/Dashboard.d.mts +4 -0
  79. package/dist/react/Dashboard.mjs +27 -4
  80. package/dist/react/DashboardList.mjs +22 -22
  81. package/dist/react/DashboardListRow.mjs +49 -0
  82. package/dist/react/Discard.mjs +5 -2
  83. package/dist/react/Editing.mjs +19 -5
  84. package/dist/react/FilterBar.d.mts +7 -9
  85. package/dist/react/Grid.mjs +7 -19
  86. package/dist/react/Header.mjs +1 -1
  87. package/dist/react/History.mjs +5 -0
  88. package/dist/react/ReadFailed.mjs +23 -0
  89. package/dist/react/Spaces.mjs +15 -1
  90. package/dist/react/Tile.d.mts +2 -0
  91. package/dist/react/Tile.mjs +45 -10
  92. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  93. package/dist/react/arrange-steps.mjs +16 -13
  94. package/dist/react/arrange.mjs +10 -3
  95. package/dist/react/builder/Calcs.mjs +35 -11
  96. package/dist/react/builder/FilterEditor.mjs +196 -0
  97. package/dist/react/builder/Filters.mjs +172 -116
  98. package/dist/react/builder/Formula.mjs +82 -0
  99. package/dist/react/builder/Groups.mjs +1 -0
  100. package/dist/react/builder/Preview.mjs +1 -1
  101. package/dist/react/builder/RangeEditor.mjs +184 -0
  102. package/dist/react/builder/Sections.mjs +41 -6
  103. package/dist/react/builder/Time.mjs +138 -60
  104. package/dist/react/builder/Values.mjs +85 -0
  105. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  106. package/dist/react/builder/base.d.mts +5 -0
  107. package/dist/react/builder/base.mjs +33 -8
  108. package/dist/react/builder/calc.mjs +15 -1
  109. package/dist/react/builder/escape.d.mts +1 -0
  110. package/dist/react/builder/escape.mjs +62 -0
  111. package/dist/react/builder/filter-tree.d.mts +9 -0
  112. package/dist/react/builder/filter-tree.mjs +186 -0
  113. package/dist/react/builder/formula-parse.d.mts +18 -0
  114. package/dist/react/builder/formula-parse.mjs +136 -0
  115. package/dist/react/builder/labels.d.mts +1 -1
  116. package/dist/react/builder/state.d.mts +2 -1
  117. package/dist/react/builder/state.mjs +23 -37
  118. package/dist/react/builder/useBuilder.d.mts +12 -1
  119. package/dist/react/builder/useBuilder.mjs +6 -3
  120. package/dist/react/builder/words.d.mts +59 -0
  121. package/dist/react/builder/words.mjs +73 -0
  122. package/dist/react/context.d.mts +15 -1
  123. package/dist/react/context.mjs +9 -3
  124. package/dist/react/drill/Bars.mjs +2 -2
  125. package/dist/react/drill/props.mjs +2 -1
  126. package/dist/react/drill/useDrill.d.mts +1 -1
  127. package/dist/react/drill/words.d.mts +3 -0
  128. package/dist/react/drill/words.mjs +2 -0
  129. package/dist/react/english.mjs +20 -5
  130. package/dist/react/filters/bar.d.mts +12 -0
  131. package/dist/react/filters/bar.mjs +135 -0
  132. package/dist/react/filters/calendar.mjs +193 -0
  133. package/dist/react/filters/chip.mjs +174 -0
  134. package/dist/react/filters/context.d.mts +22 -0
  135. package/dist/react/filters/context.mjs +78 -0
  136. package/dist/react/filters/dates.mjs +89 -0
  137. package/dist/react/filters/days.d.mts +36 -0
  138. package/dist/react/filters/days.mjs +87 -0
  139. package/dist/react/filters/field-step.mjs +81 -0
  140. package/dist/react/filters/hooks.d.mts +34 -0
  141. package/dist/react/filters/hooks.mjs +94 -0
  142. package/dist/react/filters/listbox.mjs +131 -0
  143. package/dist/react/filters/logic.d.mts +59 -0
  144. package/dist/react/filters/logic.mjs +109 -0
  145. package/dist/react/filters/menu-search.mjs +211 -0
  146. package/dist/react/filters/menu.mjs +85 -0
  147. package/dist/react/filters/number.mjs +127 -0
  148. package/dist/react/filters/numbers.d.mts +47 -0
  149. package/dist/react/filters/numbers.mjs +151 -0
  150. package/dist/react/filters/operator.mjs +104 -0
  151. package/dist/react/filters/phone.mjs +104 -0
  152. package/dist/react/filters/popover.d.mts +19 -0
  153. package/dist/react/filters/popover.mjs +153 -0
  154. package/dist/react/filters/rules.d.mts +8 -0
  155. package/dist/react/filters/rules.mjs +55 -0
  156. package/dist/react/filters/sheet.mjs +196 -0
  157. package/dist/react/filters/state.mjs +132 -0
  158. package/dist/react/filters/suggest.d.mts +47 -0
  159. package/dist/react/filters/suggest.mjs +97 -0
  160. package/dist/react/filters/values.mjs +166 -0
  161. package/dist/react/filters/words.d.mts +81 -0
  162. package/dist/react/filters/words.mjs +73 -0
  163. package/dist/react/format.mjs +11 -4
  164. package/dist/react/index.d.mts +15 -6
  165. package/dist/react/index.mjs +10 -4
  166. package/dist/react/messages.d.mts +34 -2
  167. package/dist/react/place.mjs +7 -3
  168. package/dist/react/renderers/index.d.mts +3 -21
  169. package/dist/react/renderers/index.mjs +68 -6
  170. package/dist/react/renderers/list.d.mts +2 -1
  171. package/dist/react/renderers/list.mjs +9 -12
  172. package/dist/react/renderers/props.d.mts +26 -0
  173. package/dist/react/scope.d.mts +4 -0
  174. package/dist/react/scope.mjs +19 -2
  175. package/dist/react/series-slots.d.mts +37 -0
  176. package/dist/react/series-slots.mjs +71 -0
  177. package/dist/react/series.d.mts +39 -9
  178. package/dist/react/series.mjs +144 -47
  179. package/dist/react/theme.css +930 -19
  180. package/dist/react/useBoard.d.mts +2 -0
  181. package/dist/react/useDashboard.d.mts +3 -0
  182. package/dist/react/useDashboard.mjs +6 -0
  183. package/dist/react/view-grid.mjs +16 -0
  184. package/dist/recharts/axes.mjs +28 -0
  185. package/dist/recharts/axis.mjs +84 -0
  186. package/dist/recharts/bar.d.mts +7 -0
  187. package/dist/recharts/bar.mjs +141 -0
  188. package/dist/recharts/charts.d.mts +4 -5
  189. package/dist/recharts/charts.mjs +2 -208
  190. package/dist/recharts/index.d.mts +3 -1
  191. package/dist/recharts/index.mjs +4 -1
  192. package/dist/recharts/line.d.mts +2 -0
  193. package/dist/recharts/line.mjs +112 -0
  194. package/dist/recharts/marks.mjs +47 -18
  195. package/dist/recharts/parts.mjs +103 -0
  196. package/dist/recharts/table.mjs +71 -0
  197. package/dist/records-read.mjs +1 -1
  198. package/dist/registry/filter-bar.json +26 -0
  199. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  200. package/dist/store/apply.mjs +3 -1
  201. package/package.json +6 -2
  202. package/dist/react/FilterBar.mjs +0 -119
@@ -1,13 +1,14 @@
1
1
  import { useDashboards } from "../context.mjs";
2
+ import { useEscapeToLeave } from "./escape.mjs";
2
3
  import { CalcSection } from "./Calcs.mjs";
3
4
  import { FilterSection } from "./Filters.mjs";
4
5
  import { GroupSection } from "./Groups.mjs";
5
6
  import { Preview } from "./Preview.mjs";
6
- import { Chip, MeasureSection } from "./Sections.mjs";
7
+ import { Chip, KeptNote, MeasureSection, OpenSection } from "./Sections.mjs";
7
8
  import { TimeSection } from "./Time.mjs";
8
9
  import { useBuilder } from "./useBuilder.mjs";
9
10
  import { useEffect, useRef, useState } from "react";
10
- import { jsx, jsxs } from "react/jsx-runtime";
11
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
12
  // src/builder/WidgetBuilder.tsx
12
13
  /** The usual kinds first; any other renderer the host registered follows, by its kind. */
13
14
  const USUAL = [
@@ -97,51 +98,41 @@ function DashboardNote({ b, controls }) {
97
98
  /** Rare things, folded: the widget as JSON, to hand to an agent or keep in code. */
98
99
  function OptionsSection({ b }) {
99
100
  const { messages } = useDashboards();
100
- const [copied, setCopied] = useState(false);
101
+ const [copied, setCopied] = useState("no");
101
102
  const widget = b.widget;
102
103
  if (widget === void 0) return null;
104
+ const json = JSON.stringify(widget, null, 2);
103
105
  const copy = async () => {
104
- await navigator.clipboard.writeText(JSON.stringify(widget, null, 2));
105
- setCopied(true);
106
+ try {
107
+ await navigator.clipboard.writeText(json);
108
+ setCopied("yes");
109
+ } catch {
110
+ setCopied("refused");
111
+ }
106
112
  };
107
113
  return /* @__PURE__ */ jsxs("details", {
108
114
  className: "dd-builder-section",
109
- children: [/* @__PURE__ */ jsx("summary", { children: messages.options }), /* @__PURE__ */ jsx("button", {
110
- type: "button",
111
- className: "dd-button",
112
- onClick: () => void copy(),
113
- children: copied ? messages.copied : messages.copyJson
114
- })]
115
- });
116
- }
117
- /** Whether a key went to a field the person is typing in, where Escape is theirs. */
118
- const isTyping = (event) => event.target instanceof HTMLElement && event.target.closest("input, textarea, select, [contenteditable]") !== null;
119
- /**
120
- * Escape leaves an untouched builder as Cancel does, unless a picker already took it. With
121
- * unsaved work it never throws it away: outside a field it moves focus to Cancel, so leaving
122
- * is one more deliberate key; in a field it is the field's.
123
- */
124
- function useEscapeToLeave(widget, onCancel) {
125
- const start = useRef(widget);
126
- const latest = useRef({
127
- widget,
128
- onCancel
115
+ children: [
116
+ /* @__PURE__ */ jsx("summary", { children: messages.options }),
117
+ /* @__PURE__ */ jsx("button", {
118
+ type: "button",
119
+ className: "dd-button",
120
+ onClick: () => void copy(),
121
+ children: copied === "yes" ? messages.copied : messages.copyJson
122
+ }),
123
+ copied === "refused" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", {
124
+ className: "dd-builder-note",
125
+ role: "status",
126
+ children: messages.copyByHand
127
+ }), /* @__PURE__ */ jsx("textarea", {
128
+ className: "dd-builder-json",
129
+ readOnly: true,
130
+ value: json,
131
+ "aria-label": messages.copyJson,
132
+ ref: (el) => el?.select()
133
+ })] }) : null
134
+ ]
129
135
  });
130
- latest.current = {
131
- widget,
132
- onCancel
133
- };
134
- useEffect(() => {
135
- const onKey = (event) => {
136
- if (event.key !== "Escape" || event.defaultPrevented) return;
137
- if (latest.current.widget === start.current) latest.current.onCancel();
138
- else if (!isTyping(event)) document.querySelector("[data-builder-cancel]")?.focus();
139
- };
140
- globalThis.addEventListener("keydown", onKey);
141
- return () => {
142
- globalThis.removeEventListener("keydown", onKey);
143
- };
144
- }, []);
145
136
  }
146
137
  /**
147
138
  * The widget builder: one full page. Pick a measure by searching, then group, filter, add a
@@ -150,9 +141,13 @@ function useEscapeToLeave(widget, onCancel) {
150
141
  */
151
142
  function WidgetBuilder({ initial, backLabel, controls, error, ...actions }) {
152
143
  const b = useBuilder(initial);
153
- useEscapeToLeave(JSON.stringify(b.widget), actions.onCancel);
144
+ const { messages } = useDashboards();
145
+ const [open, setOpen] = useState(initial === void 0 ? messages.measure : void 0);
146
+ const root = useRef(null);
147
+ useEscapeToLeave(root, JSON.stringify(b.widget), actions.onCancel);
154
148
  return /* @__PURE__ */ jsxs("div", {
155
149
  className: "dd-builder",
150
+ ref: root,
156
151
  children: [
157
152
  backLabel === void 0 ? null : /* @__PURE__ */ jsxs("button", {
158
153
  type: "button",
@@ -173,14 +168,19 @@ function WidgetBuilder({ initial, backLabel, controls, error, ...actions }) {
173
168
  className: "dd-builder-body",
174
169
  children: [/* @__PURE__ */ jsxs("div", {
175
170
  className: "dd-builder-panel",
176
- children: [
177
- /* @__PURE__ */ jsx(MeasureSection, { b }),
178
- /* @__PURE__ */ jsx(TimeSection, { b }),
179
- /* @__PURE__ */ jsx(GroupSection, { b }),
180
- /* @__PURE__ */ jsx(FilterSection, { b }),
181
- /* @__PURE__ */ jsx(CalcSection, { b }),
182
- /* @__PURE__ */ jsx(OptionsSection, { b })
183
- ]
171
+ children: [/* @__PURE__ */ jsxs(OpenSection.Provider, {
172
+ value: {
173
+ open,
174
+ setOpen
175
+ },
176
+ children: [
177
+ /* @__PURE__ */ jsx(MeasureSection, { b }),
178
+ /* @__PURE__ */ jsx(TimeSection, { b }),
179
+ /* @__PURE__ */ jsx(GroupSection, { b }),
180
+ /* @__PURE__ */ jsx(FilterSection, { b }),
181
+ /* @__PURE__ */ jsx(CalcSection, { b })
182
+ ]
183
+ }), /* @__PURE__ */ jsx(OptionsSection, { b })]
184
184
  }), /* @__PURE__ */ jsxs("div", {
185
185
  className: "dd-builder-main",
186
186
  children: [
@@ -189,6 +189,7 @@ function WidgetBuilder({ initial, backLabel, controls, error, ...actions }) {
189
189
  b,
190
190
  controls
191
191
  }),
192
+ /* @__PURE__ */ jsx(KeptNote, { b }),
192
193
  /* @__PURE__ */ jsx(Preview, {
193
194
  b,
194
195
  data: true
@@ -16,4 +16,9 @@ export type BuilderState = {
16
16
  query: StoredQuery | undefined;
17
17
  /** Calcs the last change removed because they no longer fit, by name; cleared by the next. */
18
18
  removed?: readonly string[];
19
+ /**
20
+ * The widget it opened, when it edits one: what the builder does not edit (its display
21
+ * settings, other named queries, a plugin's own fields) is saved back as it was.
22
+ */
23
+ base?: Widget;
19
24
  };
@@ -1,12 +1,13 @@
1
1
  import { fittingTitle, sourceIn } from "./labels.mjs";
2
2
  // src/builder/base.ts
3
- const LAST_30_DAYS = {
4
- last: 30,
3
+ /** A new widget's range: the last 7 days, today included. */
4
+ const DEFAULT_RANGE = {
5
+ last: 7,
5
6
  unit: "day",
6
7
  includeCurrent: true
7
8
  };
8
9
  function emptyBuilder(widget) {
9
- const query = widget?.queries["main"];
10
+ const query = widget?.queries.main;
10
11
  if (widget === void 0 || query === void 0) return {
11
12
  title: "",
12
13
  titleSet: false,
@@ -19,7 +20,24 @@ function emptyBuilder(widget) {
19
20
  titleSet: true,
20
21
  kind: widget.kind,
21
22
  kindSet: true,
22
- query
23
+ query,
24
+ base: widget
25
+ };
26
+ }
27
+ /** The fields every widget has; anything else on one is a host's or a plugin's own. */
28
+ const WIDGET_FIELDS = /* @__PURE__ */ new Set([
29
+ "kind",
30
+ "title",
31
+ "queries",
32
+ "display"
33
+ ]);
34
+ /** What the builder keeps but does not edit: display settings, other queries, host fields. */
35
+ function keptAside(state) {
36
+ const base = state.base;
37
+ return {
38
+ display: base?.display !== void 0 && Object.keys(base.display).length > 0,
39
+ queries: Object.keys(base?.queries ?? {}).filter((name) => name !== "main"),
40
+ fields: Object.keys(base ?? {}).filter((name) => !WIDGET_FIELDS.has(name))
23
41
  };
24
42
  }
25
43
  const lastPart = (member) => member.split(".").at(-1) ?? member;
@@ -77,7 +95,7 @@ function defaultTime(meta, name) {
77
95
  const time = sourceIn(meta, name)?.dimensions.find((d) => d.type === "time");
78
96
  return time === void 0 ? void 0 : {
79
97
  dimension: time.id,
80
- range: LAST_30_DAYS
98
+ range: DEFAULT_RANGE
81
99
  };
82
100
  }
83
101
  function setKind(state, kind) {
@@ -99,13 +117,20 @@ function setTitle(meta, state, title) {
99
117
  titleSet: true
100
118
  };
101
119
  }
102
- /** The widget to save, or undefined until it has a measure. */
120
+ /**
121
+ * The widget to save, or undefined until it has a measure. An edited widget keeps everything the
122
+ * builder does not edit; only its kind, title and main query change.
123
+ */
103
124
  function widgetOf(state) {
104
125
  if (state.query === void 0) return void 0;
105
126
  return {
127
+ ...state.base,
106
128
  kind: state.kind,
107
129
  title: state.title || "Untitled widget",
108
- queries: { main: state.query }
130
+ queries: {
131
+ ...state.base?.queries,
132
+ main: state.query
133
+ }
109
134
  };
110
135
  }
111
- export { LAST_30_DAYS, cleared, defaultTime, emptyBuilder, freshId, lastPart, refersTo, setKind, setTitle, widgetOf, withQuery };
136
+ export { DEFAULT_RANGE, cleared, defaultTime, emptyBuilder, freshId, keptAside, lastPart, refersTo, setKind, setTitle, widgetOf, withQuery };
@@ -107,4 +107,18 @@ function removeCalc(meta, state, id) {
107
107
  calc
108
108
  });
109
109
  }
110
- export { addCalc, presetsFor, removeCalc, updateCalc };
110
+ /** Adds a calculation of the widget's own, from a formula the builder has already read. */
111
+ function addFormula(meta, state, calc) {
112
+ const query = state.query;
113
+ if (query === void 0) return state;
114
+ const next = {
115
+ id: freshId(query, calc.label),
116
+ formula: calc.formula,
117
+ label: calc.label
118
+ };
119
+ return withQuery(meta, state, {
120
+ ...query,
121
+ calc: [...query.calc ?? [], next]
122
+ });
123
+ }
124
+ export { addCalc, addFormula, presetsFor, removeCalc, updateCalc };
@@ -0,0 +1 @@
1
+ import { RefObject } from "react";
@@ -0,0 +1,62 @@
1
+ import { useEffect, useRef } from "react";
2
+ // src/builder/escape.ts
3
+ /** Whether a key went to a field the person is typing in, where Escape is theirs. */
4
+ const isTyping = (event) => event.target instanceof HTMLElement && event.target.closest("input, textarea, select, [contenteditable]") !== null;
5
+ /** The builder a person last worked in: an Escape sent to the page (no focus) is its. */
6
+ let active = null;
7
+ /** Whether this Escape is this builder's: sent inside it, or to the page while it is the active one. */
8
+ function owns(root, event) {
9
+ const at = event.target instanceof Element ? event.target : null;
10
+ if (at !== null && at !== document.body) return root.contains(at);
11
+ return active === root;
12
+ }
13
+ /** Marks a builder active when it mounts and whenever focus or a press goes into it. */
14
+ function useActive(ref) {
15
+ useEffect(() => {
16
+ const root = ref.current;
17
+ if (root === null) return;
18
+ active = root;
19
+ const mark = () => {
20
+ active = root;
21
+ };
22
+ root.addEventListener("focusin", mark);
23
+ root.addEventListener("pointerdown", mark);
24
+ return () => {
25
+ root.removeEventListener("focusin", mark);
26
+ root.removeEventListener("pointerdown", mark);
27
+ if (active === root) active = null;
28
+ };
29
+ }, [ref]);
30
+ }
31
+ /**
32
+ * Escape leaves an untouched builder as Cancel does, unless a picker already took it. With
33
+ * unsaved work it never throws it away: outside a field it moves focus to this builder's Cancel,
34
+ * so leaving is one more deliberate key; in a field it is the field's. With two builders on a
35
+ * page, each answers only the Escapes that are its own.
36
+ */
37
+ function useEscapeToLeave(ref, widget, onCancel) {
38
+ const start = useRef(widget);
39
+ const latest = useRef({
40
+ widget,
41
+ onCancel
42
+ });
43
+ latest.current = {
44
+ widget,
45
+ onCancel
46
+ };
47
+ useActive(ref);
48
+ useEffect(() => {
49
+ const onKey = (event) => {
50
+ const root = ref.current;
51
+ if (event.key !== "Escape" || event.defaultPrevented || root === null) return;
52
+ if (!owns(root, event)) return;
53
+ if (latest.current.widget === start.current) latest.current.onCancel();
54
+ else if (!isTyping(event)) root.querySelector("[data-builder-cancel]")?.focus();
55
+ };
56
+ globalThis.addEventListener("keydown", onKey);
57
+ return () => {
58
+ globalThis.removeEventListener("keydown", onKey);
59
+ };
60
+ }, [ref]);
61
+ }
62
+ export { useEscapeToLeave };
@@ -0,0 +1,9 @@
1
+ import { Op, Primitive } from "derive-dashboards/core";
2
+ /**
3
+ * A widget's filter as the builder edits it: rows matching all (or any) of the top's children.
4
+ * A child is a condition, a group of conditions matching all, any or none of them, or a part the
5
+ * builder cannot edit (a viewer value, a variable, deeper nesting), which it keeps as written.
6
+ */
7
+ type Mode = "all" | "any";
8
+ export type GroupMode = Mode | "none";
9
+ export {};
@@ -0,0 +1,186 @@
1
+ // src/builder/filter-tree.ts
2
+ const TOP = "filters";
3
+ const conditionOf = (node) => "values" in node ? {
4
+ id: node.id,
5
+ member: node.member,
6
+ op: node.op,
7
+ values: node.values
8
+ } : void 0;
9
+ /** Conditions only, or undefined when any part is not one. */
10
+ function conditionsOf(nodes) {
11
+ const out = nodes.map((n) => conditionOf(n));
12
+ return out.every((c) => c !== void 0) ? out : void 0;
13
+ }
14
+ /** A group's conditions and how it matches them, or undefined when it is not one the builder edits. */
15
+ function groupParts(node) {
16
+ if ("all" in node) return {
17
+ mode: "all",
18
+ list: node.all
19
+ };
20
+ if ("any" in node) return {
21
+ mode: "any",
22
+ list: node.any
23
+ };
24
+ if ("not" in node && "any" in node.not) return {
25
+ mode: "none",
26
+ list: node.not.any
27
+ };
28
+ }
29
+ function childOf(node) {
30
+ const leaf = conditionOf(node);
31
+ if (leaf !== void 0) return {
32
+ kind: "condition",
33
+ node: leaf
34
+ };
35
+ const parts = groupParts(node);
36
+ const conditions = parts === void 0 ? void 0 : conditionsOf(parts.list);
37
+ if (parts === void 0 || conditions === void 0 || conditions.length === 0) return {
38
+ kind: "kept",
39
+ node
40
+ };
41
+ return {
42
+ kind: "group",
43
+ id: node.id,
44
+ mode: parts.mode,
45
+ conditions
46
+ };
47
+ }
48
+ /** The tree of a stored filter: its top `all` or `any`, or the one node under an implied all. */
49
+ function treeOf(filter) {
50
+ if (filter === void 0) return {
51
+ mode: "all",
52
+ children: []
53
+ };
54
+ if ("all" in filter && filter.id === TOP) return {
55
+ mode: "all",
56
+ children: filter.all.map((n) => childOf(n))
57
+ };
58
+ if ("any" in filter && filter.id === TOP) return {
59
+ mode: "any",
60
+ children: filter.any.map((n) => childOf(n))
61
+ };
62
+ return {
63
+ mode: "all",
64
+ children: [childOf(filter)]
65
+ };
66
+ }
67
+ const leafNode = (c) => ({
68
+ id: c.id,
69
+ member: c.member,
70
+ op: c.op,
71
+ values: [...c.values]
72
+ });
73
+ function nodeOf(child) {
74
+ if (child.kind === "condition") return leafNode(child.node);
75
+ if (child.kind === "kept") return child.node;
76
+ const leaves = child.conditions.map(leafNode);
77
+ if (child.mode === "none") return {
78
+ id: child.id,
79
+ not: {
80
+ id: `${child.id}-any`,
81
+ any: leaves
82
+ }
83
+ };
84
+ return child.mode === "all" ? {
85
+ id: child.id,
86
+ all: leaves
87
+ } : {
88
+ id: child.id,
89
+ any: leaves
90
+ };
91
+ }
92
+ /** The stored filter of a tree; none when it has no children. Empty groups are dropped. */
93
+ function storedOf(tree) {
94
+ const children = tree.children.filter((c) => c.kind !== "group" || c.conditions.length > 0);
95
+ if (children.length === 0) return void 0;
96
+ const nodes = children.map((c) => nodeOf(c));
97
+ return tree.mode === "all" ? {
98
+ id: TOP,
99
+ all: nodes
100
+ } : {
101
+ id: TOP,
102
+ any: nodes
103
+ };
104
+ }
105
+ function ids(node, out) {
106
+ out.add(node.id);
107
+ const kids = "all" in node ? node.all : "any" in node ? node.any : "not" in node ? [node.not] : [];
108
+ for (const k of kids) ids(k, out);
109
+ return out;
110
+ }
111
+ /** An id no node of the filter has: f1, f2, … (or g1, … for a group). */
112
+ function freeId(filter, prefix) {
113
+ const taken = filter === void 0 ? /* @__PURE__ */ new Set() : ids(filter, /* @__PURE__ */ new Set());
114
+ let n = 1;
115
+ while (taken.has(`${prefix}${String(n)}`) || taken.has(`${prefix}${String(n)}-any`)) n += 1;
116
+ return `${prefix}${String(n)}`;
117
+ }
118
+ /** Adds a condition at the top, to a group, or (with `group: "new"`) as a new group of one. */
119
+ function addCondition(filter, condition, group) {
120
+ const tree = treeOf(filter);
121
+ const node = {
122
+ ...condition,
123
+ id: freeId(filter, "f")
124
+ };
125
+ if (group === "new") {
126
+ const id = freeId(filter, "g");
127
+ return storedOf({
128
+ ...tree,
129
+ children: [...tree.children, {
130
+ kind: "group",
131
+ id,
132
+ mode: "any",
133
+ conditions: [node]
134
+ }]
135
+ });
136
+ }
137
+ if (group === void 0) return storedOf({
138
+ ...tree,
139
+ children: [...tree.children, {
140
+ kind: "condition",
141
+ node
142
+ }]
143
+ });
144
+ const children = tree.children.map((c) => c.kind === "group" && c.id === group ? {
145
+ ...c,
146
+ conditions: [...c.conditions, node]
147
+ } : c);
148
+ return storedOf({
149
+ ...tree,
150
+ children
151
+ });
152
+ }
153
+ /** Removes a condition, a group or a kept part, wherever it is. */
154
+ function removeNode(filter, id) {
155
+ const tree = treeOf(filter);
156
+ const children = tree.children.flatMap((c) => {
157
+ if (c.kind === "condition") return c.node.id === id ? [] : [c];
158
+ if (c.kind === "kept") return c.node.id === id ? [] : [c];
159
+ if (c.id === id) return [];
160
+ return [{
161
+ ...c,
162
+ conditions: c.conditions.filter((k) => k.id !== id)
163
+ }];
164
+ });
165
+ return storedOf({
166
+ ...tree,
167
+ children
168
+ });
169
+ }
170
+ /** Sets how the top matches its children, or how one group matches its conditions. */
171
+ function setMode(filter, mode, group) {
172
+ const tree = treeOf(filter);
173
+ if (group === void 0) return mode === "none" ? filter : storedOf({
174
+ ...tree,
175
+ mode
176
+ });
177
+ const children = tree.children.map((c) => c.kind === "group" && c.id === group ? {
178
+ ...c,
179
+ mode
180
+ } : c);
181
+ return storedOf({
182
+ ...tree,
183
+ children
184
+ });
185
+ }
186
+ export { addCondition, removeNode, setMode, storedOf, treeOf };
@@ -0,0 +1,18 @@
1
+ import "derive-dashboards/core";
2
+ /** What went wrong, and where: `at` is the 1-based character it was found at. */
3
+ export type FormulaProblem = {
4
+ kind: "empty";
5
+ } | {
6
+ kind: "expected";
7
+ at: number;
8
+ } | {
9
+ kind: "unknown";
10
+ at: number;
11
+ text: string;
12
+ } | {
13
+ kind: "unclosed";
14
+ at: number;
15
+ } | {
16
+ kind: "unopened";
17
+ at: number;
18
+ };
@@ -0,0 +1,136 @@
1
+ // src/builder/formula-parse.ts
2
+ /** An error that carries the problem, so the reader can stop where it found it. */
3
+ const fail = (problem) => Object.assign(new Error(problem.kind), { problem });
4
+ const isFailed = (error) => error instanceof Error && "problem" in error;
5
+ /** One pass over a formula's text: `at` is where it has read to. */
6
+ var Reader = class {
7
+ text;
8
+ names;
9
+ at = 0;
10
+ uses = /* @__PURE__ */ new Set();
11
+ constructor(text, names) {
12
+ this.text = text;
13
+ this.names = names;
14
+ }
15
+ peek() {
16
+ while (this.text[this.at] === " ") this.at += 1;
17
+ return this.text[this.at];
18
+ }
19
+ sum() {
20
+ return this.chain(["+", "-"], () => this.product());
21
+ }
22
+ product() {
23
+ return this.chain(["*", "/"], () => this.factor());
24
+ }
25
+ chain(ops, next) {
26
+ let left = next();
27
+ for (let op = this.opAt(ops); op !== void 0; op = this.opAt(ops)) {
28
+ this.at += 1;
29
+ left = {
30
+ op,
31
+ args: [left, next()]
32
+ };
33
+ }
34
+ return left;
35
+ }
36
+ /** The operator next in the text, when it is one of `ops`. */
37
+ opAt(ops) {
38
+ const c = this.peek();
39
+ return ops.find((o) => o === c);
40
+ }
41
+ factor() {
42
+ const c = this.peek();
43
+ const at = this.at + 1;
44
+ if (c === void 0) throw fail({
45
+ kind: "expected",
46
+ at
47
+ });
48
+ if (c === "-") {
49
+ this.at += 1;
50
+ return {
51
+ op: "-",
52
+ args: [{ lit: 0 }, this.factor()]
53
+ };
54
+ }
55
+ if (c === "(") return this.bracketed(at);
56
+ if (this.text.slice(this.at, this.at + 4).toLowerCase() === "abs(") {
57
+ this.at += 3;
58
+ return {
59
+ op: "abs",
60
+ args: [this.bracketed(this.at + 1)]
61
+ };
62
+ }
63
+ return this.atom(c, at);
64
+ }
65
+ /** A number or a name; anything else is a problem at `at`. */
66
+ atom(c, at) {
67
+ const rest = this.text.slice(this.at);
68
+ const number = /^\d+(\.\d+)?/u.exec(rest);
69
+ if (number !== null) {
70
+ this.at += number[0].length;
71
+ return { lit: Number(number[0]) };
72
+ }
73
+ const hit = this.names.find((n) => rest.toLowerCase().startsWith(n.label.toLowerCase()));
74
+ if (hit !== void 0) {
75
+ this.at += hit.label.length;
76
+ this.uses.add(hit.id);
77
+ return { ref: hit.id };
78
+ }
79
+ if (c === ")") throw fail({
80
+ kind: "unopened",
81
+ at
82
+ });
83
+ const word = /^[^+\-*/()]+/u.exec(rest)?.[0].trim() ?? c;
84
+ throw fail({
85
+ kind: "unknown",
86
+ at,
87
+ text: word
88
+ });
89
+ }
90
+ bracketed(at) {
91
+ this.at += 1;
92
+ const inside = this.sum();
93
+ if (this.peek() !== ")") throw fail({
94
+ kind: "unclosed",
95
+ at
96
+ });
97
+ this.at += 1;
98
+ return inside;
99
+ }
100
+ };
101
+ /**
102
+ * Reads a formula as people write it: the widget's measure and calc names, numbers, + - * /,
103
+ * brackets and abs(…). Names match without case, the longest first, so "Hours logged" wins over
104
+ * "Hours". Precedence is the usual one; a leading minus is 0 minus the value.
105
+ */
106
+ function parseFormula(text, names) {
107
+ if (text.trim() === "") return {
108
+ ok: false,
109
+ problem: { kind: "empty" }
110
+ };
111
+ const r = new Reader(text, names.toSorted((a, b) => b.label.length - a.label.length));
112
+ try {
113
+ const formula = r.sum();
114
+ const next = r.peek();
115
+ if (next === ")") throw fail({
116
+ kind: "unopened",
117
+ at: r.at + 1
118
+ });
119
+ if (next !== void 0) throw fail({
120
+ kind: "expected",
121
+ at: r.at + 1
122
+ });
123
+ return {
124
+ ok: true,
125
+ formula,
126
+ uses: [...r.uses]
127
+ };
128
+ } catch (error) {
129
+ if (isFailed(error)) return {
130
+ ok: false,
131
+ problem: error.problem
132
+ };
133
+ throw error;
134
+ }
135
+ }
136
+ export { parseFormula };
@@ -1 +1 @@
1
- import { StoredQuery } from "derive-dashboards/core";
1
+ import { MetaResponse, StoredQuery } from "derive-dashboards/core";
@@ -1,6 +1,7 @@
1
1
  import "./base.mjs";
2
+ import "./filter-tree.mjs";
2
3
  import "./labels.mjs";
3
- import { DateRange, Grain, Primitive, StoredQuery } from "derive-dashboards/core";
4
+ import { DateRange, Grain, Op, Primitive, StoredQuery } from "derive-dashboards/core";
4
5
  type Time = NonNullable<StoredQuery["time"]>;
5
6
  /** A change to the time part. A grain of "total" is one total; a compare of "none" drops it. */
6
7
  export type TimeChange = {