@svgrid/grid 2.1.21 → 2.1.23

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 (219) hide show
  1. package/README.md +9 -2
  2. package/dist/DockNodeView.svelte +306 -0
  3. package/dist/DockNodeView.svelte.d.ts +7 -0
  4. package/dist/DockPopoutHost.svelte +17 -0
  5. package/dist/DockPopoutHost.svelte.d.ts +14 -0
  6. package/dist/GridMenus.svelte +83 -3
  7. package/dist/SvAutoComplete.svelte +5 -3
  8. package/dist/SvCarousel.svelte +20 -42
  9. package/dist/SvColorInput.svelte +4 -3
  10. package/dist/SvColorInput.svelte.d.ts +1 -1
  11. package/dist/SvComboBox.svelte +7 -3
  12. package/dist/SvCommand.svelte +28 -85
  13. package/dist/SvCountryInput.svelte +1 -1
  14. package/dist/SvDateRangeInput.svelte +1 -1
  15. package/dist/SvDateTimePicker.svelte +9 -3
  16. package/dist/SvDateTimePicker.svelte.d.ts +3 -0
  17. package/dist/SvDockLayout.svelte +244 -0
  18. package/dist/SvDockLayout.svelte.d.ts +77 -0
  19. package/dist/SvDockManager.svelte +922 -0
  20. package/dist/SvDockManager.svelte.d.ts +106 -0
  21. package/dist/SvDrawer.svelte +69 -47
  22. package/dist/SvDrawer.svelte.d.ts +4 -0
  23. package/dist/SvDropDownList.svelte +85 -13
  24. package/dist/SvDropDownList.svelte.d.ts +3 -0
  25. package/dist/SvField.svelte +21 -4
  26. package/dist/SvField.svelte.d.ts +1 -0
  27. package/dist/SvForm.svelte +201 -91
  28. package/dist/SvForm.svelte.d.ts +15 -22
  29. package/dist/SvGrid.controller.svelte.d.ts +32 -1
  30. package/dist/SvGrid.controller.svelte.js +156 -27
  31. package/dist/SvGrid.css +193 -5
  32. package/dist/SvGrid.svelte +357 -12
  33. package/dist/SvGrid.types.d.ts +452 -1
  34. package/dist/SvGridDropdown.svelte +8 -1
  35. package/dist/SvGridSelect.svelte +1 -0
  36. package/dist/SvListBox.svelte +36 -14
  37. package/dist/SvMaskedInput.svelte +4 -3
  38. package/dist/SvMaskedInput.svelte.d.ts +1 -1
  39. package/dist/SvMenu.svelte +1 -1
  40. package/dist/SvMenuList.svelte +23 -71
  41. package/dist/SvMenuList.svelte.d.ts +2 -13
  42. package/dist/SvModal.svelte +12 -29
  43. package/dist/SvMultiSelect.svelte +1 -0
  44. package/dist/SvNumberInput.svelte +4 -3
  45. package/dist/SvNumberInput.svelte.d.ts +1 -1
  46. package/dist/SvPagination.svelte +18 -18
  47. package/dist/SvPasswordInput.svelte +3 -2
  48. package/dist/SvPasswordInput.svelte.d.ts +1 -1
  49. package/dist/SvPhoneInput.svelte +3 -2
  50. package/dist/SvPhoneInput.svelte.d.ts +1 -1
  51. package/dist/SvPopover.svelte +1 -1
  52. package/dist/SvStepper.svelte +6 -9
  53. package/dist/SvTagsInput.svelte +3 -2
  54. package/dist/SvTagsInput.svelte.d.ts +1 -1
  55. package/dist/SvTooltip.svelte +12 -23
  56. package/dist/SvTour.svelte +32 -4
  57. package/dist/SvTreeSelect.svelte +1 -0
  58. package/dist/build-api.js +76 -54
  59. package/dist/cdn/svgrid.js +10907 -6444
  60. package/dist/cdn/svgrid.svelte-external.js +9622 -5475
  61. package/dist/columns.js +6 -0
  62. package/dist/conditional-formatting.d.ts +67 -3
  63. package/dist/conditional-formatting.js +124 -17
  64. package/dist/createCarousel.svelte.d.ts +72 -0
  65. package/dist/createCarousel.svelte.js +80 -0
  66. package/dist/createCommand.svelte.d.ts +62 -0
  67. package/dist/createCommand.svelte.js +109 -0
  68. package/dist/createForm.svelte.d.ts +62 -0
  69. package/dist/createForm.svelte.js +374 -0
  70. package/dist/createMenu.svelte.d.ts +88 -0
  71. package/dist/createMenu.svelte.js +153 -0
  72. package/dist/createOverlay.svelte.d.ts +38 -0
  73. package/dist/createOverlay.svelte.js +68 -0
  74. package/dist/createPagination.d.ts +74 -0
  75. package/dist/createPagination.js +71 -0
  76. package/dist/createPopoverSelect.svelte.js +6 -12
  77. package/dist/createStepper.d.ts +44 -0
  78. package/dist/createStepper.js +26 -0
  79. package/dist/createTooltip.svelte.d.ts +32 -0
  80. package/dist/createTooltip.svelte.js +61 -0
  81. package/dist/datetime/timezone.d.ts +36 -0
  82. package/dist/datetime/timezone.js +110 -0
  83. package/dist/dock-context.d.ts +52 -0
  84. package/dist/dock-context.js +1 -0
  85. package/dist/dock-manager-model.d.ts +136 -0
  86. package/dist/dock-manager-model.js +514 -0
  87. package/dist/dock-model.d.ts +105 -0
  88. package/dist/dock-model.js +288 -0
  89. package/dist/dock-popout.d.ts +30 -0
  90. package/dist/dock-popout.js +81 -0
  91. package/dist/editor-contract.d.ts +2 -0
  92. package/dist/filter-operators.d.ts +6 -0
  93. package/dist/filter-operators.js +35 -2
  94. package/dist/filtering/excel-filters.d.ts +18 -1
  95. package/dist/filtering/excel-filters.js +56 -0
  96. package/dist/form-field.d.ts +73 -0
  97. package/dist/form-field.js +15 -0
  98. package/dist/index.d.ts +25 -5
  99. package/dist/index.js +40 -4
  100. package/dist/list-nav.d.ts +18 -0
  101. package/dist/list-nav.js +30 -0
  102. package/dist/list-option.d.ts +2 -0
  103. package/dist/menu-item.d.ts +20 -0
  104. package/dist/menu-item.js +1 -0
  105. package/dist/menus.d.ts +5 -0
  106. package/dist/menus.js +68 -16
  107. package/dist/panel-resize.d.ts +25 -0
  108. package/dist/panel-resize.js +40 -0
  109. package/dist/popover.d.ts +29 -3
  110. package/dist/popover.js +22 -6
  111. package/dist/recurrence.d.ts +33 -7
  112. package/dist/recurrence.js +151 -13
  113. package/dist/row-drag.d.ts +8 -0
  114. package/dist/row-drag.js +11 -0
  115. package/dist/scheduler-ical.d.ts +30 -0
  116. package/dist/scheduler-ical.js +180 -0
  117. package/dist/scheduler-model.d.ts +269 -0
  118. package/dist/scheduler-model.js +602 -0
  119. package/dist/scheduler-view.svelte.d.ts +22 -0
  120. package/dist/scheduler-view.svelte.js +13 -0
  121. package/dist/spreadsheet.js +20 -12
  122. package/dist/ui-app.types.d.ts +3 -0
  123. package/package.json +5 -1
  124. package/src/DockNodeView.svelte +306 -0
  125. package/src/DockPopoutHost.svelte +17 -0
  126. package/src/GridMenus.svelte +83 -3
  127. package/src/SvAutoComplete.svelte +5 -3
  128. package/src/SvCarousel.svelte +20 -42
  129. package/src/SvCarousel.test.ts +68 -0
  130. package/src/SvColorInput.svelte +4 -3
  131. package/src/SvComboBox.svelte +7 -3
  132. package/src/SvCommand.svelte +28 -85
  133. package/src/SvCommand.test.ts +78 -0
  134. package/src/SvCountryInput.svelte +1 -1
  135. package/src/SvDateRangeInput.svelte +1 -1
  136. package/src/SvDateTimePicker.svelte +9 -3
  137. package/src/SvDockLayout.svelte +244 -0
  138. package/src/SvDockManager.svelte +922 -0
  139. package/src/SvDrawer.svelte +69 -47
  140. package/src/SvDropDownList.svelte +85 -13
  141. package/src/SvField.svelte +21 -4
  142. package/src/SvForm.svelte +201 -91
  143. package/src/SvForm.test.ts +299 -0
  144. package/src/SvGrid.controller.svelte.ts +152 -28
  145. package/src/SvGrid.css +193 -5
  146. package/src/SvGrid.svelte +357 -12
  147. package/src/SvGrid.types.ts +463 -1
  148. package/src/SvGridDropdown.svelte +8 -1
  149. package/src/SvGridSelect.svelte +1 -0
  150. package/src/SvListBox.svelte +36 -14
  151. package/src/SvMaskedInput.svelte +4 -3
  152. package/src/SvMenu.svelte +1 -1
  153. package/src/SvMenu.test.ts +24 -0
  154. package/src/SvMenuList.svelte +23 -71
  155. package/src/SvModal.svelte +12 -29
  156. package/src/SvModal.test.ts +82 -0
  157. package/src/SvMultiSelect.svelte +1 -0
  158. package/src/SvNumberInput.svelte +4 -3
  159. package/src/SvPagination.svelte +18 -18
  160. package/src/SvPasswordInput.svelte +3 -2
  161. package/src/SvPhoneInput.svelte +3 -2
  162. package/src/SvPopover.svelte +1 -1
  163. package/src/SvStepper.svelte +6 -9
  164. package/src/SvTagsInput.svelte +3 -2
  165. package/src/SvTooltip.svelte +12 -23
  166. package/src/SvTooltip.test.ts +73 -0
  167. package/src/SvTour.svelte +32 -4
  168. package/src/SvTreeSelect.svelte +1 -0
  169. package/src/build-api.ts +74 -51
  170. package/src/columns.ts +5 -0
  171. package/src/conditional-formatting.test.ts +104 -0
  172. package/src/conditional-formatting.ts +176 -19
  173. package/src/createCarousel.svelte.ts +104 -0
  174. package/src/createCommand.svelte.ts +125 -0
  175. package/src/createForm.svelte.ts +333 -0
  176. package/src/createMenu.svelte.ts +202 -0
  177. package/src/createOverlay.svelte.ts +101 -0
  178. package/src/createPagination.test.ts +65 -0
  179. package/src/createPagination.ts +84 -0
  180. package/src/createPopoverSelect.svelte.ts +5 -9
  181. package/src/createStepper.test.ts +62 -0
  182. package/src/createStepper.ts +61 -0
  183. package/src/createTooltip.svelte.ts +86 -0
  184. package/src/datetime/timezone.test.ts +69 -0
  185. package/src/datetime/timezone.ts +134 -0
  186. package/src/dock-context.ts +47 -0
  187. package/src/dock-manager-model.test.ts +275 -0
  188. package/src/dock-manager-model.ts +593 -0
  189. package/src/dock-model.test.ts +163 -0
  190. package/src/dock-model.ts +368 -0
  191. package/src/dock-popout.ts +94 -0
  192. package/src/editor-contract.ts +2 -0
  193. package/src/filter-operators.test.ts +59 -0
  194. package/src/filter-operators.ts +35 -2
  195. package/src/filtering/excel-filters.test.ts +86 -1
  196. package/src/filtering/excel-filters.ts +65 -0
  197. package/src/form-field.ts +87 -0
  198. package/src/index.ts +158 -4
  199. package/src/list-nav.test.ts +49 -0
  200. package/src/list-nav.ts +29 -0
  201. package/src/list-option.ts +2 -0
  202. package/src/menu-item.ts +21 -0
  203. package/src/menus.test.ts +48 -0
  204. package/src/menus.ts +73 -16
  205. package/src/panel-resize.ts +52 -0
  206. package/src/popover.bounds.test.ts +93 -0
  207. package/src/popover.ts +51 -7
  208. package/src/recurrence.test.ts +88 -1
  209. package/src/recurrence.ts +166 -15
  210. package/src/row-drag.ts +10 -0
  211. package/src/scheduler-ical.test.ts +68 -0
  212. package/src/scheduler-ical.ts +180 -0
  213. package/src/scheduler-model.test.ts +546 -0
  214. package/src/scheduler-model.ts +853 -0
  215. package/src/scheduler-view.svelte.ts +33 -0
  216. package/src/spreadsheet.ts +20 -12
  217. package/src/svgrid.effect-driven-filter.svelte.test.ts +116 -0
  218. package/src/ui-app.types.ts +3 -0
  219. package/src/virtual.test.ts +6 -4
