@mdbase-dev/ui 0.2.0 → 0.2.2

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 (70) hide show
  1. package/README.md +119 -0
  2. package/css/controls.css +37 -0
  3. package/css/date-picker.css +176 -0
  4. package/css/filter-builder.css +336 -0
  5. package/css/properties.css +398 -0
  6. package/dist/AnchoredPopover.d.ts +20 -0
  7. package/dist/AnchoredPopover.js +100 -0
  8. package/dist/Combo.d.ts +41 -0
  9. package/dist/Combo.js +82 -0
  10. package/dist/DatePicker.d.ts +69 -0
  11. package/dist/DatePicker.js +317 -0
  12. package/dist/Menu.d.ts +3 -1
  13. package/dist/Menu.js +3 -2
  14. package/dist/QuickCreate.js +1 -16
  15. package/dist/collections/CollectionGate.js +20 -13
  16. package/dist/collections/use-collection-ui.d.ts +14 -2
  17. package/dist/collections/use-collection-ui.js +13 -0
  18. package/dist/date-picker-model.d.ts +31 -0
  19. package/dist/date-picker-model.js +97 -0
  20. package/dist/filter-builder/AddFilter.d.ts +13 -0
  21. package/dist/filter-builder/AddFilter.js +295 -0
  22. package/dist/filter-builder/FilterBuilder.d.ts +36 -0
  23. package/dist/filter-builder/FilterBuilder.js +225 -0
  24. package/dist/filter-builder/FilterPill.d.ts +17 -0
  25. package/dist/filter-builder/FilterPill.js +494 -0
  26. package/dist/filter-builder/context.d.ts +40 -0
  27. package/dist/filter-builder/context.js +67 -0
  28. package/dist/filter-builder/editors.d.ts +31 -0
  29. package/dist/filter-builder/editors.js +294 -0
  30. package/dist/filter-builder/filter-ast.d.ts +13 -0
  31. package/dist/filter-builder/filter-ast.js +382 -0
  32. package/dist/filter-builder/labels.d.ts +99 -0
  33. package/dist/filter-builder/labels.js +555 -0
  34. package/dist/filter-builder/menu.d.ts +21 -0
  35. package/dist/filter-builder/menu.js +60 -0
  36. package/dist/filter-builder/operators.d.ts +30 -0
  37. package/dist/filter-builder/operators.js +192 -0
  38. package/dist/filter-builder/tree.d.ts +12 -0
  39. package/dist/filter-builder/tree.js +61 -0
  40. package/dist/filter-builder/types.d.ts +69 -0
  41. package/dist/filter-builder/types.js +48 -0
  42. package/dist/filter-builder.d.ts +13 -0
  43. package/dist/filter-builder.js +10 -0
  44. package/dist/glyphs.d.ts +32 -0
  45. package/dist/glyphs.js +143 -0
  46. package/dist/locales/de/messages.json +1 -1
  47. package/dist/locales/en/messages.json +1 -1
  48. package/dist/locales/es/messages.json +1 -1
  49. package/dist/locales/fr/messages.json +1 -1
  50. package/dist/locales/it/messages.json +1 -1
  51. package/dist/locales/ja/messages.json +1 -1
  52. package/dist/locales/ko/messages.json +1 -1
  53. package/dist/locales/pt/messages.json +1 -1
  54. package/dist/locales/ru/messages.json +1 -1
  55. package/dist/locales/zh/messages.json +1 -1
  56. package/dist/popover.d.ts +5 -0
  57. package/dist/popover.js +15 -0
  58. package/dist/properties/PropertyList.d.ts +31 -0
  59. package/dist/properties/PropertyList.js +233 -0
  60. package/dist/properties/PropertyValue.d.ts +42 -0
  61. package/dist/properties/PropertyValue.js +304 -0
  62. package/dist/properties/fields.d.ts +20 -0
  63. package/dist/properties/fields.js +81 -0
  64. package/dist/properties/labels.d.ts +29 -0
  65. package/dist/properties/labels.js +127 -0
  66. package/dist/properties/model.d.ts +52 -0
  67. package/dist/properties/model.js +195 -0
  68. package/dist/properties.d.ts +13 -0
  69. package/dist/properties.js +9 -0
  70. package/package.json +25 -2
