kerfjs 5.0.0-beta.13 → 5.0.0-beta.130

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 +3370 -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 +1039 -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 +77 -0
  76. package/setup/detect.mjs +274 -0
  77. package/setup/index.d.mts +39 -0
  78. package/setup/index.mjs +1226 -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,335 @@ 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
+ wrapper.style.inset = "auto";
230
+ }
231
+ el.showPopover();
232
+ nativeOpened = true;
233
+ if (wrapper.querySelector(FOCUSABLE) !== null)
234
+ devHooks.overlayBlockedByModal?.("inert");
235
+ };
236
+ function finish() {
237
+ if (state.removed) return;
238
+ state.removed = true;
239
+ clearTimeout(exitTimer);
240
+ for (const end of finalizers) end();
241
+ wrapper.remove();
242
+ }
243
+ function close(value, closeOptions) {
244
+ const instant = closeOptions?.instant === true;
245
+ if (state.closed) {
246
+ if (instant) finish();
247
+ return;
248
+ }
106
249
  state.closed = true;
107
- if (fallbackStack !== void 0) {
108
- const stackIndex = fallbackStack.indexOf(wrapper);
109
- if (stackIndex !== -1) fallbackStack.splice(stackIndex, 1);
250
+ const { stack } = arbitration;
251
+ const stackIndex = stack.indexOf(surface);
252
+ if (stackIndex !== -1) stack.splice(stackIndex, 1);
253
+ if (stack.length === 0) {
254
+ document.removeEventListener("toggle", arbitration.onToggle, true);
255
+ for (const root of arbitration.shadowRoots)
256
+ root.removeEventListener("toggle", arbitration.onToggle, true);
257
+ arbitration.shadowRoots.clear();
110
258
  }
259
+ for (const other of stack)
260
+ if (other.restoreTo !== null && wrapper.contains(other.restoreTo))
261
+ other.restoreTo = surface.restoreTo;
262
+ const exit = !instant && (exitClass !== void 0 || exitDuration > 0) && !globalThis.matchMedia("(prefers-reduced-motion: reduce)").matches;
263
+ for (const other of [...stack])
264
+ if (stack.includes(other) && (renderedInside(other.el, wrapper) || other.anchor !== void 0 && renderedInside(other.anchor, wrapper)))
265
+ other.leave(!exit);
266
+ const active = document.activeElement;
111
267
  for (const remove of removers) remove();
112
- disposeMount();
268
+ disposeMount?.();
113
269
  if (nativeOpened) {
114
270
  nativeOpened = false;
115
271
  if (useDialog) wrapper.close();
116
272
  else wrapper.hidePopover();
117
273
  }
118
- wrapper.remove();
119
- if (restoreTo instanceof HTMLElement && restoreTo.isConnected) restoreTo.focus();
274
+ if (exit) {
275
+ wrapper.inert = true;
276
+ if (exitClass !== void 0) wrapper.classList.add(exitClass);
277
+ } else finish();
278
+ restoreFocus(active);
120
279
  resultBox.resolve?.(value);
280
+ if (exit) {
281
+ exitTimer = setTimeout(finish, exitDuration);
282
+ if ("getAnimations" in wrapper)
283
+ void Promise.allSettled(
284
+ wrapper.getAnimations({ subtree: true }).filter(
285
+ (animation) => Number.isFinite(
286
+ animation.effect?.getComputedTiming().endTime ?? Infinity
287
+ )
288
+ ).map((animation) => animation.finished)
289
+ ).then(finish);
290
+ }
291
+ }
292
+ function restoreFocus(active) {
293
+ if (active instanceof HTMLElement && active.isConnected && arbitration.stack.some((other) => other.el.contains(active))) {
294
+ if (document.activeElement !== active) active.focus();
295
+ return;
296
+ }
297
+ const { restoreTo } = surface;
298
+ if (restoreTo instanceof HTMLElement && restoreTo.isConnected)
299
+ restoreTo.focus();
121
300
  }
122
301
  function userDismiss() {
123
302
  onDismiss?.();
124
303
  close();
125
304
  }
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) {
305
+ try {
306
+ container.appendChild(wrapper);
307
+ disposeMount = mount(
308
+ wrapper,
309
+ typeof content === "function" ? content : () => content
310
+ );
311
+ if (bottomSheet) followKeyboardInset(wrapper, finalizers);
312
+ if (arbitration.stack.push(surface) === 1)
313
+ document.addEventListener("toggle", arbitration.onToggle, true);
314
+ watchShadowRoots(arbitration, shadowRoots);
315
+ if (useDialog) {
316
+ wrapper.showModal();
317
+ nativeOpened = true;
318
+ rehostAbove(arbitration, wrapper);
319
+ } else if (usePopover) {
320
+ wrapper.showPopover();
321
+ nativeOpened = true;
322
+ wrapper.style.inset = "auto";
323
+ }
324
+ installDismissal();
325
+ if (container.closest(OVERLAY_HOST_SELECTOR) !== null) {
326
+ makeTabReachable();
327
+ removers.push(attach(wrapper, () => () => close(void 0, INSTANT)));
328
+ }
329
+ if (containerContext !== void 0) {
330
+ const { dialog } = containerContext;
331
+ const onDialogClose = () => close();
332
+ dialog.addEventListener("close", onDialogClose);
333
+ removers.push(() => dialog.removeEventListener("close", onDialogClose));
334
+ }
335
+ applyInitialFocus();
336
+ } catch (error) {
337
+ close(void 0, INSTANT);
338
+ throw error;
339
+ }
340
+ if (liftOverModal) {
341
+ if (!useDialog && !usePopover) devHooks.overlayBlockedByModal?.("hidden");
342
+ else if (usePopover && wrapper.querySelector(FOCUSABLE) !== null)
343
+ devHooks.overlayBlockedByModal?.("inert");
344
+ }
345
+ return { el: wrapper, close, result };
346
+ function installDismissal() {
347
+ const wantEscape = triggers.includes("escape");
348
+ if (useDialog) {
349
+ const onCancel = (event) => {
350
+ event.preventDefault();
351
+ if (wantEscape && owns("escape")) userDismiss();
352
+ };
353
+ wrapper.addEventListener("cancel", onCancel);
354
+ removers.push(() => wrapper.removeEventListener("cancel", onCancel));
355
+ } else if (wantEscape || trap) {
356
+ const onKeydown = (event) => {
357
+ if (wantEscape && event.key === "Escape") {
358
+ if (!owns("escape", event)) return;
359
+ event.stopPropagation();
145
360
  event.preventDefault();
361
+ arbitration.handled.add(event);
362
+ userDismiss();
146
363
  return;
147
364
  }
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();
365
+ if (trap && event.key === "Tab" && owns("trap")) {
366
+ const items = focusable(wrapper);
367
+ if (items.length === 0) {
368
+ event.preventDefault();
369
+ return;
370
+ }
371
+ const first = items[0];
372
+ const last = items[items.length - 1];
373
+ const active = document.activeElement;
374
+ const outside = !wrapper.contains(active);
375
+ if (event.shiftKey && (active === first || outside)) {
376
+ event.preventDefault();
377
+ last.focus();
378
+ } else if (!event.shiftKey && (active === last || outside)) {
379
+ event.preventDefault();
380
+ first.focus();
381
+ }
158
382
  }
159
- }
160
- };
161
- document.addEventListener("keydown", onKeydown, true);
162
- removers.push(() => document.removeEventListener("keydown", onKeydown, true));
383
+ };
384
+ document.addEventListener("keydown", onKeydown, true);
385
+ removers.push(
386
+ () => document.removeEventListener("keydown", onKeydown, true)
387
+ );
388
+ }
389
+ if (triggers.includes("backdrop")) {
390
+ const onClick = (event) => {
391
+ if (event.target !== wrapper || !owns("backdrop", event)) return;
392
+ arbitration.handled.add(event);
393
+ userDismiss();
394
+ };
395
+ wrapper.addEventListener("click", onClick);
396
+ removers.push(() => wrapper.removeEventListener("click", onClick));
397
+ }
398
+ if (triggers.includes("outside")) {
399
+ const ignore = toArray(outsideIgnore);
400
+ const onDocClick = (event) => {
401
+ const target = event.target;
402
+ if (target === null) return;
403
+ if (wrapper.contains(target)) return;
404
+ if (ignore.some((el) => el === target || el.contains(target))) return;
405
+ if (!owns("outside", event)) return;
406
+ arbitration.handled.add(event);
407
+ userDismiss();
408
+ };
409
+ document.addEventListener("click", onDocClick, true);
410
+ removers.push(
411
+ () => document.removeEventListener("click", onDocClick, true)
412
+ );
413
+ }
163
414
  }
