@gridkitjs/forms-dom 0.0.0-dev-20261206092422

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/dist/index.js ADDED
@@ -0,0 +1,2326 @@
1
+ // src/announcer.ts
2
+ var NO_BREAK_SPACE = String.fromCodePoint(160);
3
+ function createLiveAnnouncer(container = document.body, options = {}) {
4
+ const region = document.createElement("div");
5
+ region.className = options.className ?? "gridkit-forms-sr-only";
6
+ region.setAttribute("role", "status");
7
+ region.setAttribute("aria-live", "polite");
8
+ container.append(region);
9
+ let last = "";
10
+ let padded = false;
11
+ return {
12
+ announce(text) {
13
+ padded = text === last && !padded;
14
+ last = text;
15
+ region.textContent = padded ? text + NO_BREAK_SPACE : text;
16
+ },
17
+ destroy() {
18
+ region.remove();
19
+ }
20
+ };
21
+ }
22
+
23
+ // src/form/attachFocusGroup.ts
24
+ function attachFocusGroup(root, initialOptions) {
25
+ let options = initialOptions;
26
+ let tabbing = false;
27
+ let away = null;
28
+ const listeners = new AbortController();
29
+ const { signal } = listeners;
30
+ const isInside = (node) => root.contains(node) || options.isInside?.(node) === true;
31
+ function comeHome() {
32
+ away?.abort();
33
+ away = null;
34
+ }
35
+ function onKeyDown(event) {
36
+ tabbing = event.key === "Tab" && !event.defaultPrevented;
37
+ }
38
+ function onPointerDown() {
39
+ tabbing = false;
40
+ }
41
+ function goAway() {
42
+ if (away !== null) {
43
+ return;
44
+ }
45
+ away = new AbortController();
46
+ const document2 = root.ownerDocument;
47
+ document2.addEventListener(
48
+ "focusin",
49
+ (event) => {
50
+ const { target } = event;
51
+ if (!(target instanceof Node)) {
52
+ return;
53
+ }
54
+ if (root.contains(target)) {
55
+ comeHome();
56
+ return;
57
+ }
58
+ if (isInside(target)) {
59
+ return;
60
+ }
61
+ const by = tabbing ? "tab" : "blur";
62
+ tabbing = false;
63
+ comeHome();
64
+ options.onLeave(by, event);
65
+ },
66
+ { signal: away.signal }
67
+ );
68
+ document2.addEventListener(
69
+ "keydown",
70
+ (event) => {
71
+ if (event.target instanceof Node && !root.contains(event.target)) {
72
+ onKeyDown(event);
73
+ }
74
+ },
75
+ { signal: away.signal }
76
+ );
77
+ document2.addEventListener("pointerdown", onPointerDown, {
78
+ signal: away.signal
79
+ });
80
+ }
81
+ root.addEventListener("keydown", onKeyDown, { signal });
82
+ root.addEventListener("pointerdown", onPointerDown, { signal });
83
+ root.addEventListener(
84
+ "focusout",
85
+ (event) => {
86
+ const by = tabbing ? "tab" : "blur";
87
+ tabbing = false;
88
+ const next = event.relatedTarget;
89
+ if (next instanceof Node && root.contains(next)) {
90
+ return;
91
+ }
92
+ if (next instanceof Node && isInside(next)) {
93
+ goAway();
94
+ return;
95
+ }
96
+ options.onLeave(by, event);
97
+ },
98
+ { signal }
99
+ );
100
+ return {
101
+ setOptions: (next) => {
102
+ options = next;
103
+ },
104
+ detach: () => {
105
+ listeners.abort();
106
+ comeHome();
107
+ }
108
+ };
109
+ }
110
+
111
+ // src/form/formControls.ts
112
+ var ENTER_MOVES_FROM = /* @__PURE__ */ new Set([
113
+ "text",
114
+ "search",
115
+ "email",
116
+ "tel",
117
+ "url",
118
+ "password",
119
+ "number",
120
+ "checkbox"
121
+ ]);
122
+ var NOT_EDITABLE = /* @__PURE__ */ new Set(["hidden", "button", "submit", "reset", "image"]);
123
+ function isFormControl(element) {
124
+ return element.localName === "input" || element.localName === "select" || element.localName === "textarea";
125
+ }
126
+ function controlsOf(form) {
127
+ return [...form.elements].filter(isFormControl);
128
+ }
129
+ function findFirstInvalidControl(form) {
130
+ return controlsOf(form).find(
131
+ (control) => control.willValidate && !control.validity.valid
132
+ ) ?? null;
133
+ }
134
+ function focusTargetIn(target) {
135
+ if (isFormControl(target) || target.matches("button, [tabindex]")) {
136
+ return target;
137
+ }
138
+ return target.querySelector(
139
+ "input:not([type=hidden]), select, textarea, button, [tabindex]"
140
+ );
141
+ }
142
+ function canMoveTo(control) {
143
+ if (control instanceof HTMLInputElement && NOT_EDITABLE.has(control.type)) {
144
+ return false;
145
+ }
146
+ const readOnly = "readOnly" in control && control.readOnly || control.getAttribute("aria-readonly") === "true";
147
+ return !control.disabled && !readOnly && control.getClientRects().length > 0;
148
+ }
149
+ function attachEnterNavigation(form) {
150
+ function onKeyDown(event) {
151
+ const { target } = event;
152
+ if (event.key !== "Enter" || event.defaultPrevented || event.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !(target instanceof HTMLInputElement) || !ENTER_MOVES_FROM.has(target.type)) {
153
+ return;
154
+ }
155
+ event.preventDefault();
156
+ const controls = controlsOf(form);
157
+ const next = controls.slice(controls.indexOf(target) + 1).find((control) => canMoveTo(control));
158
+ if (next === void 0) {
159
+ form.requestSubmit();
160
+ } else {
161
+ next.focus();
162
+ }
163
+ }
164
+ form.addEventListener("keydown", onKeyDown);
165
+ return {
166
+ detach: () => {
167
+ form.removeEventListener("keydown", onKeyDown);
168
+ }
169
+ };
170
+ }
171
+ function compareDocumentOrder(a, b) {
172
+ if (a === b) {
173
+ return 0;
174
+ }
175
+ return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
176
+ }
177
+
178
+ // src/layout/attachFitCount.ts
179
+ function pixels(value) {
180
+ const parsed = Number.parseFloat(value);
181
+ return Number.isNaN(parsed) ? 0 : parsed;
182
+ }
183
+ function attachFitCount(root, { max, onCount }) {
184
+ let count = null;
185
+ const container = root.parentElement;
186
+ function measure() {
187
+ const item = root.firstElementChild;
188
+ if (container === null || !(item instanceof HTMLElement)) {
189
+ return;
190
+ }
191
+ const gap = pixels(getComputedStyle(root).columnGap);
192
+ const room = container.clientWidth;
193
+ const width = item.offsetWidth;
194
+ const fits = width === 0 ? max : Math.floor((room + gap) / (width + gap));
195
+ const next = Math.min(Math.max(fits, 1), max);
196
+ if (next !== count) {
197
+ count = next;
198
+ onCount(next);
199
+ }
200
+ }
201
+ const observer = new ResizeObserver(measure);
202
+ if (container !== null) {
203
+ observer.observe(container);
204
+ }
205
+ if (root.firstElementChild !== null) {
206
+ observer.observe(root.firstElementChild);
207
+ }
208
+ measure();
209
+ return {
210
+ detach: () => {
211
+ observer.disconnect();
212
+ }
213
+ };
214
+ }
215
+
216
+ // src/listbox/attachChecklist.ts
217
+ var ITEM = "[data-gridkit-checklist-item]";
218
+ var INDEX = "data-gridkit-checklist-index";
219
+ var SETTLED = { kind: "settled" };
220
+ var DETACHED = { kind: "detached" };
221
+ function indexOf(item) {
222
+ return Number(item.getAttribute(INDEX));
223
+ }
224
+ function attachChecklist(list, options) {
225
+ let count = 0;
226
+ let active = 0;
227
+ let state = SETTLED;
228
+ function items() {
229
+ return Array.from(list.querySelectorAll(ITEM));
230
+ }
231
+ function itemAt(index) {
232
+ return list.querySelector(
233
+ `${ITEM}[${INDEX}="${String(index)}"]`
234
+ );
235
+ }
236
+ function itemOf(target) {
237
+ const item = target instanceof Element ? target.closest(ITEM) : null;
238
+ return item !== null && list.contains(item) ? item : null;
239
+ }
240
+ function setTabStop() {
241
+ const all = items();
242
+ const stop = all.find((item) => indexOf(item) === active) ?? all[0];
243
+ for (const item of all) {
244
+ item.tabIndex = item === stop ? 0 : -1;
245
+ }
246
+ }
247
+ function makeActive(index) {
248
+ if (index !== active) {
249
+ active = index;
250
+ options.onFocusChange?.(index);
251
+ }
252
+ }
253
+ function moveTo(index) {
254
+ if (state.kind === "detached" || count === 0) {
255
+ return;
256
+ }
257
+ const target = Math.max(0, Math.min(index, count - 1));
258
+ makeActive(target);
259
+ setTabStop();
260
+ options.scrollToIndex(target);
261
+ const item = itemAt(target);
262
+ if (item === null) {
263
+ state = { kind: "awaiting-item", index: target };
264
+ } else {
265
+ state = SETTLED;
266
+ item.focus({ preventScroll: true });
267
+ }
268
+ }
269
+ function pageSize() {
270
+ const top = list.getBoundingClientRect().top + list.clientTop;
271
+ const bottom = top + list.clientHeight;
272
+ const whole = items().filter((item) => {
273
+ const box = item.getBoundingClientRect();
274
+ return box.top >= top && box.bottom <= bottom;
275
+ }).length;
276
+ return Math.max(1, whole);
277
+ }
278
+ function onKeyDown(event) {
279
+ const item = itemOf(event.target);
280
+ if (item === null || event.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
281
+ return;
282
+ }
283
+ switch (event.key) {
284
+ case "ArrowDown":
285
+ moveTo(active + 1);
286
+ break;
287
+ case "ArrowUp":
288
+ moveTo(active - 1);
289
+ break;
290
+ case "Home":
291
+ moveTo(0);
292
+ break;
293
+ case "End":
294
+ moveTo(count - 1);
295
+ break;
296
+ case "PageDown":
297
+ moveTo(active + pageSize());
298
+ break;
299
+ case "PageUp":
300
+ moveTo(active - pageSize());
301
+ break;
302
+ case " ":
303
+ if (!event.repeat) {
304
+ options.onToggle(indexOf(item));
305
+ }
306
+ break;
307
+ default:
308
+ return;
309
+ }
310
+ event.preventDefault();
311
+ }
312
+ function onFocusIn(event) {
313
+ const item = itemOf(event.target);
314
+ if (item !== null) {
315
+ state = SETTLED;
316
+ makeActive(indexOf(item));
317
+ setTabStop();
318
+ }
319
+ }
320
+ function onClick(event) {
321
+ const item = itemOf(event.target);
322
+ if (item !== null) {
323
+ options.onToggle(indexOf(item));
324
+ item.focus({ preventScroll: true });
325
+ }
326
+ }
327
+ function focusAwaitedItemIfMounted() {
328
+ const item = state.kind === "awaiting-item" ? itemAt(state.index) : null;
329
+ if (item === null) {
330
+ return;
331
+ }
332
+ state = SETTLED;
333
+ const focused = document.activeElement;
334
+ if (focused === null || focused === document.body || list.contains(focused)) {
335
+ item.focus({ preventScroll: true });
336
+ }
337
+ }
338
+ const observer = new MutationObserver(() => {
339
+ setTabStop();
340
+ focusAwaitedItemIfMounted();
341
+ });
342
+ observer.observe(list, {
343
+ childList: true,
344
+ subtree: true,
345
+ attributeFilter: [INDEX]
346
+ });
347
+ list.tabIndex = -1;
348
+ setTabStop();
349
+ list.addEventListener("keydown", onKeyDown);
350
+ list.addEventListener("focusin", onFocusIn);
351
+ list.addEventListener("click", onClick);
352
+ return {
353
+ setCount(next) {
354
+ if (state.kind === "detached") {
355
+ return;
356
+ }
357
+ count = next;
358
+ active = Math.max(0, Math.min(active, count - 1));
359
+ if (state.kind === "awaiting-item") {
360
+ state = count === 0 ? SETTLED : {
361
+ kind: "awaiting-item",
362
+ index: Math.min(state.index, count - 1)
363
+ };
364
+ }
365
+ setTabStop();
366
+ focusAwaitedItemIfMounted();
367
+ },
368
+ focusItem: moveTo,
369
+ detach() {
370
+ state = DETACHED;
371
+ observer.disconnect();
372
+ list.removeEventListener("keydown", onKeyDown);
373
+ list.removeEventListener("focusin", onFocusIn);
374
+ list.removeEventListener("click", onClick);
375
+ }
376
+ };
377
+ }
378
+
379
+ // src/overlay/overlayStack.ts
380
+ var STACK_KEY = /* @__PURE__ */ Symbol.for("@gridkitjs/overlay-stack");
381
+ function createStack() {
382
+ const overlays = [];
383
+ return {
384
+ overlays,
385
+ onKeyDown: (event) => {
386
+ const topmost = overlays.at(-1);
387
+ if (event.key !== "Escape" || event.isComposing || topmost === void 0) {
388
+ return;
389
+ }
390
+ event.preventDefault();
391
+ event.stopPropagation();
392
+ topmost.onEscape();
393
+ }
394
+ };
395
+ }
396
+ function pageStack() {
397
+ const holder = globalThis;
398
+ const stack = holder[STACK_KEY] ?? createStack();
399
+ holder[STACK_KEY] = stack;
400
+ return stack;
401
+ }
402
+ function pushOverlay(overlay) {
403
+ const { overlays, onKeyDown } = pageStack();
404
+ if (overlays.length === 0) {
405
+ window.addEventListener("keydown", onKeyDown, true);
406
+ }
407
+ overlays.push(overlay);
408
+ }
409
+ function removeOverlay(overlay) {
410
+ const { overlays, onKeyDown } = pageStack();
411
+ const index = overlays.indexOf(overlay);
412
+ if (index === -1) {
413
+ return;
414
+ }
415
+ const above = overlays.splice(index).slice(1).reverse();
416
+ for (const child of above) {
417
+ child.onParentDetached();
418
+ }
419
+ if (overlays.length === 0) {
420
+ window.removeEventListener("keydown", onKeyDown, true);
421
+ }
422
+ }
423
+ function isInsideOverlayAbove(overlay, target) {
424
+ const { overlays } = pageStack();
425
+ const index = overlays.indexOf(overlay);
426
+ return index !== -1 && overlays.slice(index + 1).some((above) => above.panel.contains(target));
427
+ }
428
+
429
+ // src/overlay/placeOverlay.ts
430
+ var OPPOSITE_SIDE = {
431
+ top: "bottom",
432
+ bottom: "top",
433
+ left: "right",
434
+ right: "left"
435
+ };
436
+ function isVertical(side) {
437
+ return side === "top" || side === "bottom";
438
+ }
439
+ function roomBeside(side, anchor, viewport) {
440
+ switch (side) {
441
+ case "top":
442
+ return anchor.top;
443
+ case "bottom":
444
+ return viewport.height - (anchor.top + anchor.height);
445
+ case "left":
446
+ return anchor.left;
447
+ case "right":
448
+ return viewport.width - (anchor.left + anchor.width);
449
+ }
450
+ }
451
+ function chooseSide(preferred, needed, anchor, viewport) {
452
+ const opposite = OPPOSITE_SIDE[preferred];
453
+ const room = roomBeside(preferred, anchor, viewport);
454
+ const oppositeRoom = roomBeside(opposite, anchor, viewport);
455
+ if (room >= needed) {
456
+ return preferred;
457
+ }
458
+ return oppositeRoom >= needed || oppositeRoom > room ? opposite : preferred;
459
+ }
460
+ function chooseAlign(preferred, fitsAtStart, fitsAtEnd) {
461
+ if (preferred === "start") {
462
+ return fitsAtStart || !fitsAtEnd ? "start" : "end";
463
+ }
464
+ return fitsAtEnd || !fitsAtStart ? "end" : "start";
465
+ }
466
+ function offsetBeside(side, anchor, panel, gap) {
467
+ switch (side) {
468
+ case "top":
469
+ return anchor.top - gap - panel.height;
470
+ case "bottom":
471
+ return anchor.top + anchor.height + gap;
472
+ case "left":
473
+ return anchor.left - gap - panel.width;
474
+ case "right":
475
+ return anchor.left + anchor.width + gap;
476
+ }
477
+ }
478
+ function clampIntoView(value, limit) {
479
+ return Math.max(0, Math.min(value, limit));
480
+ }
481
+ function placeOverlay(anchor, panel, viewport, options = {}) {
482
+ if (options.direction !== "rtl") {
483
+ return placeLeftToRight(anchor, panel, viewport, options);
484
+ }
485
+ const mirrored = placeLeftToRight(
486
+ { ...anchor, left: viewport.width - anchor.left - anchor.width },
487
+ panel,
488
+ viewport,
489
+ options
490
+ );
491
+ return {
492
+ ...mirrored,
493
+ left: viewport.width - mirrored.left - panel.width
494
+ };
495
+ }
496
+ function placeLeftToRight(anchor, panel, viewport, options) {
497
+ const [preferredSide, preferredAlign] = (options.placement ?? "bottom-start").split("-");
498
+ const gap = options.gap ?? 0;
499
+ const offset = options.offset ?? 0;
500
+ const vertical = isVertical(preferredSide);
501
+ const side = chooseSide(
502
+ preferredSide,
503
+ (vertical ? panel.height : panel.width) + gap,
504
+ anchor,
505
+ viewport
506
+ );
507
+ const anchorStart = (vertical ? anchor.left : anchor.top) + offset;
508
+ const anchorEnd = anchorStart + (vertical ? anchor.width : anchor.height);
509
+ const extent = vertical ? panel.width : panel.height;
510
+ const room = vertical ? viewport.width : viewport.height;
511
+ const align = chooseAlign(
512
+ preferredAlign,
513
+ anchorStart + extent <= room,
514
+ anchorEnd - extent >= 0
515
+ );
516
+ const along = align === "start" ? anchorStart : anchorEnd - extent;
517
+ const away = offsetBeside(side, anchor, panel, gap);
518
+ return {
519
+ top: clampIntoView(vertical ? away : along, viewport.height - panel.height),
520
+ left: clampIntoView(vertical ? along : away, viewport.width - panel.width),
521
+ placement: `${side}-${align}`
522
+ };
523
+ }
524
+
525
+ // src/writingDirection.ts
526
+ function writingDirection(element) {
527
+ return getComputedStyle(element).direction === "rtl" ? "rtl" : "ltr";
528
+ }
529
+
530
+ // src/overlay/attachOverlay.ts
531
+ var FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]";
532
+ function tabbables(panel) {
533
+ return Array.from(panel.querySelectorAll(FOCUSABLE)).filter(
534
+ (element) => element.tabIndex >= 0 && !element.matches(":disabled") && element.checkVisibility({ visibilityProperty: true })
535
+ );
536
+ }
537
+ function anchorRect(anchor) {
538
+ if (anchor instanceof Element) {
539
+ const { top, left, width, height } = anchor.getBoundingClientRect();
540
+ return { top, left, width, height };
541
+ }
542
+ return { top: anchor.y, left: anchor.x, width: 0, height: 0 };
543
+ }
544
+ function initialFocusTarget(panel, initialFocus) {
545
+ if (initialFocus === "none") {
546
+ return null;
547
+ }
548
+ if (initialFocus instanceof HTMLElement) {
549
+ return initialFocus;
550
+ }
551
+ const first = initialFocus === "first" ? panel.querySelector(FOCUSABLE) : null;
552
+ if (first !== null) {
553
+ return first;
554
+ }
555
+ if (!panel.hasAttribute("tabindex")) {
556
+ panel.tabIndex = -1;
557
+ }
558
+ return panel;
559
+ }
560
+ function attachOverlay(anchor, panel, options) {
561
+ const { onDismiss } = options;
562
+ const returnFocusTo = options.returnFocusTo === void 0 ? document.activeElement instanceof HTMLElement ? document.activeElement : null : options.returnFocusTo;
563
+ const stacked = {
564
+ panel,
565
+ onEscape: () => {
566
+ onDismiss("escape");
567
+ },
568
+ onParentDetached: () => {
569
+ onDismiss("parent");
570
+ detach();
571
+ }
572
+ };
573
+ function inside(target) {
574
+ return target instanceof Node && (panel.contains(target) || isInsideOverlayAbove(stacked, target));
575
+ }
576
+ function belongs(target) {
577
+ return inside(target) || anchor instanceof Element && target instanceof Node && anchor.contains(target);
578
+ }
579
+ function onPointerDown(event) {
580
+ if (!belongs(event.target)) {
581
+ onDismiss("outside");
582
+ }
583
+ }
584
+ let settlingFrame = null;
585
+ function onInput() {
586
+ if (settlingFrame !== null) {
587
+ cancelAnimationFrame(settlingFrame);
588
+ }
589
+ settlingFrame = requestAnimationFrame(() => {
590
+ settlingFrame = requestAnimationFrame(() => {
591
+ settlingFrame = null;
592
+ });
593
+ });
594
+ }
595
+ function movesAnchor(target) {
596
+ return !(anchor instanceof Element) || !(target instanceof Node) || target.nodeType === Node.DOCUMENT_NODE || target.contains(anchor);
597
+ }
598
+ function onScroll(event) {
599
+ if (!inside(event.target) && settlingFrame === null && movesAnchor(event.target)) {
600
+ onDismiss("scroll");
601
+ }
602
+ }
603
+ function onResize() {
604
+ onDismiss("resize");
605
+ }
606
+ function onFocusOut(event) {
607
+ if (event.relatedTarget !== null && !belongs(event.relatedTarget)) {
608
+ onDismiss("blur");
609
+ }
610
+ }
611
+ function onTrapKeyDown(event) {
612
+ if (event.key !== "Tab" || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !(event.target instanceof Node) || isInsideOverlayAbove(stacked, event.target)) {
613
+ return;
614
+ }
615
+ const stops = tabbables(panel).filter(
616
+ (element) => !isInsideOverlayAbove(stacked, element)
617
+ );
618
+ const first = stops[0];
619
+ const last = stops.at(-1);
620
+ if (first === void 0 || last === void 0) {
621
+ event.preventDefault();
622
+ return;
623
+ }
624
+ const position = event.target.compareDocumentPosition(
625
+ event.shiftKey ? first : last
626
+ );
627
+ const leaving = event.shiftKey ? (position & Node.DOCUMENT_POSITION_PRECEDING) === 0 : (position & Node.DOCUMENT_POSITION_FOLLOWING) === 0;
628
+ if (leaving) {
629
+ event.preventDefault();
630
+ (event.shiftKey ? last : first).focus();
631
+ }
632
+ }
633
+ function onWindowBlur() {
634
+ onDismiss("blur");
635
+ }
636
+ let lastAnchorBox = null;
637
+ function anchorBox() {
638
+ if (lastAnchorBox === null || !(anchor instanceof Element) || anchor.isConnected) {
639
+ lastAnchorBox = anchorRect(anchor);
640
+ }
641
+ return lastAnchorBox;
642
+ }
643
+ function place() {
644
+ panel.style.top = "0px";
645
+ panel.style.left = "0px";
646
+ const { width, height } = panel.getBoundingClientRect();
647
+ const position = placeOverlay(
648
+ anchorBox(),
649
+ { width, height },
650
+ {
651
+ width: document.documentElement.clientWidth,
652
+ height: document.documentElement.clientHeight
653
+ },
654
+ { ...options, direction: options.direction ?? writingDirection(panel) }
655
+ );
656
+ panel.style.top = `${String(position.top)}px`;
657
+ panel.style.left = `${String(position.left)}px`;
658
+ panel.setAttribute("data-gridkit-placement", position.placement);
659
+ }
660
+ panel.style.position = "fixed";
661
+ place();
662
+ const resizeObserver = new ResizeObserver(place);
663
+ resizeObserver.observe(panel);
664
+ pushOverlay(stacked);
665
+ initialFocusTarget(panel, options.initialFocus ?? "first")?.focus({
666
+ preventScroll: true
667
+ });
668
+ document.addEventListener("pointerdown", onPointerDown, true);
669
+ window.addEventListener("scroll", onScroll, { capture: true, passive: true });
670
+ window.addEventListener("resize", onResize);
671
+ window.addEventListener("blur", onWindowBlur);
672
+ panel.addEventListener("focusout", onFocusOut);
673
+ if (options.trapFocus === true) {
674
+ panel.addEventListener("keydown", onTrapKeyDown);
675
+ }
676
+ if (options.ignoreScrollAfterInput === true) {
677
+ panel.addEventListener("input", onInput);
678
+ panel.addEventListener("change", onInput);
679
+ }
680
+ let attached = true;
681
+ function detach() {
682
+ if (!attached) {
683
+ return;
684
+ }
685
+ attached = false;
686
+ const active = document.activeElement;
687
+ const focusInside = active === null || active === document.body || inside(active);
688
+ removeOverlay(stacked);
689
+ resizeObserver.disconnect();
690
+ document.removeEventListener("pointerdown", onPointerDown, true);
691
+ window.removeEventListener("scroll", onScroll, { capture: true });
692
+ window.removeEventListener("resize", onResize);
693
+ window.removeEventListener("blur", onWindowBlur);
694
+ panel.removeEventListener("focusout", onFocusOut);
695
+ panel.removeEventListener("keydown", onTrapKeyDown);
696
+ panel.removeEventListener("input", onInput);
697
+ panel.removeEventListener("change", onInput);
698
+ if (settlingFrame !== null) {
699
+ cancelAnimationFrame(settlingFrame);
700
+ }
701
+ if (!focusInside) {
702
+ return;
703
+ }
704
+ const target = returnFocusTo?.isConnected === true ? returnFocusTo : options.returnFocusFallback?.();
705
+ target?.focus({ preventScroll: true });
706
+ }
707
+ return detach;
708
+ }
709
+
710
+ // src/rowVirtualizer.ts
711
+ import { visibleRange } from "@gridkitjs/forms-core";
712
+ var READY = { kind: "ready" };
713
+ function sameRange(a, b) {
714
+ return a.startIndex === b.startIndex && a.endIndex === b.endIndex && a.offsetBefore === b.offsetBefore && a.offsetAfter === b.offsetAfter;
715
+ }
716
+ function createRowVirtualizer(scrollElement, options) {
717
+ const { estimatedRowHeight, overscan, onRange } = options;
718
+ let heights = [];
719
+ let scrollTop = scrollElement.scrollTop;
720
+ let viewportHeight = scrollElement.clientHeight;
721
+ let range = null;
722
+ let phase = READY;
723
+ const elements = /* @__PURE__ */ new Map();
724
+ const indexByElement = /* @__PURE__ */ new Map();
725
+ const refCallbacks = /* @__PURE__ */ new Map();
726
+ function recompute() {
727
+ if (phase.kind === "destroyed") {
728
+ return;
729
+ }
730
+ const next = visibleRange(
731
+ heights,
732
+ estimatedRowHeight,
733
+ scrollTop,
734
+ viewportHeight,
735
+ overscan
736
+ );
737
+ if (range !== null && sameRange(range, next)) {
738
+ return;
739
+ }
740
+ range = next;
741
+ onRange(next);
742
+ }
743
+ const rowObserver = new ResizeObserver((entries) => {
744
+ let changed = false;
745
+ for (const entry of entries) {
746
+ const index = indexByElement.get(entry.target);
747
+ if (index === void 0) continue;
748
+ const height = entry.target.getBoundingClientRect().height;
749
+ if (heights[index] !== height) {
750
+ heights[index] = height;
751
+ changed = true;
752
+ }
753
+ }
754
+ if (changed) {
755
+ recompute();
756
+ }
757
+ });
758
+ const viewportObserver = new ResizeObserver(() => {
759
+ viewportHeight = scrollElement.clientHeight;
760
+ recompute();
761
+ });
762
+ viewportObserver.observe(scrollElement);
763
+ function handleScroll() {
764
+ scrollTop = scrollElement.scrollTop;
765
+ recompute();
766
+ }
767
+ scrollElement.addEventListener("scroll", handleScroll, { passive: true });
768
+ function estimateOffsetBefore(index) {
769
+ let total = 0;
770
+ for (let current = 0; current < index; current++) {
771
+ total += heights[current] ?? estimatedRowHeight;
772
+ }
773
+ return total;
774
+ }
775
+ recompute();
776
+ return {
777
+ setRowCount(count) {
778
+ if (phase.kind === "awaiting-row" && phase.index >= count) {
779
+ phase = READY;
780
+ }
781
+ heights = Array.from({ length: count }, (_, index) => heights[index]);
782
+ recompute();
783
+ },
784
+ resetHeights() {
785
+ if (phase.kind === "awaiting-row") {
786
+ phase = READY;
787
+ }
788
+ heights = new Array(heights.length).fill(void 0);
789
+ recompute();
790
+ },
791
+ measureRow(index) {
792
+ let callback = refCallbacks.get(index);
793
+ if (callback === void 0) {
794
+ callback = (element) => {
795
+ const previous = elements.get(index);
796
+ if (previous !== void 0) {
797
+ rowObserver.unobserve(previous);
798
+ indexByElement.delete(previous);
799
+ elements.delete(index);
800
+ }
801
+ if (element === null || phase.kind === "destroyed") {
802
+ return;
803
+ }
804
+ elements.set(index, element);
805
+ indexByElement.set(element, index);
806
+ rowObserver.observe(element);
807
+ if (phase.kind === "awaiting-row" && phase.index === index) {
808
+ element.scrollIntoView(phase.options);
809
+ phase = READY;
810
+ }
811
+ };
812
+ refCallbacks.set(index, callback);
813
+ }
814
+ return callback;
815
+ },
816
+ measureRows(rows) {
817
+ if (phase.kind === "destroyed") {
818
+ return;
819
+ }
820
+ for (const [index, element] of rows) {
821
+ if (index >= 0 && index < heights.length) {
822
+ heights[index] = element.getBoundingClientRect().height;
823
+ }
824
+ }
825
+ recompute();
826
+ },
827
+ scrollToIndex(index, scrollOptions) {
828
+ if (phase.kind === "destroyed" || heights.length === 0) {
829
+ return;
830
+ }
831
+ const clamped = Math.max(0, Math.min(index, heights.length - 1));
832
+ const mounted = elements.get(clamped);
833
+ if (mounted !== void 0) {
834
+ phase = READY;
835
+ mounted.scrollIntoView(scrollOptions);
836
+ return;
837
+ }
838
+ phase = { kind: "awaiting-row", index: clamped, options: scrollOptions };
839
+ scrollElement.scrollTop = estimateOffsetBefore(clamped);
840
+ },
841
+ destroy() {
842
+ phase = { kind: "destroyed" };
843
+ scrollElement.removeEventListener("scroll", handleScroll);
844
+ viewportObserver.disconnect();
845
+ rowObserver.disconnect();
846
+ elements.clear();
847
+ indexByElement.clear();
848
+ }
849
+ };
850
+ }
851
+
852
+ // src/scheduleTimeout.ts
853
+ var scheduleTimeout = (callback, delay) => {
854
+ const timer = setTimeout(callback, delay);
855
+ return () => {
856
+ clearTimeout(timer);
857
+ };
858
+ };
859
+
860
+ // src/step/attachHoldRepeat.ts
861
+ var IDLE = { kind: "idle" };
862
+ var DETACHED2 = { kind: "detached" };
863
+ var DELAY = 400;
864
+ var INTERVAL = 60;
865
+ var FAST_INTERVAL = 30;
866
+ var FAST_AFTER = 20;
867
+ function attachHoldRepeat(button, initialOptions) {
868
+ let options = initialOptions;
869
+ let state = IDLE;
870
+ const listeners = new AbortController();
871
+ const { signal } = listeners;
872
+ function release(next) {
873
+ if (state.kind === "waiting" || state.kind === "repeating") {
874
+ state.cancel();
875
+ const { pointerId } = state;
876
+ state = next;
877
+ if (button.hasPointerCapture(pointerId)) {
878
+ button.releasePointerCapture(pointerId);
879
+ }
880
+ return;
881
+ }
882
+ if (state.kind !== "detached") {
883
+ state = next;
884
+ }
885
+ }
886
+ function repeat(press, count) {
887
+ if (!options.onRepeat(press)) {
888
+ release(IDLE);
889
+ return;
890
+ }
891
+ const taken = count + 1;
892
+ const interval = taken >= (options.fastAfter ?? FAST_AFTER) ? options.fastInterval ?? FAST_INTERVAL : options.interval ?? INTERVAL;
893
+ state = {
894
+ kind: "repeating",
895
+ pointerId: press.pointerId,
896
+ press,
897
+ count: taken,
898
+ cancel: scheduleTimeout(() => {
899
+ repeat(press, taken);
900
+ }, interval)
901
+ };
902
+ }
903
+ function onPointerDown(event) {
904
+ if (state.kind !== "idle" || event.button !== 0) {
905
+ return;
906
+ }
907
+ if (!options.onRepeat(event)) {
908
+ return;
909
+ }
910
+ try {
911
+ button.setPointerCapture(event.pointerId);
912
+ } catch {
913
+ }
914
+ state = {
915
+ kind: "waiting",
916
+ pointerId: event.pointerId,
917
+ press: event,
918
+ cancel: scheduleTimeout(() => {
919
+ repeat(event, 0);
920
+ }, options.delay ?? DELAY)
921
+ };
922
+ }
923
+ function onPointerMove(event) {
924
+ if (state.kind !== "waiting" && state.kind !== "repeating" || event.pointerId !== state.pointerId) {
925
+ return;
926
+ }
927
+ const box = button.getBoundingClientRect();
928
+ if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) {
929
+ release(IDLE);
930
+ }
931
+ }
932
+ function onEnd(event) {
933
+ if ((state.kind === "waiting" || state.kind === "repeating") && event.pointerId === state.pointerId) {
934
+ release(IDLE);
935
+ }
936
+ }
937
+ button.addEventListener("pointerdown", onPointerDown, { signal });
938
+ button.addEventListener("pointermove", onPointerMove, { signal });
939
+ button.addEventListener("pointerup", onEnd, { signal });
940
+ button.addEventListener("pointercancel", onEnd, { signal });
941
+ button.addEventListener("lostpointercapture", onEnd, { signal });
942
+ button.addEventListener(
943
+ "contextmenu",
944
+ (event) => {
945
+ event.preventDefault();
946
+ },
947
+ { signal }
948
+ );
949
+ return {
950
+ setOptions: (next) => {
951
+ options = next;
952
+ },
953
+ cancel: () => {
954
+ release(IDLE);
955
+ },
956
+ detach: () => {
957
+ release(DETACHED2);
958
+ listeners.abort();
959
+ }
960
+ };
961
+ }
962
+
963
+ // src/step/attachStepKeys.ts
964
+ var WHEEL_STEP_PIXELS = 50;
965
+ function keyStep(key, edges) {
966
+ switch (key) {
967
+ case "ArrowUp":
968
+ return ["up", "step"];
969
+ case "ArrowDown":
970
+ return ["down", "step"];
971
+ case "PageUp":
972
+ return ["up", "large"];
973
+ case "PageDown":
974
+ return ["down", "large"];
975
+ case "Home":
976
+ return edges?.min === true ? ["down", "edge"] : null;
977
+ case "End":
978
+ return edges?.max === true ? ["up", "edge"] : null;
979
+ default:
980
+ return null;
981
+ }
982
+ }
983
+ function hasFocus(control) {
984
+ const root = control.getRootNode();
985
+ return (root instanceof Document || root instanceof ShadowRoot) && root.activeElement === control;
986
+ }
987
+ function attachStepKeys(control, initialOptions) {
988
+ let options = initialOptions;
989
+ let wheelTravel = 0;
990
+ const listeners = new AbortController();
991
+ const { signal } = listeners;
992
+ control.addEventListener(
993
+ "keydown",
994
+ (event) => {
995
+ const legacy = event;
996
+ if (event.defaultPrevented || event.isComposing || legacy.keyCode === 229 || event.ctrlKey || event.altKey || event.metaKey) {
997
+ return;
998
+ }
999
+ const step = keyStep(event.key, options.edges);
1000
+ if (step === null) {
1001
+ return;
1002
+ }
1003
+ event.preventDefault();
1004
+ options.onStep(step[0], step[1], event);
1005
+ },
1006
+ { signal }
1007
+ );
1008
+ control.addEventListener(
1009
+ "wheel",
1010
+ (event) => {
1011
+ if (options.wheel !== true || !hasFocus(control)) {
1012
+ wheelTravel = 0;
1013
+ return;
1014
+ }
1015
+ event.preventDefault();
1016
+ const unit = event.deltaMode === WheelEvent.DOM_DELTA_PIXEL ? 1 : WHEEL_STEP_PIXELS;
1017
+ wheelTravel += event.deltaY * unit;
1018
+ while (Math.abs(wheelTravel) >= WHEEL_STEP_PIXELS) {
1019
+ const direction = wheelTravel < 0 ? "up" : "down";
1020
+ wheelTravel -= Math.sign(wheelTravel) * WHEEL_STEP_PIXELS;
1021
+ options.onStep(direction, "step", event);
1022
+ }
1023
+ },
1024
+ { signal, passive: false }
1025
+ );
1026
+ control.addEventListener(
1027
+ "blur",
1028
+ () => {
1029
+ wheelTravel = 0;
1030
+ },
1031
+ { signal }
1032
+ );
1033
+ return {
1034
+ setOptions: (next) => {
1035
+ options = next;
1036
+ },
1037
+ detach: () => {
1038
+ listeners.abort();
1039
+ }
1040
+ };
1041
+ }
1042
+
1043
+ // src/text/attachAutoGrow.ts
1044
+ function pixels2(value) {
1045
+ const parsed = Number.parseFloat(value);
1046
+ return Number.isNaN(parsed) ? 0 : parsed;
1047
+ }
1048
+ var NORMAL_LINE_HEIGHT = 1.2;
1049
+ function attachAutoGrow(textarea, initialOptions) {
1050
+ let options = initialOptions;
1051
+ let width = -1;
1052
+ let detached = false;
1053
+ let frame = 0;
1054
+ const listeners = new AbortController();
1055
+ function update() {
1056
+ if (detached) {
1057
+ return;
1058
+ }
1059
+ const style = getComputedStyle(textarea);
1060
+ const lineHeight = style.lineHeight === "normal" ? pixels2(style.fontSize) * NORMAL_LINE_HEIGHT : pixels2(style.lineHeight);
1061
+ const padding = pixels2(style.paddingTop) + pixels2(style.paddingBottom);
1062
+ const border = pixels2(style.borderTopWidth) + pixels2(style.borderBottomWidth);
1063
+ const min = Math.max(1, options.minRows) * lineHeight;
1064
+ const max = Math.max(options.minRows, options.maxRows) * lineHeight;
1065
+ textarea.style.height = "0px";
1066
+ const content = textarea.scrollHeight - padding;
1067
+ const inner = Math.min(Math.max(content, min), max);
1068
+ const outer = style.boxSizing === "border-box" ? inner + padding + border : inner;
1069
+ textarea.style.height = `${String(outer)}px`;
1070
+ textarea.style.overflowY = content > max + 1 ? "auto" : "hidden";
1071
+ }
1072
+ const resizes = new ResizeObserver(([entry]) => {
1073
+ const next = entry?.contentRect.width ?? width;
1074
+ if (next !== width) {
1075
+ width = next;
1076
+ cancelAnimationFrame(frame);
1077
+ frame = requestAnimationFrame(() => {
1078
+ frame = 0;
1079
+ update();
1080
+ });
1081
+ }
1082
+ });
1083
+ resizes.observe(textarea);
1084
+ textarea.addEventListener("input", update, { signal: listeners.signal });
1085
+ update();
1086
+ return {
1087
+ update,
1088
+ setOptions: (next) => {
1089
+ options = next;
1090
+ update();
1091
+ },
1092
+ detach: () => {
1093
+ detached = true;
1094
+ listeners.abort();
1095
+ resizes.disconnect();
1096
+ cancelAnimationFrame(frame);
1097
+ }
1098
+ };
1099
+ }
1100
+
1101
+ // src/text/applyEdit.ts
1102
+ var graphemes;
1103
+ function graphemeSegmenter() {
1104
+ graphemes ??= new Intl.Segmenter(void 0, { granularity: "grapheme" });
1105
+ return graphemes;
1106
+ }
1107
+ function graphemeStartBefore(text, index) {
1108
+ let start = index;
1109
+ for (const segment of graphemeSegmenter().segment(text.slice(0, index))) {
1110
+ start = segment.index;
1111
+ }
1112
+ return start;
1113
+ }
1114
+ function graphemeEndAfter(text, index) {
1115
+ const segments = graphemeSegmenter().segment(text.slice(index));
1116
+ const first = segments[Symbol.iterator]().next();
1117
+ return first.done ? index : index + first.value.segment.length;
1118
+ }
1119
+ function wordStartBefore(text, index) {
1120
+ const word = /\S*\s*$/u.exec(text.slice(0, index))?.[0] ?? "";
1121
+ return index - word.length;
1122
+ }
1123
+ function wordEndAfter(text, index) {
1124
+ const word = /^\s*\S*/u.exec(text.slice(index))?.[0] ?? "";
1125
+ return index + word.length;
1126
+ }
1127
+ function lineStartBefore(text, index) {
1128
+ return text.lastIndexOf("\n", index - 1) + 1;
1129
+ }
1130
+ function lineEndAfter(text, index) {
1131
+ const end = text.indexOf("\n", index);
1132
+ return end === -1 ? text.length : end;
1133
+ }
1134
+ function deletedAround(text, caret, inputType) {
1135
+ switch (inputType) {
1136
+ case "deleteContentBackward":
1137
+ return { start: graphemeStartBefore(text, caret), end: caret };
1138
+ case "deleteContentForward":
1139
+ return { start: caret, end: graphemeEndAfter(text, caret) };
1140
+ case "deleteWordBackward":
1141
+ return { start: wordStartBefore(text, caret), end: caret };
1142
+ case "deleteWordForward":
1143
+ return { start: caret, end: wordEndAfter(text, caret) };
1144
+ case "deleteSoftLineBackward":
1145
+ case "deleteHardLineBackward":
1146
+ return { start: lineStartBefore(text, caret), end: caret };
1147
+ case "deleteSoftLineForward":
1148
+ case "deleteHardLineForward":
1149
+ return { start: caret, end: lineEndAfter(text, caret) };
1150
+ case "deleteEntireSoftLine":
1151
+ return {
1152
+ start: lineStartBefore(text, caret),
1153
+ end: lineEndAfter(text, caret)
1154
+ };
1155
+ default:
1156
+ return { start: caret, end: caret };
1157
+ }
1158
+ }
1159
+ function splice(text, { start, end }, insert) {
1160
+ return text.slice(0, start) + insert + text.slice(end);
1161
+ }
1162
+ function applyEdit(text, range, inputType, data) {
1163
+ switch (inputType) {
1164
+ case "insertLineBreak":
1165
+ case "insertParagraph":
1166
+ return splice(text, range, "\n");
1167
+ case "insertReplacementText":
1168
+ case "insertTranspose":
1169
+ return null;
1170
+ }
1171
+ if (inputType.startsWith("insert")) {
1172
+ return splice(text, range, data ?? "");
1173
+ }
1174
+ if (inputType.startsWith("delete")) {
1175
+ return splice(
1176
+ text,
1177
+ range.start === range.end ? deletedAround(text, range.start, inputType) : range,
1178
+ ""
1179
+ );
1180
+ }
1181
+ return null;
1182
+ }
1183
+
1184
+ // src/text/attachTextInput.ts
1185
+ var READY2 = { kind: "ready" };
1186
+ var DETACHED3 = { kind: "detached" };
1187
+ function sourceOf(inputType) {
1188
+ if (inputType === null) {
1189
+ return "typing";
1190
+ }
1191
+ if (inputType.startsWith("insertFromPaste")) {
1192
+ return "paste";
1193
+ }
1194
+ if (inputType === "insertFromDrop" || inputType === "deleteByDrag") {
1195
+ return "drop";
1196
+ }
1197
+ return inputType.startsWith("history") ? "undo" : "typing";
1198
+ }
1199
+ function hasFocus2(control) {
1200
+ const root = control.getRootNode();
1201
+ return (root instanceof Document || root instanceof ShadowRoot) && root.activeElement === control;
1202
+ }
1203
+ function snapshot(control) {
1204
+ return {
1205
+ text: control.value,
1206
+ selectionStart: control.selectionStart,
1207
+ selectionEnd: control.selectionEnd,
1208
+ selectionDirection: control.selectionDirection
1209
+ };
1210
+ }
1211
+ function caretFromEnd(previousText, caret, nextText) {
1212
+ return Math.max(0, nextText.length - (previousText.length - caret));
1213
+ }
1214
+ function errorText(messages) {
1215
+ return messages.find((message) => message.severity === "error")?.text ?? "";
1216
+ }
1217
+ function attachTextInput(control, controller, initialOptions = {}) {
1218
+ let options = initialOptions;
1219
+ let state = READY2;
1220
+ let customValidity = "";
1221
+ let pointerFocus = false;
1222
+ const listeners = new AbortController();
1223
+ const { signal } = listeners;
1224
+ function selection() {
1225
+ const { selectionStart, selectionEnd } = control;
1226
+ if (state.kind === "composing") {
1227
+ return {
1228
+ start: state.start,
1229
+ end: control.value.length - state.suffixLength
1230
+ };
1231
+ }
1232
+ return selectionStart === null || selectionEnd === null ? null : { start: selectionStart, end: selectionEnd };
1233
+ }
1234
+ function details(event) {
1235
+ if (!(event instanceof InputEvent)) {
1236
+ return null;
1237
+ }
1238
+ return {
1239
+ inputType: event.inputType === "" ? null : event.inputType,
1240
+ data: event.data,
1241
+ selectionStart: control.selectionStart,
1242
+ selectionEnd: control.selectionEnd,
1243
+ isComposing: event.isComposing
1244
+ };
1245
+ }
1246
+ function writeText(text) {
1247
+ if (!hasFocus2(control)) {
1248
+ control.value = text;
1249
+ return;
1250
+ }
1251
+ const before = state.kind === "editing" || state.kind === "rewriting" ? state.before : null;
1252
+ if (before?.text === text) {
1253
+ control.value = text;
1254
+ if (before.selectionStart !== null && before.selectionEnd !== null) {
1255
+ control.setSelectionRange(
1256
+ before.selectionStart,
1257
+ before.selectionEnd,
1258
+ before.selectionDirection ?? void 0
1259
+ );
1260
+ }
1261
+ return;
1262
+ }
1263
+ const { selectionStart, selectionEnd, selectionDirection } = control;
1264
+ const previous = control.value;
1265
+ control.value = text;
1266
+ if (selectionStart !== null && selectionEnd !== null) {
1267
+ const map = options.mapCaret ?? caretFromEnd;
1268
+ control.setSelectionRange(
1269
+ map(previous, selectionStart, text),
1270
+ map(previous, selectionEnd, text),
1271
+ selectionDirection ?? void 0
1272
+ );
1273
+ }
1274
+ }
1275
+ function render() {
1276
+ if (state.kind === "composing" || state.kind === "detached") {
1277
+ return;
1278
+ }
1279
+ const text = controller.getText();
1280
+ if (control.value !== text) {
1281
+ writeText(text);
1282
+ }
1283
+ const validity = errorText(controller.getMessages());
1284
+ if (validity !== customValidity) {
1285
+ customValidity = validity;
1286
+ control.setCustomValidity(validity);
1287
+ }
1288
+ }
1289
+ function rewrite(cause, data) {
1290
+ const range = selection();
1291
+ state = { kind: "rewriting", before: snapshot(control) };
1292
+ const editing = control.ownerDocument;
1293
+ if (!editing.execCommand("insertText", false, data) && range !== null) {
1294
+ control.setRangeText(data, range.start, range.end, "end");
1295
+ }
1296
+ controller.input({ ...cause, text: control.value });
1297
+ state = READY2;
1298
+ }
1299
+ function editsNothing(inputType) {
1300
+ return control instanceof HTMLInputElement && (inputType === "insertLineBreak" || inputType === "insertParagraph");
1301
+ }
1302
+ function replace(cause, text, caret) {
1303
+ if (control.value !== text) {
1304
+ state = { kind: "rewriting", before: snapshot(control) };
1305
+ control.setSelectionRange(0, control.value.length);
1306
+ const editing = control.ownerDocument;
1307
+ const inserted = text === "" ? editing.execCommand("delete", false) : editing.execCommand("insertText", false, text);
1308
+ if (!inserted || control.value !== text) {
1309
+ control.value = text;
1310
+ }
1311
+ controller.input({ ...cause, text: control.value });
1312
+ state = READY2;
1313
+ }
1314
+ if (control.value === text) {
1315
+ control.setSelectionRange(caret, caret);
1316
+ }
1317
+ }
1318
+ function decide(inputType, data, nativeEvent, cancelable, composing) {
1319
+ const range = selection();
1320
+ const proposed = range === null || inputType === null ? null : applyEdit(control.value, range, inputType, data);
1321
+ const input = {
1322
+ inputType,
1323
+ data,
1324
+ selectionStart: range?.start ?? null,
1325
+ selectionEnd: range?.end ?? null,
1326
+ isComposing: composing
1327
+ };
1328
+ const edit = {
1329
+ text: proposed ?? control.value,
1330
+ source: sourceOf(inputType),
1331
+ input,
1332
+ nativeEvent
1333
+ };
1334
+ const decision = controller.beforeInput({
1335
+ ...edit,
1336
+ cancelable: cancelable && !composing
1337
+ });
1338
+ return { edit, decision };
1339
+ }
1340
+ function applyOwn(edit, decision) {
1341
+ if (decision.kind === "rewrite") {
1342
+ rewrite(
1343
+ {
1344
+ ...edit,
1345
+ input: edit.input && { ...edit.input, data: decision.data }
1346
+ },
1347
+ decision.data
1348
+ );
1349
+ } else if (decision.kind === "replace") {
1350
+ replace(edit, decision.text, decision.caret);
1351
+ }
1352
+ }
1353
+ function onBeforeInput(event) {
1354
+ const inputType = event.inputType === "" ? null : event.inputType;
1355
+ if (state.kind === "rewriting" || editsNothing(inputType)) {
1356
+ return;
1357
+ }
1358
+ const { edit, decision } = decide(
1359
+ inputType,
1360
+ event.data,
1361
+ event,
1362
+ event.cancelable,
1363
+ event.isComposing || state.kind === "composing"
1364
+ );
1365
+ if (decision.kind === "allow") {
1366
+ if (state.kind !== "composing") {
1367
+ state = { kind: "editing", before: snapshot(control) };
1368
+ }
1369
+ return;
1370
+ }
1371
+ event.preventDefault();
1372
+ applyOwn(edit, decision);
1373
+ }
1374
+ function typeText(data, nativeEvent) {
1375
+ const { edit, decision } = decide(
1376
+ "insertText",
1377
+ data,
1378
+ nativeEvent,
1379
+ true,
1380
+ false
1381
+ );
1382
+ applyOwn(
1383
+ edit,
1384
+ decision.kind === "allow" ? { kind: "rewrite", data } : decision
1385
+ );
1386
+ }
1387
+ function onInput(event) {
1388
+ if (state.kind === "rewriting") {
1389
+ return;
1390
+ }
1391
+ const input = details(event);
1392
+ controller.input({
1393
+ text: control.value,
1394
+ source: controller.getState().phase.kind === "idle" ? "autofill" : sourceOf(input?.inputType ?? null),
1395
+ input,
1396
+ nativeEvent: event
1397
+ });
1398
+ if (state.kind === "editing") {
1399
+ state = READY2;
1400
+ }
1401
+ }
1402
+ function onCompositionStart() {
1403
+ const range = selection() ?? { start: 0, end: control.value.length };
1404
+ state = {
1405
+ kind: "composing",
1406
+ start: range.start,
1407
+ suffixLength: control.value.length - range.end,
1408
+ before: control.value
1409
+ };
1410
+ }
1411
+ function filterComposed(composition, nativeEvent) {
1412
+ const { start, suffixLength, before } = composition;
1413
+ const data = control.value.slice(
1414
+ start,
1415
+ control.value.length - suffixLength
1416
+ );
1417
+ const replacedEnd = before.length - suffixLength;
1418
+ if (data === "" || replacedEnd < start) {
1419
+ return;
1420
+ }
1421
+ const edit = {
1422
+ text: control.value,
1423
+ source: "typing",
1424
+ input: {
1425
+ inputType: "insertCompositionText",
1426
+ data,
1427
+ selectionStart: start,
1428
+ selectionEnd: replacedEnd,
1429
+ isComposing: false
1430
+ },
1431
+ nativeEvent
1432
+ };
1433
+ const decision = controller.filterComposition(edit, before);
1434
+ switch (decision.kind) {
1435
+ case "allow":
1436
+ return;
1437
+ case "prevent":
1438
+ replace(edit, before, start);
1439
+ return;
1440
+ case "rewrite":
1441
+ replace(
1442
+ edit,
1443
+ before.slice(0, start) + decision.data + before.slice(replacedEnd),
1444
+ start + decision.data.length
1445
+ );
1446
+ return;
1447
+ case "replace":
1448
+ replace(edit, decision.text, decision.caret);
1449
+ return;
1450
+ }
1451
+ }
1452
+ function onCompositionEnd(event) {
1453
+ const composition = state.kind === "composing" ? state : null;
1454
+ if (control.value !== controller.getText()) {
1455
+ controller.input({
1456
+ text: control.value,
1457
+ source: "typing",
1458
+ input: {
1459
+ inputType: "insertCompositionText",
1460
+ data: event.data,
1461
+ selectionStart: control.selectionStart,
1462
+ selectionEnd: control.selectionEnd,
1463
+ isComposing: true
1464
+ },
1465
+ nativeEvent: event
1466
+ });
1467
+ }
1468
+ state = READY2;
1469
+ if (composition !== null) {
1470
+ filterComposed(composition, event);
1471
+ }
1472
+ controller.endComposition(event);
1473
+ render();
1474
+ }
1475
+ function isComposing(event) {
1476
+ const legacy = event;
1477
+ return event.isComposing || state.kind === "composing" || legacy.keyCode === 229;
1478
+ }
1479
+ function commitsOnEnter(event) {
1480
+ return control instanceof HTMLTextAreaElement ? event.ctrlKey || event.metaKey : true;
1481
+ }
1482
+ function onKeyDown(event) {
1483
+ if (event.defaultPrevented || isComposing(event)) {
1484
+ return;
1485
+ }
1486
+ const modified = event.ctrlKey || event.altKey || event.metaKey;
1487
+ if (event.code === "NumpadDecimal" && event.key.length === 1 && options.decimalKey !== void 0 && !modified && !control.readOnly && !control.disabled) {
1488
+ event.preventDefault();
1489
+ typeText(options.decimalKey, event);
1490
+ return;
1491
+ }
1492
+ switch (event.key) {
1493
+ case "Enter":
1494
+ if (commitsOnEnter(event)) {
1495
+ controller.commit("enter", event);
1496
+ }
1497
+ return;
1498
+ case "Tab":
1499
+ if (!modified && !inGroup() && controller.commit("tab", event).kind === "refused") {
1500
+ event.preventDefault();
1501
+ }
1502
+ return;
1503
+ case "Escape":
1504
+ if (!modified && !event.shiftKey && escape(event)) {
1505
+ event.preventDefault();
1506
+ }
1507
+ return;
1508
+ }
1509
+ }
1510
+ function escape(event) {
1511
+ switch (options.escape ?? "revert") {
1512
+ case "revert":
1513
+ return controller.revert(event);
1514
+ case "clear":
1515
+ if (control.readOnly || controller.getText() === "") {
1516
+ return false;
1517
+ }
1518
+ options.onClear?.(event);
1519
+ controller.clear(event);
1520
+ return true;
1521
+ case "none":
1522
+ return false;
1523
+ }
1524
+ }
1525
+ function inGroup() {
1526
+ return options.focus === "group";
1527
+ }
1528
+ function onFocus(event) {
1529
+ if (!inGroup()) {
1530
+ controller.focus(event);
1531
+ }
1532
+ if (options.selectOnFocus === true && !pointerFocus) {
1533
+ control.select();
1534
+ }
1535
+ pointerFocus = false;
1536
+ }
1537
+ function limitCaret() {
1538
+ const { lastCaret } = options;
1539
+ const { selectionStart, selectionEnd } = control;
1540
+ if (lastCaret === void 0 || selectionStart === null || selectionStart !== selectionEnd || !hasFocus2(control)) {
1541
+ return;
1542
+ }
1543
+ const last = lastCaret(control.value);
1544
+ if (selectionStart > last) {
1545
+ control.setSelectionRange(last, last);
1546
+ }
1547
+ }
1548
+ function onReset(event) {
1549
+ if (event.defaultPrevented || event.target !== control.form) {
1550
+ return;
1551
+ }
1552
+ controller.reset();
1553
+ control.defaultValue = controller.getText();
1554
+ }
1555
+ const element = control;
1556
+ element.addEventListener("focus", onFocus, { signal });
1557
+ element.addEventListener(
1558
+ "pointerdown",
1559
+ () => {
1560
+ pointerFocus = !hasFocus2(control);
1561
+ },
1562
+ { signal }
1563
+ );
1564
+ element.addEventListener(
1565
+ "click",
1566
+ () => {
1567
+ pointerFocus = false;
1568
+ limitCaret();
1569
+ },
1570
+ { signal }
1571
+ );
1572
+ element.addEventListener(
1573
+ "blur",
1574
+ (event) => {
1575
+ if (!inGroup()) {
1576
+ controller.blur(event);
1577
+ }
1578
+ },
1579
+ { signal }
1580
+ );
1581
+ element.addEventListener("beforeinput", onBeforeInput, { signal });
1582
+ element.addEventListener("input", onInput, { signal });
1583
+ element.addEventListener("compositionstart", onCompositionStart, { signal });
1584
+ element.addEventListener("compositionend", onCompositionEnd, { signal });
1585
+ element.addEventListener("keydown", onKeyDown, { signal });
1586
+ control.ownerDocument.addEventListener("reset", onReset, { signal });
1587
+ const unsubscribe = controller.subscribe(render);
1588
+ if (hasFocus2(control) && !inGroup()) {
1589
+ controller.focus(null);
1590
+ }
1591
+ render();
1592
+ return {
1593
+ setOptions: (next) => {
1594
+ options = next;
1595
+ },
1596
+ detach: () => {
1597
+ if (state.kind === "detached") {
1598
+ return;
1599
+ }
1600
+ state = DETACHED3;
1601
+ listeners.abort();
1602
+ unsubscribe();
1603
+ control.setCustomValidity("");
1604
+ }
1605
+ };
1606
+ }
1607
+
1608
+ // src/toggle/attachToggle.ts
1609
+ import {
1610
+ nextCheckedValue
1611
+ } from "@gridkitjs/forms-core";
1612
+ function hasFocus3(control) {
1613
+ const root = control.getRootNode();
1614
+ return (root instanceof Document || root instanceof ShadowRoot) && root.activeElement === control;
1615
+ }
1616
+ function errorText2(messages) {
1617
+ return messages.find((message) => message.severity === "error")?.text ?? "";
1618
+ }
1619
+ function attachToggle(control, controller, initialOptions = {}) {
1620
+ let options = initialOptions;
1621
+ let attached = true;
1622
+ let customValidity = "";
1623
+ let spaceKey = null;
1624
+ const listeners = new AbortController();
1625
+ const { signal } = listeners;
1626
+ function render() {
1627
+ if (!attached) {
1628
+ return;
1629
+ }
1630
+ const { value } = controller.getState();
1631
+ control.checked = value === true;
1632
+ control.indeterminate = value === null;
1633
+ const validity = errorText2(controller.getMessages());
1634
+ if (validity !== customValidity) {
1635
+ customValidity = validity;
1636
+ control.setCustomValidity(validity);
1637
+ }
1638
+ }
1639
+ function onClick(event) {
1640
+ const nativeEvent = spaceKey ?? event;
1641
+ spaceKey = null;
1642
+ if (options.readOnly === true) {
1643
+ event.preventDefault();
1644
+ return;
1645
+ }
1646
+ const next = nextCheckedValue(
1647
+ controller.getState().value,
1648
+ options.threeState === true
1649
+ );
1650
+ controller.pick(next, "toggle", "toggle", nativeEvent);
1651
+ render();
1652
+ }
1653
+ function onKeyDown(event) {
1654
+ spaceKey = event.key === " " && !event.defaultPrevented ? event : null;
1655
+ }
1656
+ function onReset(event) {
1657
+ if (event.defaultPrevented || event.target !== control.form) {
1658
+ return;
1659
+ }
1660
+ controller.reset();
1661
+ control.defaultChecked = controller.getState().value === true;
1662
+ }
1663
+ control.addEventListener("click", onClick, { signal });
1664
+ control.addEventListener("keydown", onKeyDown, { signal });
1665
+ control.addEventListener(
1666
+ "pointerdown",
1667
+ () => {
1668
+ spaceKey = null;
1669
+ },
1670
+ { signal }
1671
+ );
1672
+ control.addEventListener(
1673
+ "focus",
1674
+ (event) => {
1675
+ controller.focus(event);
1676
+ },
1677
+ { signal }
1678
+ );
1679
+ control.addEventListener(
1680
+ "blur",
1681
+ (event) => {
1682
+ spaceKey = null;
1683
+ controller.blur(event);
1684
+ },
1685
+ { signal }
1686
+ );
1687
+ control.ownerDocument.addEventListener("reset", onReset, { signal });
1688
+ const unsubscribe = controller.subscribe(render);
1689
+ if (hasFocus3(control)) {
1690
+ controller.focus(null);
1691
+ }
1692
+ render();
1693
+ return {
1694
+ setOptions: (next) => {
1695
+ options = next;
1696
+ },
1697
+ detach: () => {
1698
+ if (!attached) {
1699
+ return;
1700
+ }
1701
+ attached = false;
1702
+ listeners.abort();
1703
+ unsubscribe();
1704
+ control.setCustomValidity("");
1705
+ }
1706
+ };
1707
+ }
1708
+
1709
+ // src/segments/attachSegments.ts
1710
+ import {
1711
+ idleSegments,
1712
+ segmentAria,
1713
+ segmentReducer,
1714
+ segmentSpans,
1715
+ splitSegments
1716
+ } from "@gridkitjs/forms-core";
1717
+ var NO_CAUSE = { nativeEvent: null, inputType: null, data: null };
1718
+ function segmentOf(entry) {
1719
+ return entry.kind === "active" || entry.kind === "typing" || entry.kind === "composing" ? entry.segment : null;
1720
+ }
1721
+ var EMPTYING = /* @__PURE__ */ new Set([
1722
+ "deleteContentForward",
1723
+ "deleteWordBackward",
1724
+ "deleteWordForward",
1725
+ "deleteSoftLineBackward",
1726
+ "deleteSoftLineForward",
1727
+ "deleteHardLineBackward",
1728
+ "deleteHardLineForward",
1729
+ "deleteByCut",
1730
+ "deleteContent"
1731
+ ]);
1732
+ function attachSegments(group, controller, initialOptions) {
1733
+ let options = initialOptions;
1734
+ let state = idleSegments(controller.getText());
1735
+ let pressedFocused = null;
1736
+ const listeners = new AbortController();
1737
+ const { signal } = listeners;
1738
+ function segmentInputs() {
1739
+ return Array.from(
1740
+ group.querySelectorAll(
1741
+ "input[data-gridkit-forms-segment]"
1742
+ )
1743
+ );
1744
+ }
1745
+ function textBox() {
1746
+ return group.querySelector(
1747
+ "input[data-gridkit-forms-segment-text]"
1748
+ );
1749
+ }
1750
+ function segmentsWrapper() {
1751
+ return group.querySelector("[data-gridkit-forms-segments]");
1752
+ }
1753
+ function activeElement() {
1754
+ const root = group.getRootNode();
1755
+ return root instanceof Document || root instanceof ShadowRoot ? root.activeElement : null;
1756
+ }
1757
+ function focusWithin() {
1758
+ const active = activeElement();
1759
+ return active !== null && group.contains(active);
1760
+ }
1761
+ function caretToEnd(input) {
1762
+ input.setSelectionRange(input.value.length, input.value.length);
1763
+ }
1764
+ function place(focus) {
1765
+ if (focus === null) {
1766
+ return;
1767
+ }
1768
+ const box2 = textBox();
1769
+ const wrapper = segmentsWrapper();
1770
+ if (focus === "text") {
1771
+ if (box2 === null) {
1772
+ return;
1773
+ }
1774
+ box2.hidden = false;
1775
+ if (activeElement() !== box2) {
1776
+ box2.focus();
1777
+ }
1778
+ caretToEnd(box2);
1779
+ if (wrapper !== null) {
1780
+ wrapper.hidden = true;
1781
+ }
1782
+ return;
1783
+ }
1784
+ const input = segmentInputs()[focus];
1785
+ if (input === void 0) {
1786
+ return;
1787
+ }
1788
+ if (wrapper !== null) {
1789
+ wrapper.hidden = false;
1790
+ }
1791
+ if (activeElement() !== input) {
1792
+ input.focus();
1793
+ }
1794
+ caretToEnd(input);
1795
+ if (box2 !== null) {
1796
+ box2.hidden = true;
1797
+ }
1798
+ }
1799
+ function held() {
1800
+ const text = controller.getText();
1801
+ if (text !== state.text) {
1802
+ const step = segmentReducer(
1803
+ state,
1804
+ { type: "outside", text },
1805
+ options.context
1806
+ );
1807
+ const moved = state.entry.kind === "text" !== (step.state.entry.kind === "text");
1808
+ state = step.state;
1809
+ if (moved && focusWithin()) {
1810
+ place(step.focus);
1811
+ }
1812
+ }
1813
+ return state;
1814
+ }
1815
+ function setAttribute(element, name, value) {
1816
+ if (value === null) {
1817
+ element.removeAttribute(name);
1818
+ } else if (element.getAttribute(name) !== value) {
1819
+ element.setAttribute(name, value);
1820
+ }
1821
+ }
1822
+ function render() {
1823
+ const current = held();
1824
+ const { layout } = options.context;
1825
+ const texts = splitSegments(layout, current.text);
1826
+ const shown = texts ?? layout.segments.map(() => "");
1827
+ const active = activeElement();
1828
+ segmentInputs().forEach((input, index) => {
1829
+ const text = shown[index] ?? "";
1830
+ if (input.value !== text) {
1831
+ input.value = text;
1832
+ if (input === active) {
1833
+ caretToEnd(input);
1834
+ }
1835
+ }
1836
+ const aria = segmentAria(
1837
+ layout,
1838
+ index,
1839
+ shown,
1840
+ options.locale,
1841
+ options.messages
1842
+ );
1843
+ setAttribute(
1844
+ input,
1845
+ "aria-valuenow",
1846
+ aria.valueNow === null ? null : String(aria.valueNow)
1847
+ );
1848
+ setAttribute(input, "aria-valuemin", String(aria.valueMin));
1849
+ setAttribute(input, "aria-valuemax", String(aria.valueMax));
1850
+ setAttribute(input, "aria-valuetext", aria.valueText);
1851
+ });
1852
+ if (!focusWithin()) {
1853
+ const free = current.entry.kind === "text" || texts === null;
1854
+ const box2 = textBox();
1855
+ const wrapper = segmentsWrapper();
1856
+ if (box2 !== null) {
1857
+ box2.hidden = !free;
1858
+ }
1859
+ if (wrapper !== null) {
1860
+ wrapper.hidden = free;
1861
+ }
1862
+ }
1863
+ }
1864
+ function editFor(before, step, cause) {
1865
+ const edited = segmentOf(before.entry);
1866
+ const span = edited === null ? void 0 : segmentSpans(options.context.layout, step.state.text)?.[edited];
1867
+ return {
1868
+ text: step.state.text,
1869
+ source: cause.source ?? step.source ?? "typing",
1870
+ nativeEvent: cause.nativeEvent,
1871
+ input: {
1872
+ inputType: cause.inputType,
1873
+ data: cause.data,
1874
+ selectionStart: span?.[0] ?? null,
1875
+ selectionEnd: span?.[1] ?? null,
1876
+ isComposing: false
1877
+ }
1878
+ };
1879
+ }
1880
+ function apply(before, proposed, cause) {
1881
+ let step = proposed;
1882
+ let { data } = cause;
1883
+ if (step.source !== null) {
1884
+ const verdict = controller.beforeInput({
1885
+ ...editFor(before, step, cause),
1886
+ cancelable: true
1887
+ });
1888
+ if (verdict.kind === "prevent") {
1889
+ render();
1890
+ return;
1891
+ }
1892
+ if (verdict.kind === "rewrite") {
1893
+ step = segmentReducer(
1894
+ before,
1895
+ { type: "key", text: verdict.data },
1896
+ options.context
1897
+ );
1898
+ data = verdict.data;
1899
+ }
1900
+ }
1901
+ if (step.source === null) {
1902
+ state = step.state;
1903
+ } else {
1904
+ report(before, step, editFor(before, step, { ...cause, data }));
1905
+ }
1906
+ place(step.focus);
1907
+ render();
1908
+ }
1909
+ function report(before, step, edit) {
1910
+ if (step.applied !== void 0) {
1911
+ state = {
1912
+ entry: before.entry.kind === "text" ? before.entry : { kind: "text", before: before.text },
1913
+ text: step.applied
1914
+ };
1915
+ controller.input({
1916
+ ...edit,
1917
+ text: step.applied,
1918
+ input: withoutPlace(edit)
1919
+ });
1920
+ }
1921
+ state = step.state;
1922
+ controller.input(edit);
1923
+ }
1924
+ function withoutPlace(edit) {
1925
+ return edit.input && { ...edit.input, selectionStart: null, selectionEnd: null };
1926
+ }
1927
+ function run(action, cause = NO_CAUSE) {
1928
+ const before = held();
1929
+ apply(before, segmentReducer(before, action, options.context), cause);
1930
+ }
1931
+ function finish(nativeEvent) {
1932
+ run({ type: "finish" }, { ...NO_CAUSE, nativeEvent });
1933
+ }
1934
+ function isComposing(event) {
1935
+ const legacy = event;
1936
+ return event.isComposing || state.entry.kind === "composing" || legacy.keyCode === 229;
1937
+ }
1938
+ function neighbourOnScreen(index, key) {
1939
+ const inputs = segmentInputs();
1940
+ const byPosition = inputs.map((input, at) => ({ at, left: input.getBoundingClientRect().left })).sort((a, b) => a.left - b.left);
1941
+ const position = byPosition.findIndex((entry) => entry.at === index);
1942
+ const next = byPosition[position + (key === "ArrowRight" ? 1 : -1)];
1943
+ return next?.at ?? null;
1944
+ }
1945
+ function onSegmentKey(event, input, index) {
1946
+ const editable = !input.readOnly;
1947
+ const step = (direction, size) => {
1948
+ event.preventDefault();
1949
+ if (editable) {
1950
+ run(
1951
+ { type: "step", direction, size },
1952
+ { nativeEvent: event, inputType: null, data: null }
1953
+ );
1954
+ }
1955
+ };
1956
+ switch (event.key) {
1957
+ case "Enter":
1958
+ finish(event);
1959
+ controller.commit("enter", event);
1960
+ return;
1961
+ case "Backspace":
1962
+ case "Delete":
1963
+ event.preventDefault();
1964
+ if (editable) {
1965
+ run(
1966
+ { type: event.key === "Backspace" ? "backspace" : "delete" },
1967
+ {
1968
+ nativeEvent: event,
1969
+ inputType: event.key === "Backspace" ? "deleteContentBackward" : "deleteContentForward",
1970
+ data: null
1971
+ }
1972
+ );
1973
+ }
1974
+ return;
1975
+ case "ArrowUp":
1976
+ step("up", "step");
1977
+ return;
1978
+ case "ArrowDown":
1979
+ step("down", "step");
1980
+ return;
1981
+ case "PageUp":
1982
+ step("up", "large");
1983
+ return;
1984
+ case "PageDown":
1985
+ step("down", "large");
1986
+ return;
1987
+ case "Home":
1988
+ step("down", "edge");
1989
+ return;
1990
+ case "End":
1991
+ step("up", "edge");
1992
+ return;
1993
+ case "ArrowLeft":
1994
+ case "ArrowRight": {
1995
+ event.preventDefault();
1996
+ const to = neighbourOnScreen(index, event.key);
1997
+ if (to !== null) {
1998
+ run(
1999
+ { type: "focus", segment: to },
2000
+ { ...NO_CAUSE, nativeEvent: event }
2001
+ );
2002
+ }
2003
+ return;
2004
+ }
2005
+ }
2006
+ }
2007
+ function onKeyDown(event) {
2008
+ if (event.defaultPrevented || isComposing(event)) {
2009
+ return;
2010
+ }
2011
+ const { target } = event;
2012
+ const inputs = segmentInputs();
2013
+ const index = target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;
2014
+ const box2 = textBox();
2015
+ const inBox = target !== null && target === box2;
2016
+ const input = inputs[index];
2017
+ if (!inBox && input === void 0) {
2018
+ return;
2019
+ }
2020
+ const modified = event.ctrlKey || event.altKey || event.metaKey;
2021
+ if (input !== void 0 && options.onOpenPicker !== void 0 && (event.key === "F4" && !modified || event.altKey && event.key === "ArrowDown")) {
2022
+ event.preventDefault();
2023
+ options.onOpenPicker(event);
2024
+ return;
2025
+ }
2026
+ switch (event.key) {
2027
+ case "Tab":
2028
+ if (modified) {
2029
+ return;
2030
+ }
2031
+ finish(event);
2032
+ if (controller.commit("tab", event).kind === "refused") {
2033
+ event.preventDefault();
2034
+ }
2035
+ return;
2036
+ case "Escape":
2037
+ if (modified || event.shiftKey) {
2038
+ return;
2039
+ }
2040
+ if (inBox && state.entry.kind === "text") {
2041
+ event.preventDefault();
2042
+ run(
2043
+ { type: "textEdit", text: "" },
2044
+ { ...NO_CAUSE, nativeEvent: event }
2045
+ );
2046
+ } else if ((options.escape ?? "revert") === "revert" && controller.revert(event)) {
2047
+ event.preventDefault();
2048
+ }
2049
+ return;
2050
+ }
2051
+ if (input !== void 0 && !modified) {
2052
+ onSegmentKey(event, input, index);
2053
+ }
2054
+ }
2055
+ function onBeforeInput(event) {
2056
+ const { target } = event;
2057
+ if (!(target instanceof HTMLInputElement)) {
2058
+ return;
2059
+ }
2060
+ const index = segmentInputs().indexOf(target);
2061
+ if (index < 0 || !event.cancelable || event.isComposing) {
2062
+ return;
2063
+ }
2064
+ event.preventDefault();
2065
+ if (target.readOnly) {
2066
+ return;
2067
+ }
2068
+ const inputType = event.inputType;
2069
+ const cause = {
2070
+ nativeEvent: event,
2071
+ inputType,
2072
+ data: event.data
2073
+ };
2074
+ if (inputType === "insertText" || inputType === "insertReplacementText") {
2075
+ run({ type: "key", text: event.data ?? "" }, cause);
2076
+ } else if (inputType === "insertFromPaste" || inputType === "insertFromDrop") {
2077
+ const text = event.dataTransfer?.getData("text/plain") ?? event.data;
2078
+ run(
2079
+ { type: "paste", text: text ?? "" },
2080
+ {
2081
+ ...cause,
2082
+ data: text,
2083
+ source: inputType === "insertFromDrop" ? "drop" : "paste"
2084
+ }
2085
+ );
2086
+ } else if (inputType === "deleteContentBackward") {
2087
+ run({ type: "backspace" }, cause);
2088
+ } else if (EMPTYING.has(inputType)) {
2089
+ run({ type: "delete" }, cause);
2090
+ }
2091
+ }
2092
+ function onPaste(event) {
2093
+ const { target } = event;
2094
+ if (!(target instanceof HTMLInputElement) || !segmentInputs().includes(target)) {
2095
+ return;
2096
+ }
2097
+ event.preventDefault();
2098
+ if (target.readOnly) {
2099
+ return;
2100
+ }
2101
+ const text = event.clipboardData?.getData("text/plain") ?? "";
2102
+ run(
2103
+ { type: "paste", text },
2104
+ {
2105
+ nativeEvent: event,
2106
+ inputType: "insertFromPaste",
2107
+ data: text,
2108
+ source: "paste"
2109
+ }
2110
+ );
2111
+ }
2112
+ function onCompositionStart(event) {
2113
+ if (event.target instanceof HTMLInputElement && segmentInputs().includes(event.target)) {
2114
+ run({ type: "compositionStart" });
2115
+ }
2116
+ }
2117
+ function onCompositionEnd(event) {
2118
+ const { target } = event;
2119
+ if (!(target instanceof HTMLInputElement) || state.entry.kind !== "composing") {
2120
+ return;
2121
+ }
2122
+ const before = splitSegments(options.context.layout, state.text);
2123
+ target.value = before?.[state.entry.segment] ?? "";
2124
+ run(
2125
+ { type: "compositionEnd", text: event.data },
2126
+ {
2127
+ nativeEvent: event,
2128
+ inputType: "insertCompositionText",
2129
+ data: event.data
2130
+ }
2131
+ );
2132
+ }
2133
+ function onInput(event) {
2134
+ if (event.target instanceof HTMLInputElement && segmentInputs().includes(event.target) && state.entry.kind !== "composing") {
2135
+ render();
2136
+ }
2137
+ }
2138
+ function onFocusIn(event) {
2139
+ const { target } = event;
2140
+ const box2 = textBox();
2141
+ const index = target instanceof HTMLInputElement ? segmentInputs().indexOf(target) : -1;
2142
+ const inBox = target !== null && target === box2;
2143
+ if (index < 0 && !inBox) {
2144
+ return;
2145
+ }
2146
+ const current = held();
2147
+ if (current.entry.kind === "idle") {
2148
+ controller.focus(event);
2149
+ }
2150
+ if (inBox) {
2151
+ if (state.entry.kind !== "text") {
2152
+ run({ type: "focus", segment: 0 }, { ...NO_CAUSE, nativeEvent: event });
2153
+ }
2154
+ return;
2155
+ }
2156
+ if (segmentOf(state.entry) !== index) {
2157
+ run(
2158
+ { type: "focus", segment: index },
2159
+ { ...NO_CAUSE, nativeEvent: event }
2160
+ );
2161
+ }
2162
+ }
2163
+ function leave(nativeEvent) {
2164
+ const before = held();
2165
+ if (before.entry.kind === "idle") {
2166
+ return;
2167
+ }
2168
+ const step = segmentReducer(before, { type: "leave" }, options.context);
2169
+ if (step.source !== null) {
2170
+ const edit = editFor(before, step, { ...NO_CAUSE, nativeEvent });
2171
+ const verdict = controller.beforeInput({ ...edit, cancelable: true });
2172
+ if (verdict.kind !== "prevent") {
2173
+ state = { entry: before.entry, text: step.state.text };
2174
+ controller.input(edit);
2175
+ }
2176
+ }
2177
+ controller.blur(nativeEvent);
2178
+ state = idleSegments(controller.getText());
2179
+ render();
2180
+ }
2181
+ function focusSegment(segment = "firstEmpty") {
2182
+ const current = held();
2183
+ const { layout } = options.context;
2184
+ const texts = splitSegments(layout, current.text);
2185
+ if (texts === null || current.entry.kind === "text") {
2186
+ const box2 = textBox();
2187
+ if (box2 !== null) {
2188
+ box2.hidden = false;
2189
+ box2.focus();
2190
+ }
2191
+ return;
2192
+ }
2193
+ const index = segment === "firstEmpty" ? Math.max(
2194
+ texts.findIndex((text) => text === ""),
2195
+ 0
2196
+ ) : segment;
2197
+ segmentInputs()[index]?.focus();
2198
+ }
2199
+ function isOwnControl(target) {
2200
+ return target instanceof Element && target.closest("input, button, select, textarea, a, label") !== null;
2201
+ }
2202
+ group.addEventListener("keydown", onKeyDown, { signal });
2203
+ group.addEventListener("beforeinput", onBeforeInput, { signal });
2204
+ group.addEventListener("input", onInput, { signal });
2205
+ group.addEventListener("paste", onPaste, { signal });
2206
+ group.addEventListener("compositionstart", onCompositionStart, { signal });
2207
+ group.addEventListener("compositionend", onCompositionEnd, { signal });
2208
+ group.addEventListener("focusin", onFocusIn, { signal });
2209
+ group.addEventListener(
2210
+ "mousedown",
2211
+ (event) => {
2212
+ if (!isOwnControl(event.target) && focusWithin()) {
2213
+ event.preventDefault();
2214
+ }
2215
+ },
2216
+ { signal }
2217
+ );
2218
+ group.addEventListener(
2219
+ "pointerdown",
2220
+ (event) => {
2221
+ const { target } = event;
2222
+ pressedFocused = target instanceof HTMLInputElement && target === activeElement() && segmentInputs().includes(target) ? target : null;
2223
+ },
2224
+ { signal }
2225
+ );
2226
+ group.addEventListener(
2227
+ "click",
2228
+ (event) => {
2229
+ const { target } = event;
2230
+ const inputs = segmentInputs();
2231
+ const disabled = inputs.every((input) => input.disabled);
2232
+ if (!isOwnControl(target)) {
2233
+ if (!disabled) {
2234
+ focusSegment("firstEmpty");
2235
+ }
2236
+ return;
2237
+ }
2238
+ const index = target instanceof HTMLInputElement ? inputs.indexOf(target) : -1;
2239
+ const pressed = pressedFocused;
2240
+ pressedFocused = null;
2241
+ if (index >= 0 && pressed !== null && pressed === target && !pressed.readOnly && options.context.layout.segments[index]?.type === "dayPeriod") {
2242
+ run(
2243
+ { type: "step", direction: "up", size: "step" },
2244
+ { nativeEvent: event, inputType: null, data: null }
2245
+ );
2246
+ }
2247
+ },
2248
+ { signal }
2249
+ );
2250
+ const focusGroup = attachFocusGroup(group, {
2251
+ onLeave: (_by, nativeEvent) => {
2252
+ leave(nativeEvent);
2253
+ },
2254
+ isInside: (node) => options.isInside?.(node) === true
2255
+ });
2256
+ const boxController = {
2257
+ ...controller,
2258
+ input: (edit) => {
2259
+ if (edit.input?.isComposing === true || held().entry.kind !== "text") {
2260
+ controller.input(edit);
2261
+ return;
2262
+ }
2263
+ const before = state;
2264
+ const step = segmentReducer(
2265
+ before,
2266
+ { type: "textEdit", text: edit.text, source: edit.source },
2267
+ options.context
2268
+ );
2269
+ report(
2270
+ before,
2271
+ step,
2272
+ step.state.text === edit.text ? edit : { ...edit, text: step.state.text, input: withoutPlace(edit) }
2273
+ );
2274
+ place(step.focus);
2275
+ render();
2276
+ }
2277
+ };
2278
+ const box = textBox();
2279
+ const boxPipeline = box === null ? null : attachTextInput(box, boxController, { focus: "group", escape: "none" });
2280
+ const unsubscribe = controller.subscribe(render);
2281
+ const focused = activeElement();
2282
+ if (focused instanceof HTMLInputElement) {
2283
+ const index = segmentInputs().indexOf(focused);
2284
+ if (index >= 0) {
2285
+ controller.focus(null);
2286
+ run({ type: "focus", segment: index });
2287
+ }
2288
+ }
2289
+ render();
2290
+ return {
2291
+ setOptions: (next) => {
2292
+ options = next;
2293
+ render();
2294
+ },
2295
+ focus: focusSegment,
2296
+ getState: () => state,
2297
+ detach: () => {
2298
+ listeners.abort();
2299
+ focusGroup.detach();
2300
+ boxPipeline?.detach();
2301
+ unsubscribe();
2302
+ }
2303
+ };
2304
+ }
2305
+ export {
2306
+ attachAutoGrow,
2307
+ attachChecklist,
2308
+ attachEnterNavigation,
2309
+ attachFitCount,
2310
+ attachFocusGroup,
2311
+ attachHoldRepeat,
2312
+ attachOverlay,
2313
+ attachSegments,
2314
+ attachStepKeys,
2315
+ attachTextInput,
2316
+ attachToggle,
2317
+ compareDocumentOrder,
2318
+ createLiveAnnouncer,
2319
+ createRowVirtualizer,
2320
+ findFirstInvalidControl,
2321
+ focusTargetIn,
2322
+ placeOverlay,
2323
+ scheduleTimeout,
2324
+ writingDirection
2325
+ };
2326
+ //# sourceMappingURL=index.js.map