kerfjs 5.0.0-beta.13 → 5.0.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +3384 -108
  2. package/README.md +101 -37
  3. package/ai/cursorrules +127 -68
  4. package/ai/manifest.json +36 -7
  5. package/ai/skill.md +167 -86
  6. package/ai/ui-skill.md +18 -0
  7. package/dist/actions.d.ts +1 -1
  8. package/dist/actions.js +10 -6
  9. package/dist/actions.js.map +1 -1
  10. package/dist/array-signal.js +1 -1
  11. package/dist/async.d.ts +7 -3
  12. package/dist/async.js +39 -22
  13. package/dist/async.js.map +1 -1
  14. package/dist/attach.js +1 -66
  15. package/dist/attach.js.map +1 -1
  16. package/dist/{chunk-GY4XV2UV.js → chunk-4TX6YJDM.js} +10 -3
  17. package/dist/chunk-4TX6YJDM.js.map +1 -0
  18. package/dist/{chunk-SVATPF5R.js → chunk-5QDM6HPD.js} +637 -277
  19. package/dist/chunk-5QDM6HPD.js.map +1 -0
  20. package/dist/{chunk-QIP723L4.js → chunk-5WRGJZV6.js} +3 -2
  21. package/dist/chunk-5WRGJZV6.js.map +1 -0
  22. package/dist/chunk-AP2FT33F.js +87 -0
  23. package/dist/chunk-AP2FT33F.js.map +1 -0
  24. package/dist/chunk-BTOKH5FA.js +70 -0
  25. package/dist/chunk-BTOKH5FA.js.map +1 -0
  26. package/dist/{chunk-ZDCJZCNO.js → chunk-GGADRIQO.js} +168 -97
  27. package/dist/chunk-GGADRIQO.js.map +1 -0
  28. package/dist/chunk-KOEGJCIS.js +65 -0
  29. package/dist/chunk-KOEGJCIS.js.map +1 -0
  30. package/dist/{chunk-HW7KSM2Y.js → chunk-KUHXPPJ4.js} +1 -1
  31. package/dist/chunk-KUHXPPJ4.js.map +1 -0
  32. package/dist/{chunk-UZJ6I4T6.js → chunk-MK42GLPV.js} +1 -1
  33. package/dist/chunk-MK42GLPV.js.map +1 -0
  34. package/dist/chunk-N4VHHOCM.js +27 -0
  35. package/dist/chunk-N4VHHOCM.js.map +1 -0
  36. package/dist/{chunk-V46JKE44.js → chunk-NRPLVJVR.js} +43 -14
  37. package/dist/chunk-NRPLVJVR.js.map +1 -0
  38. package/dist/{chunk-LVH3GC6B.js → chunk-QOAB2ESQ.js} +3 -3
  39. package/dist/chunk-QOAB2ESQ.js.map +1 -0
  40. package/dist/{chunk-KZJXHFIB.js → chunk-V322Z7FX.js} +5 -5
  41. package/dist/chunk-V322Z7FX.js.map +1 -0
  42. package/dist/{delegate-CL9VTZFb.d.ts → delegate--CrfgYtC.d.ts} +0 -34
  43. package/dist/dev.d.ts +46 -15
  44. package/dist/dev.js +185 -40
  45. package/dist/dev.js.map +1 -1
  46. package/dist/html.js +20 -8
  47. package/dist/html.js.map +1 -1
  48. package/dist/index.d.ts +98 -13
  49. package/dist/index.js +49 -21
  50. package/dist/index.js.map +1 -1
  51. package/dist/jsx-runtime.d.ts +25 -10
  52. package/dist/jsx-runtime.js +1 -1
  53. package/dist/list.d.ts +7 -3
  54. package/dist/list.js +236 -78
  55. package/dist/list.js.map +1 -1
  56. package/dist/overlay.d.ts +287 -142
  57. package/dist/overlay.js +1040 -369
  58. package/dist/overlay.js.map +1 -1
  59. package/dist/remount.js +2 -2
  60. package/dist/remount.js.map +1 -1
  61. package/dist/router.d.ts +22 -6
  62. package/dist/router.js +58 -19
  63. package/dist/router.js.map +1 -1
  64. package/dist/scope.d.ts +45 -8
  65. package/dist/scope.js +69 -30
  66. package/dist/scope.js.map +1 -1
  67. package/dist/testing.js +1 -1
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +8 -3
  70. package/dist/timing.js.map +1 -1
  71. package/llms.txt +17 -6
  72. package/package.json +48 -12
  73. package/setup/apply.mjs +202 -0
  74. package/setup/cli.mjs +95 -0
  75. package/setup/common.mjs +91 -0
  76. package/setup/detect.mjs +274 -0
  77. package/setup/index.d.mts +39 -0
  78. package/setup/index.mjs +1290 -0
  79. package/setup/jsonc.mjs +201 -0
  80. package/setup/state.schema.json +57 -0
  81. package/setup/ui-baseline.mjs +210 -0
  82. package/dist/chunk-GY4XV2UV.js.map +0 -1
  83. package/dist/chunk-HW7KSM2Y.js.map +0 -1
  84. package/dist/chunk-KPXIOG2C.js +0 -54
  85. package/dist/chunk-KPXIOG2C.js.map +0 -1
  86. package/dist/chunk-KZJXHFIB.js.map +0 -1
  87. package/dist/chunk-LVH3GC6B.js.map +0 -1
  88. package/dist/chunk-QIP723L4.js.map +0 -1
  89. package/dist/chunk-SVATPF5R.js.map +0 -1
  90. package/dist/chunk-U6FK33SG.js +0 -20
  91. package/dist/chunk-U6FK33SG.js.map +0 -1
  92. package/dist/chunk-UZJ6I4T6.js.map +0 -1
  93. package/dist/chunk-V46JKE44.js.map +0 -1
  94. package/dist/chunk-ZDCJZCNO.js.map +0 -1
package/dist/overlay.js CHANGED
@@ -1,48 +1,19 @@
1
- import { mount } from './chunk-SVATPF5R.js';
2
- import { delegate } from './chunk-KPXIOG2C.js';
1
+ import { attach } from './chunk-BTOKH5FA.js';
2
+ import { mount } from './chunk-5QDM6HPD.js';
3
+ import { delegate } from './chunk-AP2FT33F.js';
3
4
 
4
5
 
5
- import { jsx, escapeHtml } from './chunk-ZDCJZCNO.js';
6
+ import { jsx, escapeHtml } from './chunk-GGADRIQO.js';
6
7
 
7
-
8
-
9
-
10
- // src/overlay-position.ts
11
- function positionAnchored(el, anchor, options = {}) {
12
- const { placement = "bottom", align = "start", gap = 4 } = options;
13
- el.style.position = "fixed";
14
- el.style.margin = "0";
15
- const anchorRect = anchor.getBoundingClientRect();
16
- const elementRect = el.getBoundingClientRect();
17
- const viewportWidth = window.innerWidth;
18
- const viewportHeight = window.innerHeight;
19
- const belowTop = anchorRect.bottom + gap;
20
- const aboveTop = anchorRect.top - gap - elementRect.height;
21
- let below = placement !== "top";
22
- if (below && belowTop + elementRect.height > viewportHeight && aboveTop >= 0) below = false;
23
- else if (!below && aboveTop < 0 && belowTop + elementRect.height <= viewportHeight) below = true;
24
- let left = align === "end" ? anchorRect.right - elementRect.width : anchorRect.left;
25
- left = Math.max(0, Math.min(left, viewportWidth - elementRect.width));
26
- el.style.left = `${left}px`;
27
- el.style.top = `${below ? belowTop : aboveTop}px`;
28
- }
29
- function autoReposition(el, anchor, options = {}) {
30
- const reposition = () => positionAnchored(el, anchor, options);
31
- reposition();
32
- window.addEventListener("scroll", reposition, true);
33
- window.addEventListener("resize", reposition);
34
- return () => {
35
- window.removeEventListener("scroll", reposition, true);
36
- window.removeEventListener("resize", reposition);
37
- };
38
- }
8
+ import { OVERLAY_HOST_SELECTOR } from './chunk-4TX6YJDM.js';
9
+ import { devHooks } from './chunk-KUHXPPJ4.js';
39
10
 
40
11
  // src/overlay-core.ts
41
12
  var FOCUSABLE = 'a[href],area[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),iframe,[tabindex]:not([tabindex="-1"]),[contenteditable="true"]';
42
13
  function focusable(root) {
43
- const items = Array.from(root.querySelectorAll(FOCUSABLE)).filter(
44
- (el) => !el.hasAttribute("hidden") && el.tabIndex >= 0
45
- );
14
+ const items = Array.from(
15
+ root.querySelectorAll(FOCUSABLE)
16
+ ).filter((el) => !el.hasAttribute("hidden") && el.tabIndex >= 0);
46
17
  for (const el of items) if (!el.hasAttribute("tabindex")) el.tabIndex = 0;
47
18
  return items;
48
19
  }
