@zealakit/overlay-react 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +1 -0
  2. package/dist/animation/presence.js +3 -2
  3. package/dist/components/arrow.js +2 -0
  4. package/dist/components/context-menu/content.js +1 -1
  5. package/dist/components/context-menu/context-menu.js +2 -12
  6. package/dist/components/context-menu/index.d.ts +4 -4
  7. package/dist/components/context-menu/index.js +2 -2
  8. package/dist/components/context-menu/items.js +3 -3
  9. package/dist/components/context-menu/menu-navigation.js +22 -6
  10. package/dist/components/context-menu/menu-surface.d.ts +4 -4
  11. package/dist/components/context-menu/menu-surface.js +10 -11
  12. package/dist/components/context-menu/sub.d.ts +1 -1
  13. package/dist/components/context-menu/sub.js +3 -13
  14. package/dist/components/context-menu/trigger.js +0 -1
  15. package/dist/components/dialog/content.d.ts +3 -3
  16. package/dist/components/dialog/content.js +13 -15
  17. package/dist/components/dialog/dialog.js +1 -1
  18. package/dist/components/dialog/helpers.js +1 -0
  19. package/dist/components/dialog/index.d.ts +1 -1
  20. package/dist/components/dialog/trigger.js +2 -0
  21. package/dist/components/popover/content.d.ts +24 -24
  22. package/dist/components/popover/content.js +13 -17
  23. package/dist/components/popover/helpers.js +1 -0
  24. package/dist/components/popover/index.d.ts +2 -2
  25. package/dist/components/popover/index.js +1 -1
  26. package/dist/components/popover/popover.js +3 -1
  27. package/dist/components/portal.d.ts +1 -1
  28. package/dist/components/slot.js +1 -4
  29. package/dist/components/tooltip/content.d.ts +2 -2
  30. package/dist/components/tooltip/content.js +1 -3
  31. package/dist/components/tooltip/index.d.ts +5 -5
  32. package/dist/components/tooltip/index.js +4 -4
  33. package/dist/components/tooltip/provider.js +2 -2
  34. package/dist/components/tooltip/tooltip.js +19 -28
  35. package/dist/hooks/use-layer.js +4 -4
  36. package/dist/hooks/use-overlay.js +4 -4
  37. package/dist/hooks/use-positioner.js +3 -12
  38. package/dist/index.d.ts +4 -4
  39. package/dist/index.js +4 -4
  40. package/dist/vendor/core/animation/keyframes.d.ts +12 -3
  41. package/dist/vendor/core/animation/keyframes.js +63 -25
  42. package/dist/vendor/core/animation/run-animation.d.ts +1 -1
  43. package/dist/vendor/core/animation/run-animation.js +5 -10
  44. package/dist/vendor/core/controller/animator.js +2 -2
  45. package/dist/vendor/core/controller/context-menu-behavior.js +48 -37
  46. package/dist/vendor/core/controller/overlay-controller.d.ts +1 -1
  47. package/dist/vendor/core/controller/overlay-controller.js +52 -72
  48. package/dist/vendor/core/controller/tooltip-behavior.js +1 -3
  49. package/dist/vendor/core/controller/types.d.ts +15 -1
  50. package/dist/vendor/core/events/outside.d.ts +6 -3
  51. package/dist/vendor/core/events/outside.js +12 -25
  52. package/dist/vendor/core/events/pointer.d.ts +7 -7
  53. package/dist/vendor/core/events/pointer.js +7 -9
  54. package/dist/vendor/core/focus/focus.js +45 -105
  55. package/dist/vendor/core/layer/create-layer-stack.d.ts +14 -12
  56. package/dist/vendor/core/layer/create-layer-stack.js +114 -158
  57. package/dist/vendor/core/layer/create-layer.js +1 -2
  58. package/dist/vendor/core/layer/index.d.ts +1 -2
  59. package/dist/vendor/core/layer/index.js +1 -2
  60. package/dist/vendor/core/menu/index.d.ts +1 -1
  61. package/dist/vendor/core/menu/index.js +1 -1
  62. package/dist/vendor/core/menu/navigation.d.ts +0 -12
  63. package/dist/vendor/core/menu/navigation.js +0 -42
  64. package/dist/vendor/core/modal/background.js +13 -5
  65. package/dist/vendor/core/portal/index.d.ts +1 -1
  66. package/dist/vendor/core/portal/index.js +1 -1
  67. package/dist/vendor/core/positioning/compute.js +3 -3
  68. package/dist/vendor/core/positioning/coordinates.js +1 -1
  69. package/dist/vendor/core/positioning/create-positioner.d.ts +6 -3
  70. package/dist/vendor/core/positioning/create-positioner.js +86 -76
  71. package/dist/vendor/core/positioning/placement.js +1 -3
  72. package/dist/vendor/core/scroll-lock/scroll-lock.d.ts +8 -6
  73. package/dist/vendor/core/scroll-lock/scroll-lock.js +14 -60
  74. package/dist/vendor/core/types/animation.d.ts +10 -18
  75. package/dist/vendor/core/types/animation.js +3 -5
  76. package/dist/vendor/core/types/dismissal.d.ts +15 -2
  77. package/dist/vendor/core/types/geometry.d.ts +14 -5
  78. package/dist/vendor/core/types/layer.d.ts +2 -0
  79. package/dist/vendor/core/types/positioner.d.ts +8 -1
  80. package/dist/vendor/core/utils/global-state.js +6 -0
  81. package/package.json +4 -13
  82. package/dist/vendor/core/layer/manager.d.ts +0 -9
  83. package/dist/vendor/core/layer/manager.js +0 -157
