@atlaskit/top-layer 0.14.0 → 0.16.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 (97) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/cjs/dialog/create-close-event.js +1 -2
  3. package/dist/cjs/dialog/dialog-content.js +33 -4
  4. package/dist/cjs/dialog-scroll-lock/index.js +17 -7
  5. package/dist/cjs/entry-points/dialog.js +6 -0
  6. package/dist/cjs/entry-points/popover.js +6 -0
  7. package/dist/cjs/entry-points/use-popover-id.js +3 -1
  8. package/dist/cjs/internal/get-aria-for-trigger.js +8 -3
  9. package/dist/cjs/internal/use-anchor-position-at-point.js +4 -2
  10. package/dist/cjs/internal/use-anchor-position.js +3 -2
  11. package/dist/cjs/internal/use-animated-visibility.js +233 -155
  12. package/dist/cjs/internal/use-focus-wrap.js +5 -3
  13. package/dist/cjs/internal/use-initial-focus.js +196 -50
  14. package/dist/cjs/internal/use-width-from-anchor.js +5 -4
  15. package/dist/cjs/popover/create-close-event.js +1 -2
  16. package/dist/cjs/popover/popover.js +58 -9
  17. package/dist/es2019/dialog/create-close-event.js +1 -2
  18. package/dist/es2019/dialog/dialog-content.js +33 -4
  19. package/dist/es2019/dialog-scroll-lock/index.js +18 -8
  20. package/dist/es2019/entry-points/dialog.js +1 -1
  21. package/dist/es2019/entry-points/popover.js +1 -1
  22. package/dist/es2019/entry-points/use-popover-id.js +3 -1
  23. package/dist/es2019/internal/get-aria-for-trigger.js +8 -3
  24. package/dist/es2019/internal/use-anchor-position-at-point.js +4 -2
  25. package/dist/es2019/internal/use-anchor-position.js +3 -2
  26. package/dist/es2019/internal/use-animated-visibility.js +222 -149
  27. package/dist/es2019/internal/use-focus-wrap.js +5 -4
  28. package/dist/es2019/internal/use-initial-focus.js +189 -45
  29. package/dist/es2019/internal/use-width-from-anchor.js +5 -4
  30. package/dist/es2019/popover/create-close-event.js +1 -2
  31. package/dist/es2019/popover/popover.js +59 -10
  32. package/dist/esm/dialog/create-close-event.js +1 -2
  33. package/dist/esm/dialog/dialog-content.js +33 -4
  34. package/dist/esm/dialog-scroll-lock/index.js +17 -8
  35. package/dist/esm/entry-points/dialog.js +1 -1
  36. package/dist/esm/entry-points/popover.js +1 -1
  37. package/dist/esm/entry-points/use-popover-id.js +3 -1
  38. package/dist/esm/internal/get-aria-for-trigger.js +8 -3
  39. package/dist/esm/internal/use-anchor-position-at-point.js +4 -2
  40. package/dist/esm/internal/use-anchor-position.js +3 -2
  41. package/dist/esm/internal/use-animated-visibility.js +235 -157
  42. package/dist/esm/internal/use-focus-wrap.js +5 -4
  43. package/dist/esm/internal/use-initial-focus.js +196 -51
  44. package/dist/esm/internal/use-width-from-anchor.js +5 -4
  45. package/dist/esm/popover/create-close-event.js +1 -2
  46. package/dist/esm/popover/popover.js +59 -10
  47. package/dist/types/animations/types.d.ts +0 -8
  48. package/dist/types/dialog/create-close-event.d.ts +1 -2
  49. package/dist/types/dialog/types.d.ts +9 -1
  50. package/dist/types/dialog-scroll-lock/index.d.ts +22 -6
  51. package/dist/types/entry-points/animations.d.ts +1 -1
  52. package/dist/types/entry-points/dialog.d.ts +1 -1
  53. package/dist/types/entry-points/popover.d.ts +1 -1
  54. package/dist/types/internal/get-aria-for-trigger.d.ts +8 -1
  55. package/dist/types/internal/use-anchor-position-at-point.d.ts +6 -1
  56. package/dist/types/internal/use-anchor-position.d.ts +14 -1
  57. package/dist/types/internal/use-animated-visibility.d.ts +48 -19
  58. package/dist/types/internal/use-focus-wrap.d.ts +6 -1
  59. package/dist/types/internal/use-initial-focus.d.ts +55 -4
  60. package/dist/types/internal/use-width-from-anchor.d.ts +3 -2
  61. package/dist/types/popover/create-close-event.d.ts +1 -2
  62. package/dist/types/popover/types.d.ts +13 -2
  63. package/dist/types-ts4.5/animations/types.d.ts +0 -8
  64. package/dist/types-ts4.5/dialog/create-close-event.d.ts +1 -2
  65. package/dist/types-ts4.5/dialog/types.d.ts +9 -1
  66. package/dist/types-ts4.5/dialog-scroll-lock/index.d.ts +22 -6
  67. package/dist/types-ts4.5/entry-points/animations.d.ts +1 -1
  68. package/dist/types-ts4.5/entry-points/dialog.d.ts +1 -1
  69. package/dist/types-ts4.5/entry-points/popover.d.ts +1 -1
  70. package/dist/types-ts4.5/internal/get-aria-for-trigger.d.ts +8 -1
  71. package/dist/types-ts4.5/internal/use-anchor-position-at-point.d.ts +6 -1
  72. package/dist/types-ts4.5/internal/use-anchor-position.d.ts +14 -1
  73. package/dist/types-ts4.5/internal/use-animated-visibility.d.ts +48 -19
  74. package/dist/types-ts4.5/internal/use-focus-wrap.d.ts +6 -1
  75. package/dist/types-ts4.5/internal/use-initial-focus.d.ts +55 -4
  76. package/dist/types-ts4.5/internal/use-width-from-anchor.d.ts +3 -2
  77. package/dist/types-ts4.5/popover/create-close-event.d.ts +1 -2
  78. package/dist/types-ts4.5/popover/types.d.ts +13 -2
  79. package/package.json +1 -1
  80. package/create-close-event/package.json +0 -17
  81. package/dialog/create-close-event/package.json +0 -17
  82. package/dist/cjs/entry-points/create-close-event.js +0 -19
  83. package/dist/cjs/entry-points/dialog/create-close-event.js +0 -12
  84. package/dist/cjs/entry-points/popover/create-close-event.js +0 -12
  85. package/dist/es2019/entry-points/create-close-event.js +0 -9
  86. package/dist/es2019/entry-points/dialog/create-close-event.js +0 -1
  87. package/dist/es2019/entry-points/popover/create-close-event.js +0 -1
  88. package/dist/esm/entry-points/create-close-event.js +0 -9
  89. package/dist/esm/entry-points/dialog/create-close-event.js +0 -1
  90. package/dist/esm/entry-points/popover/create-close-event.js +0 -1
  91. package/dist/types/entry-points/create-close-event.d.ts +0 -11
  92. package/dist/types/entry-points/dialog/create-close-event.d.ts +0 -2
  93. package/dist/types/entry-points/popover/create-close-event.d.ts +0 -2
  94. package/dist/types-ts4.5/entry-points/create-close-event.d.ts +0 -11
  95. package/dist/types-ts4.5/entry-points/dialog/create-close-event.d.ts +0 -2
  96. package/dist/types-ts4.5/entry-points/popover/create-close-event.d.ts +0 -2
  97. package/popover/create-close-event/package.json +0 -17