@@ -52,10 +23,146 @@ function supportsDialog() {
52
23
  function supportsPopover() {
53
24
  return typeof HTMLElement !== "undefined" && typeof HTMLElement.prototype.showPopover === "function";
54
25
  }
55
- var FALLBACK_OVERLAY_STACK = /* @__PURE__ */ Symbol("kerf.fallbackOverlayStack");
56
- function fallbackOverlayStack(wrapper) {
57
- const document2 = wrapper.ownerDocument;
58
- return document2[FALLBACK_OVERLAY_STACK] ??= [];
26
+ var INSTANT = { instant: true };
27
+ function toArray(value) {
28
+ if (value === void 0) return [];
29
+ return Array.isArray(value) ? [...value] : [value];
30
+ }
31
+ var KEYBOARD_INSET = "--kerf-keyboard-inset";
32
+ function followKeyboardInset(el, removers) {
33
+ const viewport = globalThis.visualViewport;
34
+ if (viewport == null) return;
35
+ const publish = () => {
36
+ const inset = viewport.scale > 1.01 ? 0 : Math.round(
37
+ globalThis.innerHeight - viewport.height - viewport.offsetTop
38
+ );
39
+ if (inset > 0) el.style.setProperty(KEYBOARD_INSET, `${inset}px`);
40
+ else el.style.removeProperty(KEYBOARD_INSET);
41
+ };
42
+ viewport.addEventListener("resize", publish);
43
+ viewport.addEventListener("scroll", publish);
44
+ removers.push(() => {
45
+ viewport.removeEventListener("resize", publish);
46
+ viewport.removeEventListener("scroll", publish);
47
+ el.style.removeProperty(KEYBOARD_INSET);
48
+ });
49
+ publish();
50
+ }
51
+ var OVERLAY_ARBITRATION = /* @__PURE__ */ Symbol("kerf.overlayArbitration");
52
+ function overlayArbitration(doc) {
53
+ const arbitrated = doc;
54
+ return arbitrated[OVERLAY_ARBITRATION] ??= {
55
+ stack: [],
56
+ handled: /* @__PURE__ */ new WeakSet(),
57
+ // KF-AHY6H4: an app-owned modal `<dialog>` opened outside kerf would leave
58
+ // the kerf surfaces already showing inert beneath it. A dialog fires
59
+ // `toggle` after it opens (it does not bubble, so listen in the capture
60
+ // phase); re-host above it exactly as kerf does for its own dialogs, which
61
+ // are skipped here because `overlay()` already re-hosted synchronously.
62
+ onToggle: (event) => {
63
+ const dialog = event.target;
64
+ const arbitration = arbitrated[OVERLAY_ARBITRATION];
65
+ if (dialog.tagName === "DIALOG" && !arbitration.stack.some(({ el }) => el === dialog) && isOpenModal(dialog, arbitration))
66
+ rehostAbove(arbitration, dialog);
67
+ },
68
+ shadowRoots: /* @__PURE__ */ new Set()
69
+ };
70
+ }
71
+ function openShadowRoots(root, found = []) {
72
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
73
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
74
+ const shadow = node.shadowRoot;
75
+ if (shadow !== null) {
76
+ found.push(shadow);
77
+ openShadowRoots(shadow, found);
78
+ }
79
+ }
80
+ return found;
81
+ }
82
+ function watchShadowRoots(arbitration, roots) {
83
+ for (const root of roots)
84
+ if (!arbitration.shadowRoots.has(root)) {
85
+ arbitration.shadowRoots.add(root);
86
+ root.addEventListener("toggle", arbitration.onToggle, true);
87
+ }
88
+ }
89
+ function renderedInside(el, dialog) {
90
+ for (let node = el; node !== null; ) {
91
+ if (node === dialog) return true;
92
+ const root = node.getRootNode();
93
+ node = node.assignedSlot ?? node.parentElement ?? (root instanceof ShadowRoot ? root.host : null);
94
+ }
95
+ return false;
96
+ }
97
+ function rehostAbove(arbitration, dialog) {
98
+ for (const { el, liftAbove } of arbitration.stack)
99
+ if (el !== dialog && el.isConnected && !renderedInside(el, dialog))
100
+ liftAbove?.();
101
+ }
102
+ function isOpenModal(dialog, arbitration) {
103
+ if (!dialog.isConnected || dialog.open !== true)
104
+ return false;
105
+ if (arbitration.stack.some(({ el, modal }) => modal && el === dialog))
106
+ return true;
107
+ try {
108
+ return dialog.matches(":modal");
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+ function modalDialogOpen(doc, arbitration, shadowRoots) {
114
+ return arbitration.stack.some(({ el }) => isOpenModal(el, arbitration)) || [doc, ...shadowRoots].some(
115
+ (root) => Array.from(root.querySelectorAll("dialog[open]")).some(
116
+ (dialog) => isOpenModal(dialog, arbitration)
117
+ )
118
+ );
119
+ }
120
+ function modalContext(el, arbitration) {
121
+ let child;
122
+ for (let node = el; node !== null; ) {
123
+ const dialog = node.localName === "dialog" ? node : child?.assignedSlot?.closest("dialog");
124
+ if (dialog != null)
125
+ return isOpenModal(dialog, arbitration) ? { dialog, root: node } : void 0;
126
+ child = node;
127
+ const root = node.getRootNode();
128
+ node = node.parentElement ?? (root instanceof ShadowRoot ? root.host : null);
129
+ }
130
+ return void 0;
131
+ }
132
+ function overlayHost(anchor) {
133
+ const arbitration = overlayArbitration(document);
134
+ const context = modalContext(anchor, arbitration);
135
+ if (context === void 0) return void 0;
136
+ const { dialog, root } = context;
137
+ let host = Array.from(root.querySelectorAll(OVERLAY_HOST_SELECTOR)).find(
138
+ (el) => modalContext(el, arbitration)?.root === root
139
+ );
140
+ if (host === void 0 && (root !== dialog || arbitration.stack.some(({ el }) => el === dialog))) {
141
+ root.insertAdjacentHTML(
142
+ "beforeend",
143
+ '<div data-kerf-overlay-host data-morph-skip data-morph-preserve style="display:contents"></div>'
144
+ );
145
+ host = root.lastElementChild;
146
+ }
147
+ return host;
148
+ }
149
+ function ownsInput(stack, self, kind) {
150
+ for (let i = stack.indexOf(self) + 1; i < stack.length; i++) {
151
+ const above = stack[i];
152
+ if (above.modal || kind !== "trap" && above.triggers.includes(kind))
153
+ return false;
154
+ }
155
+ return true;
156
+ }
157
+ function assertInitialFocusSelector(selector) {
158
+ try {
159
+ document.createDocumentFragment().querySelector(selector);
160
+ } catch (cause) {
161
+ throw new Error(
162
+ `overlay(): invalid initialFocus selector ${JSON.stringify(selector)}`,
163
+ { cause }
164
+ );
165
+ }
59
166
  }
60
167
  function overlay(content, options = {}) {
61
168
  const {
@@ -67,224 +174,336 @@ function overlay(content, options = {}) {
67
174
  role = "dialog",
68
175
  onDismiss,
69
176
  outsideIgnore,
70
- native = false
177
+ native = false,
178
+ presentation = "modal",
179
+ exitClass,
180
+ exitDuration = 0
71
181
  } = options;
72
- const triggers = dismiss === false ? [] : Array.isArray(dismiss) ? dismiss : [dismiss];
73
- const restoreTo = document.activeElement;
74
- const useDialog = native && trap && supportsDialog();
75
- const usePopover = native && !trap && supportsPopover();
182
+ if (typeof initialFocus === "string")
183
+ assertInitialFocusSelector(initialFocus);
184
+ const triggers = dismiss === false ? [] : toArray(dismiss);
185
+ const arbitration = overlayArbitration(document);
186
+ const containerContext = modalContext(container, arbitration);
187
+ const shadowRoots = openShadowRoots(document);
188
+ const liftOverModal = !native && containerContext === void 0 && modalDialogOpen(document, arbitration, shadowRoots);
189
+ const topLayer = native || liftOverModal;
190
+ const useDialog = topLayer && trap && supportsDialog();
191
+ const usePopover = topLayer && !trap && supportsPopover();
76
192
  const wrapper = useDialog ? document.createElement("dialog") : document.createElement("div");
77
193
  wrapper.className = className;
78
194
  if (usePopover) wrapper.setAttribute("popover", "manual");
195
+ const bottomSheet = presentation === "bottom-sheet";
196
+ if (bottomSheet) wrapper.setAttribute("data-presentation", "bottom-sheet");
79
197
  if (trap && !useDialog) {
80
198
  wrapper.setAttribute("role", role);
81
199
  wrapper.setAttribute("aria-modal", "true");
82
200
  }
83
- container.appendChild(wrapper);
84
- const fallback = !useDialog && !usePopover;
85
- const fallbackStack = fallback ? fallbackOverlayStack(wrapper) : void 0;
86
- const isTopmostFallback = () => fallbackStack === void 0 || fallbackStack[fallbackStack.length - 1] === wrapper;
87
- const disposeMount = mount(wrapper, typeof content === "function" ? content : () => content);
88
- fallbackStack?.push(wrapper);
89
- let nativeOpened = false;
90
- if (useDialog) {
91
- wrapper.showModal();
92
- nativeOpened = true;
93
- } else if (usePopover) {
94
- wrapper.showPopover();
95
- wrapper.style.inset = "auto";
96
- nativeOpened = true;
97
- }
201
+ const surface = {
202
+ el: wrapper,
203
+ triggers,
204
+ modal: trap,
205
+ restoreTo: document.activeElement,
206
+ leave: (now) => close(void 0, now ? INSTANT : void 0)
207
+ };
208
+ const owns = (kind, event) => !(event !== void 0 && arbitration.handled.has(event)) && ownsInput(arbitration.stack, surface, kind);
98
209
  const removers = [];
210
+ const finalizers = [];
99
211
  const resultBox = {};
100
212
  const result = new Promise((resolve) => {
101
213
  resultBox.resolve = resolve;
102
214
  });
103
- const state = { closed: false };
104
- function close(value) {
105
- if (state.closed) return;
215
+ const state = { closed: false, removed: false };
216
+ let disposeMount;
217
+ let nativeOpened = false;
218
+ let exitTimer;
219
+ if (!trap)
220
+ surface.liftAbove = () => {
221
+ if (!supportsPopover()) {
222
+ devHooks.overlayBlockedByModal?.("hidden");
223
+ return;
224
+ }
225
+ const el = wrapper;
226
+ if (nativeOpened) el.hidePopover();
227
+ else {
228
+ wrapper.setAttribute("popover", "manual");
229
+ for (const side of ["top", "right", "bottom", "left"])
230
+ if (wrapper.style[side] === "") wrapper.style[side] = "auto";
231
+ }
232
+ el.showPopover();
233
+ nativeOpened = true;
234
+ if (wrapper.querySelector(FOCUSABLE) !== null)
235
+ devHooks.overlayBlockedByModal?.("inert");
236
+ };
237
+ function finish() {
238
+ if (state.removed) return;
239
+ state.removed = true;
240
+ clearTimeout(exitTimer);
241
+ for (const end of finalizers) end();
242
+ wrapper.remove();
243
+ }
244
+ function close(value, closeOptions) {
245
+ const instant = closeOptions?.instant === true;
246
+ if (state.closed) {
247
+ if (instant) finish();
248
+ return;
249
+ }
106
250
  state.closed = true;
107
- if (fallbackStack !== void 0) {
108
- const stackIndex = fallbackStack.indexOf(wrapper);
109
- if (stackIndex !== -1) fallbackStack.splice(stackIndex, 1);
251
+ const { stack } = arbitration;
252
+ const stackIndex = stack.indexOf(surface);
253
+ if (stackIndex !== -1) stack.splice(stackIndex, 1);
254
+ if (stack.length === 0) {
255
+ document.removeEventListener("toggle", arbitration.onToggle, true);
256
+ for (const root of arbitration.shadowRoots)
257
+ root.removeEventListener("toggle", arbitration.onToggle, true);
258
+ arbitration.shadowRoots.clear();
110
259
  }
260
+ for (const other of stack)
261
+ if (other.restoreTo !== null && wrapper.contains(other.restoreTo))
262
+ other.restoreTo = surface.restoreTo;
263
+ const exit = !instant && (exitClass !== void 0 || exitDuration > 0) && !globalThis.matchMedia("(prefers-reduced-motion: reduce)").matches;
264
+ for (const other of [...stack])
265
+ if (stack.includes(other) && (renderedInside(other.el, wrapper) || other.anchor !== void 0 && renderedInside(other.anchor, wrapper)))
266
+ other.leave(!exit);
267
+ const active = document.activeElement;
111
268
  for (const remove of removers) remove();
112
- disposeMount();
269
+ disposeMount?.();
113
270
  if (nativeOpened) {
114
271
  nativeOpened = false;
115
272
  if (useDialog) wrapper.close();
116
273
  else wrapper.hidePopover();
117
274
  }
118
- wrapper.remove();
119
- if (restoreTo instanceof HTMLElement && restoreTo.isConnected) restoreTo.focus();
275
+ if (exit) {
276
+ wrapper.inert = true;
277
+ if (exitClass !== void 0) wrapper.classList.add(exitClass);
278
+ } else finish();
279
+ restoreFocus(active);
120
280
  resultBox.resolve?.(value);
281
+ if (exit) {
282
+ exitTimer = setTimeout(finish, exitDuration);
283
+ if ("getAnimations" in wrapper)
284
+ void Promise.allSettled(
285
+ wrapper.getAnimations({ subtree: true }).filter(
286
+ (animation) => Number.isFinite(
287
+ animation.effect?.getComputedTiming().endTime ?? Infinity
288
+ )
289
+ ).map((animation) => animation.finished)
290
+ ).then(finish);
291
+ }
292
+ }
293
+ function restoreFocus(active) {
294
+ if (active instanceof HTMLElement && active.isConnected && arbitration.stack.some((other) => other.el.contains(active))) {
295
+ if (document.activeElement !== active) active.focus();
296
+ return;
297
+ }
298
+ const { restoreTo } = surface;
299
+ if (restoreTo instanceof HTMLElement && restoreTo.isConnected)
300
+ restoreTo.focus();
121
301
  }
122
302
  function userDismiss() {
123
303
  onDismiss?.();
124
304
  close();
125
305
  }
126
- const wantEscape = triggers.includes("escape");
127
- if (useDialog) {
128
- const onCancel = (event) => {
129
- event.preventDefault();
130
- if (wantEscape) userDismiss();
131
- };
132
- wrapper.addEventListener("cancel", onCancel);
133
- removers.push(() => wrapper.removeEventListener("cancel", onCancel));
134
- } else if (wantEscape || trap) {
135
- const onKeydown = (event) => {
136
- if (!isTopmostFallback()) return;
137
- if (wantEscape && event.key === "Escape") {
138
- event.stopPropagation();
139
- userDismiss();
140
- return;
141
- }
142
- if (trap && event.key === "Tab") {
143
- const items = focusable(wrapper);
144
- if (items.length === 0) {
306
+ try {
307
+ container.appendChild(wrapper);
308
+ disposeMount = mount(
309
+ wrapper,
310
+ typeof content === "function" ? content : () => content
311
+ );
312
+ if (bottomSheet) followKeyboardInset(wrapper, finalizers);
313
+ if (arbitration.stack.push(surface) === 1)
314
+ document.addEventListener("toggle", arbitration.onToggle, true);
315
+ watchShadowRoots(arbitration, shadowRoots);
316
+ if (useDialog) {
317
+ wrapper.showModal();
318
+ nativeOpened = true;
319
+ rehostAbove(arbitration, wrapper);
320
+ } else if (usePopover) {
321
+ wrapper.showPopover();
322
+ nativeOpened = true;
323
+ wrapper.style.inset = "auto";
324
+ }
325
+ installDismissal();
326
+ if (container.closest(OVERLAY_HOST_SELECTOR) !== null) {
327
+ makeTabReachable();
328
+ removers.push(attach(wrapper, () => () => close(void 0, INSTANT)));
329
+ }
330
+ if (containerContext !== void 0) {
331
+ const { dialog } = containerContext;
332
+ const onDialogClose = () => close();
333
+ dialog.addEventListener("close", onDialogClose);
334
+ removers.push(() => dialog.removeEventListener("close", onDialogClose));
335
+ }
336
+ applyInitialFocus();
337
+ } catch (error) {
338
+ close(void 0, INSTANT);
339
+ throw error;
340
+ }
341
+ if (liftOverModal) {
342
+ if (!useDialog && !usePopover) devHooks.overlayBlockedByModal?.("hidden");
343
+ else if (usePopover && wrapper.querySelector(FOCUSABLE) !== null)
344
+ devHooks.overlayBlockedByModal?.("inert");
345
+ }
346
+ return { el: wrapper, close, result };
347
+ function installDismissal() {
348
+ const wantEscape = triggers.includes("escape");
349
+ if (useDialog) {
350
+ const onCancel = (event) => {
351
+ event.preventDefault();
352
+ if (wantEscape && owns("escape")) userDismiss();
353
+ };
354
+ wrapper.addEventListener("cancel", onCancel);
355
+ removers.push(() => wrapper.removeEventListener("cancel", onCancel));
356
+ } else if (wantEscape || trap) {
357
+ const onKeydown = (event) => {
358
+ if (wantEscape && event.key === "Escape") {
359
+ if (!owns("escape", event)) return;
360
+ event.stopPropagation();
145
361
  event.preventDefault();
362
+ arbitration.handled.add(event);
363
+ userDismiss();
146
364
  return;
147
365
  }
148
- const first = items[0];
149
- const last = items[items.length - 1];
150
- const active = document.activeElement;
151
- const outside = !wrapper.contains(active);
152
- if (event.shiftKey && (active === first || outside)) {
153
- event.preventDefault();
154
- last.focus();
155
- } else if (!event.shiftKey && (active === last || outside)) {
156
- event.preventDefault();
157
- first.focus();
366
+ if (trap && event.key === "Tab" && owns("trap")) {
367
+ const items = focusable(wrapper);
368
+ if (items.length === 0) {
369
+ event.preventDefault();
370
+ return;
371
+ }
372
+ const first = items[0];
373
+ const last = items[items.length - 1];
374
+ const active = document.activeElement;
375
+ const outside = !wrapper.contains(active);
376
+ if (event.shiftKey && (active === first || outside)) {
377
+ event.preventDefault();
378
+ last.focus();
379
+ } else if (!event.shiftKey && (active === last || outside)) {
380
+ event.preventDefault();
381
+ first.focus();
382
+ }
158
383
  }
159
- }
160
- };
161
- document.addEventListener("keydown", onKeydown, true);
162
- removers.push(() => document.removeEventListener("keydown", onKeydown, true));
384
+ };
385
+ document.addEventListener("keydown", onKeydown, true);
386
+ removers.push(
387
+ () => document.removeEventListener("keydown", onKeydown, true)
388
+ );
389
+ }
390
+ if (triggers.includes("backdrop")) {
391
+ const onClick = (event) => {
392
+ if (event.target !== wrapper || !owns("backdrop", event)) return;
393
+ arbitration.handled.add(event);
394
+ userDismiss();
395
+ };
396
+ wrapper.addEventListener("click", onClick);
397
+ removers.push(() => wrapper.removeEventListener("click", onClick));
398
+ }
399
+ if (triggers.includes("outside")) {
400
+ const ignore = toArray(outsideIgnore);
401
+ const onDocClick = (event) => {
402
+ const target = event.target;
403
+ if (target === null) return;
404
+ if (wrapper.contains(target)) return;
405
+ if (ignore.some((el) => el === target || el.contains(target))) return;
406
+ if (!owns("outside", event)) return;
407
+ arbitration.handled.add(event);
408
+ userDismiss();
409
+ };
410
+ document.addEventListener("click", onDocClick, true);
411
+ removers.push(
412
+ () => document.removeEventListener("click", onDocClick, true)
413
+ );
414
+ }
163
415
  }
164
- if (triggers.includes("backdrop")) {
165
- const onClick = (event) => {
166
- if (!isTopmostFallback()) return;
167
- if (event.target === wrapper) userDismiss();
416
+ function makeTabReachable() {
417
+ focusable(wrapper);
418
+ const onTab = (event) => {
419
+ if (event.key === "Tab") focusable(wrapper);
168
420
  };
169
- wrapper.addEventListener("click", onClick);
170
- removers.push(() => wrapper.removeEventListener("click", onClick));
421
+ document.addEventListener("keydown", onTab, true);
422
+ removers.push(() => document.removeEventListener("keydown", onTab, true));
171
423
  }
172
- if (triggers.includes("outside")) {
173
- const ignore = outsideIgnore === void 0 ? [] : Array.isArray(outsideIgnore) ? outsideIgnore : [outsideIgnore];
174
- const onDocClick = (event) => {
175
- if (!isTopmostFallback()) return;
176
- const target = event.target;
177
- if (target === null) return;
178
- if (wrapper.contains(target)) return;
179
- if (ignore.some((el) => el === target || el.contains(target))) return;
180
- userDismiss();
181
- };
182
- document.addEventListener("click", onDocClick, true);
183
- removers.push(() => document.removeEventListener("click", onDocClick, true));
424
+ function focusWrapper() {
425
+ wrapper.tabIndex = -1;
426
+ wrapper.focus();
184
427
  }
185
- if (initialFocus !== false) {
186
- if (typeof initialFocus === "string") {
187
- wrapper.querySelector(initialFocus)?.focus();
188
- } else {
189
- const first = focusable(wrapper)[0];
190
- if (first !== void 0) {
191
- first.focus();
192
- } else {
193
- wrapper.tabIndex = -1;
194
- wrapper.focus();
195
- }
428
+ function applyInitialFocus() {
429
+ if (initialFocus === false) return;
430
+ const target = typeof initialFocus === "string" ? wrapper.querySelector(initialFocus) : focusable(wrapper)[0] ?? null;
431
+ if (target === null) {
432
+ if (initialFocus === true) focusWrapper();
433
+ return;
196
434
  }
435
+ if (tryFocus(target) || !isCustomElement(target)) return;
436
+ focusWrapper();
437
+ void whenRendered(target).then(() => {
438
+ if (!state.closed && activeIn(wrapper) === wrapper) tryFocus(target);
439
+ });
197
440
  }
198
- return { el: wrapper, close, result };
199
441
  }
200
- function popover(anchor, content, options = {}) {
201
- const {
202
- container,
203
- className = "kerf-popover",
204
- placement = "bottom",
205
- align = "start",
206
- gap = 4,
207
- dismiss = ["outside"],
208
- initialFocus = false,
209
- outsideIgnore,
210
- onDismiss,
211
- native = false
212
- } = options;
213
- const extraIgnore = outsideIgnore === void 0 ? [] : Array.isArray(outsideIgnore) ? [...outsideIgnore] : [outsideIgnore];
214
- const handle = overlay(content, {
215
- container,
216
- className,
217
- dismiss,
218
- trap: false,
219
- initialFocus,
220
- onDismiss,
221
- outsideIgnore: [anchor, ...extraIgnore],
222
- native
223
- });
224
- const stopReposition = autoReposition(handle.el, anchor, { placement, align, gap });
225
- void handle.result.then(stopReposition);
226
- return handle;
442
+ function isCustomElement(el) {
443
+ return el.localName.includes("-");
227
444
  }
228
- function tooltip(anchor, content, options = {}) {
229
- const {
230
- container,
231
- className = "kerf-tooltip",
232
- delay = 400,
233
- hideDelay = 100,
234
- role = "tooltip",
235
- placement = "top",
236
- align = "start",
237
- gap = 4,
238
- native = false
239
- } = options;
240
- const body = typeof content === "function" ? content : typeof content === "string" ? jsx("span", { class: `${className}__text`, children: content }) : content;
241
- const timers = {};
242
- let current;
243
- let presence = 0;
244
- function show() {
245
- const handle = overlay(body, { container, className, dismiss: false, trap: false, initialFocus: false, native });
246
- handle.el.setAttribute("role", role);
247
- const stop = autoReposition(handle.el, anchor, { placement, align, gap });
248
- current = { handle, stop };
445
+ function tryFocus(el) {
446
+ try {
447
+ el.focus();
448
+ } catch {
449
+ return false;
249
450
  }
250
- function hide() {
251
- if (current === void 0) return;
252
- current.stop();
253
- current.handle.close();
254
- current = void 0;
451
+ return activeIn(el) === el;
452
+ }
453
+ function activeIn(el) {
454
+ return el.getRootNode().activeElement;
455
+ }
456
+ async function whenRendered(el) {
457
+ await globalThis.customElements.whenDefined(el.localName);
458
+ await el.updateComplete;
459
+ await new Promise((resolve) => globalThis.requestAnimationFrame(resolve));
460
+ }
461
+ function anchorOverlay(handle, anchor, leave) {
462
+ const surface = overlayArbitration(document).stack.find(
463
+ ({ el }) => el === handle.el
464
+ );
465
+ surface.anchor = anchor;
466
+ if (leave !== void 0) surface.leave = leave;
467
+ }
468
+ function wireDialog(handle, wire, settle) {
469
+ const disposers = [];
470
+ const failure = [];
471
+ try {
472
+ wire(
473
+ (dispose) => void disposers.push(dispose),
474
+ (action) => () => {
475
+ try {
476
+ action();
477
+ } catch (error) {
478
+ failure[0] = error;
479
+ handle.close(failure);
480
+ }
481
+ }
482
+ );
483
+ } catch (error) {
484
+ disposers.forEach((dispose) => dispose());
485
+ handle.close(void 0, INSTANT);
486
+ throw error;
255
487
  }
256
- const onEnter = (event) => {
257
- presence |= event.type === "focus" ? 2 : 1;
258
- if (timers.hide !== void 0) clearTimeout(timers.hide);
259
- if (current !== void 0) return;
260
- if (timers.show !== void 0) clearTimeout(timers.show);
261
- timers.show = setTimeout(show, delay);
262
- };
263
- const onLeave = (event) => {
264
- presence &= event.type === "blur" ? -3 : -2;
265
- if (presence) return;
266
- if (timers.show !== void 0) clearTimeout(timers.show);
267
- if (current === void 0) return;
268
- timers.hide = setTimeout(hide, hideDelay);
269
- };
270
- anchor.addEventListener("pointerenter", onEnter);
271
- anchor.addEventListener("pointerleave", onLeave);
272
- anchor.addEventListener("focus", onEnter);
273
- anchor.addEventListener("blur", onLeave);
274
- return () => {
275
- anchor.removeEventListener("pointerenter", onEnter);
276
- anchor.removeEventListener("pointerleave", onLeave);
277
- anchor.removeEventListener("focus", onEnter);
278
- anchor.removeEventListener("blur", onLeave);
279
- if (timers.show !== void 0) clearTimeout(timers.show);
280
- if (timers.hide !== void 0) clearTimeout(timers.hide);
281
- hide();
282
- };
488
+ return handle.result.then((value) => {
489
+ if (value === failure) throw failure[0];
490
+ return settle(value);
491
+ });
283
492
  }
284
493
 
285
494
  // src/overlay-choice.ts
286
495
  function choice(message, actions, options = {}) {
287
- const { container, className = "kerf-overlay", title, defaultValue, native = false, render } = options;
496
+ const {
497
+ container,
498
+ className = "kerf-overlay",
499
+ title,
500
+ defaultValue,
501
+ native = false,
502
+ presentation,
503
+ exitClass,
504
+ exitDuration,
505
+ render
506
+ } = options;
288
507
  const hasDefault = "defaultValue" in options;
289
508
  const actionAttrs = actions.map((_, i) => ({ "data-choice": String(i) }));
290
509
  const body = render !== void 0 ? render({ message, actions: actionAttrs }) : jsx("div", {
@@ -315,22 +534,33 @@ function choice(message, actions, options = {}) {
315
534
  dismiss: ["escape", "backdrop"],
316
535
  initialFocus: "[data-choice]",
317
536
  trap: true,
318
- native
319
- });
320
- delegate(handle.el, "click", "[data-choice]", (_event, el) => {
321
- resolveChoice(actions[Number(el.getAttribute("data-choice"))].value);
322
- handle.close();
537
+ native,
538
+ presentation,
539
+ exitClass,
540
+ exitDuration
323
541
  });
324
- if (hasDefault) {
325
- handle.el.addEventListener("keydown", (event) => {
326
- if (event.key === "Enter") {
327
- event.preventDefault();
328
- resolveChoice(defaultValue);
329
- handle.close();
542
+ void wireDialog(
543
+ handle,
544
+ (track) => {
545
+ track(
546
+ delegate(handle.el, "click", "[data-choice]", (_event, el) => {
547
+ resolveChoice(actions[Number(el.getAttribute("data-choice"))].value);
548
+ handle.close();
549
+ })
550
+ );
551
+ if (hasDefault) {
552
+ const onKeydown = (event) => {
553
+ if (event.key === "Enter") {
554
+ event.preventDefault();
555
+ resolveChoice(defaultValue);
556
+ handle.close();
557
+ }
558
+ };
559
+ handle.el.addEventListener("keydown", onKeydown);
330
560
  }
331
- });
332
- }
333
- void handle.result.then(() => resolveChoice(null));
561
+ },
562
+ () => resolveChoice(null)
563
+ );
334
564
  return result;
335
565
  }
336
566
 
@@ -344,9 +574,16 @@ function confirm(message, options = {}) {
344
574
  cancelText = "Cancel",
345
575
  danger = false,
346
576
  native = false,
577
+ presentation,
578
+ exitClass,
579
+ exitDuration,
347
580
  render
348
581
  } = options;
349
- const body = render !== void 0 ? render({ message, ok: { "data-confirm": "ok" }, cancel: { "data-confirm": "cancel" } }) : jsx("div", {
582
+ const body = render !== void 0 ? render({
583
+ message,
584
+ ok: { "data-confirm": "ok" },
585
+ cancel: { "data-confirm": "cancel" }
586
+ }) : jsx("div", {
350
587
  class: "kerf-confirm",
351
588
  children: [
352
589
  title !== void 0 ? jsx("h2", { class: "kerf-confirm__title", children: title }) : "",
@@ -354,7 +591,11 @@ function confirm(message, options = {}) {
354
591
  jsx("div", {
355
592
  class: "kerf-confirm__actions",
356
593
  children: [
357
- jsx("button", { type: "button", "data-confirm": "cancel", children: cancelText }),
594
+ jsx("button", {
595
+ type: "button",
596
+ "data-confirm": "cancel",
597
+ children: cancelText
598
+ }),
358
599
  jsx("button", {
359
600
  type: "button",
360
601
  "data-confirm": "ok",
@@ -371,12 +612,145 @@ function confirm(message, options = {}) {
371
612
  dismiss: ["escape", "backdrop"],
372
613
  initialFocus: '[data-confirm="ok"]',
373
614
  trap: true,
374
- native
615
+ native,
616
+ presentation,
617
+ exitClass,
618
+ exitDuration
375
619
  });
376
- delegate(handle.el, "click", "[data-confirm]", (_event, el) => {
377
- handle.close(el.getAttribute("data-confirm") === "ok");
620
+ return wireDialog(
621
+ handle,
622
+ () => {
623
+ delegate(handle.el, "click", "[data-confirm]", (_event, el) => {
624
+ handle.close(el.getAttribute("data-confirm") === "ok");
625
+ });
626
+ },
627
+ (value) => value === true
628
+ );
629
+ }
630
+
631
+ // src/overlay-prompt.ts
632
+ function runValidator(validate, value, owner) {
633
+ const result = validate?.(value);
634
+ if (typeof result?.then === "function") {
635
+ result.then(void 0, () => void 0);
636
+ throw new TypeError(`${owner}: validate returned a promise.`);
637
+ }
638
+ return typeof result === "string" && result.length > 0 ? result : void 0;
639
+ }
640
+ function prompt(message, options = {}) {
641
+ const {
642
+ container,
643
+ className = "kerf-overlay",
644
+ title,
645
+ defaultValue = "",
646
+ placeholder,
647
+ inputType = "text",
648
+ okText = "OK",
649
+ cancelText = "Cancel",
650
+ validate,
651
+ native = false,
652
+ presentation,
653
+ exitClass,
654
+ exitDuration,
655
+ render
656
+ } = options;
657
+ const inputAttrs = {
658
+ "data-prompt-input": "",
659
+ type: inputType,
660
+ value: defaultValue,
661
+ ...placeholder !== void 0 ? { placeholder } : {}
662
+ };
663
+ const body = render !== void 0 ? render({
664
+ message,
665
+ input: inputAttrs,
666
+ error: { "data-prompt-error": "" },
667
+ ok: { "data-prompt": "ok" },
668
+ cancel: { "data-prompt": "cancel" }
669
+ }) : jsx("div", {
670
+ class: "kerf-prompt",
671
+ children: [
672
+ title !== void 0 ? jsx("h2", { class: "kerf-prompt__title", children: title }) : "",
673
+ jsx("label", { class: "kerf-prompt__message", children: message }),
674
+ jsx("input", { class: "kerf-prompt__input", ...inputAttrs }),
675
+ jsx("p", {
676
+ class: "kerf-prompt__error",
677
+ "data-prompt-error": "",
678
+ children: ""
679
+ }),
680
+ jsx("div", {
681
+ class: "kerf-prompt__actions",
682
+ children: [
683
+ jsx("button", {
684
+ type: "button",
685
+ "data-prompt": "cancel",
686
+ children: cancelText
687
+ }),
688
+ jsx("button", {
689
+ type: "button",
690
+ "data-prompt": "ok",
691
+ class: "kerf-prompt__ok",
692
+ children: okText
693
+ })
694
+ ]
695
+ })
696
+ ]
697
+ });
698
+ const handle = overlay(body, {
699
+ container,
700
+ className,
701
+ dismiss: ["escape", "backdrop"],
702
+ initialFocus: "[data-prompt-input]",
703
+ trap: true,
704
+ native,
705
+ presentation,
706
+ exitClass,
707
+ exitDuration
378
708
  });
379
- return handle.result.then((value) => value === true);
709
+ return wireDialog(
710
+ handle,
711
+ (track, guard) => {
712
+ const inputFor = (problem = "render missing") => {
713
+ const input = handle.el.querySelector(
714
+ "input[data-prompt-input]"
715
+ );
716
+ if (input !== null) return input;
717
+ throw new Error(`prompt(): ${problem} <input data-prompt-input>.`);
718
+ };
719
+ inputFor();
720
+ const errorEl = handle.el.querySelector(
721
+ "[data-prompt-error]"
722
+ );
723
+ if (errorEl !== null) errorEl.hidden = true;
724
+ const attemptOk = guard(() => {
725
+ const input = inputFor("removed after open:");
726
+ const value = input.value;
727
+ const error = runValidator(validate, value, "prompt()");
728
+ if (error !== void 0) {
729
+ if (errorEl !== null) {
730
+ errorEl.textContent = error;
731
+ errorEl.hidden = false;
732
+ }
733
+ input.focus();
734
+ return;
735
+ }
736
+ handle.close(value);
737
+ });
738
+ track(
739
+ delegate(handle.el, "click", "[data-prompt]", (_event, el) => {
740
+ if (el.getAttribute("data-prompt") === "ok") attemptOk();
741
+ else handle.close(null);
742
+ })
743
+ );
744
+ const onKeydown = (event) => {
745
+ if (event.key === "Enter" && event.target?.matches("input[data-prompt-input]")) {
746
+ event.preventDefault();
747
+ attemptOk();
748
+ }
749
+ };
750
+ handle.el.addEventListener("keydown", onKeydown);
751
+ },
752
+ (value) => typeof value === "string" ? value : null
753
+ );
380
754
  }
381
755
 
382
756
  // src/overlay-form.ts
@@ -388,6 +762,9 @@ function form(fields, options = {}) {
388
762
  okText = "OK",
389
763
  cancelText = "Cancel",
390
764
  native = false,
765
+ presentation,
766
+ exitClass,
767
+ exitDuration,
391
768
  render
392
769
  } = options;
393
770
  const fieldAttrs = (field) => ({
@@ -414,16 +791,30 @@ function form(fields, options = {}) {
414
791
  (field) => jsx("div", {
415
792
  class: "kerf-form__field",
416
793
  children: [
417
- jsx("label", { class: "kerf-form__label", children: field.label ?? field.name }),
418
- jsx("input", { class: "kerf-form__input", ...fieldAttrs(field) }),
419
- jsx("p", { class: "kerf-form__error", "data-field-error": field.name, children: "" })
794
+ jsx("label", {
795
+ class: "kerf-form__label",
796
+ children: field.label ?? field.name
797
+ }),
798
+ jsx("input", {
799
+ class: "kerf-form__input",
800
+ ...fieldAttrs(field)
801
+ }),
802
+ jsx("p", {
803
+ class: "kerf-form__error",
804
+ "data-field-error": field.name,
805
+ children: ""
806
+ })
420
807
  ]
421
808
  })
422
809
  ),
423
810
  jsx("div", {
424
811
  class: "kerf-form__actions",
425
812
  children: [
426
- jsx("button", { type: "button", "data-form": "cancel", children: cancelText }),
813
+ jsx("button", {
814
+ type: "button",
815
+ "data-form": "cancel",
816
+ children: cancelText
817
+ }),
427
818
  jsx("button", {
428
819
  type: "button",
429
820
  "data-form": "ok",
@@ -440,152 +831,326 @@ function form(fields, options = {}) {
440
831
  dismiss: ["escape", "backdrop"],
441
832
  initialFocus: "[data-field]",
442
833
  trap: true,
443
- native
834
+ native,
835
+ presentation,
836
+ exitClass,
837
+ exitDuration
444
838
  });
445
- const errorFor = (name) => Array.from(handle.el.querySelectorAll("[data-field-error]")).find(
446
- (el) => el.getAttribute("data-field-error") === name
447
- ) ?? null;
448
- const inputFor = (name) => {
449
- const input = Array.from(handle.el.querySelectorAll("input[data-field]")).find(
450
- (el) => el.getAttribute("data-field") === name
451
- );
452
- if (input !== void 0) return input;
453
- handle.close(null);
454
- throw new Error(`form(): render missing <input data-field="${name}">.`);
455
- };
456
- for (const field of fields) {
457
- inputFor(field.name);
458
- const errorEl = errorFor(field.name);
459
- if (errorEl !== null) errorEl.hidden = true;
460
- }
461
- function attemptOk() {
462
- const record = {};
463
- let firstInvalid = null;
464
- for (const field of fields) {
465
- const el = inputFor(field.name);
466
- const value = el.value;
467
- record[field.name] = value;
468
- const error = field.validate?.(value);
469
- const errorEl = errorFor(field.name);
470
- if (typeof error === "string" && error.length > 0) {
471
- if (errorEl !== null) {
472
- errorEl.textContent = error;
473
- errorEl.hidden = false;
474
- }
475
- if (firstInvalid === null) firstInvalid = el;
476
- } else if (errorEl !== null) {
477
- errorEl.hidden = true;
839
+ return wireDialog(
840
+ handle,
841
+ (track, guard) => {
842
+ const errorFor = (name) => Array.from(
843
+ handle.el.querySelectorAll("[data-field-error]")
844
+ ).find((el) => el.getAttribute("data-field-error") === name) ?? null;
845
+ const inputFor = (name, problem = "render missing") => {
846
+ const input = Array.from(
847
+ handle.el.querySelectorAll("input[data-field]")
848
+ ).find((el) => el.getAttribute("data-field") === name);
849
+ if (input !== void 0) return input;
850
+ throw new Error(`form(): ${problem} <input data-field="${name}">.`);
851
+ };
852
+ for (const field of fields) {
853
+ inputFor(field.name);
854
+ const errorEl = errorFor(field.name);
855
+ if (errorEl !== null) errorEl.hidden = true;
478
856
  }
479
- }
480
- if (firstInvalid !== null) {
481
- firstInvalid.focus();
857
+ const attemptOk = guard(() => {
858
+ const record = {};
859
+ let firstInvalid = null;
860
+ for (const field of fields) {
861
+ const el = inputFor(field.name, "removed after open:");
862
+ const value = el.value;
863
+ record[field.name] = value;
864
+ const error = runValidator(field.validate, value, "form()");
865
+ const errorEl = errorFor(field.name);
866
+ if (error !== void 0) {
867
+ if (errorEl !== null) {
868
+ errorEl.textContent = error;
869
+ errorEl.hidden = false;
870
+ }
871
+ if (firstInvalid === null) firstInvalid = el;
872
+ } else if (errorEl !== null) {
873
+ errorEl.hidden = true;
874
+ }
875
+ }
876
+ if (firstInvalid !== null) {
877
+ firstInvalid.focus();
878
+ return;
879
+ }
880
+ handle.close(record);
881
+ });
882
+ track(
883
+ delegate(handle.el, "click", "[data-form]", (_event, el) => {
884
+ if (el.getAttribute("data-form") === "ok") attemptOk();
885
+ else handle.close(null);
886
+ })
887
+ );
888
+ const onKeydown = (event) => {
889
+ if (event.key === "Enter" && event.target?.matches("[data-field]")) {
890
+ event.preventDefault();
891
+ attemptOk();
892
+ }
893
+ };
894
+ handle.el.addEventListener("keydown", onKeydown);
895
+ },
896
+ (value) => value !== null && typeof value === "object" ? value : null
897
+ );
898
+ }
899
+
900
+ // src/overlay-position.ts
901
+ var AVAILABLE_HEIGHT = "--kerf-anchor-available-height";
902
+ function positionAnchored(el, anchor, options = {}) {
903
+ const {
904
+ placement = "bottom",
905
+ align = "start",
906
+ gap = 4,
907
+ viewportMargin = 0,
908
+ fitHeight = false
909
+ } = options;
910
+ el.style.position = "fixed";
911
+ el.style.margin = "0";
912
+ const anchorRect = anchor.getBoundingClientRect();
913
+ const elementRect = el.getBoundingClientRect();
914
+ const viewportWidth = window.innerWidth;
915
+ const viewportHeight = window.innerHeight;
916
+ const height = fitHeight ? fullHeight(el, elementRect) : elementRect.height;
917
+ const belowTop = anchorRect.bottom + gap;
918
+ const roomBelow = viewportHeight - viewportMargin - belowTop;
919
+ const roomAbove = anchorRect.top - gap - viewportMargin;
920
+ let below = placement !== "top";
921
+ if (height > roomBelow && height > roomAbove) {
922
+ if (fitHeight) below = roomBelow >= roomAbove;
923
+ } else if (below && height > roomBelow) below = false;
924
+ else if (!below && height > roomAbove) below = true;
925
+ let left = align === "end" ? anchorRect.right - elementRect.width : anchorRect.left;
926
+ left = Math.max(
927
+ viewportMargin,
928
+ Math.min(left, viewportWidth - viewportMargin - elementRect.width)
929
+ );
930
+ const [originX, originY, scaleX, scaleY] = fixedOrigin(el);
931
+ el.style.left = `${(left - originX) / scaleX}px`;
932
+ if (fitHeight) {
933
+ const room = Math.max(0, below ? roomBelow : roomAbove);
934
+ el.style.setProperty(AVAILABLE_HEIGHT, `${room / scaleY}px`);
935
+ if (!below) {
936
+ const edge = anchorRect.top - gap;
937
+ el.style.top = "auto";
938
+ el.style.bottom = `${(fixedBottom(el, originY, scaleY) - edge) / scaleY}px`;
482
939
  return;
483
940
  }
484
- handle.close(record);
941
+ el.style.bottom = "auto";
485
942
  }
486
- delegate(handle.el, "click", "[data-form]", (_event, el) => {
487
- if (el.getAttribute("data-form") === "ok") attemptOk();
488
- else handle.close(null);
489
- });
490
- handle.el.addEventListener("keydown", (event) => {
491
- if (event.key === "Enter" && event.target?.matches("[data-field]")) {
492
- event.preventDefault();
493
- attemptOk();
943
+ const top = below ? belowTop : anchorRect.top - gap - height;
944
+ el.style.top = `${(top - originY) / scaleY}px`;
945
+ }
946
+ function fullHeight(el, rect) {
947
+ const scale = el.offsetHeight ? rect.height / el.offsetHeight : 1;
948
+ const full = rect.height + Math.max(0, el.scrollHeight - el.clientHeight) * scale;
949
+ return Math.min(full, ownMaxHeight(el) * scale);
950
+ }
951
+ var VERTICAL_EDGES = [
952
+ "paddingTop",
953
+ "paddingBottom",
954
+ "borderTopWidth",
955
+ "borderBottomWidth"
956
+ ];
957
+ var UNBOUNDED_ROOM = "9999999px";
958
+ var SWAPPED = [
959
+ AVAILABLE_HEIGHT,
960
+ "height",
961
+ "transition-property",
962
+ "transition-duration",
963
+ "transition-delay"
964
+ ];
965
+ var TRANSITIONS = 2;
966
+ function ownMaxHeight(el) {
967
+ const style = window.getComputedStyle(el);
968
+ const maxHeight = animatedMaxHeight(el) ?? swappedMaxHeight(el, style);
969
+ const inset = style.boxSizing === "border-box" ? 0 : VERTICAL_EDGES.reduce(
970
+ (sum, edge) => sum + (Number.parseFloat(style[edge]) || 0),
971
+ 0
972
+ );
973
+ if (maxHeight.endsWith("px")) return Number.parseFloat(maxHeight) + inset;
974
+ if (/^[a-z-]+$|var\(/.test(maxHeight)) return Infinity;
975
+ return resolveHeight(el, maxHeight) + inset;
976
+ }
977
+ function swappedMaxHeight(el, style) {
978
+ const inline = el.style;
979
+ const saved = SWAPPED.map((name) => [
980
+ name,
981
+ inline.getPropertyValue(name),
982
+ inline.getPropertyPriority(name)
983
+ ]);
984
+ const lists = SWAPPED.map((name) => style.getPropertyValue(name).split(","));
985
+ const transitions = lists[TRANSITIONS];
986
+ if (transitions[0] && transitions[0] !== "none") {
987
+ for (let index = TRANSITIONS; index < SWAPPED.length; index++) {
988
+ const items = lists[index];
989
+ const appended = index > TRANSITIONS ? ["0s", "0s"] : ["max-height", "height"];
990
+ inline.setProperty(
991
+ SWAPPED[index],
992
+ [
993
+ ...transitions.map((_, entry) => items[entry % items.length]),
994
+ ...appended
995
+ ].join(),
996
+ "important"
997
+ );
494
998
  }
999
+ }
1000
+ const height = style.height;
1001
+ const { scrollTop, scrollLeft } = el;
1002
+ if (height.endsWith("px")) inline.setProperty("height", height, "important");
1003
+ inline.setProperty(AVAILABLE_HEIGHT, UNBOUNDED_ROOM);
1004
+ const maxHeight = style.maxHeight;
1005
+ saved.forEach(([name, value, priority], index) => {
1006
+ if (value) inline.setProperty(name, value, priority);
1007
+ else inline.removeProperty(name);
1008
+ if (index === TRANSITIONS - 1) style.getPropertyValue("max-height");
495
1009
  });
496
- return handle.result.then(
497
- (value) => value !== null && typeof value === "object" ? value : null
1010
+ if (scrollTop && el.scrollTop !== scrollTop) el.scrollTop = scrollTop;
1011
+ if (scrollLeft && el.scrollLeft !== scrollLeft) el.scrollLeft = scrollLeft;
1012
+ return maxHeight;
1013
+ }
1014
+ function animatedMaxHeight(el) {
1015
+ const animations = el.getAnimations?.() ?? [];
1016
+ for (let index = animations.length - 1; index >= 0; index--) {
1017
+ const animation = animations[index];
1018
+ const effect = animation.effect;
1019
+ const frames = (effect?.getKeyframes() ?? []).filter(
1020
+ (frame) => frame["maxHeight"] != null
1021
+ );
1022
+ if (!frames.length) continue;
1023
+ if (animation.playState === "finished") return void 0;
1024
+ const { direction, currentIteration } = effect.getComputedTiming();
1025
+ const odd = (currentIteration ?? 0) % 2 === 1;
1026
+ const reversed = (direction === "reverse" || direction === "alternate" && odd || direction === "alternate-reverse" && !odd) !== animation.playbackRate < 0;
1027
+ return String(frames[reversed ? 0 : frames.length - 1]["maxHeight"]);
1028
+ }
1029
+ return void 0;
1030
+ }
1031
+ function resolveHeight(el, height) {
1032
+ return withFixedProbe(
1033
+ el,
1034
+ "width:0;box-sizing:content-box;min-height:0;max-height:none;visibility:hidden",
1035
+ (probe) => {
1036
+ probe.style.height = height;
1037
+ if (!probe.style.height) return Infinity;
1038
+ return Number.parseFloat(window.getComputedStyle(probe).height);
1039
+ },
1040
+ Infinity
1041
+ );
1042
+ }
1043
+ function withFixedProbe(el, css, measure, detached) {
1044
+ const parent = el.parentNode;
1045
+ if (!parent) return detached;
1046
+ const probe = el.ownerDocument.createElement("div");
1047
+ probe.style.cssText = `position:fixed;left:0;top:0;display:block;margin:0;padding:0;border:0;${css}`;
1048
+ parent.insertBefore(probe, el);
1049
+ const result = measure(probe);
1050
+ probe.remove();
1051
+ return result;
1052
+ }
1053
+ function fixedOrigin(el) {
1054
+ return withFixedProbe(
1055
+ el,
1056
+ "width:1px;height:1px",
1057
+ (probe) => {
1058
+ const rect = probe.getBoundingClientRect();
1059
+ return [rect.left, rect.top, rect.width || 1, rect.height || 1];
1060
+ },
1061
+ [0, 0, 1, 1]
1062
+ );
1063
+ }
1064
+ function fixedBottom(el, originY, scaleY) {
1065
+ const fallback = originY + window.innerHeight * scaleY;
1066
+ return withFixedProbe(
1067
+ el,
1068
+ "width:1px;height:1px;top:auto;bottom:0",
1069
+ (probe) => {
1070
+ const rect = probe.getBoundingClientRect();
1071
+ return rect.height ? rect.bottom : fallback;
1072
+ },
1073
+ fallback
498
1074
  );
499
1075
  }
1076
+ function autoReposition(el, anchor, options = {}) {
1077
+ const RO = globalThis.ResizeObserver;
1078
+ const nodes = [anchor, el];
1079
+ let settled = "";
1080
+ const sizes = () => nodes.map((node) => {
1081
+ const rect = node.getBoundingClientRect();
1082
+ return [rect.width, rect.height];
1083
+ }).join();
1084
+ const reposition = () => {
1085
+ positionAnchored(el, anchor, options);
1086
+ if (RO) settled = sizes();
1087
+ };
1088
+ reposition();
1089
+ window.addEventListener("scroll", reposition, true);
1090
+ window.addEventListener("resize", reposition);
1091
+ const observer = RO && new RO(() => {
1092
+ if (sizes() !== settled) reposition();
1093
+ });
1094
+ nodes.forEach((node) => observer?.observe(node));
1095
+ return () => {
1096
+ window.removeEventListener("scroll", reposition, true);
1097
+ window.removeEventListener("resize", reposition);
1098
+ observer?.disconnect();
1099
+ };
1100
+ }
500
1101
 
501
- // src/overlay-prompt.ts
502
- function prompt(message, options = {}) {
1102
+ // src/overlay-popover.ts
1103
+ function popover(anchor, content, options = {}) {
503
1104
  const {
504
1105
  container,
505
- className = "kerf-overlay",
506
- title,
507
- defaultValue = "",
508
- placeholder,
509
- inputType = "text",
510
- okText = "OK",
511
- cancelText = "Cancel",
512
- validate,
1106
+ className = "kerf-popover",
1107
+ placement = "bottom",
1108
+ align = "start",
1109
+ gap = 4,
1110
+ viewportMargin,
1111
+ fitHeight,
1112
+ dismiss = ["outside"],
1113
+ initialFocus = false,
1114
+ outsideIgnore,
1115
+ onDismiss,
513
1116
  native = false,
514
- render
1117
+ exitClass,
1118
+ exitDuration
515
1119
  } = options;
516
- const inputAttrs = {
517
- "data-prompt-input": "",
518
- type: inputType,
519
- value: defaultValue,
520
- ...placeholder !== void 0 ? { placeholder } : {}
521
- };
522
- const body = render !== void 0 ? render({
523
- message,
524
- input: inputAttrs,
525
- error: { "data-prompt-error": "" },
526
- ok: { "data-prompt": "ok" },
527
- cancel: { "data-prompt": "cancel" }
528
- }) : jsx("div", {
529
- class: "kerf-prompt",
530
- children: [
531
- title !== void 0 ? jsx("h2", { class: "kerf-prompt__title", children: title }) : "",
532
- jsx("label", { class: "kerf-prompt__message", children: message }),
533
- jsx("input", { class: "kerf-prompt__input", ...inputAttrs }),
534
- jsx("p", { class: "kerf-prompt__error", "data-prompt-error": "", children: "" }),
535
- jsx("div", {
536
- class: "kerf-prompt__actions",
537
- children: [
538
- jsx("button", { type: "button", "data-prompt": "cancel", children: cancelText }),
539
- jsx("button", {
540
- type: "button",
541
- "data-prompt": "ok",
542
- class: "kerf-prompt__ok",
543
- children: okText
544
- })
545
- ]
546
- })
547
- ]
548
- });
549
- const handle = overlay(body, {
550
- container,
1120
+ const extraIgnore = toArray(outsideIgnore);
1121
+ const handle = overlay(content, {
1122
+ container: container ?? overlayHost(anchor),
551
1123
  className,
552
- dismiss: ["escape", "backdrop"],
553
- initialFocus: "[data-prompt-input]",
554
- trap: true,
555
- native
1124
+ dismiss,
1125
+ trap: false,
1126
+ initialFocus,
1127
+ onDismiss,
1128
+ outsideIgnore: [anchor, ...extraIgnore],
1129
+ native,
1130
+ exitClass,
1131
+ exitDuration
556
1132
  });
557
- const input = handle.el.querySelector("input[data-prompt-input]");
558
- if (input === null) {
559
- handle.close(null);
560
- throw new Error("prompt(): render missing <input data-prompt-input>.");
561
- }
562
- const promptInput = input;
563
- const errorEl = handle.el.querySelector("[data-prompt-error]");
564
- if (errorEl !== null) errorEl.hidden = true;
565
- function attemptOk() {
566
- const value = promptInput.value;
567
- const error = validate?.(value);
568
- if (typeof error === "string" && error.length > 0) {
569
- if (errorEl !== null) {
570
- errorEl.textContent = error;
571
- errorEl.hidden = false;
572
- }
573
- promptInput.focus();
574
- return;
575
- }
576
- handle.close(value);
1133
+ let stopReposition;
1134
+ try {
1135
+ stopReposition = autoReposition(handle.el, anchor, {
1136
+ placement,
1137
+ align,
1138
+ gap,
1139
+ viewportMargin,
1140
+ fitHeight
1141
+ });
1142
+ } catch (error) {
1143
+ handle.close(void 0, INSTANT);
1144
+ throw error;
577
1145
  }
578
- delegate(handle.el, "click", "[data-prompt]", (_event, el) => {
579
- if (el.getAttribute("data-prompt") === "ok") attemptOk();
580
- else handle.close(null);
581
- });
582
- handle.el.addEventListener("keydown", (event) => {
583
- if (event.key === "Enter" && event.target === promptInput) {
584
- event.preventDefault();
585
- attemptOk();
586
- }
587
- });
588
- return handle.result.then((value) => typeof value === "string" ? value : null);
1146
+ void handle.result.then(stopReposition);
1147
+ anchorOverlay(handle, anchor);
1148
+ void handle.result.then(
1149
+ attach(anchor, () => () => {
1150
+ if (!anchor.isConnected) handle.close(void 0, INSTANT);
1151
+ })
1152
+ );
1153
+ return handle;
589
1154
  }
590
1155
 
591
1156
  // src/overlay-toast.ts
@@ -628,7 +1193,12 @@ function toast(content, options = {}) {
628
1193
  region.appendChild(el);
629
1194
  const render = typeof content === "function" ? content : () => typeof content === "string" ? escapeHtml(content) : content;
630
1195
  const disposeMount = mount(el, render);
631
- const state = { dismissed: false, removed: false, timer: void 0, exitTimer: void 0 };
1196
+ const state = {
1197
+ dismissed: false,
1198
+ removed: false,
1199
+ timer: void 0,
1200
+ exitTimer: void 0
1201
+ };
632
1202
  if (enterClass !== void 0) {
633
1203
  globalThis.requestAnimationFrame(() => {
634
1204
  if (!state.dismissed) el.classList.add(enterClass);
@@ -669,6 +1239,107 @@ function toast(content, options = {}) {
669
1239
  return { el, dismiss };
670
1240
  }
671
1241
 
1242
+ // src/overlay-tooltip.ts
1243
+ function tooltip(anchor, content, options = {}) {
1244
+ const {
1245
+ container,
1246
+ className = "kerf-tooltip",
1247
+ delay = 400,
1248
+ hideDelay = 100,
1249
+ role = "tooltip",
1250
+ placement = "top",
1251
+ align = "start",
1252
+ gap = 4,
1253
+ viewportMargin,
1254
+ fitHeight,
1255
+ native = false,
1256
+ exitClass,
1257
+ exitDuration
1258
+ } = options;
1259
+ const body = typeof content === "function" ? content : typeof content === "string" ? jsx("span", { class: `${className}__text`, children: content }) : content;
1260
+ const timers = {};
1261
+ let current;
1262
+ let leaving;
1263
+ let presence = 0;
1264
+ function show() {
1265
+ if (!anchor.isConnected || anchor.closest("[inert]") !== null) return;
1266
+ leaving?.close(void 0, INSTANT);
1267
+ leaving = void 0;
1268
+ const handle = overlay(body, {
1269
+ container: container ?? overlayHost(anchor),
1270
+ className,
1271
+ dismiss: false,
1272
+ trap: false,
1273
+ initialFocus: false,
1274
+ native,
1275
+ exitClass,
1276
+ exitDuration
1277
+ });
1278
+ handle.el.setAttribute("role", role);
1279
+ let stop;
1280
+ try {
1281
+ stop = autoReposition(handle.el, anchor, {
1282
+ placement,
1283
+ align,
1284
+ gap,
1285
+ viewportMargin,
1286
+ fitHeight
1287
+ });
1288
+ } catch (error) {
1289
+ handle.close(void 0, INSTANT);
1290
+ throw error;
1291
+ }
1292
+ const unwatch = attach(anchor, () => () => drop(INSTANT));
1293
+ current = { handle, stop, unwatch };
1294
+ anchorOverlay(handle, anchor, (now) => drop(now ? INSTANT : void 0));
1295
+ void handle.result.then(() => {
1296
+ if (current?.handle === handle) hide();
1297
+ });
1298
+ }
1299
+ function drop(closeOptions) {
1300
+ presence = 0;
1301
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1302
+ hide(closeOptions);
1303
+ }
1304
+ function hide(closeOptions) {
1305
+ const shown = current;
1306
+ if (shown === void 0) return;
1307
+ current = void 0;
1308
+ shown.unwatch();
1309
+ shown.stop();
1310
+ shown.handle.close(void 0, closeOptions);
1311
+ leaving = shown.handle;
1312
+ }
1313
+ const onEnter = (event) => {
1314
+ presence |= event.type === "focus" ? 2 : 1;
1315
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1316
+ if (current !== void 0) return;
1317
+ if (timers.show !== void 0) clearTimeout(timers.show);
1318
+ timers.show = setTimeout(show, delay);
1319
+ };
1320
+ const onLeave = (event) => {
1321
+ presence &= event.type === "blur" ? -3 : -2;
1322
+ if (presence) return;
1323
+ if (timers.show !== void 0) clearTimeout(timers.show);
1324
+ if (current === void 0) return;
1325
+ timers.hide = setTimeout(() => hide(), hideDelay);
1326
+ };
1327
+ anchor.addEventListener("pointerenter", onEnter);
1328
+ anchor.addEventListener("pointerleave", onLeave);
1329
+ anchor.addEventListener("focus", onEnter);
1330
+ anchor.addEventListener("blur", onLeave);
1331
+ return () => {
1332
+ anchor.removeEventListener("pointerenter", onEnter);
1333
+ anchor.removeEventListener("pointerleave", onLeave);
1334
+ anchor.removeEventListener("focus", onEnter);
1335
+ anchor.removeEventListener("blur", onLeave);
1336
+ if (timers.show !== void 0) clearTimeout(timers.show);
1337
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1338
+ hide(INSTANT);
1339
+ leaving?.close(void 0, INSTANT);
1340
+ };
1341
+ }
1342
+
672
1343
  export { autoReposition, choice, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };
673
1344
 
674
1345
  //# sourceMappingURL=overlay.js.map