@@ -0,0 +1,62 @@
1
+ /**
2
+ * createForm - the HEADLESS core behind <SvForm>: values / errors / touched
3
+ * state, required + rule + custom validation (validate-on-blur-then-live), and a
4
+ * submit that validates every field first. No markup, no controls - you render
5
+ * the fields however you like and read/write through the core.
6
+ *
7
+ * ```svelte
8
+ * <script lang="ts">
9
+ * import { createForm } from '@svgrid/grid'
10
+ * const form = createForm({ fields: () => fields, onSubmit: (v) => save(v) })
11
+ * </script>
12
+ * <form onsubmit={(e) => { e.preventDefault(); form.submit() }}>
13
+ * {#each fields as f}
14
+ * <input value={form.value(f.name) ?? ''}
15
+ * oninput={(e) => form.setValue(f.name, e.currentTarget.value)}
16
+ * onblur={() => form.handleBlur(f.name)} />
17
+ * {#if form.error(f.name)}<span>{form.error(f.name)}</span>{/if}
18
+ * {/each}
19
+ * </form>
20
+ * ```
21
+ */
22
+ import { type FormEntry } from './form-field';
23
+ export type FormConfig = {
24
+ /** The schema - a mix of flat fields and titled sections. */
25
+ fields: () => ReadonlyArray<FormEntry>;
26
+ /** Seed values on creation. */
27
+ initial?: Record<string, any>;
28
+ /** Called with the (visible-field) values on a valid submit. May be async;
29
+ * `submitting` stays true until the returned promise settles. */
30
+ onSubmit?: (values: Record<string, any>) => void | Promise<void>;
31
+ onChange?: (values: Record<string, any>) => void;
32
+ };
33
+ export declare function createForm(config: FormConfig): {
34
+ readonly values: Record<string, any>;
35
+ readonly submitting: boolean;
36
+ readonly isDirty: boolean;
37
+ value: (name: string) => any;
38
+ error: (name: string) => string | undefined;
39
+ isTouched: (name: string) => boolean;
40
+ hasError: (name: string) => boolean;
41
+ isValidating: (name: string) => boolean;
42
+ isFieldDirty: (name: string) => boolean;
43
+ isVisible: (name: string) => boolean;
44
+ isDisabled: (name: string) => boolean;
45
+ entries: () => readonly FormEntry[];
46
+ arrayItems: (name: string) => Record<string, any>[];
47
+ itemValue: (name: string, i: number, field: string) => any;
48
+ itemError: (name: string, i: number, field: string) => string | undefined;
49
+ addItem: (name: string, item?: Record<string, any>) => void;
50
+ removeItem: (name: string, i: number) => void;
51
+ moveItem: (name: string, from: number, to: number) => void;
52
+ setItemValue: (name: string, i: number, field: string, v: any) => void;
53
+ handleItemBlur: (name: string, i: number, field: string) => void;
54
+ setValue: (name: string, v: any) => void;
55
+ handleBlur: (name: string) => void;
56
+ validateField: (name: string) => boolean;
57
+ validateFields: (names: string[]) => Promise<boolean>;
58
+ submit: () => Promise<boolean>;
59
+ reset: (next?: Record<string, any>) => void;
60
+ setErrors: (map: Record<string, string>) => void;
61
+ };
62
+ export type Form = ReturnType<typeof createForm>;
@@ -0,0 +1,374 @@
1
+ /**
2
+ * createForm - the HEADLESS core behind <SvForm>: values / errors / touched
3
+ * state, required + rule + custom validation (validate-on-blur-then-live), and a
4
+ * submit that validates every field first. No markup, no controls - you render
5
+ * the fields however you like and read/write through the core.
6
+ *
7
+ * ```svelte
8
+ * <script lang="ts">
9
+ * import { createForm } from '@svgrid/grid'
10
+ * const form = createForm({ fields: () => fields, onSubmit: (v) => save(v) })
11
+ * </script>
12
+ * <form onsubmit={(e) => { e.preventDefault(); form.submit() }}>
13
+ * {#each fields as f}
14
+ * <input value={form.value(f.name) ?? ''}
15
+ * oninput={(e) => form.setValue(f.name, e.currentTarget.value)}
16
+ * onblur={() => form.handleBlur(f.name)} />
17
+ * {#if form.error(f.name)}<span>{form.error(f.name)}</span>{/if}
18
+ * {/each}
19
+ * </form>
20
+ * ```
21
+ */
22
+ import { flattenFields } from './form-field';
23
+ import { runRules } from './validators';
24
+ /** Deep-ish equality for dirty tracking: identity for primitives, structural
25
+ * (JSON) for arrays/objects. Good enough for form values. */
26
+ function eq(a, b) {
27
+ if (Object.is(a, b))
28
+ return true;
29
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
30
+ try {
31
+ return JSON.stringify(a) === JSON.stringify(b);
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ return false;
38
+ }
39
+ /** Resolve a `boolean | (values) => boolean` field flag. */
40
+ function resolveFlag(flag, dflt, values) {
41
+ if (flag == null)
42
+ return dflt;
43
+ return typeof flag === 'function' ? !!flag(values) : !!flag;
44
+ }
45
+ export function createForm(config) {
46
+ let values = $state({ ...(config.initial ?? {}) });
47
+ let errors = $state({});
48
+ let touched = $state({});
49
+ let submitting = $state(false);
50
+ let validating = $state({});
51
+ // Baseline for dirty tracking + reset. Rebased when `reset(next)` is passed.
52
+ let baseline = { ...(config.initial ?? {}) };
53
+ // Async-validation bookkeeping: debounce timers + a per-field run sequence so
54
+ // only the latest response wins (stale responses are dropped).
55
+ const asyncTimers = new Map();
56
+ const asyncSeq = new Map();
57
+ // The flat field list (sections flattened) drives all values/validation.
58
+ const flat = () => flattenFields(config.fields());
59
+ const fieldOf = (name) => flat().find((f) => f.name === name);
60
+ const isVisible = (name) => resolveFlag(fieldOf(name)?.visible, true, values);
61
+ const isDisabled = (name) => resolveFlag(fieldOf(name)?.disabled, false, values);
62
+ function setError(name, err) {
63
+ const next = { ...errors };
64
+ if (err)
65
+ next[name] = err;
66
+ else
67
+ delete next[name];
68
+ errors = next;
69
+ }
70
+ /** The synchronous checks: required, then declarative rules, then a sync
71
+ * `validate`. Returns the first error message, or null. `ctx` is the values
72
+ * object rules/validate see - the form values, or a single item for array
73
+ * rows (so within-row cross-field rules work). */
74
+ function syncError(field, v, ctx = values) {
75
+ if (field.required && (v == null || v === '' || (Array.isArray(v) && !v.length)))
76
+ return `${field.label} is required`;
77
+ if (field.rules) {
78
+ const e = runRules(v, field.rules, ctx);
79
+ if (e)
80
+ return e;
81
+ }
82
+ if (field.validate) {
83
+ const e = field.validate(v, ctx);
84
+ if (e)
85
+ return e;
86
+ }
87
+ return null;
88
+ }
89
+ function cancelAsync(name) {
90
+ const t = asyncTimers.get(name);
91
+ if (t) {
92
+ clearTimeout(t);
93
+ asyncTimers.delete(name);
94
+ }
95
+ // Bump the sequence so any in-flight response is treated as stale.
96
+ asyncSeq.set(name, (asyncSeq.get(name) ?? 0) + 1);
97
+ if (validating[name])
98
+ validating = { ...validating, [name]: false };
99
+ }
100
+ /** Run a field's async validator now (guarded against stale responses). */
101
+ async function runAsync(name) {
102
+ const field = fieldOf(name);
103
+ if (!field?.asyncValidate || !isVisible(name))
104
+ return true;
105
+ if (syncError(field, values[name]))
106
+ return false; // sync error already shown
107
+ const seq = (asyncSeq.get(name) ?? 0) + 1;
108
+ asyncSeq.set(name, seq);
109
+ validating = { ...validating, [name]: true };
110
+ try {
111
+ const err = await field.asyncValidate(values[name], values);
112
+ if (asyncSeq.get(name) !== seq)
113
+ return true; // superseded - ignore
114
+ setError(name, err ?? null);
115
+ return !err;
116
+ }
117
+ finally {
118
+ if (asyncSeq.get(name) === seq)
119
+ validating = { ...validating, [name]: false };
120
+ }
121
+ }
122
+ function scheduleAsync(name) {
123
+ const field = fieldOf(name);
124
+ if (!field?.asyncValidate)
125
+ return;
126
+ const prev = asyncTimers.get(name);
127
+ if (prev)
128
+ clearTimeout(prev);
129
+ asyncTimers.set(name, setTimeout(() => { asyncTimers.delete(name); runAsync(name); }, field.asyncDebounce ?? 300));
130
+ }
131
+ function validateField(name) {
132
+ const field = fieldOf(name);
133
+ if (!field)
134
+ return true;
135
+ // Hidden fields never block submit; clear any stale error + pending check.
136
+ if (!isVisible(name)) {
137
+ setError(name, null);
138
+ cancelAsync(name);
139
+ return true;
140
+ }
141
+ if (field.type === 'array')
142
+ return validateArray(field);
143
+ const err = syncError(field, values[name]);
144
+ setError(name, err);
145
+ if (err) {
146
+ cancelAsync(name);
147
+ return false;
148
+ }
149
+ // Sync passed - kick off the debounced async check if there is one.
150
+ if (field.asyncValidate)
151
+ scheduleAsync(name);
152
+ return true;
153
+ }
154
+ // --- Field arrays (repeatable groups) -----------------------------------
155
+ const arrayItems = (name) => Array.isArray(values[name]) ? values[name] : [];
156
+ const itemValue = (name, i, field) => arrayItems(name)[i]?.[field];
157
+ const itemError = (name, i, field) => errors[`${name}.${i}.${field}`];
158
+ function clearNamespacedErrors(name) {
159
+ const prefix = `${name}.`;
160
+ const next = { ...errors };
161
+ let changed = false;
162
+ for (const k of Object.keys(next))
163
+ if (k.startsWith(prefix)) {
164
+ delete next[k];
165
+ changed = true;
166
+ }
167
+ if (changed)
168
+ errors = next;
169
+ }
170
+ function setItems(name, next) {
171
+ values = { ...values, [name]: next };
172
+ config.onChange?.(values);
173
+ }
174
+ function addItem(name, item) {
175
+ const seed = item ?? Object.fromEntries((fieldOf(name)?.itemFields ?? []).map((f) => [f.name, undefined]));
176
+ setItems(name, [...arrayItems(name), seed]);
177
+ }
178
+ function removeItem(name, i) {
179
+ const items = arrayItems(name).slice();
180
+ items.splice(i, 1);
181
+ clearNamespacedErrors(name); // item indices shift - drop stale keys
182
+ setItems(name, items);
183
+ }
184
+ function moveItem(name, from, to) {
185
+ const items = arrayItems(name).slice();
186
+ if (from < 0 || from >= items.length || to < 0 || to >= items.length)
187
+ return;
188
+ const [it] = items.splice(from, 1);
189
+ items.splice(to, 0, it);
190
+ clearNamespacedErrors(name);
191
+ setItems(name, items);
192
+ }
193
+ function setItemValue(name, i, field, v) {
194
+ setItems(name, arrayItems(name).map((it, ix) => (ix === i ? { ...it, [field]: v } : it)));
195
+ if (touched[`${name}.${i}.${field}`])
196
+ validateItemField(name, i, field);
197
+ }
198
+ function handleItemBlur(name, i, field) {
199
+ touched = { ...touched, [`${name}.${i}.${field}`]: true };
200
+ validateItemField(name, i, field);
201
+ }
202
+ function validateItemField(name, i, fieldName) {
203
+ const itemField = fieldOf(name)?.itemFields?.find((f) => f.name === fieldName);
204
+ if (!itemField)
205
+ return true;
206
+ const item = arrayItems(name)[i] ?? {};
207
+ const err = syncError(itemField, item[fieldName], item);
208
+ setError(`${name}.${i}.${fieldName}`, err);
209
+ return !err;
210
+ }
211
+ function validateArray(field) {
212
+ const name = field.name;
213
+ const items = arrayItems(name);
214
+ let arrErr = null;
215
+ if (field.required && items.length === 0)
216
+ arrErr = `${field.label} is required`;
217
+ else if (field.minItems != null && items.length < field.minItems)
218
+ arrErr = `Add at least ${field.minItems} item(s)`;
219
+ else if (field.maxItems != null && items.length > field.maxItems)
220
+ arrErr = `At most ${field.maxItems} item(s)`;
221
+ setError(name, arrErr);
222
+ let ok = !arrErr;
223
+ clearNamespacedErrors(name); // rebuild fresh per-item errors
224
+ for (let i = 0; i < items.length; i++)
225
+ for (const itf of field.itemFields ?? [])
226
+ if (!validateItemField(name, i, itf.name))
227
+ ok = false;
228
+ return ok;
229
+ }
230
+ function setValue(name, v) {
231
+ values = { ...values, [name]: v };
232
+ config.onChange?.(values);
233
+ // Re-validate live once the field has been blurred at least once.
234
+ if (touched[name])
235
+ validateField(name);
236
+ }
237
+ function handleBlur(name) {
238
+ touched = { ...touched, [name]: true };
239
+ validateField(name);
240
+ }
241
+ async function submit() {
242
+ let ok = true;
243
+ const t = { ...touched };
244
+ for (const f of flat()) {
245
+ if (!isVisible(f.name))
246
+ continue;
247
+ t[f.name] = true;
248
+ if (!validateField(f.name))
249
+ ok = false;
250
+ }
251
+ touched = t;
252
+ if (!ok)
253
+ return false;
254
+ // Await async validators (run now, skipping their debounce). Any failure blocks.
255
+ const asyncFields = flat().filter((f) => f.asyncValidate && isVisible(f.name));
256
+ if (asyncFields.length) {
257
+ for (const f of asyncFields) {
258
+ const timer = asyncTimers.get(f.name);
259
+ if (timer) {
260
+ clearTimeout(timer);
261
+ asyncTimers.delete(f.name);
262
+ }
263
+ }
264
+ const results = await Promise.all(asyncFields.map((f) => runAsync(f.name)));
265
+ if (results.some((r) => !r))
266
+ return false;
267
+ }
268
+ // Exclude hidden fields from the submitted payload; keep any non-field keys.
269
+ const payload = { ...values };
270
+ for (const f of flat())
271
+ if (!isVisible(f.name))
272
+ delete payload[f.name];
273
+ submitting = true;
274
+ try {
275
+ await config.onSubmit?.(payload);
276
+ }
277
+ finally {
278
+ submitting = false;
279
+ }
280
+ return true;
281
+ }
282
+ /** Validate a subset of fields by name (sync + their async validators). Used
283
+ * to gate a wizard step before advancing. Returns true when all pass. */
284
+ async function validateFields(names) {
285
+ let ok = true;
286
+ const t = { ...touched };
287
+ for (const name of names) {
288
+ if (!isVisible(name))
289
+ continue;
290
+ t[name] = true;
291
+ if (!validateField(name))
292
+ ok = false;
293
+ }
294
+ touched = t;
295
+ if (!ok)
296
+ return false;
297
+ const asyncNames = names.filter((n) => fieldOf(n)?.asyncValidate && isVisible(n));
298
+ if (asyncNames.length) {
299
+ for (const n of asyncNames) {
300
+ const timer = asyncTimers.get(n);
301
+ if (timer) {
302
+ clearTimeout(timer);
303
+ asyncTimers.delete(n);
304
+ }
305
+ }
306
+ const results = await Promise.all(asyncNames.map((n) => runAsync(n)));
307
+ if (results.some((r) => !r))
308
+ return false;
309
+ }
310
+ return true;
311
+ }
312
+ /** Restore values to the baseline (or a new one), clearing errors + touched. */
313
+ function reset(next) {
314
+ if (next)
315
+ baseline = { ...next };
316
+ values = { ...baseline };
317
+ errors = {};
318
+ touched = {};
319
+ config.onChange?.(values);
320
+ }
321
+ /** Inject errors (e.g. server-side validation after submit) and mark those
322
+ * fields touched so the messages show. Empty message clears a field's error. */
323
+ function setErrors(map) {
324
+ const nextErr = { ...errors };
325
+ const nextTouched = { ...touched };
326
+ for (const [k, msg] of Object.entries(map)) {
327
+ if (msg) {
328
+ nextErr[k] = msg;
329
+ nextTouched[k] = true;
330
+ }
331
+ else
332
+ delete nextErr[k];
333
+ }
334
+ errors = nextErr;
335
+ touched = nextTouched;
336
+ }
337
+ const isFieldDirty = (name) => !eq(values[name], baseline[name]);
338
+ return {
339
+ get values() { return values; },
340
+ get submitting() { return submitting; },
341
+ get isDirty() {
342
+ const keys = new Set([...Object.keys(values), ...Object.keys(baseline)]);
343
+ for (const k of keys)
344
+ if (!eq(values[k], baseline[k]))
345
+ return true;
346
+ return false;
347
+ },
348
+ value: (name) => values[name],
349
+ error: (name) => errors[name],
350
+ isTouched: (name) => !!touched[name],
351
+ hasError: (name) => !!errors[name],
352
+ isValidating: (name) => !!validating[name],
353
+ isFieldDirty,
354
+ isVisible,
355
+ isDisabled,
356
+ entries: () => config.fields(),
357
+ // Field arrays
358
+ arrayItems,
359
+ itemValue,
360
+ itemError,
361
+ addItem,
362
+ removeItem,
363
+ moveItem,
364
+ setItemValue,
365
+ handleItemBlur,
366
+ setValue,
367
+ handleBlur,
368
+ validateField,
369
+ validateFields,
370
+ submit,
371
+ reset,
372
+ setErrors,
373
+ };
374
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * createMenu - the HEADLESS core behind <SvMenuList> / <SvMenu>, in the same
3
+ * spirit as `createListbox`: a runes-based state machine for ONE menu level -
4
+ * roving focus over enabled items, submenu open/collapse, and the full WAI-ARIA
5
+ * menu keyboard contract (arrows, Home/End, Enter/Space, Escape, Tab, and
6
+ * rtl-aware ArrowLeft/Right) - with **prop-getters** you spread onto your own
7
+ * markup. No styles, no DOM assumptions.
8
+ *
9
+ * A menu tree is recursive, so you create one core per nesting level (exactly
10
+ * what the recursive <SvMenuList> does). The styled component is just one
11
+ * renderer over this core.
12
+ *
13
+ * ```svelte
14
+ * <script lang="ts">
15
+ * import { createMenu, type MenuItem } from '@svgrid/grid'
16
+ * let listEl = $state<HTMLElement | null>(null)
17
+ * const menu = createMenu({
18
+ * items: () => items,
19
+ * onSelect: (it) => run(it),
20
+ * onClose: () => close(),
21
+ * focusItem: (i) => queueMicrotask(() => listEl?.querySelector(`[data-mi="${i}"]`)?.focus()),
22
+ * })
23
+ * </script>
24
+ * <div bind:this={listEl} {...menu.listProps()}>
25
+ * {#each items as item, i}
26
+ * <button {...menu.itemProps(i)}>{item.label}</button>
27
+ * {/each}
28
+ * </div>
29
+ * ```
30
+ */
31
+ import type { MenuItem } from './menu-item';
32
+ import type { EditorDir } from './editor-contract';
33
+ /** Reactive inputs are getters so the core tracks live prop changes (the same
34
+ * controlled pattern as `createListbox`). */
35
+ export type MenuConfig = {
36
+ items: () => ReadonlyArray<MenuItem>;
37
+ /** Report the chosen leaf item (a non-parent menuitem). */
38
+ onSelect: (item: MenuItem) => void;
39
+ /** Close the WHOLE menu tree - a leaf was chosen, or Escape / Tab / dismissal. */
40
+ onClose: () => void;
41
+ /** This level is a submenu: enables ArrowLeft (or ArrowRight under rtl) to
42
+ * collapse back into the opener. The root level has nowhere to collapse. */
43
+ submenu?: () => boolean;
44
+ /** Collapse just THIS submenu level and refocus the item that opened it. */
45
+ onCollapse?: () => void;
46
+ /** Text direction; under `rtl` the open/collapse arrow keys swap. */
47
+ dir?: () => EditorDir | undefined;
48
+ /** DOM focus hook, invoked ONLY on keyboard navigation (never on hover) so the
49
+ * core stays DOM-free. Receives the item index that should take focus. */
50
+ focusItem?: (index: number) => void;
51
+ };
52
+ export type MenuItemProps = {
53
+ role: 'menuitem';
54
+ 'data-mi': number;
55
+ tabindex: 0 | -1;
56
+ 'aria-haspopup': 'menu' | undefined;
57
+ 'aria-expanded': boolean | undefined;
58
+ 'aria-disabled': true | undefined;
59
+ disabled: boolean | undefined;
60
+ onkeydown: (event: KeyboardEvent) => void;
61
+ onpointerenter: () => void;
62
+ onclick: () => void;
63
+ };
64
+ export declare function createMenu(config: MenuConfig): {
65
+ readonly active: number;
66
+ readonly openSub: number;
67
+ /** Enabled (focusable) item indices. */
68
+ readonly focusables: number[];
69
+ isActive: (i: number) => boolean;
70
+ isSubOpen: (i: number) => boolean;
71
+ itemTabIndex: (i: number) => 0 | -1;
72
+ move: (delta: number) => void;
73
+ first: () => void;
74
+ last: () => void;
75
+ /** Highlight + DOM-focus item `i` (e.g. to refocus a submenu's opener). */
76
+ focus: (i: number) => void;
77
+ hover: (i: number) => void;
78
+ choose: (item: MenuItem) => void;
79
+ onItemKeydown: (e: KeyboardEvent, i: number) => void;
80
+ /** Spread onto the menu container element. */
81
+ listProps: () => {
82
+ role: "menu";
83
+ };
84
+ /** Spread onto the menuitem element at `i`. */
85
+ itemProps: (i: number) => MenuItemProps;
86
+ };
87
+ export type Menu = ReturnType<typeof createMenu>;
88
+ export type { MenuItem };
@@ -0,0 +1,153 @@
1
+ import { enabledIndices, wrapMove } from './list-nav';
2
+ let uid = 0;
3
+ export function createMenu(config) {
4
+ const items = () => config.items();
5
+ const submenu = () => config.submenu?.() ?? false;
6
+ const rtl = () => (config.dir?.() ?? 'ltr') === 'rtl';
7
+ // -1 = nothing focused yet (the first enabled item is the tab stop).
8
+ let active = $state(-1);
9
+ let openSub = $state(-1);
10
+ // Real (non-separator, non-disabled) item indices, for roving focus.
11
+ const focusables = $derived(enabledIndices(items().length, (i) => {
12
+ const it = items()[i];
13
+ return !it || it.separator === true || it.disabled === true;
14
+ }));
15
+ /** Move focus to item `i` (keyboard): highlight it, close any open submenu at
16
+ * this level, and drive real DOM focus through the host's hook. */
17
+ function focus(i) {
18
+ active = i;
19
+ openSub = -1;
20
+ config.focusItem?.(i);
21
+ }
22
+ function move(delta) {
23
+ const next = wrapMove(focusables, active, delta);
24
+ if (next >= 0)
25
+ focus(next);
26
+ }
27
+ function first() {
28
+ const f = focusables[0];
29
+ if (f != null)
30
+ focus(f);
31
+ }
32
+ function last() {
33
+ const l = focusables.at(-1);
34
+ if (l != null)
35
+ focus(l);
36
+ }
37
+ /** Hover highlight: sets active WITHOUT stealing DOM focus, and opens a parent
38
+ * item's submenu (mirrors the pointerenter behaviour). */
39
+ function hover(i) {
40
+ const it = items()[i];
41
+ if (!it || it.disabled || it.separator)
42
+ return;
43
+ active = i;
44
+ openSub = it.children?.length ? i : -1;
45
+ }
46
+ function choose(item) {
47
+ if (item.disabled || item.separator)
48
+ return;
49
+ if (item.children?.length) {
50
+ openSub = items().indexOf(item);
51
+ return;
52
+ }
53
+ item.onSelect?.();
54
+ config.onSelect(item);
55
+ config.onClose();
56
+ }
57
+ function onItemKeydown(e, i) {
58
+ const item = items()[i];
59
+ // Open this item's submenu (ArrowRight, or ArrowLeft under rtl).
60
+ const openThis = () => {
61
+ if (item?.children?.length) {
62
+ e.preventDefault();
63
+ openSub = i;
64
+ }
65
+ };
66
+ // Collapse just THIS list back into its parent (opposite key under rtl).
67
+ const collapseThis = () => {
68
+ if (submenu()) {
69
+ e.preventDefault();
70
+ config.onCollapse?.();
71
+ }
72
+ };
73
+ switch (e.key) {
74
+ case 'ArrowDown':
75
+ e.preventDefault();
76
+ move(1);
77
+ break;
78
+ case 'ArrowUp':
79
+ e.preventDefault();
80
+ move(-1);
81
+ break;
82
+ case 'Home':
83
+ e.preventDefault();
84
+ first();
85
+ break;
86
+ case 'End':
87
+ e.preventDefault();
88
+ last();
89
+ break;
90
+ case 'ArrowRight':
91
+ (rtl() ? collapseThis : openThis)();
92
+ break;
93
+ case 'ArrowLeft':
94
+ (rtl() ? openThis : collapseThis)();
95
+ break;
96
+ case 'Enter':
97
+ case ' ':
98
+ e.preventDefault();
99
+ if (item)
100
+ choose(item);
101
+ break;
102
+ case 'Escape':
103
+ e.preventDefault();
104
+ config.onClose();
105
+ break;
106
+ // Tab leaves the menu entirely (WAI-ARIA menu-button pattern): close the
107
+ // whole tree rather than trapping focus inside a portalled panel.
108
+ case 'Tab':
109
+ config.onClose();
110
+ break;
111
+ }
112
+ }
113
+ function itemTabIndex(i) {
114
+ return active === i || (active === -1 && i === focusables[0]) ? 0 : -1;
115
+ }
116
+ return {
117
+ get active() { return active; },
118
+ get openSub() { return openSub; },
119
+ /** Enabled (focusable) item indices. */
120
+ get focusables() { return focusables; },
121
+ isActive: (i) => i === active,
122
+ isSubOpen: (i) => i === openSub,
123
+ itemTabIndex,
124
+ move,
125
+ first,
126
+ last,
127
+ /** Highlight + DOM-focus item `i` (e.g. to refocus a submenu's opener). */
128
+ focus,
129
+ hover,
130
+ choose,
131
+ onItemKeydown,
132
+ /** Spread onto the menu container element. */
133
+ listProps: () => ({ role: 'menu' }),
134
+ /** Spread onto the menuitem element at `i`. */
135
+ itemProps: (i) => {
136
+ const it = items()[i];
137
+ const hasKids = !!it?.children?.length;
138
+ return {
139
+ role: 'menuitem',
140
+ 'data-mi': i,
141
+ tabindex: itemTabIndex(i),
142
+ 'aria-haspopup': hasKids ? 'menu' : undefined,
143
+ 'aria-expanded': hasKids ? openSub === i : undefined,
144
+ 'aria-disabled': it?.disabled ? true : undefined,
145
+ disabled: it?.disabled,
146
+ onkeydown: (e) => onItemKeydown(e, i),
147
+ onpointerenter: () => hover(i),
148
+ onclick: () => { if (it)
149
+ choose(it); },
150
+ };
151
+ },
152
+ };
153
+ }