@@ -1,5 +1,5 @@
1
1
  import type { OverlayController, OverlayControllerOptions } from "./types.js";
2
- export type { OverlayArrowOptions, OverlayChangeReason, OverlayController, OverlayControllerKind, OverlayControllerOptions, OverlayControllerState, OverlayFocusTarget, } from "./types.js";
2
+ export type { OverlayArrowOptions, OverlayChangeReason, OverlayController, OverlayControllerKind, OverlayControllerOptions, OverlayControllerState, OverlayFocusTarget, OverlayOptionsPatch, } from "./types.js";
3
3
  /**
4
4
  * Shared DOM controller used by the non-React adapters.
5
5
  *
@@ -1,7 +1,5 @@
1
1
  import { createFocusContainment, focusElement, focusFirst, getActiveElement, restoreFocus, } from "../focus/focus.js";
2
2
  import { acquireSharedLayerStack } from "../layer/create-layer-stack.js";
3
- import { isEscapeKey } from "../events/keyboard.js";
4
- import { isPointerOutside } from "../events/pointer.js";
5
3
  import { applyArrowStyles, createPositioner, DEFAULT_ARROW_SIZE, getArrowStyles, resetArrowStyles, snapshotArrowStyles, } from "../positioning/index.js";
6
4
  import { parsePlacement } from "../positioning/placement.js";
7
5
  import { lockBodyScroll } from "../scroll-lock/scroll-lock.js";
@@ -9,12 +7,11 @@ import { isBrowser } from "../utils/dom.js";
9
7
  import { listen } from "../lifecycle/index.js";
10
8
  import { getMenuItems } from "../menu/navigation.js";
11
9
  import { acquireModalBackground } from "../modal/background.js";
12
- import { moveToPortal, restorePortal, } from "../portal/portal.js";
13
- import { getGlobalState } from "../utils/global-state.js";
10
+ import { moveToPortal, restorePortal } from "../portal/portal.js";
11
+ import { createId } from "@zealakit/ui-engine";
14
12
  import { createOverlayAnimator } from "./animator.js";
15
13
  import { createContextMenuBehavior } from "./context-menu-behavior.js";
16
14
  import { createTooltipBehavior } from "./tooltip-behavior.js";
17
- const idCounter = getGlobalState("overlay-id", () => ({ value: 0 }));
18
15
  function focusTarget(content, target) {
19
16
  if (target === null || target === false) {
20
17
  return;
@@ -46,7 +43,8 @@ export function createOverlayController(initial) {
46
43
  let controlledOpen = initial.open ?? internalOpen;
47
44
  let isControlled = initial.open !== undefined;
48
45
  let disabled = initial.disabled ?? false;
49
- const contentId = initial.content.id || `overlay-${++idCounter.value}-content`;
46
+ // X11: ids come from the engine so two bundled copies never collide.
47
+ const contentId = initial.content.id || `${createId("overlay")}-content`;
50
48
  const doc = initial.content.ownerDocument;
51
49
  initial.content.id = contentId;
52
50
  if (initial.dir === "rtl") {
@@ -116,7 +114,9 @@ export function createOverlayController(initial) {
116
114
  requestOpen: (reason) => requestOpen(reason),
117
115
  requestClose: (reason) => requestClose(reason),
118
116
  };
119
- const animator = createOverlayAnimator(host, initial.animation, () => destroyed, () => finalizeClose());
117
+ const animator = createOverlayAnimator(host, initial.animation, () => destroyed,
118
+ // oxlint-disable-next-line eslint/no-use-before-define -- invoked after finalizeClose is initialized
119
+ () => finalizeClose());
120
120
  const tooltip = createTooltipBehavior(host);
121
121
  const contextMenu = createContextMenuBehavior(host);
122
122
  const snapshot = () => ({
@@ -135,15 +135,14 @@ export function createOverlayController(initial) {
135
135
  : createPositioner({
136
136
  reference: null,
137
137
  floating: null,
138
- placement: initial.placement ??
139
- (initial.kind === "tooltip" ? "top" : "bottom-start"),
138
+ placement: initial.placement ?? (initial.kind === "tooltip" ? "top" : "bottom-start"),
140
139
  offset: initial.offset ?? 0,
141
140
  alignOffset: initial.alignOffset ?? 0,
142
141
  flip: initial.flip ?? true,
143
142
  shift: initial.shift ?? true,
144
143
  padding: initial.padding ?? 0,
145
- boundary: initial.boundary,
146
- strategy: initial.strategy,
144
+ ...(initial.boundary === undefined ? {} : { boundary: initial.boundary }),
145
+ ...(initial.strategy === undefined ? {} : { strategy: initial.strategy }),
147
146
  autoUpdate: initial.autoUpdate ?? true,
148
147
  arrow: arrowPositionerOption(),
149
148
  });
@@ -165,7 +164,7 @@ export function createOverlayController(initial) {
165
164
  applyArrowStyles(arrowElement, getArrowStyles({
166
165
  placement: result.placement,
167
166
  arrow: result.arrow,
168
- size: options.arrow?.size,
167
+ ...(options.arrow?.size === undefined ? {} : { size: options.arrow.size }),
169
168
  }));
170
169
  }
171
170
  if (animator.pendingEnter) {
@@ -175,7 +174,9 @@ export function createOverlayController(initial) {
175
174
  const setTriggerOpenState = (open) => {
176
175
  const trigger = options.trigger;
177
176
  trigger.dataset.state = open ? "open" : "closed";
178
- if (options.kind !== "tooltip") {
177
+ // A tooltip trigger does not expand anything, and a context-menu target is a
178
+ // generic element, where ARIA does not allow `aria-expanded`.
179
+ if (options.kind !== "tooltip" && options.kind !== "context-menu") {
179
180
  trigger.setAttribute("aria-expanded", String(open));
180
181
  }
181
182
  if (open) {
@@ -206,9 +207,6 @@ export function createOverlayController(initial) {
206
207
  }
207
208
  };
208
209
  const ensureStack = () => {
209
- if (initial.kind === "tooltip" || options.kind === "tooltip") {
210
- return null;
211
- }
212
210
  if (stack) {
213
211
  return stack;
214
212
  }
@@ -229,16 +227,13 @@ export function createOverlayController(initial) {
229
227
  layerHandle = activeStack.register({
230
228
  element: options.content,
231
229
  reference: options.trigger,
232
- boundaries: options.boundaries,
230
+ ...(options.boundaries === undefined ? {} : { boundaries: options.boundaries }),
233
231
  parent: options.parentLayer ?? null,
234
232
  dismissOnEscape: options.dismissOnEscape ?? true,
235
233
  dismissOnOutsidePress: options.dismissOnOutsidePress ?? true,
234
+ modal: options.kind === "dialog" ? (options.modal ?? true) : false,
236
235
  onDismiss: (reason) => {
237
- requestClose(reason === "escape-key"
238
- ? "escape-key"
239
- : reason === "outside-press"
240
- ? "outside-press"
241
- : "reference-press");
236
+ requestClose(reason);
242
237
  },
243
238
  });
244
239
  };
@@ -272,31 +267,16 @@ export function createOverlayController(initial) {
272
267
  if (docCleanups.length > 0) {
273
268
  return;
274
269
  }
275
- if (options.kind === "tooltip") {
276
- docCleanups.push(listen(doc, "keydown", (event) => {
277
- if (event.defaultPrevented || !isEscapeKey(event)) {
278
- return;
279
- }
280
- event.preventDefault();
281
- requestClose("escape-key");
282
- }, true), listen(doc, "pointerdown", (event) => {
283
- if (options.content.contains(event.target) ||
284
- options.trigger.contains(event.target) ||
285
- !isPointerOutside(event, [options.content, options.trigger])) {
286
- return;
287
- }
288
- requestClose("outside-press");
289
- }, true));
290
- return;
291
- }
270
+ // Escape and outside presses are owned by the engine's layer stack (§3
271
+ // rule 5). Only context-menu specific page behaviour stays here: opening a
272
+ // new context menu elsewhere closes the current one (E5).
292
273
  if (options.kind === "context-menu") {
293
274
  docCleanups.push(listen(doc, "contextmenu", (event) => {
294
275
  const target = event.target;
295
276
  if (!target) {
296
277
  return;
297
278
  }
298
- if (options.content.contains(target) ||
299
- options.trigger.contains(target)) {
279
+ if (options.content.contains(target) || options.trigger.contains(target)) {
300
280
  return;
301
281
  }
302
282
  const element = target;
@@ -337,9 +317,7 @@ export function createOverlayController(initial) {
337
317
  const states = [];
338
318
  // A backdrop that wraps the content moves as one unit.
339
319
  const wrapped = options.backdrop?.contains(options.content) ?? false;
340
- const contentState = wrapped
341
- ? null
342
- : moveToPortal(options.content, options.portal);
320
+ const contentState = wrapped ? null : moveToPortal(options.content, options.portal);
343
321
  if (contentState) {
344
322
  states.push(contentState);
345
323
  }
@@ -395,11 +373,7 @@ export function createOverlayController(initial) {
395
373
  scrollCleanup = lockBodyScroll(doc);
396
374
  }
397
375
  }
398
- const initialTarget = options.initialFocus !== undefined
399
- ? options.initialFocus
400
- : modal
401
- ? "container"
402
- : null;
376
+ const initialTarget = options.initialFocus !== undefined ? options.initialFocus : modal ? "container" : null;
403
377
  focusTarget(options.content, initialTarget);
404
378
  if (options.trapFocus ?? modal) {
405
379
  containment = createFocusContainment({
@@ -562,6 +536,9 @@ export function createOverlayController(initial) {
562
536
  return positioner.update();
563
537
  };
564
538
  const setOptions = (next) => {
539
+ // An explicit `undefined` in the patch resets that option to its default, so
540
+ // the merged object can hold undefined where the creation type says it cannot.
541
+ // Every read below already falls back with `??`.
565
542
  options = { ...options, ...next };
566
543
  if (next.animation !== undefined) {
567
544
  animator.setConfig(next.animation);
@@ -589,29 +566,34 @@ export function createOverlayController(initial) {
589
566
  }
590
567
  }
591
568
  }
592
- if (next.placement !== undefined ||
593
- next.offset !== undefined ||
594
- next.alignOffset !== undefined ||
595
- next.flip !== undefined ||
596
- next.shift !== undefined ||
597
- next.padding !== undefined ||
598
- next.boundary !== undefined ||
599
- next.strategy !== undefined ||
600
- next.autoUpdate !== undefined ||
601
- next.dir !== undefined) {
602
- if (next.dir === "rtl" && options.content.isConnected) {
569
+ // A key that is *present* with an explicit undefined resets that option to
570
+ // the positioner default; an absent key leaves it untouched.
571
+ const POSITIONING_KEYS = [
572
+ "placement",
573
+ "offset",
574
+ "alignOffset",
575
+ "flip",
576
+ "shift",
577
+ "padding",
578
+ "boundary",
579
+ "strategy",
580
+ "autoUpdate",
581
+ "dir",
582
+ ];
583
+ if (POSITIONING_KEYS.some((key) => key in next)) {
584
+ if (options.dir === "rtl" && options.content.isConnected) {
603
585
  options.content.dir = "rtl";
604
586
  }
605
587
  positioner.setOptions({
606
- placement: next.placement ?? options.placement ?? "bottom",
607
- offset: next.offset ?? options.offset,
608
- alignOffset: next.alignOffset ?? options.alignOffset,
609
- flip: next.flip ?? options.flip,
610
- shift: next.shift ?? options.shift,
611
- padding: next.padding ?? options.padding,
612
- boundary: next.boundary ?? options.boundary,
613
- strategy: next.strategy ?? options.strategy,
614
- autoUpdate: next.autoUpdate ?? options.autoUpdate,
588
+ placement: options.placement ?? (options.kind === "tooltip" ? "top" : "bottom-start"),
589
+ offset: options.offset,
590
+ alignOffset: options.alignOffset,
591
+ flip: options.flip,
592
+ shift: options.shift,
593
+ padding: options.padding,
594
+ boundary: options.boundary,
595
+ strategy: options.strategy,
596
+ autoUpdate: options.autoUpdate,
615
597
  });
616
598
  }
617
599
  emitState();
@@ -631,9 +613,7 @@ export function createOverlayController(initial) {
631
613
  focusInside = false;
632
614
  }
633
615
  };
634
- const triggerClick = options.kind === "popover" || options.kind === "dialog"
635
- ? handleTriggerClick
636
- : null;
616
+ const triggerClick = options.kind === "popover" || options.kind === "dialog" ? handleTriggerClick : null;
637
617
  if (triggerClick) {
638
618
  options.trigger.addEventListener("click", triggerClick);
639
619
  }
@@ -30,9 +30,7 @@ export function createTooltipBehavior(host) {
30
30
  closeTimer = setTimeout(() => {
31
31
  closeTimer = null;
32
32
  const current = host.getOptions();
33
- if (!pointerOver &&
34
- !focused &&
35
- (!(current.hoverableContent ?? true) || !contentHovered)) {
33
+ if (!pointerOver && !focused && (!(current.hoverableContent ?? true) || !contentHovered)) {
36
34
  host.requestClose("programmatic");
37
35
  }
38
36
  }, wait);
@@ -14,6 +14,13 @@ export type OverlayArrowOptions = {
14
14
  /** Space kept between the arrow and the popup edges. Defaults to 0. */