@@ -1,6 +1,5 @@
1
1
  import { useEffect, useRef } from 'react';
2
2
  import { getFirstFocusable } from '../focus/get-first-focusable';
3
-
4
3
  /**
5
4
  * Determines the correct element to receive initial focus within a popover,
6
5
  * based on its ARIA role.
@@ -17,10 +16,106 @@ import { getFirstFocusable } from '../focus/get-first-focusable';
17
16
  * has no effect on hidden popover content. Consumers must set the native
18
17
  * attribute via a ref callback (e.g. `node.setAttribute('autofocus', '')`).
19
18
  * React 19+ reflects the JSX prop as the HTML attribute automatically.
19
+ *
20
+ * Combobox pattern exception: if the popup is controlled by a focused
21
+ * combobox-like trigger (its `aria-controls` references this popup),
22
+ * focus stays on the textbox regardless of role. See
23
+ * `isComboboxControllingPopup`.
24
+ */
25
+
26
+ /**
27
+ * WAI-ARIA APG Combobox Pattern: when a combobox controls a popup (listbox,
28
+ * grid, tree, or menu), DOM focus must remain on the textbox. Subsequent
29
+ * navigation through popup items uses `aria-activedescendant` (or proxied
30
+ * keyboard events), never DOM focus movement.
31
+ *
32
+ * Detects both variants in a single pass:
33
+ * - In-popup combobox: the textbox lives inside the popup `container`
34
+ * (the popup is rendered as a child of the combobox wrapper).
35
+ * - External combobox: the textbox is rendered OUTSIDE the popup
36
+ * (`react-select` pattern, where the listbox is portalled separately
37
+ * from the textbox).
38
+ *
39
+ * Acceptance criteria for the active element:
40
+ * - Role / element-type filter: `role="combobox"`, `role="textbox"`,
41
+ * `TEXTAREA`, `contentEditable`, or `INPUT` of text-like type
42
+ * (`text`, `search`, `email`, `url`, `tel`, `password`, or
43
+ * unspecified). Non-text input types (`button`, `checkbox`, etc.)
44
+ * are rejected.
45
+ * - Reference filter: `aria-controls` (or legacy `aria-owns`) IDREFS
46
+ * must resolve to an element that IS or CONTAINS the popup container.
47
+ *
48
+ * See: https://www.w3.org/WAI/ARIA/apg/patterns/combobox/
20
49
  */