164
- if (triggers.includes("backdrop")) {
165
- const onClick = (event) => {
166
- if (!isTopmostFallback()) return;
167
- if (event.target === wrapper) userDismiss();
415
+ function makeTabReachable() {
416
+ focusable(wrapper);
417
+ const onTab = (event) => {
418
+ if (event.key === "Tab") focusable(wrapper);
168
419
  };
169
- wrapper.addEventListener("click", onClick);
170
- removers.push(() => wrapper.removeEventListener("click", onClick));
420
+ document.addEventListener("keydown", onTab, true);
421
+ removers.push(() => document.removeEventListener("keydown", onTab, true));
171
422
  }
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));
423
+ function focusWrapper() {
424
+ wrapper.tabIndex = -1;
425
+ wrapper.focus();
184
426
  }
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
- }
427
+ function applyInitialFocus() {
428
+ if (initialFocus === false) return;
429
+ const target = typeof initialFocus === "string" ? wrapper.querySelector(initialFocus) : focusable(wrapper)[0] ?? null;
430
+ if (target === null) {
431
+ if (initialFocus === true) focusWrapper();
432
+ return;
196
433
  }
434
+ if (tryFocus(target) || !isCustomElement(target)) return;
435
+ focusWrapper();
436
+ void whenRendered(target).then(() => {
437
+ if (!state.closed && activeIn(wrapper) === wrapper) tryFocus(target);
438
+ });
197
439
  }
