@shikiform/hooks 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @shikiform/hooks
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Headless hooks for query tables, array tables, shadow drafts, and lazy inputs.
4
+
5
+ ```bash
6
+ npm i @shikiform/hooks
7
+ ```
8
+
9
+ Peer dependencies: `react` and `react-dom` (`^18 || ^19`). Depends on `@shikiform/react`.
@@ -0,0 +1,670 @@
1
+ import { useState, useRef, useCallback, useEffect, useMemo, useContext } from 'react';
2
+ import { joinPath, engineOf, normalizePath, ShikiUsageError, parentPath, createForm } from '@shikiform/core/internal';
3
+ import { useScope, useFieldGroupRegistration, useArrayAt, useRequiredForm, FormContext, ArrayContext, resolveName } from '@shikiform/react/internal';
4
+
5
+ // src/use-array-table.ts
6
+ function useArrayTable(name, options = {}) {
7
+ const path = joinPath(useScope().path, name);
8
+ useFieldGroupRegistration(path);
9
+ return useArrayTableAt(path, options);
10
+ }
11
+ function useArrayTableAt(path, options = {}) {
12
+ return useArrayTableOver(path, useArrayAt(path, options.rowKey), options);
13
+ }
14
+ function useArrayTableOver(path, array, options = {}) {
15
+ const form = useRequiredForm(`useArrayTable('${path}') / <ArrayField component={[ArrayTable]}>`);
16
+ const rows = array.keys;
17
+ const paging = options.pagination === false ? null : options.pagination ?? {};
18
+ const server = !!paging && paging.total !== void 0;
19
+ const [local, setLocal] = useState({ page: paging?.current ?? 1, pageSize: paging?.pageSize ?? 10 });
20
+ const pageSize = paging ? server ? paging.pageSize ?? local.pageSize : local.pageSize : Math.max(rows.length, 1);
21
+ const total = server ? paging.total : rows.length;
22
+ const pageCount = Math.max(1, Math.ceil(total / pageSize));
23
+ const rawPage = paging ? server ? paging.current ?? local.page : local.page : 1;
24
+ const page = server ? rawPage : Math.min(Math.max(1, rawPage), pageCount);
25
+ const start = paging && !server ? (page - 1) * pageSize : 0;
26
+ const slice = paging && !server ? rows.slice(start, start + pageSize) : rows;
27
+ const offset = server ? (page - 1) * pageSize : 0;
28
+ const pageRows = slice.map((row) => ({ ...row, position: offset + row.index + 1 }));
29
+ const showPager = !!paging && !((paging.hideOnSinglePage ?? true) && total <= pageSize);
30
+ const optionsRef = useRef(options);
31
+ optionsRef.current = options;
32
+ const record = useCallback((index) => form.getValue(`${path}.${index}`), [form, path]);
33
+ const isExpandable = useCallback(
34
+ (index) => {
35
+ const test = optionsRef.current.rowExpandable;
36
+ return test ? !!test(record(index), index) : true;
37
+ },
38
+ [record]
39
+ );
40
+ const [ownSelected, setOwnSelected] = useState([]);
41
+ const controlled = options.selectedKeys !== void 0;
42
+ const selectedKeys = controlled ? options.selectedKeys : ownSelected;
43
+ const selectedRef = useRef(selectedKeys);
44
+ selectedRef.current = selectedKeys;
45
+ const setSelectedKeys = useCallback((next) => {
46
+ const value = typeof next === "function" ? next(selectedRef.current) : next;
47
+ selectedRef.current = value;
48
+ if (optionsRef.current.selectedKeys === void 0) setOwnSelected(value);
49
+ optionsRef.current.onSelectionChange?.(value);
50
+ }, []);
51
+ const [expandedKeys, setExpandedKeys] = useState([]);
52
+ const [removing, setRemoving] = useState([]);
53
+ const pageKeys = pageRows.map((row) => row.key);
54
+ const pageSignature = `${page}:${pageSize}`;
55
+ const lastPage = useRef(pageSignature);
56
+ useEffect(() => {
57
+ const changed = lastPage.current !== pageSignature;
58
+ lastPage.current = pageSignature;
59
+ if (changed && !optionsRef.current.preserveSelection && selectedRef.current.length) setSelectedKeys([]);
60
+ if (optionsRef.current.defaultExpandAll) {
61
+ setExpandedKeys(pageRows.filter((row) => isExpandable(row.index)).map((row) => row.key));
62
+ } else if (changed) setExpandedKeys([]);
63
+ }, [pageSignature, pageKeys.join("|")]);
64
+ const setPage = useCallback(
65
+ (nextPage, nextSize) => {
66
+ const size = nextSize ?? pageSize;
67
+ const target = size !== pageSize ? 1 : nextPage;
68
+ setLocal({ page: target, pageSize: size });
69
+ optionsRef.current.pagination && optionsRef.current.pagination.onChange?.(target, size);
70
+ },
71
+ [pageSize]
72
+ );
73
+ return useMemo(() => {
74
+ const keyAt = (index) => rows[index]?.key;
75
+ return {
76
+ path,
77
+ rows,
78
+ pageRows,
79
+ record,
80
+ positionOf: (index) => offset + index + 1,
81
+ total,
82
+ page,
83
+ pageSize,
84
+ pageCount,
85
+ showPager,
86
+ setPage,
87
+ selectedKeys,
88
+ setSelectedKeys,
89
+ toggleSelected: (key) => setSelectedKeys((prev) => prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]),
90
+ selectPage: () => setSelectedKeys((prev) => unique([...prev, ...pageKeys])),
91
+ invertPage: () => setSelectedKeys((prev) => [...prev.filter((key) => !pageKeys.includes(key)), ...pageKeys.filter((key) => !prev.includes(key))]),
92
+ clearSelection: () => setSelectedKeys([]),
93
+ selectedRecords: () => rows.filter((row) => selectedKeys.includes(row.key)).map((row) => record(row.index)),
94
+ expandedKeys,
95
+ setExpandedKeys,
96
+ toggleExpanded: (key) => setExpandedKeys((prev) => prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]),
97
+ isExpandable,
98
+ removing,
99
+ remove: async (index) => {
100
+ const key = keyAt(index);
101
+ if (key === void 0) return false;
102
+ const hook = optionsRef.current.onRemove;
103
+ if (hook) {
104
+ setRemoving((prev) => [...prev, key]);
105
+ try {
106
+ await hook(index, record(index));
107
+ } catch {
108
+ return false;
109
+ } finally {
110
+ setRemoving((prev) => prev.filter((item) => item !== key));
111
+ }
112
+ }
113
+ const now = form.structureKeys(path, optionsRef.current.rowKey).find((row) => row.key === key);
114
+ if (!now) return false;
115
+ form.removeArray(path, now.index);
116
+ setSelectedKeys((prev) => prev.filter((item) => item !== key));
117
+ setExpandedKeys((prev) => prev.filter((item) => item !== key));
118
+ return true;
119
+ },
120
+ add: (row, addOptions) => {
121
+ const { rowKey, createRowKey } = optionsRef.current;
122
+ if (rowKey && createRowKey && isRecord(row) && row[rowKey] == null) {
123
+ const rest = { ...row };
124
+ delete rest[rowKey];
125
+ row = { ...rest, [rowKey]: createRowKey(rest) };
126
+ }
127
+ form.pushArray(path, row);
128
+ if (addOptions?.jump === false || !paging || server) return;
129
+ const count = form.structureKeys(path, optionsRef.current.rowKey).length;
130
+ setPage(Math.max(1, Math.ceil(count / pageSize)), pageSize);
131
+ },
132
+ copy: (index, transform) => {
133
+ const source = record(index);
134
+ let next = source && typeof source === "object" ? structuredClone(source) : source;
135
+ const { rowKey, createRowKey } = optionsRef.current;
136
+ if (rowKey && isRecord(next)) {
137
+ delete next[rowKey];
138
+ if (createRowKey) next = { ...next, [rowKey]: createRowKey(next) };
139
+ }
140
+ if (transform) next = transform(next, source);
141
+ form.insertArray(path, index + 1, next);
142
+ },
143
+ moveUp: (index) => {
144
+ if (index > 0) form.moveArray(path, index, index - 1);
145
+ },
146
+ moveDown: (index) => {
147
+ if (index < rows.length - 1) form.moveArray(path, index, index + 1);
148
+ },
149
+ move: (from, to) => form.moveArray(path, from, to)
150
+ };
151
+ }, [path, rows, pageRows.length, pageKeys.join("|"), page, pageSize, total, showPager, selectedKeys, expandedKeys, removing, record, isExpandable, setPage, form, server]);
152
+ }
153
+ function isRecord(value) {
154
+ return !!value && typeof value === "object" && !Array.isArray(value);
155
+ }
156
+ function unique(items) {
157
+ return [...new Set(items)];
158
+ }
159
+ function useColumnSettings(columns) {
160
+ const initial = useRef(columns);
161
+ const [state, setState] = useState(() => ({ order: columns.map((column) => column.key), hidden: hiddenOf(columns), widths: {}, density: "middle" }));
162
+ const known = columns.map((column) => column.key);
163
+ const order = [...state.order.filter((key) => known.includes(key)), ...known.filter((key) => !state.order.includes(key))];
164
+ const byKey = new Map(columns.map((column) => [column.key, column]));
165
+ const items = order.map((key) => ({
166
+ key,
167
+ title: byKey.get(key)?.title,
168
+ show: !state.hidden.includes(key),
169
+ width: state.widths[key] ?? byKey.get(key)?.width
170
+ }));
171
+ const toggle = useCallback(
172
+ (key) => setState((prev) => ({ ...prev, hidden: prev.hidden.includes(key) ? prev.hidden.filter((item) => item !== key) : [...prev.hidden, key] })),
173
+ []
174
+ );
175
+ const move = useCallback(
176
+ (from, to) => setState((prev) => {
177
+ const next = [...order];
178
+ const [item] = next.splice(from, 1);
179
+ if (item === void 0) return prev;
180
+ next.splice(Math.min(Math.max(to, 0), next.length), 0, item);
181
+ return { ...prev, order: next };
182
+ }),
183
+ [order.join("|")]
184
+ );
185
+ const setWidth = useCallback((key, width) => setState((prev) => ({ ...prev, widths: { ...prev.widths, [key]: Math.max(40, Math.round(width)) } })), []);
186
+ const setDensity = useCallback((density) => setState((prev) => ({ ...prev, density })), []);
187
+ const [drag, setDrag] = useState({ from: null, over: null });
188
+ const dragFrom = useRef(null);
189
+ const moveKey = useCallback(
190
+ (from, to) => {
191
+ const fromIndex = order.indexOf(from);
192
+ const toIndex = order.indexOf(to);
193
+ if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) return;
194
+ move(fromIndex, toIndex);
195
+ },
196
+ [order.join("|"), move]
197
+ );
198
+ const dragProps = (key) => ({
199
+ draggable: true,
200
+ ...drag.from === key ? { "data-dragging": "true" } : {},
201
+ ...drag.over === key && drag.from !== key ? { "data-drag-over": "true" } : {},
202
+ onDragStart: (event) => {
203
+ dragFrom.current = key;
204
+ event.dataTransfer?.setData?.("text/plain", key);
205
+ if (event.dataTransfer) event.dataTransfer.effectAllowed = "move";
206
+ setDrag({ from: key, over: null });
207
+ },
208
+ onDragOver: (event) => {
209
+ if (dragFrom.current === null) return;
210
+ event.preventDefault();
211
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
212
+ setDrag((prev) => prev.over === key ? prev : { from: dragFrom.current, over: key });
213
+ },
214
+ onDragLeave: () => setDrag((prev) => prev.over === key ? { ...prev, over: null } : prev),
215
+ onDrop: (event) => {
216
+ const from = dragFrom.current;
217
+ if (from === null) return;
218
+ event.preventDefault();
219
+ dragFrom.current = null;
220
+ setDrag({ from: null, over: null });
221
+ moveKey(from, key);
222
+ },
223
+ onDragEnd: () => {
224
+ dragFrom.current = null;
225
+ setDrag({ from: null, over: null });
226
+ }
227
+ });
228
+ const reset = useCallback(
229
+ () => setState({ order: initial.current.map((column) => column.key), hidden: hiddenOf(initial.current), widths: {}, density: "middle" }),
230
+ []
231
+ );
232
+ const stableApi = useMemo(
233
+ () => ({ items, visibleKeys: items.filter((item) => item.show).map((item) => item.key), toggle, move, moveKey, setWidth, density: state.density, setDensity, reset }),
234
+ [JSON.stringify(items.map(({ key, show, width }) => [key, show, width])), state.density, toggle, move, moveKey, setWidth, setDensity, reset]
235
+ );
236
+ return { ...stableApi, dragProps, drag };
237
+ }
238
+ function hiddenOf(columns) {
239
+ return columns.filter((column) => column.hidden).map((column) => column.key);
240
+ }
241
+ function useShadowFormOver(options = {}) {
242
+ const contextForm = useContext(FormContext);
243
+ const scope = useScope();
244
+ const arrayCtx = useContext(ArrayContext);
245
+ let boundHost = null;
246
+ let targetPath = "";
247
+ if (options.form !== void 0) {
248
+ boundHost = engineOf(options.form);
249
+ targetPath = options.name ? normalizePath(options.name) : "";
250
+ } else if (options.name !== void 0) {
251
+ if (!contextForm) {
252
+ if (process.env.NODE_ENV !== "production") {
253
+ throw new ShikiUsageError("useShadowForm({ name }) needs a surrounding <Form> or a `form` option.");
254
+ }
255
+ throw new Error("useShadowForm({ name }) needs a surrounding <Form> or a `form` option");
256
+ }
257
+ boundHost = contextForm;
258
+ targetPath = normalizePath(resolveName(boundHost, scope, normalizePath(options.name)));
259
+ } else if (contextForm && scope.path !== "") {
260
+ boundHost = contextForm;
261
+ targetPath = normalizePath(scope.path);
262
+ }
263
+ const isAdd = options.add !== void 0 && options.add !== false;
264
+ if (isAdd && (!boundHost || !targetPath)) {
265
+ if (process.env.NODE_ENV !== "production") {
266
+ throw new ShikiUsageError(
267
+ "useShadowForm({ add }) needs a bound array path (`name` inside <Form>, `form` + `name`, or an enclosing scope)."
268
+ );
269
+ }
270
+ throw new Error("useShadowForm({ add }) needs a bound array path");
271
+ }
272
+ const targetParent = targetPath ? parentPath(targetPath) : null;
273
+ const resolvedRowKey = options.rowKey ?? (targetParent !== null && targetParent === arrayCtx?.path ? arrayCtx.rowKey : void 0);
274
+ const optionsRef = useRef(options);
275
+ optionsRef.current = options;
276
+ const bindingRef = useRef({ host: boundHost, targetPath, isAdd, rowKey: resolvedRowKey });
277
+ bindingRef.current = { host: boundHost, targetPath, isAdd, rowKey: resolvedRowKey };
278
+ const snapshotTarget = useCallback(() => {
279
+ const { host, targetPath: path, isAdd: addMode, rowKey } = bindingRef.current;
280
+ if (!host) return null;
281
+ if (addMode) return { kind: "add", host, arrayPath: path };
282
+ const parent = path ? parentPath(path) : null;
283
+ const last = parent === null ? path : path.slice(parent.length + 1);
284
+ if (parent !== null && /^\d+$/.test(last) && Array.isArray(host.getValue(parent))) {
285
+ const index = Number(last);
286
+ const key = host.structureKeys(parent, rowKey)[index]?.key;
287
+ return { kind: "row", host, arrayPath: parent, key, rowKey };
288
+ }
289
+ return { kind: "object", host, path };
290
+ }, []);
291
+ const build = useCallback((explicitInit, hasExplicitInit) => {
292
+ const current = optionsRef.current;
293
+ const { host, targetPath: path, isAdd: addMode } = bindingRef.current;
294
+ const forked = host ? host.forkOptions(addMode ? `${path}.*` : path) : void 0;
295
+ let initialValues;
296
+ if (hasExplicitInit) {
297
+ initialValues = explicitInit;
298
+ } else if (addMode) {
299
+ if (typeof current.add === "object" && current.add !== null) {
300
+ initialValues = clonePlain(current.add);
301
+ } else if (current.initialValues !== void 0) {
302
+ initialValues = clonePlain(current.initialValues);
303
+ } else {
304
+ initialValues = {};
305
+ }
306
+ } else if (current.initialValues !== void 0) {
307
+ initialValues = clonePlain(current.initialValues);
308
+ } else {
309
+ initialValues = forked?.initialValues;
310
+ }
311
+ const fields = mergeFields(
312
+ forked?.fields,
313
+ current.fields
314
+ );
315
+ const trees = forked?.trees || current.formOptions?.trees ? { ...forked?.trees, ...current.formOptions?.trees } : void 0;
316
+ const messages = forked?.messages || current.formOptions?.messages ? { ...forked?.messages, ...current.formOptions?.messages } : void 0;
317
+ return createForm({
318
+ ...forked,
319
+ ...current.formOptions,
320
+ ...messages ? { messages } : {},
321
+ ...trees ? { trees } : {},
322
+ initialValues,
323
+ ...fields ? { fields } : {},
324
+ effects: current.effects
325
+ });
326
+ }, []);
327
+ const [state, setState] = useState(() => ({
328
+ form: build(void 0, false),
329
+ visible: false,
330
+ loading: false,
331
+ submitting: false,
332
+ context: void 0,
333
+ target: null
334
+ }));
335
+ const stateRef = useRef(state);
336
+ stateRef.current = state;
337
+ const seq = useRef(0);
338
+ const open = useCallback(
339
+ async (init, context) => {
340
+ const ticket = ++seq.current;
341
+ const target = snapshotTarget();
342
+ if (typeof init === "function") {
343
+ setState((prev) => ({
344
+ ...prev,
345
+ visible: true,
346
+ loading: true,
347
+ submitting: false,
348
+ context,
349
+ target,
350
+ form: build({}, true)
351
+ }));
352
+ try {
353
+ const loaded = await init();
354
+ if (ticket !== seq.current) return;
355
+ setState((prev) => ({
356
+ ...prev,
357
+ loading: false,
358
+ form: build(clonePlain(loaded), loaded !== void 0)
359
+ }));
360
+ } catch (error) {
361
+ if (ticket !== seq.current) return;
362
+ setState((prev) => ({ ...prev, loading: false }));
363
+ throw error;
364
+ }
365
+ return;
366
+ }
367
+ setState({
368
+ visible: true,
369
+ loading: false,
370
+ submitting: false,
371
+ context,
372
+ target,
373
+ form: build(clonePlain(init), init !== void 0)
374
+ });
375
+ },
376
+ [build, snapshotTarget]
377
+ );
378
+ const cancel = useCallback(() => {
379
+ seq.current += 1;
380
+ const context = stateRef.current.context;
381
+ setState((prev) => ({ ...prev, visible: false, loading: false, submitting: false, context: void 0, target: null }));
382
+ optionsRef.current.onCancel?.(context);
383
+ }, []);
384
+ const confirm = useCallback(
385
+ async (onOk) => {
386
+ const { form, context, target } = stateRef.current;
387
+ const ticket = seq.current;
388
+ setState((prev) => ({ ...prev, submitting: true }));
389
+ try {
390
+ const result = await form.submit();
391
+ if (!result.ok) return { ok: false, errors: result.errors };
392
+ const first = await optionsRef.current.onOk?.(result.values, context);
393
+ const second = await onOk?.(result.values, context);
394
+ if (first !== false && second !== false && target) {
395
+ writeBack(target, result.values, optionsRef.current.merge, optionsRef.current.append);
396
+ }
397
+ if (ticket === seq.current) {
398
+ seq.current += 1;
399
+ setState((prev) => ({ ...prev, visible: false, submitting: false, context: void 0, target: null }));
400
+ }
401
+ return { ok: true, values: result.values };
402
+ } finally {
403
+ setState((prev) => prev.submitting ? { ...prev, submitting: false } : prev);
404
+ }
405
+ },
406
+ []
407
+ );
408
+ const { target: _target, ...publicState } = state;
409
+ return { ...publicState, open, confirm, cancel };
410
+ }
411
+ function useShadowForm(options = {}) {
412
+ const { name, form, add, rowKey, merge, initialValues, fields, effects, formOptions, onOk, onCancel } = options;
413
+ return useShadowFormOver({
414
+ name,
415
+ form,
416
+ add,
417
+ rowKey,
418
+ merge,
419
+ initialValues,
420
+ fields,
421
+ effects,
422
+ formOptions,
423
+ onOk,
424
+ onCancel
425
+ });
426
+ }
427
+ function writeBack(target, values, merge, append) {
428
+ if (target.kind === "add") {
429
+ if (append) append(values);
430
+ else target.host.pushArray(target.arrayPath, values);
431
+ return;
432
+ }
433
+ if (target.kind === "row") {
434
+ const found = target.key !== void 0 ? target.host.structureKeys(target.arrayPath, target.rowKey).find((item) => item.key === target.key) : void 0;
435
+ if (!found) {
436
+ if (process.env.NODE_ENV !== "production") {
437
+ console.warn(
438
+ `[shikiform] Shadow form row in "${target.arrayPath}" was removed before confirm; skipping write-back.`
439
+ );
440
+ }
441
+ return;
442
+ }
443
+ const current2 = target.host.getValue(`${target.arrayPath}.${found.index}`);
444
+ const next2 = merge ? merge(current2, values) : shallowMergePlain(current2, values);
445
+ target.host.replaceArray(target.arrayPath, found.index, next2);
446
+ return;
447
+ }
448
+ const current = target.host.getValue(target.path);
449
+ const next = merge ? merge(current, values) : shallowMergePlain(current, values);
450
+ if (target.path === "" && isPlainObject(next)) {
451
+ target.host.batch(() => {
452
+ for (const [key, value] of Object.entries(next)) target.host.setValue(key, value);
453
+ });
454
+ return;
455
+ }
456
+ target.host.setValue(target.path, next);
457
+ }
458
+ function mergeFields(base, override) {
459
+ if (!base && !override) return void 0;
460
+ if (!base) return override;
461
+ if (!override) return base;
462
+ const out = { ...base };
463
+ for (const [key, spec] of Object.entries(override)) {
464
+ if (spec !== void 0) out[key] = out[key] ? { ...out[key], ...spec } : spec;
465
+ }
466
+ return out;
467
+ }
468
+ function isPlainObject(value) {
469
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
470
+ const proto = Object.getPrototypeOf(value);
471
+ return proto === Object.prototype || proto === null;
472
+ }
473
+ function shallowMergePlain(current, values) {
474
+ if (isPlainObject(current) && isPlainObject(values)) {
475
+ return { ...current, ...values };
476
+ }
477
+ return values;
478
+ }
479
+ function clonePlain(value) {
480
+ if (value === void 0 || value === null) return value;
481
+ try {
482
+ return structuredClone(value);
483
+ } catch {
484
+ return JSON.parse(JSON.stringify(value));
485
+ }
486
+ }
487
+ function useSuggestion(options) {
488
+ const fetchRef = useRef(options.fetch);
489
+ fetchRef.current = options.fetch;
490
+ const debounce = options.debounce ?? 300;
491
+ const minLength = options.minLength ?? 1;
492
+ const [state, setState] = useState({
493
+ keyword: "",
494
+ options: [],
495
+ loading: false,
496
+ error: void 0
497
+ });
498
+ const remembered = useRef(/* @__PURE__ */ new Map());
499
+ const timer = useRef(null);
500
+ const abort = useRef(null);
501
+ const seq = useRef(0);
502
+ useEffect(
503
+ () => () => {
504
+ if (timer.current) clearTimeout(timer.current);
505
+ abort.current?.abort();
506
+ },
507
+ []
508
+ );
509
+ const search = useCallback(
510
+ (keyword) => {
511
+ const ticket = ++seq.current;
512
+ if (timer.current) clearTimeout(timer.current);
513
+ abort.current?.abort();
514
+ abort.current = null;
515
+ if (keyword.length < minLength) {
516
+ setState({ keyword, options: [], loading: false, error: void 0 });
517
+ return;
518
+ }
519
+ setState((prev) => ({ ...prev, keyword, loading: true, error: void 0 }));
520
+ timer.current = setTimeout(() => {
521
+ const controller = new AbortController();
522
+ abort.current = controller;
523
+ Promise.resolve(fetchRef.current(keyword, { signal: controller.signal })).then(
524
+ (list) => {
525
+ if (ticket !== seq.current) return;
526
+ setState({ keyword, options: list.slice(), loading: false, error: void 0 });
527
+ },
528
+ (error) => {
529
+ if (ticket !== seq.current) return;
530
+ setState((prev) => ({ ...prev, loading: false, error }));
531
+ }
532
+ );
533
+ }, debounce);
534
+ },
535
+ [debounce, minLength]
536
+ );
537
+ const remember = useCallback((picked) => {
538
+ for (const option of picked) remembered.current.set(keyOf(option.value), option);
539
+ }, []);
540
+ const merged = [...state.options];
541
+ for (const option of remembered.current.values()) {
542
+ if (!merged.some((item) => keyOf(item.value) === keyOf(option.value))) merged.push(option);
543
+ }
544
+ const labelOf = (value) => merged.find((item) => keyOf(item.value) === keyOf(value))?.label;
545
+ return { ...state, options: merged, search, remember, labelOf };
546
+ }
547
+ function keyOf(value) {
548
+ return typeof value === "string" ? value : JSON.stringify(value);
549
+ }
550
+ function useLazyCascader(options) {
551
+ const loadRef = useRef(options.load);
552
+ loadRef.current = options.load;
553
+ const tree = useRef([]);
554
+ const pending = useRef(/* @__PURE__ */ new Map());
555
+ const [version, setVersion] = useState(0);
556
+ const [loading, setLoading] = useState(false);
557
+ const bump = () => setVersion((v) => v + 1);
558
+ const loadChildren = useCallback(async (path) => {
559
+ const node = find(tree.current, path);
560
+ if (!node || node.isLeaf || node.children) return;
561
+ const id = JSON.stringify(path);
562
+ const existing = pending.current.get(id);
563
+ if (existing) return existing;
564
+ node.loading = true;
565
+ bump();
566
+ const task = Promise.resolve(loadRef.current(path)).then((children) => {
567
+ node.children = children.map((child) => ({ ...child }));
568
+ if (!children.length) node.isLeaf = true;
569
+ }).finally(() => {
570
+ node.loading = false;
571
+ pending.current.delete(id);
572
+ tree.current = [...tree.current];
573
+ bump();
574
+ });
575
+ pending.current.set(id, task);
576
+ return task;
577
+ }, []);
578
+ const rootReady = useRef(null);
579
+ const ensure = useCallback(
580
+ async (paths) => {
581
+ if (rootReady.current) await rootReady.current;
582
+ await Promise.all(
583
+ paths.map(async (path) => {
584
+ for (let depth = 1; depth < path.length; depth++) await loadChildren(path.slice(0, depth));
585
+ })
586
+ );
587
+ },
588
+ [loadChildren]
589
+ );
590
+ const pathsRef = useRef(options.paths);
591
+ pathsRef.current = options.paths;
592
+ const enabled = options.enabled !== false;
593
+ useEffect(() => {
594
+ if (!enabled) return;
595
+ let live = true;
596
+ setLoading(true);
597
+ rootReady.current = Promise.resolve(loadRef.current([])).then((root) => {
598
+ if (!live) return;
599
+ tree.current = root.map((node) => clone(node));
600
+ bump();
601
+ });
602
+ rootReady.current.then(() => live && pathsRef.current?.length ? ensure(pathsRef.current) : void 0).finally(() => {
603
+ if (live) setLoading(false);
604
+ });
605
+ return () => {
606
+ live = false;
607
+ };
608
+ }, [enabled]);
609
+ return {
610
+ options: tree.current,
611
+ loading,
612
+ loadChildren,
613
+ ensure,
614
+ labelsOf: (path) => {
615
+ const labels = [];
616
+ let level = tree.current;
617
+ for (const value of path) {
618
+ const node = level?.find((item) => item.value == value);
619
+ if (!node) break;
620
+ labels.push(node.label);
621
+ level = node.children;
622
+ }
623
+ return labels;
624
+ }
625
+ };
626
+ }
627
+ function find(tree, path) {
628
+ let level = tree;
629
+ let node;
630
+ for (const value of path) {
631
+ node = level?.find((item) => item.value == value);
632
+ if (!node) return void 0;
633
+ level = node.children;
634
+ }
635
+ return node;
636
+ }
637
+ function clone(node) {
638
+ return { ...node, children: node.children?.map(clone) };
639
+ }
640
+ function cascaderPaths(value, multiple) {
641
+ if (!Array.isArray(value) || !value.length) return [];
642
+ const unwrap = (path) => path.map((item) => item && typeof item === "object" ? item.value : item);
643
+ return multiple ? value.filter(Array.isArray).map((path) => unwrap(path)) : [unwrap(value)];
644
+ }
645
+ function useCascaderLabels(options) {
646
+ const list = !Array.isArray(options.value) || !options.value.length ? [] : options.multiple ? options.value.filter(Array.isArray) : [options.value];
647
+ const labeled = (item) => !!item && typeof item === "object" && typeof item.label === "string";
648
+ const needsTree = !!options.load && list.some((path) => path.some((item) => !labeled(item)));
649
+ const paths = cascaderPaths(options.value, options.multiple);
650
+ const tree = useLazyCascader({ load: options.load ?? (() => []), paths, enabled: needsTree });
651
+ const key = JSON.stringify(paths);
652
+ const seen = useRef(key);
653
+ useEffect(() => {
654
+ if (!needsTree || key === seen.current) return;
655
+ seen.current = key;
656
+ void tree.ensure(paths);
657
+ });
658
+ const labels = list.map((path, index) => {
659
+ const loaded = needsTree ? tree.labelsOf(paths[index]) : [];
660
+ return path.map((item, depth) => {
661
+ if (labeled(item)) return item.label;
662
+ return loaded[depth] ?? String(item && typeof item === "object" ? item.value : item);
663
+ });
664
+ });
665
+ return { labels, loading: needsTree && tree.loading };
666
+ }
667
+
668
+ export { cascaderPaths, useArrayTable, useArrayTableOver, useCascaderLabels, useColumnSettings, useLazyCascader, useShadowForm, useShadowFormOver, useSuggestion };
669
+ //# sourceMappingURL=chunk-ODAZS5QS.js.map
670
+ //# sourceMappingURL=chunk-ODAZS5QS.js.map