21
- function getInitialFocusTarget(_ref) {
22
- var container = _ref.container,
23
- role = _ref.role;
50
+ // `<input>` types treated as text-like for combobox detection.
51
+ // Non-text input types (`button`, `checkbox`, `submit`, etc.) are rejected.
52
+ // A missing `type` attribute defaults to `text` per the HTML spec, so we
53
+ // normalize that case before lookup rather than including an empty string here.
54
+ var TEXT_LIKE_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'password']);
55
+ function isTextboxLikeElement(element) {
56
+ var role = element.getAttribute('role');
57
+ if (role === 'combobox' || role === 'textbox') {
58
+ return true;
59
+ }
60
+ // `tagName` is uppercase for HTML elements but can be mixed-case for
61
+ // XML/SVG. Normalize once so downstream comparisons stay lowercase.
62
+ var tag = element.tagName.toLowerCase();
63
+ if (tag === 'textarea') {
64
+ return true;
65
+ }
66
+ if (element.isContentEditable) {
67
+ return true;
68
+ }
69
+ if (tag === 'input') {
70
+ var _element$getAttribute;
71
+ var type = ((_element$getAttribute = element.getAttribute('type')) !== null && _element$getAttribute !== void 0 ? _element$getAttribute : 'text').toLowerCase();
72
+ return TEXT_LIKE_INPUT_TYPES.has(type);
73
+ }
74
+ return false;
75
+ }
76
+ function isComboboxControllingPopup(_ref) {
77
+ var _active$getAttribute;
78
+ var container = _ref.container;
79
+ var ownerDocument = container.ownerDocument;
80
+ var active = ownerDocument.activeElement;
81
+ if (!(active instanceof HTMLElement)) {
82
+ return false;
83
+ }
84
+ if (!isTextboxLikeElement(active)) {
85
+ return false;
86
+ }
87
+
88
+ // Accept legacy `aria-owns` in addition to `aria-controls`.
89
+ // `aria-controls` / `aria-owns` are IDREFS (space-separated list of IDs)
90
+ // per the WAI-ARIA spec, so we must split and check membership rather
91
+ // than comparing with strict equality. A combobox that controls both
92
+ // this popup and another element (e.g. a results status region) must
93
+ // still be recognised as controlling this popup.
94
+ var idRefs = (_active$getAttribute = active.getAttribute('aria-controls')) !== null && _active$getAttribute !== void 0 ? _active$getAttribute : active.getAttribute('aria-owns');
95
+ if (!idRefs) {
96
+ return false;
97
+ }
98
+
99
+ // Match if any referenced element IS, CONTAINS, or IS CONTAINED BY the
100
+ // popup container. The "contained by" case covers wrapper-style adopters
101
+ // like react-select, where the combobox input's `aria-controls` points at
102
+ // a listbox element that is a descendant of the Popover host (the
103
+ // listbox role lives on a child the wrapped library owns, not on the
104
+ // host we render).
105
+ var referencedIds = idRefs.split(/\s+/).filter(function (id) {
106
+ return id !== '';
107
+ });
108
+ return referencedIds.some(function (id) {
109
+ var referenced = ownerDocument.getElementById(id);
110
+ if (!referenced) {
111
+ return false;
112
+ }
113
+ return referenced === container || referenced.contains(container) || container.contains(referenced);
114
+ });
115
+ }
116
+ function getInitialFocusTarget(_ref2) {
117
+ var container = _ref2.container,
118
+ role = _ref2.role;
24
119
  if (role === 'dialog' || role === 'alertdialog') {
25
120
  // Prefer element with the native HTML autofocus attribute.
26
121
  var autofocusEl = container.querySelector('[autofocus]');
@@ -33,6 +128,13 @@ function getInitialFocusTarget(_ref) {
33
128
  });
34
129
  }
35
130
  if (role === 'menu') {
131
+ // ARIA Combobox Pattern: if the popup is owned by a focused combobox,
132
+ // leave focus on the textbox. Navigation is proxied via the combobox.
133
+ if (isComboboxControllingPopup({
134
+ container: container
135
+ })) {
136
+ return null;
137
+ }
36
138
  // Initial focus placement is the extent of what top-layer provides
37
139
  // for menus. All subsequent keyboard navigation (arrow keys, Home/End,
38
140
  // type-ahead, Enter/Space, submenu coordination) is the responsibility
@@ -44,11 +146,31 @@ function getInitialFocusTarget(_ref) {
44
146
  });
45
147
  }