198
- return { el: wrapper, close, result };
199
440
  }
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;
441
+ function isCustomElement(el) {
442
+ return el.localName.includes("-");
227
443
  }
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 };
444
+ function tryFocus(el) {
445
+ try {
446
+ el.focus();
447
+ } catch {
448
+ return false;
249
449
  }
250
- function hide() {
251
- if (current === void 0) return;
252
- current.stop();
253
- current.handle.close();
254
- current = void 0;
450
+ return activeIn(el) === el;
451
+ }
452
+ function activeIn(el) {
453
+ return el.getRootNode().activeElement;
454
+ }
455
+ async function whenRendered(el) {
456
+ await globalThis.customElements.whenDefined(el.localName);
457
+ await el.updateComplete;
458
+ await new Promise((resolve) => globalThis.requestAnimationFrame(resolve));
459
+ }
460
+ function anchorOverlay(handle, anchor, leave) {
461
+ const surface = overlayArbitration(document).stack.find(
462
+ ({ el }) => el === handle.el
463
+ );
464
+ surface.anchor = anchor;
465
+ if (leave !== void 0) surface.leave = leave;
466
+ }
467
+ function wireDialog(handle, wire, settle) {
468
+ const disposers = [];
469
+ const failure = [];
470
+ try {
471
+ wire(
472
+ (dispose) => void disposers.push(dispose),
473
+ (action) => () => {
474
+ try {
475
+ action();
476
+ } catch (error) {
477
+ failure[0] = error;
478
+ handle.close(failure);
479
+ }
480
+ }
481
+ );
482
+ } catch (error) {
483
+ disposers.forEach((dispose) => dispose());
484
+ handle.close(void 0, INSTANT);
485
+ throw error;
255
486
  }
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
- };
487
+ return handle.result.then((value) => {
488
+ if (value === failure) throw failure[0];
489
+ return settle(value);
490
+ });
283
491
  }
284
492
 
285
493
  // src/overlay-choice.ts