@@ -0,0 +1,97 @@
1
+ export const DAY = 86_400_000;
2
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/u;
3
+ /** A calendar day as a number of days, free of time zones: midnight UTC of that day. */
4
+ export const stamp = (year, month, day) => Date.UTC(year, month, day);
5
+ /** `2026-11-28` as a day, or null when it is not a real date. */
6
+ export function parseDay(text) {
7
+ const match = iso.exec(text.trim());
8
+ if (!match) return null;
9
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
10
+ const at = stamp(year, month - 1, day);
11
+ const date = new Date(at);
12
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? at : null;
13
+ }
14
+ export function dayText(at) {
15
+ return new Date(at).toISOString().slice(0, 10);
16
+ }
17
+ /** Today, where the person is. */
18
+ export function todayStamp(now = new Date()) {
19
+ return stamp(now.getFullYear(), now.getMonth(), now.getDate());
20
+ }
21
+ export const weekdayNames = (locale, width) => {
22
+ const format = new Intl.DateTimeFormat(locale, {
23
+ weekday: width,
24
+ timeZone: "UTC"
25
+ });
26
+ // 2024-01-07 was a Sunday.
27
+ return Array.from({
28
+ length: 7
29
+ }, (_unused, index) => format.format(stamp(2024, 0, 7 + index)));
30
+ };
31
+ /** Text as it is compared: a typed apostrophe is the one a catalogue writes (`aujourd’hui`). */
32
+ const plain = text => text.trim().toLowerCase().replaceAll("’", "'");
33
+ /**
34
+ * What someone typed as a day: a date as it is stored (`2026-11-28`), one of the day's names
35
+ * (today, tomorrow, yesterday), a weekday (the next one), or a number of days or weeks from
36
+ * today (`+3`, `-1`, `2w`). Null when it is none of those.
37
+ */
38
+ export function readDay(text, words, now = new Date(), locale) {
39
+ const typed = plain(text);
40
+ if (!typed) return null;
41
+ const exact = parseDay(typed);
42
+ if (exact !== null) return exact;
43
+ const today = todayStamp(now);
44
+ const named = [[words.today, 0], [words.tomorrow, 1], [words.yesterday, -1]];
45
+ for (const [word, offset] of named) {
46
+ if (plain(word) === typed) return today + offset * DAY;
47
+ }
48
+ const relative = /^([+-]?)(\d{1,4})\s*([dw]?)$/u.exec(typed);
49
+ if (relative && (relative[1] || relative[3])) {
50
+ const days = Number(relative[2]) * (relative[3] === "w" ? 7 : 1);
51
+ return today + (relative[1] === "-" ? -days : days) * DAY;
52
+ }
53
+ if (typed.length >= 2) {
54
+ const long = weekdayNames(locale, "long").map(name => name.toLowerCase());
55
+ const index = long.findIndex(name => name.startsWith(typed));
56
+ if (index >= 0) {
57
+ const ahead = (index - new Date(today).getUTCDay() + 7) % 7 || 7;
58
+ return today + ahead * DAY;
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+ /** A day as people read it: `28 Nov 2026`, without the year when it is this one and `short` is set. */
64
+ export function formatDay(value, options = {}) {
65
+ const at = parseDay(value);
66
+ if (at === null) return value;
67
+ const sameYear = new Date(at).getUTCFullYear() === (options.now ?? new Date()).getFullYear();
68
+ return new Intl.DateTimeFormat(options.locale, {
69
+ day: "numeric",
70
+ month: "short",
71
+ ...(options.short && sameYear ? {} : {
72
+ year: "numeric"
73
+ }),
74
+ timeZone: "UTC"
75
+ }).format(at);
76
+ }
77
+ /** The first day of the week where the person is: 0 for Sunday. Monday where the browser cannot say. */
78
+ export function weekStart(locale) {
79
+ try {
80
+ const info = new Intl.Locale(locale ?? navigator.language);
81
+ const first = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay;
82
+ return typeof first === "number" ? first % 7 : 1;
83
+ } catch {
84
+ return 1;
85
+ }
86
+ }
87
+ /** The six weeks a month is shown in, starting on the week's first day. */
88
+ export function monthGrid(year, month, firstDay) {
89
+ const first = stamp(year, month, 1);
90
+ const lead = (new Date(first).getUTCDay() - firstDay + 7) % 7;
91
+ const start = first - lead * DAY;
92
+ return Array.from({
93
+ length: 6
94
+ }, (_week, week) => Array.from({
95
+ length: 7
96
+ }, (_day, day) => start + (week * 7 + day) * DAY));
97
+ }
@@ -0,0 +1,13 @@
1
+ import { type JSX } from "react";
2
+ import { type Tier } from "./context.js";
3
+ export interface AddFilterProps {
4
+ tier: Tier;
5
+ /** The group new filters join; null for the root of the chosen scope. */
6
+ groupId: string | null;
7
+ onClose: (restoreFocus: boolean) => void;
8
+ }
9
+ /**
10
+ * What `Filter` opens: a list of fields to search, then (in place) the value for the field
11
+ * picked. A checked value applies at once; a typed one on Enter or its button.
12
+ */
13
+ export declare function AddFilter({ tier, groupId, onClose }: AddFilterProps): JSX.Element;
@@ -0,0 +1,295 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Fragment, useId, useLayoutEffect, useRef, useState } from "react";
3
+ import { Glyph } from "../glyphs.js";
4
+ import { Segmented } from "../Segmented.js";
5
+ import { Select } from "../Select.js";
6
+ import { isComplete } from "./filter-ast.js";
7
+ import { fieldOf, FX, KIND_ICONS, useBar } from "./context.js";
8
+ import { ExprEditor, ValuePanel } from "./editors.js";
9
+ import { changeOperator, defaultOperator, labelOf, operatorMenu, UNARY } from "./operators.js";
10
+ import { findNode, newId, replaceNode, upsertChild } from "./tree.js";
11
+ const keepFocus = event => event.preventDefault();
12
+ /**
13
+ * What `Filter` opens: a list of fields to search, then (in place) the value for the field
14
+ * picked. A checked value applies at once; a typed one on Enter or its button.
15
+ */
16
+ export function AddFilter({
17
+ tier,
18
+ groupId,
19
+ onClose
20
+ }) {
21
+ const bar = useBar();
22
+ const {
23
+ labels
24
+ } = bar;
25
+ const ids = useId();
26
+ const [scope, setScope] = useState(tier);
27
+ const [state, setState] = useState({
28
+ step: "pick"
29
+ });
30
+ const [search, setSearch] = useState("");
31
+ const [active, setActive] = useState(0);
32
+ const target = groupId ? tier : scope;
33
+ const step = useRef(null);
34
+ // Each step puts the keyboard where the next thing is typed or chosen: after a field is
35
+ // picked, in its value; after the comparison changes, in the value again.
36
+ const stage = state.step === "rule" ? `rule:${state.rule.field}:${state.rule.op}` : state.step;
37
+ const first = useRef(true);
38
+ useLayoutEffect(() => {
39
+ if (first.current) {
40
+ // The popover places the focus when it opens.
41
+ first.current = false;
42
+ return;
43
+ }
44
+ step.current?.querySelector("[data-autofocus]")?.focus({
45
+ preventScroll: true
46
+ });
47
+ }, [stage]);
48
+ const put = node => bar.edit(target, tree => upsertChild(tree, groupId ?? tree.id, node));
49
+ const drop = id => bar.edit(target, tree => replaceNode(tree, id, null));
50
+ const apply = (rule, inserted) => {
51
+ const complete = isComplete(rule);
52
+ if (complete) put(rule);else if (inserted) drop(rule.id);
53
+ setState({
54
+ step: "rule",
55
+ rule,
56
+ inserted: complete
57
+ });
58
+ };
59
+ if (state.step === "rule") {
60
+ const {
61
+ rule,
62
+ inserted
63
+ } = state;
64
+ const field = fieldOf(bar.fields, rule);
65
+ const pickOp = op => {
66
+ const next = changeOperator(rule, field, op);
67
+ apply(next, inserted);
68
+ if (UNARY.has(op)) onClose(true);
69
+ };
70
+ return _jsxs("div", {
71
+ className: "mdbase-filter-step",
72
+ ref: step,
73
+ children: [_jsxs("div", {
74
+ className: "mdbase-filter-step-head",
75
+ children: [_jsx("button", {
76
+ type: "button",
77
+ className: "mdbase-filter-icon-button",
78
+ "aria-label": labels.back,
79
+ onClick: () => {
80
+ if (inserted) drop(rule.id);
81
+ setState({
82
+ step: "pick"
83
+ });
84
+ },
85
+ children: _jsx(Glyph, {
86
+ name: "left"
87
+ })
88
+ }), _jsxs("span", {
89
+ className: "mdbase-filter-step-field",
90
+ title: labelOf(field),
91
+ children: [KIND_ICONS[field.kind], _jsx("span", {
92
+ children: labelOf(field)
93
+ })]
94
+ }), _jsx(Select, {
95
+ className: "is-compact mdbase-filter-operator",
96
+ "aria-label": labels.operator,
97
+ value: rule.op,
98
+ options: operatorMenu(labels, field.kind, rule).map(item => ({
99
+ value: item.op,
100
+ label: item.label
101
+ })),
102
+ onChange: op => pickOp(op)
103
+ })]
104
+ }), !UNARY.has(rule.op) && _jsx(ValuePanel, {
105
+ rule: rule,
106
+ field: field,
107
+ contextVars: bar.contextVars,
108
+ commitOnBlur: false,
109
+ action: labels.addFilter,
110
+ onChange: next => apply(next, inserted),
111
+ onDone: () => onClose(true)
112
+ })]
113
+ });
114
+ }
115
+ if (state.step === "expr") {
116
+ const {
117
+ id
118
+ } = state;
119
+ return _jsxs("div", {
120
+ className: "mdbase-filter-step",
121
+ ref: step,
122
+ children: [_jsxs("div", {
123
+ className: "mdbase-filter-step-head",
124
+ children: [_jsx("button", {
125
+ type: "button",
126
+ className: "mdbase-filter-icon-button",
127
+ "aria-label": labels.back,
128
+ onClick: () => setState({
129
+ step: "pick"
130
+ }),
131
+ children: _jsx(Glyph, {
132
+ name: "left"
133
+ })
134
+ }), _jsxs("span", {
135
+ className: "mdbase-filter-step-field",
136
+ children: [FX, _jsx("span", {
137
+ children: labels.customExpression
138
+ })]
139
+ })]
140
+ }), _jsx(ExprEditor, {
141
+ expression: "",
142
+ id: id,
143
+ commitOnBlur: false,
144
+ onApply: expression => {
145
+ put({
146
+ kind: "expr",
147
+ id,
148
+ expression
149
+ });
150
+ onClose(true);
151
+ },
152
+ onConvert: rule => {
153
+ put(rule);
154
+ onClose(true);
155
+ }
156
+ })]
157
+ });
158
+ }
159
+ const needle = search.trim().toLowerCase();
160
+ const fields = bar.fields.filter(field => !bar.locked.has(field.key) && (!needle || labelOf(field).toLowerCase().includes(needle) || field.key.toLowerCase().includes(needle)));
161
+ const startRule = field => setState({
162
+ step: "rule",
163
+ inserted: false,
164
+ rule: {
165
+ kind: "rule",
166
+ id: newId(),
167
+ field: field.key,
168
+ op: defaultOperator(field.kind)
169
+ }
170
+ });
171
+ const parent = groupId ? findNode(bar.trees[target], groupId) : null;
172
+ const options = [...fields.map(field => ({
173
+ id: `${ids}f-${field.key}`,
174
+ label: labelOf(field),
175
+ icon: KIND_ICONS[field.kind],
176
+ pick: () => startRule(field)
177
+ })), {
178
+ id: `${ids}expr`,
179
+ label: labels.customExpression,
180
+ icon: FX,
181
+ hint: "CEL",
182
+ pick: () => setState({
183
+ step: "expr",
184
+ id: newId()
185
+ })
186
+ }, {
187
+ id: `${ids}group`,
188
+ label: labels.filterGroup,
189
+ icon: _jsx(Glyph, {
190
+ name: "group"
191
+ }),
192
+ hint: labels.filterGroupHint,
193
+ pick: () => {
194
+ const group = {
195
+ kind: "group",
196
+ id: newId(),
197
+ combinator: parent?.kind === "group" && parent.combinator === "any" ? "all" : "any",
198
+ children: []
199
+ };
200
+ put(group);
201
+ bar.setOpenKey(`${target}:${group.id}:add`);
202
+ }
203
+ }];
204
+ const current = Math.min(active, options.length - 1);
205
+ // The list always ends with the expression and group rows, so it is never empty.
206
+ const option = options[current];
207
+ return _jsxs("div", {
208
+ className: "mdbase-filter-step",
209
+ ref: step,
210
+ children: [_jsxs("div", {
211
+ className: "mdbase-filter-search",
212
+ children: [_jsx(Glyph, {
213
+ name: "search"
214
+ }), _jsx("input", {
215
+ "data-autofocus": true,
216
+ role: "combobox",
217
+ "aria-label": labels.filterByField,
218
+ "aria-expanded": true,
219
+ "aria-controls": `${ids}list`,
220
+ "aria-autocomplete": "list",
221
+ "aria-activedescendant": option.id,
222
+ placeholder: labels.filterByPlaceholder,
223
+ spellCheck: false,
224
+ autoComplete: "off",
225
+ value: search,
226
+ onChange: event => {
227
+ setSearch(event.target.value);
228
+ setActive(0);
229
+ },
230
+ onKeyDown: event => {
231
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
232
+ event.preventDefault();
233
+ setActive((current + (event.key === "ArrowDown" ? 1 : -1) + options.length) % options.length);
234
+ }
235
+ if (event.key === "Enter") {
236
+ event.preventDefault();
237
+ option.pick();
238
+ }
239
+ }
240
+ })]
241
+ }), _jsx("div", {
242
+ className: "mdbase-filter-options",
243
+ role: "listbox",
244
+ id: `${ids}list`,
245
+ "aria-label": labels.fields,
246
+ children: options.map((option, index) => _jsxs(Fragment, {
247
+ children: [index === fields.length && _jsxs(_Fragment, {
248
+ children: [!fields.length && _jsx("p", {
249
+ className: "mdbase-filter-hint mdbase-filter-empty",
250
+ children: labels.noMatchingFields
251
+ }), _jsx("div", {
252
+ className: "mdbase-menu-divider",
253
+ role: "separator"
254
+ })]
255
+ }), _jsxs("div", {
256
+ id: option.id,
257
+ role: "option",
258
+ "aria-selected": index === current,
259
+ className: "mdbase-filter-option",
260
+ onMouseDown: keepFocus,
261
+ onMouseMove: () => setActive(index),
262
+ onClick: option.pick,
263
+ children: [option.icon, _jsx("span", {
264
+ className: "mdbase-filter-option-label",
265
+ children: option.label
266
+ }), option.hint && _jsx("span", {
267
+ className: "mdbase-filter-hint",
268
+ children: option.hint
269
+ })]
270
+ })]
271
+ }, option.id))
272
+ }), !groupId && bar.tiered && _jsxs("div", {
273
+ className: "mdbase-filter-scope",
274
+ children: [_jsx("span", {
275
+ children: labels.scope
276
+ }), _jsx(Segmented, {
277
+ "aria-label": labels.scope,
278
+ value: scope,
279
+ options: [{
280
+ value: "view",
281
+ label: labels.thisView
282
+ }, {
283
+ value: "shared",
284
+ label: labels.shared
285
+ }],
286
+ onChange: next => {
287
+ setScope(next);
288
+ step.current?.querySelector("[data-autofocus]")?.focus({
289
+ preventScroll: true
290
+ });
291
+ }
292
+ })]
293
+ })]
294
+ });
295
+ }
@@ -0,0 +1,36 @@
1
+ import { type JSX } from "react";
2
+ import { type FilterLabels } from "./labels.js";
3
+ import type { FilterContextVar, FilterFieldSpec } from "./types.js";
4
+ export interface FilterBuilderProps {
5
+ /** The `where` expression being edited. The builder is controlled: edits go through `onChange`. */
6
+ query: string;
7
+ fields: FilterFieldSpec[];
8
+ /** `this.*` bindings offered as values. */
9
+ contextVars?: FilterContextVar[] | undefined;
10
+ /** Why the current query failed, shown under the bar. */
11
+ error?: string | undefined;
12
+ /** Fields the host owns: their rules stay editable but cannot be removed, and they are not offered for new rules. */
13
+ lockedFields?: string[] | undefined;
14
+ onChange: (nextQuery: string) => void;
15
+ /**
16
+ * A second tier applied with `query`, such as the `query.where` an
17
+ * `mdbase.view` file shares across its views. Its filters sit on the bar
18
+ * marked "Shared" when `onSharedChange` is given, and filters can move
19
+ * between the tiers.
20
+ */
21
+ sharedQuery?: string | undefined;
22
+ onSharedChange?: ((nextQuery: string) => void) | undefined;
23
+ /** The bar's accessible name; defaults to `labels.filters`. */
24
+ ariaLabel?: string | undefined;
25
+ /** Open the list of fields as soon as the bar appears, when the bar was asked for in order to add a filter. */
26
+ defaultOpen?: boolean | undefined;
27
+ /** Text to show in place of the shared catalogue's, for what a host words its own way. */
28
+ labels?: Partial<FilterLabels> | undefined;
29
+ }
30
+ /**
31
+ * A filter bar for the CEL `where` expression of an `mdbase.view`. Each filter is a pill
32
+ * (`field | operator | value | ×`) whose parts are changed where they stand, custom CEL is an
33
+ * `fx` pill, nested groups are clusters of pills, and `Filter` opens the list of fields to add
34
+ * one from.
35
+ */
36
+ export declare function FilterBuilder({ query, fields, contextVars, error, lockedFields, onChange, sharedQuery, onSharedChange, ariaLabel, defaultOpen, labels: labelOverrides }: FilterBuilderProps): JSX.Element;
@@ -0,0 +1,225 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { AnchoredPopover } from "../AnchoredPopover.js";
4
+ import { Glyph } from "../glyphs.js";
5
+ import { useLocaleRevision } from "../i18n.js";
6
+ import { AddFilter } from "./AddFilter.js";
7
+ import { Bar, combinatorHint, openPart } from "./context.js";
8
+ import { compileWhere, countActive, parseWhere } from "./filter-ast.js";
9
+ import { FilterNodeView, GroupCluster } from "./FilterPill.js";
10
+ import { filterLabels } from "./labels.js";
11
+ import { FilterMenu } from "./menu.js";
12
+ import { appendAll, findNode, reid, replaceNode } from "./tree.js";
13
+ /**
14
+ * The edited tree, kept locally so drafts (rules without a value, empty
15
+ * groups) and node ids survive while the compiled query is unchanged or the
16
+ * host has not yet echoed an edit back. A query the builder did not emit is
17
+ * re-parsed.
18
+ */
19
+ function useFilterTree(query, onChange) {
20
+ const [state, setState] = useState(() => ({
21
+ seen: query,
22
+ source: query,
23
+ tree: parseWhere(query)
24
+ }));
25
+ let current = state;
26
+ if (query !== state.seen) current = query === state.source ? {
27
+ ...state,
28
+ seen: query
29
+ } : {
30
+ seen: query,
31
+ source: query,
32
+ tree: parseWhere(query)
33
+ };
34
+ if (current !== state) setState(current);
35
+ const update = tree => {
36
+ const where = compileWhere(tree);
37
+ setState({
38
+ seen: current.seen,
39
+ source: where,
40
+ tree
41
+ });
42
+ if (where !== current.source) onChange?.(where);
43
+ };
44
+ return {
45
+ tree: current.tree,
46
+ update
47
+ };
48
+ }
49
+ const rootName = (labels, combinator) => ({
50
+ all: labels.matchAll,
51
+ any: labels.matchAny,
52
+ none: labels.exclude
53
+ })[combinator];
54
+ const ADD = "bar:add";
55
+ /**
56
+ * A filter bar for the CEL `where` expression of an `mdbase.view`. Each filter is a pill
57
+ * (`field | operator | value | ×`) whose parts are changed where they stand, custom CEL is an
58
+ * `fx` pill, nested groups are clusters of pills, and `Filter` opens the list of fields to add
59
+ * one from.
60
+ */
61
+ export function FilterBuilder({
62
+ query,
63
+ fields,
64
+ contextVars = [],
65
+ error,
66
+ lockedFields = [],
67
+ onChange,
68
+ sharedQuery = "",
69
+ onSharedChange,
70
+ ariaLabel,
71
+ defaultOpen = false,
72
+ labels: labelOverrides
73
+ }) {
74
+ useLocaleRevision();
75
+ const labels = {
76
+ ...filterLabels(),
77
+ ...labelOverrides
78
+ };
79
+ const view = useFilterTree(query, onChange);
80
+ const shared = useFilterTree(sharedQuery, onSharedChange);
81
+ const tiered = onSharedChange !== undefined;
82
+ const [openKey, setOpenKey] = useState(defaultOpen ? ADD : null);
83
+ const rootRef = useRef(null);
84
+ const addRef = useRef(null);
85
+ const chipRef = useRef(null);
86
+ const pendingFocus = useRef(null);
87
+ const lockedKey = lockedFields.join("\n");
88
+ const locked = useMemo(() => new Set(lockedKey ? lockedKey.split("\n") : []), [lockedKey]);
89
+ const trees = {
90
+ view: view.tree,
91
+ shared: shared.tree
92
+ };
93
+ const updates = {
94
+ view: view.update,
95
+ shared: shared.update
96
+ };
97
+ const bar = {
98
+ labels,
99
+ fields,
100
+ contextVars,
101
+ locked,
102
+ tiered,
103
+ trees,
104
+ openKey,
105
+ setOpenKey,
106
+ edit: (tier, change) => updates[tier](change(trees[tier])),
107
+ move: (from, id) => {
108
+ const node = findNode(trees[from], id);
109
+ if (!node) return;
110
+ const to = from === "view" ? "shared" : "view";
111
+ const moved = reid(node);
112
+ updates[from](replaceNode(trees[from], id, null));
113
+ updates[to](appendAll(trees[to], moved));
114
+ pendingFocus.current = `[data-key="${to}:${moved.id}"]`;
115
+ },
116
+ focusAdd: () => {
117
+ pendingFocus.current = ".mdbase-filter-add";
118
+ },
119
+ focusNode: (tier, id) => {
120
+ pendingFocus.current = `[data-key="${tier}:${id}"]`;
121
+ }
122
+ };
123
+ useLayoutEffect(() => {
124
+ const selector = pendingFocus.current;
125
+ if (!selector) return;
126
+ pendingFocus.current = null;
127
+ const target = rootRef.current?.querySelector(selector);
128
+ (target?.matches("button") ? target : target?.querySelector("button"))?.focus();
129
+ });
130
+ const sharedVisible = tiered && shared.tree.children.length > 0;
131
+ const root = view.tree;
132
+ // The bar's own "Match" chip speaks for the view's filters only when nothing else sits on the bar.
133
+ const chip = !sharedVisible && (root.combinator !== "all" ? root.children.length > 0 : root.children.length > 1);
134
+ const part = openPart(bar, "bar");
135
+ const total = countActive(view.tree) + (tiered ? countActive(shared.tree) : 0);
136
+ const closeAdd = restore => {
137
+ if (restore) addRef.current?.focus();
138
+ setOpenKey(null);
139
+ };
140
+ const tier = (name, tree, inline) => inline ? tree.children.map(child => _jsx(FilterNodeView, {
141
+ node: child,
142
+ tier: name,
143
+ depth: 0
144
+ }, `${name}:${child.id}`)) : _jsx(GroupCluster, {
145
+ node: tree,
146
+ tier: name,
147
+ depth: 0,
148
+ root: true
149
+ }, `${name}:${tree.id}`);
150
+ return _jsx(Bar.Provider, {
151
+ value: bar,
152
+ children: _jsxs("div", {
153
+ className: "mdbase-filter",
154
+ role: "group",
155
+ "aria-label": ariaLabel ?? labels.filters,
156
+ ref: rootRef,
157
+ children: [_jsxs("div", {
158
+ className: "mdbase-filter-bar",
159
+ children: [chip && _jsxs("span", {
160
+ className: "mdbase-filter-anchor",
161
+ children: [_jsxs("button", {
162
+ ref: chipRef,
163
+ type: "button",
164
+ className: "mdbase-filter-match",
165
+ "aria-haspopup": "menu",
166
+ "aria-expanded": part === "combinator",
167
+ title: labels.howFiltersCombine,
168
+ onClick: () => setOpenKey(part === "combinator" ? null : "bar:combinator"),
169
+ children: [rootName(labels, root.combinator), _jsx(Glyph, {
170
+ name: "down",
171
+ size: 12
172
+ })]
173
+ }), _jsx(FilterMenu, {
174
+ open: part === "combinator",
175
+ anchor: chipRef,
176
+ label: labels.match,
177
+ onClose: () => setOpenKey(null),
178
+ items: ["all", "any", "none"].map(combinator => ({
179
+ label: rootName(labels, combinator),
180
+ hint: combinatorHint(labels, combinator),
181
+ checked: root.combinator === combinator,
182
+ onSelect: () => {
183
+ view.update({
184
+ ...root,
185
+ combinator
186
+ });
187
+ chipRef.current?.focus();
188
+ setOpenKey(null);
189
+ }
190
+ }))
191
+ })]
192
+ }), sharedVisible && tier("shared", shared.tree, shared.tree.combinator === "all"), root.children.length > 0 && tier("view", root, root.combinator === "all" || chip), _jsxs("span", {
193
+ className: "mdbase-filter-anchor",
194
+ children: [_jsxs("button", {
195
+ ref: addRef,
196
+ type: "button",
197
+ className: "mdbase-filter-add",
198
+ "aria-label": labels.addFilter,
199
+ "aria-haspopup": "dialog",
200
+ "aria-expanded": openKey === ADD,
201
+ "data-active": total > 0 || undefined,
202
+ onClick: () => setOpenKey(openKey === ADD ? null : ADD),
203
+ children: [_jsx(Glyph, {
204
+ name: total > 0 ? "plus" : "filter"
205
+ }), labels.filter]
206
+ }), openKey === ADD && _jsx(AnchoredPopover, {
207
+ anchor: addRef,
208
+ label: labels.addFilter,
209
+ className: "mdbase-filter-popover mdbase-filter-command",
210
+ onClose: () => setOpenKey(null),
211
+ children: _jsx(AddFilter, {
212
+ tier: "view",
213
+ groupId: null,
214
+ onClose: closeAdd
215
+ })
216
+ })]
217
+ })]
218
+ }), error && _jsx("p", {
219
+ className: "mdbase-filter-error",
220
+ role: "alert",
221
+ children: error
222
+ })]
223
+ })
224
+ });
225
+ }
@@ -0,0 +1,17 @@
1
+ import { type JSX } from "react";
2
+ import { type Tier } from "./context.js";
3
+ import type { FilterExpr, FilterGroup, FilterNode, FilterRule } from "./types.js";
4
+ interface NodeProps<T extends FilterNode> {
5
+ node: T;
6
+ tier: Tier;
7
+ /** 0 for filters directly on the bar. */
8
+ depth: number;
9
+ }
10
+ export declare function RulePill({ node: rule, tier, depth }: NodeProps<FilterRule>): JSX.Element;
11
+ export declare function ExprPill({ node, tier, depth }: NodeProps<FilterExpr>): JSX.Element;
12
+ /** A nested group on the bar: a shaded cluster with its combinator, its own pills, and `+`. */
13
+ export declare function GroupCluster({ node: group, tier, depth, root }: NodeProps<FilterGroup> & {
14
+ root?: boolean;
15
+ }): JSX.Element;
16
+ export declare function FilterNodeView({ node, tier, depth }: NodeProps<FilterNode>): JSX.Element;
17
+ export {};