46
148
  if (role === 'listbox') {
47
- // Prefer selected option, fall back to first focusable
149
+ // ARIA Combobox Pattern: if the popup is owned by a focused
150
+ // combobox-like textbox (in-popup or external e.g. react-select),
151
+ // leave focus on the textbox. Navigation is proxied via the combobox.
152
+ if (isComboboxControllingPopup({
153
+ container: container
154
+ })) {
155
+ return null;
156
+ }
157
+ // Prefer the selected option, then fall back to the first option.
158
+ // We intentionally match by `[role="option"]` rather than by
159
+ // `getFirstFocusable`. The standard WAI-ARIA APG listbox pattern
160
+ // renders options with `tabindex="-1"` (managed via roving
161
+ // tabindex); `getFirstFocusable` excludes `tabindex="-1"` elements
162
+ // and would silently lose initial focus for spec-conformant
163
+ // listboxes. Options remain programmatically focusable.
48
164
  var selectedOption = container.querySelector('[role="option"][aria-selected="true"]');
49
165
  if (selectedOption) {
50
166
  return selectedOption;
51
167
  }
168
+ var firstOption = container.querySelector('[role="option"]');
169
+ if (firstOption) {
170
+ return firstOption;
171
+ }
172
+ // Last resort for non-standard listboxes that render no options
173
+ // but do contain a focusable element (e.g. an empty-state action).
52
174
  return getFirstFocusable({
53
175
  container: container
54
176
  });
@@ -71,58 +193,81 @@ function getInitialFocusTarget(_ref) {
71
193
  * Role is taken from the typed `role` prop - this is the consumer's contract
72
194
  * and is not subject to drift from a directly-mutated DOM attribute.
73
195
  *
74
- * Always call this hook unconditionally. Focus is only moved when `isOpen`
75
- * transitions to `true` and the role requires it.
196
+ * Always call this hook unconditionally. Focus is moved on each transition
197
+ * into a visible phase, the moment the host element first becomes visible
198
+ * for that open intent:
199
+ *
200
+ * - Animated path: on `closed → entering`. The host has just been mounted
201
+ * and the layout effect that calls `showPopover()` / `showModal()` has
202
+ * already run, so the element is in the top layer. We focus before the
203
+ * entry transition settles to match the WAI-ARIA APG expectation that
204
+ * focus lands on the new menu / dialog the instant it opens, not after
205
+ * the CSS finishes animating.
206
+ * - Non-animated path: on `closed → open` (the entering phase is skipped).
207
+ * - Reopen mid-exit: on `exiting → entering`. When a user dismisses the
208
+ * popup (Escape, close button, light dismiss) the browser natively
209
+ * restores focus to the trigger as part of `hidePopover()` /
210
+ * `<dialog>.close()`. If the consumer reopens before the exit transition
211
+ * has settled, the phase machine jumps `exiting → entering` without
212
+ * passing through `closed`, so without this branch the popup would be
213
+ * visible again with focus stranded on the trigger — a keyboard usability
214
+ * gap for menu/dialog/listbox roles.
215
+ *
216
+ * Note: there is a rare programmatic path where a consumer flips `isOpen`
217
+ * false → true without any user-initiated close gesture and had moved focus
218
+ * to a non-default target inside the popup. In that scenario this hook
219
+ * re-focuses the role-appropriate default (e.g. first menu item) rather
220
+ * than preserving the consumer-chosen target. This matches the documented
221
+ * `closed → entering` behavior and is considered acceptable given how
222
+ * abstract the scenario is. See `notes/architecture/focus.md`.
223
+ *
224
+ * Pure `entering → exiting → entering` stutters where the popup never
225
+ * reaches `closed` and the consumer toggles in the same frame are still
226
+ * collapsed: the `prevPhase` ref guard rejects any transition whose
227
+ * previous phase was not `closed` or `exiting`.
228
+ *
229
+ * Tradeoff vs the previous `requestAnimationFrame` based approach: we no
230
+ * longer wait one paint before focusing. The element is already attached
231
+ * and in the top layer when this effect runs (the show / hide layout
232
+ * effect runs first), so screen-reader announcement and visible focus
233
+ * land together. If a regression appears that needs the extra paint
234
+ * (e.g. browsers that require a layout pass before `focus()` works on a
235
+ * freshly promoted top-layer element), wrap the `focus()` call in a
236
+ * single `requestAnimationFrame` here and re-add a same-element ref
237
+ * check inside the RAF callback.
76
238
  */
77
- export function useInitialFocus(_ref2) {
78
- var elementRef = _ref2.elementRef,
79
- isOpen = _ref2.isOpen,
80
- role = _ref2.role;
81
- // Track the most recently scheduled RAF so a rapid `isOpen → false → true`
82
- // transition can cancel the previous frame before its closure runs against
83
- // a stale popover element. Without this, the RAF queued during the first
84
- // open could fire after the second open had begun and focus the wrong
85
- // instance.
86
- var pendingRafRef = useRef(null);
239
+ export function useInitialFocus(_ref3) {
240
+ var elementRef = _ref3.elementRef,
241
+ phase = _ref3.phase,
242
+ role = _ref3.role;
243
+ // Track the previous phase so we only focus on transitions into a
244
+ // visible phase from either `'closed'` (fresh mount) or `'exiting'`
245
+ // (mid-exit reopen where the browser has already restored focus to
246
+ // the trigger). Pure `entering → exiting → entering` stutters where
247
+ // the consumer toggles in the same frame are still collapsed.
248
+ var prevPhaseRef = useRef('closed');
87
249
  useEffect(function () {
88
- if (!isOpen) {
250
+ var _getInitialFocusTarge;
251
+ var prevPhase = prevPhaseRef.current;
252
+ prevPhaseRef.current = phase;
253
+
254
+ // Skip the `phase === 'closed'` transitions (host is going away,
255
+ // nothing to focus) and any transition whose previous phase was
256
+ // neither `'closed'` (fresh open) nor `'exiting'` (mid-exit
257
+ // reopen, focus already on the trigger).
258
+ if (phase === 'closed') {
259
+ return;
260
+ }
261
+ if (prevPhase !== 'closed' && prevPhase !== 'exiting') {
89
262
  return;
90
263
  }
91
264
  var el = elementRef.current;
92
265
  if (!el) {
93
266
  return;
94
267
  }
95
-
96
- // Cancel any RAF queued by the previous open cycle.
97
- if (pendingRafRef.current !== null) {
98
- cancelAnimationFrame(pendingRafRef.current);
99
- }
100
-
101
- // Use requestAnimationFrame to ensure the popover is fully rendered
102
- // and visible in the top layer before attempting to move focus.
103
- // showPopover() is called in useLayoutEffect (which runs before this
104
- // useEffect), so by the time the RAF fires after the next paint the
105
- // element is guaranteed to be in the top layer.
106
- var rafId = requestAnimationFrame(function () {
107
- var _getInitialFocusTarge;
108
- pendingRafRef.current = null;
109
- // Verify the element we captured is still the live popover. In
110
- // rapid-toggle scenarios the ref may already point to a different
111
- // instance - skip rather than focus the wrong popover.
112
- if (elementRef.current !== el) {
113
- return;
114
- }
115
- (_getInitialFocusTarge = getInitialFocusTarget({
116
- container: el,
117
- role: role
118
- })) === null || _getInitialFocusTarge === void 0 || _getInitialFocusTarge.focus();
119
- });
120
- pendingRafRef.current = rafId;
121
- return function () {
122
- cancelAnimationFrame(rafId);
123
- if (pendingRafRef.current === rafId) {
124
- pendingRafRef.current = null;
125
- }
126
- };
127
- }, [elementRef, isOpen, role]);
268
+ (_getInitialFocusTarge = getInitialFocusTarget({
269
+ container: el,
270
+ role: role
271
+ })) === null || _getInitialFocusTarge === void 0 || _getInitialFocusTarge.focus();
272
+ }, [elementRef, phase, role]);
128
273
  }
@@ -17,7 +17,8 @@ import { setStyle } from './set-style';
17
17
  export function useWidthFromAnchor(_ref) {
18
18
  var mode = _ref.mode,
19
19
  popoverRef = _ref.popoverRef,
20
- anchorRef = _ref.anchorRef;
20
+ anchorRef = _ref.anchorRef,
21
+ isOpen = _ref.isOpen;
21
22
  useLayoutEffect(function () {
22
23
  var node = popoverRef.current;
23
24
  if (!node) {
@@ -43,7 +44,7 @@ export function useWidthFromAnchor(_ref) {
43
44
  }
44
45
 
45
46
  // JS fallback: one-off read of the anchor's width.
46
- var anchor = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.current;
47
+ var anchor = anchorRef.current;
47
48
  if (anchor) {
48
49
  return setStyle({
49
50
  el: node,
@@ -75,7 +76,7 @@ export function useWidthFromAnchor(_ref) {
75
76
  }]
76
77
  });
77
78
  }
78
- var _anchor = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.current;
79
+ var _anchor = anchorRef.current;
79
80
  if (_anchor) {
80
81
  return setStyle({
81
82
  el: node,
@@ -98,5 +99,5 @@ export function useWidthFromAnchor(_ref) {
98
99
  el: node,
99
100
  styles: [minInlineSizeStyle]
100
101
  });
101
- }, [mode, popoverRef, anchorRef]);
102
+ }, [mode, popoverRef, anchorRef, isOpen]);
102
103
  }
@@ -12,8 +12,7 @@
12
12
  *
13
13
  * @example
14
14
  * ```tsx
15
- * import { createPopoverCloseEvent } from '@atlaskit/top-layer/create-close-event';
16
- * import { type TPopoverCloseReason } from '@atlaskit/top-layer/popover';
15
+ * import { createPopoverCloseEvent, type TPopoverCloseReason } from '@atlaskit/top-layer/popover';
17
16
  *
18
17
  * function onPopoverClose({ reason }: { reason: TPopoverCloseReason }) {
19
18
  * legacyOnClose(createPopoverCloseEvent({ reason }));
@@ -4,7 +4,7 @@ import _defineProperty from "@babel/runtime/helpers/defineProperty";
4
4
  import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
5
5
  import "./popover.compiled.css";
6
6
  import { ax, ix } from "@compiled/react/runtime";
7
- import React, { forwardRef, useCallback, useEffect, useId, useLayoutEffect, useRef } from 'react';
7
+ import React, { forwardRef, useCallback, useId, useLayoutEffect, useRef } from 'react';
8
8
  import { bind } from 'bind-event-listener';
9
9
  import mergeRefs from '@atlaskit/ds-lib/merge-refs';
10
10
  import once from '@atlaskit/ds-lib/once';
@@ -77,20 +77,32 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
77
77
  onEnterFinish: onEnterFinish,
78
78
  onExitFinish: onExitFinish
79
79
  }),
80
- showChildren = _useAnimatedVisibilit.showChildren,
80
+ phase = _useAnimatedVisibilit.phase,
81
81
  preset = _useAnimatedVisibilit.preset;
82
82
 
83
- // Focus management: initial focus on open (role-dependent), Tab cycling
83
+ // Pre-computed phase predicate. `isVisible` mirrors "host element is
84
+ // mounted and on screen" (any phase except `closed`); used as a dep
85
+ // signal for listener-re-bind effects so they re-attach to the fresh
86
+ // host element after a close → reopen unmount/remount cycle.
87
+ var isVisible = phase !== 'closed';
88
+
89
+ // Focus management: initial focus on entry (role-dependent), Tab cycling
84
90
  // for dialog roles. Restoration is native for outermost popovers; nested
85
91
  // focus-capturing roles are handled below via `beforetoggle` snapshot.
86
92
  // See: notes/architecture/focus-restoration.md
93
+ //
94
+ // Both hooks take `phase` directly: `useFocusWrap` keeps its listener
95
+ // attached while `phase !== 'closed'` (so focus stays trapped through
96
+ // the animated-exit window — WCAG 2.4.3 regression guard);
97
+ // `useInitialFocus` moves focus on the transition into `'open'`.
87
98
  useFocusWrap({
88
99
  elementRef: ownRef,
89
- role: role
100
+ role: role,
101
+ phase: phase
90
102
  });
91
103
  useInitialFocus({
92
104
  elementRef: ownRef,
93
- isOpen: isOpen,
105
+ phase: phase,
94
106
  role: role
95
107
  });
96
108
 
@@ -187,7 +199,23 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
187
199
  });
188
200
  }
189
201
  }, [onClose, onOpenChange, role]);
190
- useEffect(function () {
202
+
203
+ // Bind toggle/beforetoggle/keydown listeners via `useLayoutEffect` so
204
+ // they are attached BEFORE the show/hide layout effect calls
205
+ // `el.showPopover()`. `showPopover()` dispatches `beforetoggle`
206
+ // synchronously; binding the listener in a regular `useEffect`
207
+ // (which runs after layout effects) misses that first dispatch and
208
+ // the `previouslyFocusedElementRef` snapshot never gets taken — which
209
+ // breaks nested-popover focus restoration on close.
210
+ //
211
+ // `isVisible` is in deps so the listeners re-bind to the new host
212
+ // element after a host unmount/remount cycle. The cleanup detaches
213
+ // the old listeners.
214
+ //
215
+ // This layout effect MUST appear in the file before the show/hide
216
+ // layout effect — React runs layout effects in source order on the
217
+ // same commit, and we need listeners attached first.
218
+ useLayoutEffect(function () {
191
219
  var element = ownRef.current;
192
220
  if (!element) {
193
221
  return;
@@ -219,10 +247,13 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
219
247
  unbindToggle();
220
248
  unbindBeforeToggle();
221
249
  };
222
- }, [handleToggle, handleBeforeToggle]);
250
+ }, [handleToggle, handleBeforeToggle, isVisible]);
223
251
 
224
252
  // Placement-dependent animation CSS vars. Kept separate from show/hide
225
- // so preset reference changes do not re-trigger visibility.
253
+ // so preset reference changes do not re-trigger visibility. `isVisible`
254
+ // is in deps so the CSS vars are re-applied to the new host element after
255
+ // a remount cycle (otherwise the freshly mounted element would have no
256
+ // transform / placement vars set).
226
257
  useLayoutEffect(function () {
227
258
  var el = ownRef.current;
228
259
  if (!el || !(preset !== null && preset !== void 0 && preset.getProperties) || !placement) {
@@ -237,7 +268,7 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
237
268
  value = _ref3[1];
238
269
  el.style.setProperty(key, String(value));
239
270
  });
240
- }, [preset, placement]);
271
+ }, [preset, placement, isVisible]);
241
272
 
242
273
  // Show/hide based on isOpen. `showPopover`/`hidePopover` are no-ops when
243
274
  // already in the target state. Try/catch guards `InvalidStateError` on
@@ -249,6 +280,13 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
249
280
  }
250
281
  if (isOpen) {
251
282
  programmaticCloseRef.current = false;
283
+ // Reset the close-reason snapshot at the start of every open
284
+ // cycle. The ref outlives the host element (lives on the
285
+ // component, not the DOM), so a stale 'escape' from a prior
286
+ // cycle would otherwise leak into the next close — especially
287
+ // in the no-animation path where the host unmounts before
288
+ // `handleToggle` has a chance to reset the ref itself.
289
+ closeReasonRef.current = 'light-dismiss';
252
290
  try {
253
291
  el.showPopover();
254
292
  } catch (_unused) {}
@@ -264,6 +302,17 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
264
302
  el.hidePopover();
265
303
  } catch (_unused3) {}
266
304
  }, [isOpen]);
305
+
306
+ // The host element is only rendered while the popover is open or its exit
307
+ // animation is playing. Once the phase returns to `closed`, we unmount
308
+ // the host entirely so it does not leave an empty `role="..."` /
309
+ // `popover` element in the accessibility tree. The element re-mounts on
310
+ // the next `isOpen=true` commit; refs and event listeners re-bind via
311
+ // the existing layout effect and `useEffect`. The popover `id` is stable
312
+ // across opens (derived from `useId()` or the consumer-supplied `idProp`).
313
+ if (!isVisible) {
314
+ return null;
315
+ }
267
316
  return /*#__PURE__*/React.createElement("div", _extends({
268
317
  ref: combinedRef,
269
318
  id: popoverId
@@ -278,5 +327,5 @@ export var Popover = /*#__PURE__*/forwardRef(function Popover(_ref, ref) {
278
327
  }, preset ? _defineProperty({}, "data-ds-popover-".concat(preset.name), '') : undefined, {
279
328
  // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- xcss prop passes compiled atomic class names
280
329
  className: ax([styles.root, xcssFromProps])
281
- }), showChildren ? children : null);
330
+ }), children);
282
331
  });
@@ -36,11 +36,3 @@ export type TAnimationPreset = {
36
36
  */
37
37
  exitDurationMs: number;
38
38
  };
39
- /**
40
- * @deprecated Use `TAnimationPreset` instead.
41
- */
42
- export type TPopoverAnimationPreset = TAnimationPreset;
43
- /**
44
- * @deprecated Use `TAnimationPreset` instead.
45
- */
46
- export type TDialogAnimationPreset = TAnimationPreset;
@@ -11,8 +11,7 @@ import type { TDialogCloseReason } from './types';
11
11
  *
12
12
  * @example
13
13
  * ```tsx
14
- * import { createCloseEvent } from '@atlaskit/top-layer/create-close-event';
15
- * import { type TDialogCloseReason } from '@atlaskit/top-layer/dialog';
14
+ * import { createCloseEvent, type TDialogCloseReason } from '@atlaskit/top-layer/dialog';
16
15
  *
17
16
  * function onDialogClose({ reason }: { reason: TDialogCloseReason }) {
18
17
  * legacyOnClose(createCloseEvent({ reason }));
@@ -26,7 +26,15 @@ type TDialogBaseProps = {
26
26
  * - `false`: calls `close()`. When an `animate` preset is provided, the exit
27
27
  * animation plays (via `allow-discrete`) before the dialog becomes logically closed.
28
28
  *
29
- * The element stays mounted in the DOM. Visibility is controlled declaratively.
29
+ * **Lifecycle observable to consumers:**
30
+ *
31
+ * - The `<dialog>` host element is in the DOM only while open or its exit
32
+ * animation is playing. After exit completes the element is unmounted so
33
+ * it does not leave an empty `role="dialog"` element in the accessibility
34
+ * tree. The exact unmount timing is private and may change.
35
+ * - The `id` (supplied or generated) is stable across opens.
36
+ * - The `ref` is populated only while the host element is rendered. Consumers
37
+ * that read from the ref should gate the read on `isOpen` being `true`.
30
38
  */
31
39
  isOpen: boolean;
32
40
  /**
@@ -1,14 +1,29 @@
1
+ type TDialogScrollLockProps = {
2
+ /**
3
+ * Whether the parent dialog is open. The scroll lock is applied while
4
+ * `true` and released the moment this flips to `false`, regardless of
5
+ * when (or whether) React unmounts this component. Pass the same
6
+ * `isOpen` value you pass to the parent `Dialog`.
7
+ */
8
+ isOpen: boolean;
9
+ };
1
10
  /**
2
11
  * __DialogScrollLock__
3
12
  *
4
- * Prevents background page scrolling while mounted. Designed to be rendered
5
- * inside a `Dialog` so that the scroll lock is automatically removed when the
6
- * dialog closes (unmounts its children).
13
+ * Prevents background page scrolling while a dialog is open. Designed to be
14
+ * rendered inside a `Dialog` and given the same `isOpen` value.
7
15
  *
8
16
  * Native `<dialog>.showModal()` makes background content _inert_ (not
9
17
  * focusable/clickable), but does **not** prevent scroll events from reaching
10
18
  * the document body. This component fills that gap by setting
11
- * `overflow: hidden` on `document.body`.
19
+ * `overflow: hidden` on `document.body` while `isOpen` is `true`.
20
+ *
21
+ * The lock is driven by `isOpen` rather than by mount/unmount so that release
22
+ * happens synchronously in the same commit that flips `isOpen` to `false`.
23
+ * Relying on unmount alone was racy: `Dialog` defers the unmount of its
24
+ * children until the host element's close/toggle event fires, which can be
25
+ * after a consumer or test observes the dialog as hidden, leading to a
26
+ * stale `overflow: hidden` window.
12
27
  *
13
28
  * @example
14
29
  * ```tsx
@@ -16,9 +31,10 @@
16
31
  * import { DialogScrollLock } from '@atlaskit/top-layer/dialog-scroll-lock';
17
32
  *
18
33
  * <Dialog isOpen={isOpen} onClose={onClose}>
19
- * <DialogScrollLock />
34
+ * <DialogScrollLock isOpen={isOpen} />
20
35
  * {children}
21
36
  * </Dialog>
22
37
  * ```
23
38
  */
24
- export declare function DialogScrollLock(): null;
39
+ export declare function DialogScrollLock({ isOpen }: TDialogScrollLockProps): null;
40
+ export {};
@@ -1,2 +1,2 @@
1
1
  export { slideAndFade, fade, scaleAndFade, dialogSlideUpAndFade, dialogFade, } from '../animations/presets';
2
- export type { TAnimationPreset, TPopoverAnimationPreset, TDialogAnimationPreset, } from '../animations/types';
2
+ export type { TAnimationPreset } from '../animations/types';
@@ -1,2 +1,2 @@
1
- export { Dialog } from '../dialog';
1
+ export { createCloseEvent, Dialog } from '../dialog';
2
2
  export type { TDialogCloseReason, TDialogProps } from '../dialog';
@@ -1,2 +1,2 @@
1
- export { Popover } from '../popover';
1
+ export { createPopoverCloseEvent, Popover } from '../popover';
2
2
  export type { TPopoverProps, TPopoverCloseReason, TPlacementOptions } from '../popover';
@@ -33,7 +33,14 @@ type TAriaHasPopupForTrigger = Exclude<TAriaHasPopupValue, undefined>;
33
33
  type TAriaForTrigger = {
34
34
  'aria-haspopup': TAriaHasPopupForTrigger;
35
35
  'aria-expanded': boolean;
36
- 'aria-controls': string;
36
+ /**
37
+ * `aria-controls` is `undefined` while the popover is closed, because
38
+ * the popover host element is only rendered in the DOM while open. A
39
+ * dangling `aria-controls` reference (pointing at a missing ID) is
40
+ * tolerated by assistive tech but flagged by some a11y tooling, so
41
+ * we leave it unset until the target exists.
42
+ */
43
+ 'aria-controls': string | undefined;
37
44
  };
38
45
  /**
39
46
  * Returns the ARIA attributes to spread onto a click-activated popover trigger.
@@ -34,7 +34,7 @@ export type TAnchorPoint = {
34
34
  * }
35
35
  * ```
36
36
  */
37
- export declare function useAnchorPositionAtPoint({ popoverRef, placement, getPoint, isEnabled, }: {
37
+ export declare function useAnchorPositionAtPoint({ popoverRef, placement, getPoint, isEnabled, isOpen, }: {
38
38
  /**
39
39
  * Element being positioned. Passed to `useAnchorPosition`.
40
40
  */
@@ -59,4 +59,9 @@ export declare function useAnchorPositionAtPoint({ popoverRef, placement, getPoi
59
59
  * and no positioning is applied. Defaults to `true`.
60
60
  */
61
61
  isEnabled?: boolean;
62
+ /**
63
+ * Whether the popover is currently open. Forwarded to the inner
64
+ * `useAnchorPosition` so it re-runs across host remount cycles.
65
+ */
66
+ isOpen: boolean;
62
67
  }): void;
@@ -34,13 +34,19 @@ import { type TPlacementOptions } from '../internal/resolve-placement';
34
34
  * comparison is used internally so re-runs are skipped when the resolved
35
35
  * placement shape is unchanged.
36
36
  */
37
- export declare function useAnchorPosition({ anchorRef, popoverRef, placement, forceFallbackPositioning, isEnabled, }: {
37
+ export declare function useAnchorPosition({ anchorRef, popoverRef, placement, forceFallbackPositioning, isEnabled, isOpen, }: {
38
38
  /**
39
39
  * Element to position relative to.
40
40
  */
41
41
  anchorRef: RefObject<HTMLElement | null>;
42
42
  /**
43
43
  * Element being positioned (typically a popover).
44
+ *
45
+ * The popover host may be unmounted between opens (the `Popover`
46
+ * primitive unmounts after its exit animation). Pass `isOpen` so the
47
+ * positioning effect re-runs against the freshly mounted element on
48
+ * the next open. Without it, the effect's bound listeners and styles
49
+ * would target the previous (detached) element.
44
50
  */
45
51
  popoverRef: RefObject<HTMLElement | null>;
46
52
  /**
@@ -75,4 +81,11 @@ export declare function useAnchorPosition({ anchorRef, popoverRef, placement, fo
75
81
  * Defaults to `true`.
76
82
  */
77
83
  isEnabled?: boolean;
84
+ /**
85
+ * Whether the popover is currently open. Drives a re-run of the
86
+ * positioning effect when the popover host element is unmounted
87
+ * and remounted across open cycles, so listeners and styles are
88
+ * always wired to the live host element.
89
+ */
90
+ isOpen: boolean;
78
91
  }): void;