15
15
  padding?: number;
16
16
  };
17
+ /**
18
+ * A live-options patch. `undefined` is a meaningful value here (reset), so it is
19
+ * written explicitly rather than omitted by `exactOptionalPropertyTypes`.
20
+ */
21
+ export type OverlayOptionsPatch = {
22
+ [K in keyof OverlayControllerOptions]?: OverlayControllerOptions[K] | undefined;
23
+ };
17
24
  export type OverlayControllerOptions = {
18
25
  kind: OverlayControllerKind;
19
26
  trigger: HTMLElement;
@@ -85,7 +92,14 @@ export type OverlayController = {
85
92
  toggle(reason?: OverlayChangeReason): void;
86
93
  /** Reflect controlled external visibility without emitting onOpenChange. */
87
94
  setOpen(open: boolean): void;
88
- setOptions(options: Partial<OverlayControllerOptions>): void;
95
+ /**
96
+ * Patch live options.
97
+ *
98
+ * Every key is optional and may be explicitly `undefined`, which means
99
+ * **reset to the default**. An omitted key keeps the current value: the
100
+ * controller merges `{ ...old, ...next }`, so the two are not interchangeable.
101
+ */
102
+ setOptions(options: OverlayOptionsPatch): void;
89
103
  update(): Promise<PositionerResult | null>;
90
104
  subscribe(listener: (state: OverlayControllerState) => void): Cleanup;
91
105
  destroy(): void;
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * True when the event target is outside every supplied element.
3
3
  *
4
- * Uses `composedPath()` when available so shadow-DOM targets are handled, and
5
- * falls back to `contains()` for synthetic events. `EventTarget` is checked
6
- * structurally to stay safe across documents, iframes, and non-Node targets.
4
+ * Thin wrapper on the engine's composed-path containment (D6), so shadow-DOM
5
+ * targets, portaled children, and synthetic events follow the same rule the
6
+ * layer stack uses.
7
+ *
8
+ * @param event The event to test.
9
+ * @param elements The interaction boundaries.
7
10
  */
8
11
  export declare function isOutsidePress(event: Event, elements: readonly (Element | null | undefined)[]): boolean;
@@ -1,33 +1,20 @@
1
+ import { isPointerInside } from "@zealakit/ui-engine/pointer";
1
2
  /**
2
3
  * True when the event target is outside every supplied element.
3
4
  *
4
- * Uses `composedPath()` when available so shadow-DOM targets are handled, and
5
- * falls back to `contains()` for synthetic events. `EventTarget` is checked
6
- * structurally to stay safe across documents, iframes, and non-Node targets.
5
+ * Thin wrapper on the engine's composed-path containment (D6), so shadow-DOM
6
+ * targets, portaled children, and synthetic events follow the same rule the
7
+ * layer stack uses.
8
+ *
9
+ * @param event The event to test.
10
+ * @param elements The interaction boundaries.
7
11
  */
8
12
  export function isOutsidePress(event, elements) {
9
- const target = event.target;
10
- if (target === null) {
11
- return true;
12
- }
13
- const path = getComposedPath(event);
14
- if (path.length > 0) {
15
- return !elements.some((element) => element !== null && element !== undefined && path.includes(element));
16
- }
17
- const node = target;
18
- if (typeof node.nodeType !== "number") {
13
+ const sources = elements.filter((element) => element !== null && element !== undefined);
14
+ if (sources.length === 0) {
19
15
  return true;
20
16
  }
21
- return !elements.some((element) => element?.contains(node) === true);
22
- }
23
- function getComposedPath(event) {
24
- if (typeof event.composedPath !== "function") {
25
- return [];
26
- }
27
- try {
28
- return event.composedPath();
29
- }
30
- catch {
31
- return [];
32
- }
17
+ // Overlay boundaries are any `Element`; the engine helper defaults its
18
+ // generic to `HTMLElement`, and every real boundary here is one.
19
+ return !isPointerInside(event, sources);
33
20
  }
@@ -1,13 +1,13 @@
1
- /**
2
- * True for the primary button of the primary pointer.
3
- *
4
- * `isPrimary` is treated as true when absent so synthetic events behave like
5
- * left clicks.
6
- */
7
- export declare function isPrimaryPointer(event: PointerEvent): boolean;
1
+ import { isPrimaryPointer } from "@zealakit/ui-engine/pointer";
2
+ export { isPrimaryPointer };
8
3
  /**
9
4
  * A left-button press outside every supplied element.
10
5
  *
11
6
  * Secondary buttons (right/middle) deliberately do not dismiss overlays.
7
+ * Containment is decided by the engine's composed-path helper (D6), so shadow
8
+ * DOM and portaled children behave exactly like layers do.
9
+ *
10
+ * @param event The pointer event.
11
+ * @param elements The interaction boundaries.
12
12
  */
13
13
  export declare function isPointerOutside(event: PointerEvent, elements: readonly (Element | null | undefined)[]): boolean;
@@ -1,17 +1,15 @@
1
+ import { isPrimaryPointer } from "@zealakit/ui-engine/pointer";
1
2
  import { isOutsidePress } from "./outside.js";
2
- /**
3
- * True for the primary button of the primary pointer.
4
- *
5
- * `isPrimary` is treated as true when absent so synthetic events behave like
6
- * left clicks.
7
- */
8
- export function isPrimaryPointer(event) {
9
- return event.isPrimary !== false && event.button === 0;
10
- }
3
+ export { isPrimaryPointer };
11
4
  /**
12
5
  * A left-button press outside every supplied element.
13
6
  *
14
7
  * Secondary buttons (right/middle) deliberately do not dismiss overlays.
8
+ * Containment is decided by the engine's composed-path helper (D6), so shadow
9
+ * DOM and portaled children behave exactly like layers do.
10
+ *
11
+ * @param event The pointer event.
12
+ * @param elements The interaction boundaries.
15
13
  */
16
14
  export function isPointerOutside(event, elements) {
17
15
  return isPrimaryPointer(event) && isOutsidePress(event, elements);
@@ -1,3 +1,4 @@
1
+ import { createFocusScope } from "@zealakit/ui-engine";
1
2
  import { isEscapeKey } from "../events/keyboard.js";
2
3
  import { listen } from "../lifecycle/events.js";
3
4
  const FOCUSABLE_SELECTOR = [
@@ -60,9 +61,7 @@ export function isFocusable(element) {
60
61
  }
61
62
  /** Elements inside `container` that can receive focus, in DOM order. */
62
63
  export function getFocusableElements(container) {
63
- return [
64
- ...container.querySelectorAll(FOCUSABLE_SELECTOR),
65
- ].filter(isFocusable);
64
+ return [...container.querySelectorAll(FOCUSABLE_SELECTOR)].filter(isFocusable);
66
65
  }
67
66
  /**
68
67
  * Focus an element if it is connected and focusable. Returns whether focus
@@ -126,20 +125,18 @@ function resolveTarget(target) {
126
125
  * nested child layer needs its own containment.
127
126
  */
128
127
  export function createFocusContainment(options) {
128
+ const scope = createFocusScope({
129
+ // Overlay works in `Element`; the engine's sources are `HTMLElement`.
130
+ container: options.container,
131
+ trap: true,
132
+ initialFocus: "none",
133
+ returnFocus: false,
134
+ });
129
135
  let enabled = false;
130
136
  let disposed = false;
131
137
  let captured = null;
132
- let redirecting = false;
133
- let cleanups = [];
134
- const resolveContainer = () => typeof options.container === "function"
135
- ? options.container()
136
- : options.container;
137
- const detach = () => {
138
- for (const cleanup of cleanups) {
139
- cleanup();
140
- }
141
- cleanups = [];
142
- };
138
+ let removeEscape = null;
139
+ const resolveContainer = () => typeof options.container === "function" ? options.container() : options.container;
143
140
  const restore = () => {
144
141
  if (!options.restoreFocus || !captured) {
145
142
  return false;
@@ -148,75 +145,6 @@ export function createFocusContainment(options) {
148
145
  captured = null;
149
146
  return restoreFocus(target);
150
147
  };
151
- const handleKeyDown = (event) => {
152
- if (!enabled || disposed || event.defaultPrevented) {
153
- return;
154
- }
155
- const container = resolveContainer();
156
- if (!container?.isConnected) {
157
- return;
158
- }
159
- if (options.shouldContain && !options.shouldContain(event)) {
160
- return;
161
- }
162
- if (isEscapeKey(event)) {
163
- options.onEscape?.(event);
164
- return;
165
- }
166
- if (event.key !== "Tab" || event.altKey || event.ctrlKey || event.metaKey) {
167
- return;
168
- }
169
- const focusables = getFocusableElements(container);
170
- const active = getActiveElement(container.ownerDocument);
171
- const first = focusables[0] ?? null;
172
- const last = focusables[focusables.length - 1] ?? null;
173
- if (!first || !last) {
174
- event.preventDefault();
175
- focusElement(container);
176
- return;
177
- }
178
- const index = active ? focusables.indexOf(active) : -1;
179
- if (index === -1) {
180
- event.preventDefault();
181
- focusElement(event.shiftKey ? last : first);
182
- return;
183
- }
184
- if (event.shiftKey && index === 0) {
185
- event.preventDefault();
186
- focusElement(last);
187
- }
188
- else if (!event.shiftKey && index === focusables.length - 1) {
189
- event.preventDefault();
190
- focusElement(first);
191
- }
192
- };
193
- const handleFocusIn = (event) => {
194
- if (!enabled || disposed || redirecting) {
195
- return;
196
- }
197
- const container = resolveContainer();
198
- if (!container?.isConnected) {
199
- return;
200
- }
201
- if (options.shouldContain && !options.shouldContain(event)) {
202
- return;
203
- }
204
- const path = event.composedPath();
205
- if (path.includes(container)) {
206
- return;
207
- }
208
- const target = event.target;
209
- if (target &&
210
- typeof target.nodeType === "number" &&
211
- container.contains(target)) {
212
- return;
213
- }
214
- redirecting = true;
215
- if (!focusFirst(container)) {
216
- focusElement(container);
217
- }
218
- redirecting = false;
219
- };
220
148
  const focusInitial = (container) => {
221
149
  const target = options.initialFocus;
222
150
  if (!target) {
@@ -232,34 +160,41 @@ export function createFocusContainment(options) {
232
160
  }
233
161
  focusElement(resolveTarget(target));
234
162
  };
235
- const attach = (capture, initial) => {
236
- const container = resolveContainer();
237
- if (!container?.isConnected) {
238
- return false;
239
- }
240
- const documentRef = container.ownerDocument;
241
- if (capture) {
242
- captured = options.restoreFocus ? getActiveElement(documentRef) : null;
243
- }
244
- cleanups.push(listen(documentRef, "keydown", handleKeyDown));
245
- cleanups.push(listen(documentRef, "focusin", handleFocusIn, true));
246
- if (initial) {
247
- focusInitial(container);
163
+ const attachEscape = (documentRef) => {
164
+ if (options.onEscape === undefined || removeEscape !== null) {
165
+ return;
248
166
  }
249
- return true;
167
+ removeEscape = listen(documentRef, "keydown", (event) => {
168
+ if (!enabled || disposed || event.defaultPrevented || !isEscapeKey(event)) {
169
+ return;
170
+ }
171
+ options.onEscape?.(event);
172
+ });
173
+ };
174
+ const detachEscape = () => {
175
+ removeEscape?.();
176
+ removeEscape = null;
250
177
  };
251
178
  const setEnabled = (next) => {
252
179
  if (disposed || enabled === next) {
253
180
  return;
254
181
  }
255
- enabled = next;
256
182
  if (next) {
257
- if (!attach(true, true)) {
258
- enabled = false;
183
+ const container = resolveContainer();
184
+ if (!container?.isConnected) {
185
+ return;
259
186
  }
187
+ captured = options.restoreFocus ? getActiveElement(container.ownerDocument) : null;
188
+ enabled = true;
189
+ scope.activate();
190
+ attachEscape(container.ownerDocument);
191
+ focusInitial(container);
260
192
  return;
261
193
  }
262
- detach();
194
+ enabled = false;
195
+ detachEscape();
196
+ // The wrapper owns capture/restore, so the engine must not move focus.
197
+ scope.deactivate({ returnFocus: false });
263
198
  restore();
264
199
  };
265
200
  const suspend = () => {
@@ -267,15 +202,20 @@ export function createFocusContainment(options) {
267
202
  return;
268
203
  }
269
204
  enabled = false;
270
- detach();
205
+ detachEscape();
206
+ scope.deactivate({ returnFocus: false });
271
207
  };
272
208
  const resume = () => {
273
209
  if (disposed || enabled) {
274
210
  return;
275
211
  }
276
- if (attach(false, false)) {
277
- enabled = true;
212
+ const container = resolveContainer();
213
+ if (!container?.isConnected) {
214
+ return;
278
215
  }
216
+ enabled = true;
217
+ scope.activate();
218
+ attachEscape(container.ownerDocument);
279
219
  };
280
220
  const controller = {
281
221
  get isEnabled() {
@@ -304,7 +244,7 @@ export function createFocusContainment(options) {
304
244
  restore();
305
245
  }
306
246
  disposed = true;
307
- detach();
247
+ detachEscape();
308
248
  },
309
249
  };
310
250
  controller.setEnabled(options.enabled ?? true);
@@ -1,25 +1,27 @@
1
1
  import type { LayerStack, LayerStackLease, LayerStackOptions, LayerStackRegistry } from "../types/layer.js";
2
2
  /**
3
- * Shared stack for layered UI.
3
+ * Shared layer stack backed by the engine's page-wide stack.
4
4
  *
5
- * A single set of document listeners is attached while at least one registered
6
- * layer has dismissal enabled. Escape and outside presses are routed to the
7
- * topmost layer only; per-layer flags decide whether it reacts.
5
+ * The engine owns ordering, Escape and outside-press dismissal; this wrapper
6
+ * keeps overlay's `LayerStack` vocabulary for the adapters: registration
7
+ * options map to `LayerOptions`, engine reasons map to overlay's
8
+ * `DismissReason`, and snapshots expose overlay handles.
9
+ *
10
+ * There are no document listeners here: the engine's listener hub owns them
11
+ * (§3 rule 5, P1/P2).
8
12
  */
9
- export declare function createLayerStack(options?: LayerStackOptions): LayerStack;
13
+ export declare function createLayerStack(_options?: LayerStackOptions): LayerStack;
10
14
  /**
11
- * Create a per-document registry of reference-counted layer stacks.
15
+ * Per-document registry kept for the adapters' shared-stack contract.
12
16
  *
13
- * Adapters use one registry per module, so independent components on the same
14
- * document share one stack (and one listener pair) while still releasing it
15
- * when the last consumer unmounts.
17
+ * The engine already keeps one page-wide stack; this registry only shares the
18
+ * wrapper object so a React and a Vue overlay acquire the same `LayerStack`.
16
19
  */
17
20
  export declare function createLayerStackRegistry(): LayerStackRegistry;
18
21
  /**
19
22
  * Shared per-document layer stack used by all adapters by default.
20
23
  *
21
- * Keeping this registry in Core means overlays from different adapters (for
22
- * example a React overlay and a Vue overlay on the same page) still share one
23
- * listener pair and one ordering stack.
24
+ * Every adapter's wrapper talks to the same engine stack, so a React overlay
25
+ * and a Vue overlay on one page share ordering, Escape, and outside presses.
24
26
  */
25
27
  export declare function acquireSharedLayerStack(documentRef: Document): LayerStackLease;