286
494
  function choice(message, actions, options = {}) {
287
- const { container, className = "kerf-overlay", title, defaultValue, native = false, render } = options;
495
+ const {
496
+ container,
497
+ className = "kerf-overlay",
498
+ title,
499
+ defaultValue,
500
+ native = false,
501
+ presentation,
502
+ exitClass,
503
+ exitDuration,
504
+ render
505
+ } = options;
288
506
  const hasDefault = "defaultValue" in options;
289
507
  const actionAttrs = actions.map((_, i) => ({ "data-choice": String(i) }));
290
508
  const body = render !== void 0 ? render({ message, actions: actionAttrs }) : jsx("div", {
@@ -315,22 +533,33 @@ function choice(message, actions, options = {}) {
315
533
  dismiss: ["escape", "backdrop"],
316
534
  initialFocus: "[data-choice]",
317
535
  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();
536
+ native,
537
+ presentation,
538
+ exitClass,
539
+ exitDuration
323
540
  });
324
- if (hasDefault) {
325
- handle.el.addEventListener("keydown", (event) => {
326
- if (event.key === "Enter") {
327
- event.preventDefault();
328
- resolveChoice(defaultValue);
329
- handle.close();
541
+ void wireDialog(
542
+ handle,
543
+ (track) => {
544
+ track(
545
+ delegate(handle.el, "click", "[data-choice]", (_event, el) => {
546
+ resolveChoice(actions[Number(el.getAttribute("data-choice"))].value);
547
+ handle.close();
548
+ })
549
+ );
550
+ if (hasDefault) {
551
+ const onKeydown = (event) => {
552
+ if (event.key === "Enter") {
553
+ event.preventDefault();
554
+ resolveChoice(defaultValue);
555
+ handle.close();
556
+ }
557
+ };
558
+ handle.el.addEventListener("keydown", onKeydown);
330
559
  }
331
- });
332
- }
333
- void handle.result.then(() => resolveChoice(null));
560
+ },
561
+ () => resolveChoice(null)
562
+ );
334
563
  return result;
335
564
  }
336
565
 
@@ -344,9 +573,16 @@ function confirm(message, options = {}) {
344
573
  cancelText = "Cancel",
345
574
  danger = false,
346
575
  native = false,
576
+ presentation,
577
+ exitClass,
578
+ exitDuration,
347
579
  render
348
580
  } = options;
349
- const body = render !== void 0 ? render({ message, ok: { "data-confirm": "ok" }, cancel: { "data-confirm": "cancel" } }) : jsx("div", {
581
+ const body = render !== void 0 ? render({
582
+ message,
583
+ ok: { "data-confirm": "ok" },
584
+ cancel: { "data-confirm": "cancel" }
585
+ }) : jsx("div", {
350
586
  class: "kerf-confirm",
351
587
  children: [
352
588
  title !== void 0 ? jsx("h2", { class: "kerf-confirm__title", children: title }) : "",
@@ -354,7 +590,11 @@ function confirm(message, options = {}) {
354
590
  jsx("div", {
355
591
  class: "kerf-confirm__actions",
356
592
  children: [
357
- jsx("button", { type: "button", "data-confirm": "cancel", children: cancelText }),
593
+ jsx("button", {
594
+ type: "button",
595
+ "data-confirm": "cancel",
596
+ children: cancelText
597
+ }),
358
598
  jsx("button", {
359
599
  type: "button",
360
600
  "data-confirm": "ok",
@@ -371,12 +611,145 @@ function confirm(message, options = {}) {
371
611
  dismiss: ["escape", "backdrop"],
372
612
  initialFocus: '[data-confirm="ok"]',
373
613
  trap: true,
374
- native
614
+ native,
615
+ presentation,
616
+ exitClass,
617
+ exitDuration
375
618
  });
376
- delegate(handle.el, "click", "[data-confirm]", (_event, el) => {
377
- handle.close(el.getAttribute("data-confirm") === "ok");
619
+ return wireDialog(
620
+ handle,
621
+ () => {
622
+ delegate(handle.el, "click", "[data-confirm]", (_event, el) => {
623
+ handle.close(el.getAttribute("data-confirm") === "ok");
624
+ });
625
+ },
626
+ (value) => value === true
627
+ );
628
+ }
629
+
630
+ // src/overlay-prompt.ts
631
+ function runValidator(validate, value, owner) {
632
+ const result = validate?.(value);
633
+ if (typeof result?.then === "function") {
634
+ result.then(void 0, () => void 0);
635
+ throw new TypeError(`${owner}: validate returned a promise.`);
636
+ }
637
+ return typeof result === "string" && result.length > 0 ? result : void 0;
638
+ }
639
+ function prompt(message, options = {}) {
640
+ const {
641
+ container,
642
+ className = "kerf-overlay",
643
+ title,
644
+ defaultValue = "",
645
+ placeholder,
646
+ inputType = "text",
647
+ okText = "OK",
648
+ cancelText = "Cancel",
649
+ validate,
650
+ native = false,
651
+ presentation,
652
+ exitClass,
653
+ exitDuration,
654
+ render
655
+ } = options;
656
+ const inputAttrs = {
657
+ "data-prompt-input": "",
658
+ type: inputType,
659
+ value: defaultValue,
660
+ ...placeholder !== void 0 ? { placeholder } : {}
661
+ };
662
+ const body = render !== void 0 ? render({
663
+ message,
664
+ input: inputAttrs,
665
+ error: { "data-prompt-error": "" },
666
+ ok: { "data-prompt": "ok" },
667
+ cancel: { "data-prompt": "cancel" }
668
+ }) : jsx("div", {
669
+ class: "kerf-prompt",
670
+ children: [
671
+ title !== void 0 ? jsx("h2", { class: "kerf-prompt__title", children: title }) : "",
672
+ jsx("label", { class: "kerf-prompt__message", children: message }),
673
+ jsx("input", { class: "kerf-prompt__input", ...inputAttrs }),
674
+ jsx("p", {
675
+ class: "kerf-prompt__error",
676
+ "data-prompt-error": "",
677
+ children: ""
678
+ }),
679
+ jsx("div", {
680
+ class: "kerf-prompt__actions",
681
+ children: [
682
+ jsx("button", {
683
+ type: "button",
684
+ "data-prompt": "cancel",
685
+ children: cancelText
686
+ }),
687
+ jsx("button", {
688
+ type: "button",
689
+ "data-prompt": "ok",
690
+ class: "kerf-prompt__ok",
691
+ children: okText
692
+ })
693
+ ]
694
+ })
695
+ ]
696
+ });
697
+ const handle = overlay(body, {
698
+ container,
699
+ className,
700
+ dismiss: ["escape", "backdrop"],
701
+ initialFocus: "[data-prompt-input]",
702
+ trap: true,
703
+ native,
704
+ presentation,
705
+ exitClass,
706
+ exitDuration
378
707
  });
379
- return handle.result.then((value) => value === true);
708
+ return wireDialog(
709
+ handle,
710
+ (track, guard) => {
711
+ const inputFor = (problem = "render missing") => {
712
+ const input = handle.el.querySelector(
713
+ "input[data-prompt-input]"
714
+ );
715
+ if (input !== null) return input;
716
+ throw new Error(`prompt(): ${problem} <input data-prompt-input>.`);
717
+ };
718
+ inputFor();
719
+ const errorEl = handle.el.querySelector(
720
+ "[data-prompt-error]"
721
+ );
722
+ if (errorEl !== null) errorEl.hidden = true;
723
+ const attemptOk = guard(() => {
724
+ const input = inputFor("removed after open:");
725
+ const value = input.value;
726
+ const error = runValidator(validate, value, "prompt()");
727
+ if (error !== void 0) {
728
+ if (errorEl !== null) {
729
+ errorEl.textContent = error;
730
+ errorEl.hidden = false;
731
+ }
732
+ input.focus();
733
+ return;
734
+ }
735
+ handle.close(value);
736
+ });
737
+ track(
738
+ delegate(handle.el, "click", "[data-prompt]", (_event, el) => {
739
+ if (el.getAttribute("data-prompt") === "ok") attemptOk();
740
+ else handle.close(null);
741
+ })
742
+ );
743
+ const onKeydown = (event) => {
744
+ if (event.key === "Enter" && event.target?.matches("input[data-prompt-input]")) {
745
+ event.preventDefault();
746
+ attemptOk();
747
+ }
748
+ };
749
+ handle.el.addEventListener("keydown", onKeydown);
750
+ },
751
+ (value) => typeof value === "string" ? value : null
752
+ );
380
753
  }
381
754
 
382
755
  // src/overlay-form.ts
@@ -388,6 +761,9 @@ function form(fields, options = {}) {
388
761
  okText = "OK",
389
762
  cancelText = "Cancel",
390
763
  native = false,
764
+ presentation,
765
+ exitClass,
766
+ exitDuration,
391
767
  render
392
768
  } = options;
393
769
  const fieldAttrs = (field) => ({
@@ -414,16 +790,30 @@ function form(fields, options = {}) {
414
790
  (field) => jsx("div", {
415
791
  class: "kerf-form__field",
416
792
  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: "" })
793
+ jsx("label", {
794
+ class: "kerf-form__label",
795
+ children: field.label ?? field.name
796
+ }),
797
+ jsx("input", {
798
+ class: "kerf-form__input",
799
+ ...fieldAttrs(field)
800
+ }),
801
+ jsx("p", {
802
+ class: "kerf-form__error",
803
+ "data-field-error": field.name,
804
+ children: ""
805
+ })
420
806
  ]
421
807
  })
422
808
  ),
423
809
  jsx("div", {
424
810
  class: "kerf-form__actions",
425
811
  children: [
426
- jsx("button", { type: "button", "data-form": "cancel", children: cancelText }),
812
+ jsx("button", {
813
+ type: "button",
814
+ "data-form": "cancel",
815
+ children: cancelText
816
+ }),
427
817
  jsx("button", {
428
818
  type: "button",
429
819
  "data-form": "ok",
@@ -440,152 +830,326 @@ function form(fields, options = {}) {
440
830
  dismiss: ["escape", "backdrop"],
441
831
  initialFocus: "[data-field]",
442
832
  trap: true,
443
- native
833
+ native,
834
+ presentation,
835
+ exitClass,
836
+ exitDuration
444
837
  });
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;
838
+ return wireDialog(
839
+ handle,
840
+ (track, guard) => {
841
+ const errorFor = (name) => Array.from(
842
+ handle.el.querySelectorAll("[data-field-error]")
843
+ ).find((el) => el.getAttribute("data-field-error") === name) ?? null;
844
+ const inputFor = (name, problem = "render missing") => {
845
+ const input = Array.from(
846
+ handle.el.querySelectorAll("input[data-field]")
847
+ ).find((el) => el.getAttribute("data-field") === name);
848
+ if (input !== void 0) return input;
849
+ throw new Error(`form(): ${problem} <input data-field="${name}">.`);
850
+ };
851
+ for (const field of fields) {
852
+ inputFor(field.name);
853
+ const errorEl = errorFor(field.name);
854
+ if (errorEl !== null) errorEl.hidden = true;
478
855
  }
479
- }
480
- if (firstInvalid !== null) {
481
- firstInvalid.focus();
856
+ const attemptOk = guard(() => {
857
+ const record = {};
858
+ let firstInvalid = null;
859
+ for (const field of fields) {
860
+ const el = inputFor(field.name, "removed after open:");
861
+ const value = el.value;
862
+ record[field.name] = value;
863
+ const error = runValidator(field.validate, value, "form()");
864
+ const errorEl = errorFor(field.name);
865
+ if (error !== void 0) {
866
+ if (errorEl !== null) {
867
+ errorEl.textContent = error;
868
+ errorEl.hidden = false;
869
+ }
870
+ if (firstInvalid === null) firstInvalid = el;
871
+ } else if (errorEl !== null) {
872
+ errorEl.hidden = true;
873
+ }
874
+ }
875
+ if (firstInvalid !== null) {
876
+ firstInvalid.focus();
877
+ return;
878
+ }
879
+ handle.close(record);
880
+ });
881
+ track(
882
+ delegate(handle.el, "click", "[data-form]", (_event, el) => {
883
+ if (el.getAttribute("data-form") === "ok") attemptOk();
884
+ else handle.close(null);
885
+ })
886
+ );
887
+ const onKeydown = (event) => {
888
+ if (event.key === "Enter" && event.target?.matches("[data-field]")) {
889
+ event.preventDefault();
890
+ attemptOk();
891
+ }
892
+ };
893
+ handle.el.addEventListener("keydown", onKeydown);
894
+ },
895
+ (value) => value !== null && typeof value === "object" ? value : null
896
+ );
897
+ }
898
+
899
+ // src/overlay-position.ts
900
+ var AVAILABLE_HEIGHT = "--kerf-anchor-available-height";
901
+ function positionAnchored(el, anchor, options = {}) {
902
+ const {
903
+ placement = "bottom",
904
+ align = "start",
905
+ gap = 4,
906
+ viewportMargin = 0,
907
+ fitHeight = false
908
+ } = options;
909
+ el.style.position = "fixed";
910
+ el.style.margin = "0";
911
+ const anchorRect = anchor.getBoundingClientRect();
912
+ const elementRect = el.getBoundingClientRect();
913
+ const viewportWidth = window.innerWidth;
914
+ const viewportHeight = window.innerHeight;
915
+ const height = fitHeight ? fullHeight(el, elementRect) : elementRect.height;
916
+ const belowTop = anchorRect.bottom + gap;
917
+ const roomBelow = viewportHeight - viewportMargin - belowTop;
918
+ const roomAbove = anchorRect.top - gap - viewportMargin;
919
+ let below = placement !== "top";
920
+ if (height > roomBelow && height > roomAbove) {
921
+ if (fitHeight) below = roomBelow >= roomAbove;
922
+ } else if (below && height > roomBelow) below = false;
923
+ else if (!below && height > roomAbove) below = true;
924
+ let left = align === "end" ? anchorRect.right - elementRect.width : anchorRect.left;
925
+ left = Math.max(
926
+ viewportMargin,
927
+ Math.min(left, viewportWidth - viewportMargin - elementRect.width)
928
+ );
929
+ const [originX, originY, scaleX, scaleY] = fixedOrigin(el);
930
+ el.style.left = `${(left - originX) / scaleX}px`;
931
+ if (fitHeight) {
932
+ const room = Math.max(0, below ? roomBelow : roomAbove);
933
+ el.style.setProperty(AVAILABLE_HEIGHT, `${room / scaleY}px`);
934
+ if (!below) {
935
+ const edge = anchorRect.top - gap;
936
+ el.style.top = "auto";
937
+ el.style.bottom = `${(fixedBottom(el, originY, scaleY) - edge) / scaleY}px`;
482
938
  return;
483
939
  }
484
- handle.close(record);
940
+ el.style.bottom = "auto";
485
941
  }
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();
942
+ const top = below ? belowTop : anchorRect.top - gap - height;
943
+ el.style.top = `${(top - originY) / scaleY}px`;
944
+ }
945
+ function fullHeight(el, rect) {
946
+ const scale = el.offsetHeight ? rect.height / el.offsetHeight : 1;
947
+ const full = rect.height + Math.max(0, el.scrollHeight - el.clientHeight) * scale;
948
+ return Math.min(full, ownMaxHeight(el) * scale);
949
+ }
950
+ var VERTICAL_EDGES = [
951
+ "paddingTop",
952
+ "paddingBottom",
953
+ "borderTopWidth",
954
+ "borderBottomWidth"
955
+ ];
956
+ var UNBOUNDED_ROOM = "9999999px";
957
+ var SWAPPED = [
958
+ AVAILABLE_HEIGHT,
959
+ "height",
960
+ "transition-property",
961
+ "transition-duration",
962
+ "transition-delay"
963
+ ];
964
+ var TRANSITIONS = 2;
965
+ function ownMaxHeight(el) {
966
+ const style = window.getComputedStyle(el);
967
+ const maxHeight = animatedMaxHeight(el) ?? swappedMaxHeight(el, style);
968
+ const inset = style.boxSizing === "border-box" ? 0 : VERTICAL_EDGES.reduce(
969
+ (sum, edge) => sum + (Number.parseFloat(style[edge]) || 0),
970
+ 0
971
+ );
972
+ if (maxHeight.endsWith("px")) return Number.parseFloat(maxHeight) + inset;
973
+ if (/^[a-z-]+$|var\(/.test(maxHeight)) return Infinity;
974
+ return resolveHeight(el, maxHeight) + inset;
975
+ }
976
+ function swappedMaxHeight(el, style) {
977
+ const inline = el.style;
978
+ const saved = SWAPPED.map((name) => [
979
+ name,
980
+ inline.getPropertyValue(name),
981
+ inline.getPropertyPriority(name)
982
+ ]);
983
+ const lists = SWAPPED.map((name) => style.getPropertyValue(name).split(","));
984
+ const transitions = lists[TRANSITIONS];
985
+ if (transitions[0] && transitions[0] !== "none") {
986
+ for (let index = TRANSITIONS; index < SWAPPED.length; index++) {
987
+ const items = lists[index];
988
+ const appended = index > TRANSITIONS ? ["0s", "0s"] : ["max-height", "height"];
989
+ inline.setProperty(
990
+ SWAPPED[index],
991
+ [
992
+ ...transitions.map((_, entry) => items[entry % items.length]),
993
+ ...appended
994
+ ].join(),
995
+ "important"
996
+ );
494
997
  }
998
+ }
999
+ const height = style.height;
1000
+ const { scrollTop, scrollLeft } = el;
1001
+ if (height.endsWith("px")) inline.setProperty("height", height, "important");
1002
+ inline.setProperty(AVAILABLE_HEIGHT, UNBOUNDED_ROOM);
1003
+ const maxHeight = style.maxHeight;
1004
+ saved.forEach(([name, value, priority], index) => {
1005
+ if (value) inline.setProperty(name, value, priority);
1006
+ else inline.removeProperty(name);
1007
+ if (index === TRANSITIONS - 1) style.getPropertyValue("max-height");
495
1008
  });
496
- return handle.result.then(
497
- (value) => value !== null && typeof value === "object" ? value : null
1009
+ if (scrollTop && el.scrollTop !== scrollTop) el.scrollTop = scrollTop;
1010
+ if (scrollLeft && el.scrollLeft !== scrollLeft) el.scrollLeft = scrollLeft;
1011
+ return maxHeight;
1012
+ }
1013
+ function animatedMaxHeight(el) {
1014
+ const animations = el.getAnimations?.() ?? [];
1015
+ for (let index = animations.length - 1; index >= 0; index--) {
1016
+ const animation = animations[index];
1017
+ const effect = animation.effect;
1018
+ const frames = (effect?.getKeyframes() ?? []).filter(
1019
+ (frame) => frame["maxHeight"] != null
1020
+ );
1021
+ if (!frames.length) continue;
1022
+ if (animation.playState === "finished") return void 0;
1023
+ const { direction, currentIteration } = effect.getComputedTiming();
1024
+ const odd = (currentIteration ?? 0) % 2 === 1;
1025
+ const reversed = (direction === "reverse" || direction === "alternate" && odd || direction === "alternate-reverse" && !odd) !== animation.playbackRate < 0;
1026
+ return String(frames[reversed ? 0 : frames.length - 1]["maxHeight"]);
1027
+ }
1028
+ return void 0;
1029
+ }
1030
+ function resolveHeight(el, height) {
1031
+ return withFixedProbe(
1032
+ el,
1033
+ "width:0;box-sizing:content-box;min-height:0;max-height:none;visibility:hidden",
1034
+ (probe) => {
1035
+ probe.style.height = height;
1036
+ if (!probe.style.height) return Infinity;
1037
+ return Number.parseFloat(window.getComputedStyle(probe).height);
1038
+ },
1039
+ Infinity
1040
+ );
1041
+ }
1042
+ function withFixedProbe(el, css, measure, detached) {
1043
+ const parent = el.parentNode;
1044
+ if (!parent) return detached;
1045
+ const probe = el.ownerDocument.createElement("div");
1046
+ probe.style.cssText = `position:fixed;left:0;top:0;display:block;margin:0;padding:0;border:0;${css}`;
1047
+ parent.insertBefore(probe, el);
1048
+ const result = measure(probe);
1049
+ probe.remove();
1050
+ return result;
1051
+ }
1052
+ function fixedOrigin(el) {
1053
+ return withFixedProbe(
1054
+ el,
1055
+ "width:1px;height:1px",
1056
+ (probe) => {
1057
+ const rect = probe.getBoundingClientRect();
1058
+ return [rect.left, rect.top, rect.width || 1, rect.height || 1];
1059
+ },
1060
+ [0, 0, 1, 1]
1061
+ );
1062
+ }
1063
+ function fixedBottom(el, originY, scaleY) {
1064
+ const fallback = originY + window.innerHeight * scaleY;
1065
+ return withFixedProbe(
1066
+ el,
1067
+ "width:1px;height:1px;top:auto;bottom:0",
1068
+ (probe) => {
1069
+ const rect = probe.getBoundingClientRect();
1070
+ return rect.height ? rect.bottom : fallback;
1071
+ },
1072
+ fallback
498
1073
  );
499
1074
  }
1075
+ function autoReposition(el, anchor, options = {}) {
1076
+ const RO = globalThis.ResizeObserver;
1077
+ const nodes = [anchor, el];
1078
+ let settled = "";
1079
+ const sizes = () => nodes.map((node) => {
1080
+ const rect = node.getBoundingClientRect();
1081
+ return [rect.width, rect.height];
1082
+ }).join();
1083
+ const reposition = () => {
1084
+ positionAnchored(el, anchor, options);
1085
+ if (RO) settled = sizes();
1086
+ };
1087
+ reposition();
1088
+ window.addEventListener("scroll", reposition, true);
1089
+ window.addEventListener("resize", reposition);
1090
+ const observer = RO && new RO(() => {
1091
+ if (sizes() !== settled) reposition();
1092
+ });
1093
+ nodes.forEach((node) => observer?.observe(node));
1094
+ return () => {
1095
+ window.removeEventListener("scroll", reposition, true);
1096
+ window.removeEventListener("resize", reposition);
1097
+ observer?.disconnect();
1098
+ };
1099
+ }
500
1100
 
501
- // src/overlay-prompt.ts
502
- function prompt(message, options = {}) {
1101
+ // src/overlay-popover.ts
1102
+ function popover(anchor, content, options = {}) {
503
1103
  const {
504
1104
  container,
505
- className = "kerf-overlay",
506
- title,
507
- defaultValue = "",
508
- placeholder,
509
- inputType = "text",
510
- okText = "OK",
511
- cancelText = "Cancel",
512
- validate,
1105
+ className = "kerf-popover",
1106
+ placement = "bottom",
1107
+ align = "start",
1108
+ gap = 4,
1109
+ viewportMargin,
1110
+ fitHeight,
1111
+ dismiss = ["outside"],
1112
+ initialFocus = false,
1113
+ outsideIgnore,
1114
+ onDismiss,
513
1115
  native = false,
514
- render
1116
+ exitClass,
1117
+ exitDuration
515
1118
  } = 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,
1119
+ const extraIgnore = toArray(outsideIgnore);
1120
+ const handle = overlay(content, {
1121
+ container: container ?? overlayHost(anchor),
551
1122
  className,
552
- dismiss: ["escape", "backdrop"],
553
- initialFocus: "[data-prompt-input]",
554
- trap: true,
555
- native
1123
+ dismiss,
1124
+ trap: false,
1125
+ initialFocus,
1126
+ onDismiss,
1127
+ outsideIgnore: [anchor, ...extraIgnore],
1128
+ native,
1129
+ exitClass,
1130
+ exitDuration
556
1131
  });
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);
1132
+ let stopReposition;
1133
+ try {
1134
+ stopReposition = autoReposition(handle.el, anchor, {
1135
+ placement,
1136
+ align,
1137
+ gap,
1138
+ viewportMargin,
1139
+ fitHeight
1140
+ });
1141
+ } catch (error) {
1142
+ handle.close(void 0, INSTANT);
1143
+ throw error;
577
1144
  }
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);
1145
+ void handle.result.then(stopReposition);
1146
+ anchorOverlay(handle, anchor);
1147
+ void handle.result.then(
1148
+ attach(anchor, () => () => {
1149
+ if (!anchor.isConnected) handle.close(void 0, INSTANT);
1150
+ })
1151
+ );
1152
+ return handle;
589
1153
  }
590
1154
 
591
1155
  // src/overlay-toast.ts
@@ -628,7 +1192,12 @@ function toast(content, options = {}) {
628
1192
  region.appendChild(el);
629
1193
  const render = typeof content === "function" ? content : () => typeof content === "string" ? escapeHtml(content) : content;
630
1194
  const disposeMount = mount(el, render);
631
- const state = { dismissed: false, removed: false, timer: void 0, exitTimer: void 0 };
1195
+ const state = {
1196
+ dismissed: false,
1197
+ removed: false,
1198
+ timer: void 0,
1199
+ exitTimer: void 0
1200
+ };
632
1201
  if (enterClass !== void 0) {
633
1202
  globalThis.requestAnimationFrame(() => {
634
1203
  if (!state.dismissed) el.classList.add(enterClass);
@@ -669,6 +1238,107 @@ function toast(content, options = {}) {
669
1238
  return { el, dismiss };
670
1239
  }
671
1240
 
1241
+ // src/overlay-tooltip.ts
1242
+ function tooltip(anchor, content, options = {}) {
1243
+ const {
1244
+ container,
1245
+ className = "kerf-tooltip",
1246
+ delay = 400,
1247
+ hideDelay = 100,
1248
+ role = "tooltip",
1249
+ placement = "top",
1250
+ align = "start",
1251
+ gap = 4,
1252
+ viewportMargin,
1253
+ fitHeight,
1254
+ native = false,
1255
+ exitClass,
1256
+ exitDuration
1257
+ } = options;
1258
+ const body = typeof content === "function" ? content : typeof content === "string" ? jsx("span", { class: `${className}__text`, children: content }) : content;
1259
+ const timers = {};
1260
+ let current;
1261
+ let leaving;
1262
+ let presence = 0;
1263
+ function show() {
1264
+ if (!anchor.isConnected || anchor.closest("[inert]") !== null) return;
1265
+ leaving?.close(void 0, INSTANT);
1266
+ leaving = void 0;
1267
+ const handle = overlay(body, {
1268
+ container: container ?? overlayHost(anchor),
1269
+ className,
1270
+ dismiss: false,
1271
+ trap: false,
1272
+ initialFocus: false,
1273
+ native,
1274
+ exitClass,
1275
+ exitDuration
1276
+ });
1277
+ handle.el.setAttribute("role", role);
1278
+ let stop;
1279
+ try {
1280
+ stop = autoReposition(handle.el, anchor, {
1281
+ placement,
1282
+ align,
1283
+ gap,
1284
+ viewportMargin,
1285
+ fitHeight
1286
+ });
1287
+ } catch (error) {
1288
+ handle.close(void 0, INSTANT);
1289
+ throw error;
1290
+ }
1291
+ const unwatch = attach(anchor, () => () => drop(INSTANT));
1292
+ current = { handle, stop, unwatch };
1293
+ anchorOverlay(handle, anchor, (now) => drop(now ? INSTANT : void 0));
1294
+ void handle.result.then(() => {
1295
+ if (current?.handle === handle) hide();
1296
+ });
1297
+ }
1298
+ function drop(closeOptions) {
1299
+ presence = 0;
1300
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1301
+ hide(closeOptions);
1302
+ }
1303
+ function hide(closeOptions) {
1304
+ const shown = current;
1305
+ if (shown === void 0) return;
1306
+ current = void 0;
1307
+ shown.unwatch();
1308
+ shown.stop();
1309
+ shown.handle.close(void 0, closeOptions);
1310
+ leaving = shown.handle;
1311
+ }
1312
+ const onEnter = (event) => {
1313
+ presence |= event.type === "focus" ? 2 : 1;
1314
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1315
+ if (current !== void 0) return;
1316
+ if (timers.show !== void 0) clearTimeout(timers.show);
1317
+ timers.show = setTimeout(show, delay);
1318
+ };
1319
+ const onLeave = (event) => {
1320
+ presence &= event.type === "blur" ? -3 : -2;
1321
+ if (presence) return;
1322
+ if (timers.show !== void 0) clearTimeout(timers.show);
1323
+ if (current === void 0) return;
1324
+ timers.hide = setTimeout(() => hide(), hideDelay);
1325
+ };
1326
+ anchor.addEventListener("pointerenter", onEnter);
1327
+ anchor.addEventListener("pointerleave", onLeave);
1328
+ anchor.addEventListener("focus", onEnter);
1329
+ anchor.addEventListener("blur", onLeave);
1330
+ return () => {
1331
+ anchor.removeEventListener("pointerenter", onEnter);
1332
+ anchor.removeEventListener("pointerleave", onLeave);
1333
+ anchor.removeEventListener("focus", onEnter);
1334
+ anchor.removeEventListener("blur", onLeave);
1335
+ if (timers.show !== void 0) clearTimeout(timers.show);
1336
+ if (timers.hide !== void 0) clearTimeout(timers.hide);
1337
+ hide(INSTANT);
1338
+ leaving?.close(void 0, INSTANT);
1339
+ };
1340
+ }
1341
+
672
1342
  export { autoReposition, choice, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };
673
1343
 
674
1344
  //# sourceMappingURL=overlay.js.map