@atlaskit/top-layer 4.4.3 → 4.4.4

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.
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
1
+ import { useCallback, useEffect, useLayoutEffect, useReducer, useRef } from 'react';
2
2
  import { prefersReducedMotion } from './reduced-motion';
3
3
  function runCancellableSettlement({
4
4
  schedule,
@@ -12,6 +12,7 @@ function runCancellableSettlement({
12
12
  onSettled();
13
13
  });
14
14
  return () => {
15
+ // Prevent an interrupted or unmounted lifecycle from firing a stale callback.
15
16
  isCancelled = true;
16
17
  };
17
18
  }
@@ -33,6 +34,14 @@ function runOnAnimationsSettled({
33
34
  }
34
35
  });
35
36
  }
37
+ function isNativeElementOpen({
38
+ element
39
+ }) {
40
+ if (element instanceof HTMLDialogElement) {
41
+ return element.open;
42
+ }
43
+ return element.matches(':popover-open');
44
+ }
36
45
 
37
46
  /**
38
47
  * Visibility lifecycle phase shared between `useAnimatedVisibility`,
@@ -45,11 +54,11 @@ function runOnAnimationsSettled({
45
54
  * animation disabled the lifecycle goes directly `closed → open`.
46
55
  * - `open`: host element is mounted and settled. No transition is
47
56
  * playing.
48
- * - `exiting`: `isOpen` has flipped to `false` but the host element
49
- * is still mounted. Emitted while the CSS exit transition is playing
50
- * (animation enabled) OR while we wait for the browser's
51
- * `toggle`/`close` event to fire on the still-attached element so
52
- * focus restoration can run (animation disabled).
57
+ * - `exiting`: a native close has begun but the host element remains
58
+ * mounted. Usually this follows `isOpen` changing to `false`, but it can
59
+ * also begin with a browser-initiated dismissal while controlled intent
60
+ * is still open. With animation disabled, this phase lasts until the
61
+ * browser's closed `toggle` fires so native focus restoration can finish.
53
62
  *
54
63
  * State machine:
55
64
  * ```
@@ -59,41 +68,111 @@ function runOnAnimationsSettled({
59
68
  * exiting → entering (reopen mid-exit, animated)
60
69
  * exiting → open (reopen mid-handshake, non-animated)
61
70
  * ```
62
- *
63
- * `phase !== 'closed'` is the canonical "host is currently in the DOM
64
- * and on screen" predicate.
65
71
  */
66
72
 
73
+ function getInitialVisibilityState({
74
+ isOpen,
75
+ willAnimate
76
+ }) {
77
+ if (!isOpen) {
78
+ return {
79
+ phase: 'closed',
80
+ controlledIntent: 'closed'
81
+ };
82
+ }
83
+ if (willAnimate) {
84
+ return {
85
+ phase: 'entering',
86
+ controlledIntent: 'open'
87
+ };
88
+ }
89
+ return {
90
+ phase: 'open',
91
+ controlledIntent: 'open'
92
+ };
93
+ }
94
+
67
95
  /**
68
- * Manages the children mount/unmount lifecycle around CSS exit transitions.
69
- *
70
- * Used by both `Popover` and `Dialog` to share the same animation lifecycle
71
- * logic. Those components own their own show/hide mechanisms (showPopover /
72
- * hidePopover vs showModal / close) and event handling - this hook only
73
- * manages the relationship between `isOpen` and when children are rendered.
74
- *
75
- * ## Problem
96
+ * Applies one lifecycle event to the current visibility phase.
76
97
  *
77
- * We want to delay the unmount of children until a CSS exit transition has
78
- * finished playing. If we unmount children the moment `isOpen` becomes
79
- * `false`, the exit animation is never visible - the content just disappears.
98
+ * Events that are stale for the current phase are ignored. This allows
99
+ * animation callbacks and native close events to settle safely after an
100
+ * interrupted lifecycle.
101
+ */
102
+ function getNextVisibilityState(state, action) {
103
+ if (action.type === 'open-requested') {
104
+ const shouldEnter = state.phase === 'closed' || state.phase === 'exiting' && state.controlledIntent === 'closed';
105
+ if (shouldEnter && action.willAnimate) {
106
+ return {
107
+ phase: 'entering',
108
+ controlledIntent: 'open'
109
+ };
110
+ }
111
+ if (shouldEnter) {
112
+ return {
113
+ phase: 'open',
114
+ controlledIntent: 'open'
115
+ };
116
+ }
117
+ return {
118
+ ...state,
119
+ controlledIntent: 'open'
120
+ };
121
+ }
122
+ if (action.type === 'close-requested') {
123
+ return {
124
+ ...state,
125
+ controlledIntent: 'closed'
126
+ };
127
+ }
128
+ if (action.type === 'exit-started') {
129
+ if (state.phase !== 'open' && state.phase !== 'entering') {
130
+ return state;
131
+ }
132
+ return {
133
+ ...state,
134
+ phase: 'exiting'
135
+ };
136
+ }
137
+ if (action.type === 'entry-settled') {
138
+ if (state.phase !== 'entering') {
139
+ return state;
140
+ }
141
+ return {
142
+ ...state,
143
+ phase: 'open'
144
+ };
145
+ }
146
+ if (action.type === 'exit-settled') {
147
+ if (state.phase !== 'exiting') {
148
+ return state;
149
+ }
150
+ return {
151
+ ...state,
152
+ phase: 'closed'
153
+ };
154
+ }
155
+ return state;
156
+ }
157
+
158
+ /**
159
+ * Coordinates controlled intent, native visibility, lifecycle phase, and host
160
+ * mounting around CSS exit transitions. The canonical contract is documented in
161
+ * `notes/architecture/animations.md#canonical-visibility-lifecycle-contract`.
80
162
  *
81
- * ## How it works
163
+ * Used by both `Popover` and `Dialog` to share the same lifecycle logic. Those
164
+ * components own native event binding, show and hide commands, and
165
+ * component-specific event handling. This hook returns stable `onBeforeToggle`
166
+ * and `onToggle` callbacks that advance lifecycle phase and host mounting.
82
167
  *
83
- * The lifecycle is modeled as a `phase` discriminated union (`closed`,
84
- * `entering`, `open`, `exiting`). The host element is rendered while
85
- * `phase !== 'closed'`, so the `exiting` phase keeps the host mounted
86
- * while the CSS exit transition plays (or, with animation disabled,
87
- * while we wait for the browser's closing `toggle` event to fire on the
88
- * still-attached element):
168
+ * The host element is rendered while `phase !== 'closed'`. The `exiting`
169
+ * phase keeps it mounted until its CSS animation settles or, with animation
170
+ * disabled, until the browser reports that the native element has closed.
89
171
  *
90
172
  * ```
91
173
  * isOpen: true ──────────────── false
92
174
  * phase: open ──────────────── exiting ─── (exit settle) ─── closed
93
175
  * ```
94
- *
95
- * Every effect dispatches on the single `phase` value instead of a
96
- * cross-product of booleans.
97
176
  */
98
177
  export function useAnimatedVisibility({
99
178
  isOpen,
@@ -103,160 +182,162 @@ export function useAnimatedVisibility({
103
182
  onExitFinish
104
183
  }) {
105
184
  const willAnimate = shouldAnimate && !prefersReducedMotion();
106
- const isNativeClosedRef = useRef(false);
107
-
108
- // Promote `closed → entering`/`closed → open` synchronously during
109
- // render so the host element mounts in the same commit as the open
110
- // intent. All other transitions are driven by phase-specific effects.
111
- const [phase, setPhase] = useState(() => {
112
- if (!isOpen) {
113
- return 'closed';
114
- }
115
- return willAnimate ? 'entering' : 'open';
116
- });
117
-
118
- // Rearm only after controlled state and the native lifecycle have both
119
- // reached closed. Resetting as soon as `isOpen` becomes false can erase a
120
- // closing toggle that was handled in the same React batch.
121
- if (!isOpen && phase === 'closed') {
122
- isNativeClosedRef.current = false;
123
- }
124
- if (isOpen && phase === 'closed' && !isNativeClosedRef.current) {
125
- setPhase(willAnimate ? 'entering' : 'open');
126
- }
127
- if (!isOpen && (phase === 'open' || phase === 'entering')) {
128
- // Close intent. Move to `exiting` to gate the unmount on either
129
- // the exit transition (animated) or the closing toggle event
130
- // (non-animated). Includes interrupted entry (`entering → exiting`).
131
- setPhase('exiting');
132
- }
133
- if (isOpen && phase === 'exiting' && !isNativeClosedRef.current) {
134
- // Reopen mid-exit. With animation, jump back to `entering` and let
135
- // the entry transition restart from current visual state. Without
136
- // animation, jump straight to `open` (the handshake we were waiting
137
- // for is no longer relevant; the consumer wants the host visible
138
- // again synchronously).
139
- setPhase(willAnimate ? 'entering' : 'open');
140
- }
185
+ const [visibilityState, dispatch] = useReducer(getNextVisibilityState, {
186
+ isOpen,
187
+ willAnimate
188
+ }, getInitialVisibilityState);
189
+ const {
190
+ phase,
191
+ controlledIntent
192
+ } = visibilityState;
141
193
 
142
- // Keep stable refs to the latest callbacks so effects and promise callbacks
194
+ // Keep stable refs to the latest callbacks so effects and animation settlement closures
143
195
  // always call the current callback without needing them in dependency arrays.
144
196
  const onEnterFinishRef = useRef(onEnterFinish);
145
- onEnterFinishRef.current = onEnterFinish;
146
197
  const onExitFinishRef = useRef(onExitFinish);
147
- onExitFinishRef.current = onExitFinish;
198
+ const willAnimateRef = useRef(willAnimate);
199
+ useLayoutEffect(() => {
200
+ onEnterFinishRef.current = onEnterFinish;
201
+ onExitFinishRef.current = onExitFinish;
202
+ willAnimateRef.current = willAnimate;
203
+ }, [onEnterFinish, onExitFinish, willAnimate]);
148
204
 
149
- // Animated entry: wait for all active animations and move to `open`.
205
+ // Synchronize controlled intent during render so opening mounts the host in
206
+ // the same commit. Keeping the processed intent in reducer state prevents a
207
+ // browser-driven exit from being mistaken for a new controlled open request.
208
+ if (isOpen && controlledIntent === 'closed') {
209
+ dispatch({
210
+ type: 'open-requested',
211
+ willAnimate
212
+ });
213
+ }
214
+ if (!isOpen && controlledIntent === 'open') {
215
+ dispatch({
216
+ type: 'close-requested'
217
+ });
218
+ }
219
+
220
+ // Entry can commit `open` before its callback because the host stays mounted.
221
+ // This ensures consumers observe the settled DOM rather than entering styles.
222
+ // Treat the phase before the initial commit as closed so an initially open host
223
+ // notifies consumers.
224
+ const prevPhaseRef = useRef('closed');
150
225
  useEffect(() => {
151
- if (phase !== 'entering') {
226
+ const prevPhase = prevPhaseRef.current;
227
+ prevPhaseRef.current = phase;
228
+ if (prevPhase === phase) {
152
229
  return;
153
230
  }
154
- const element = elementRef.current;
155
- if (!element) {
156
- return;
231
+ if (phase === 'open') {
232
+ var _onEnterFinishRef$cur;
233
+ (_onEnterFinishRef$cur = onEnterFinishRef.current) === null || _onEnterFinishRef$cur === void 0 ? void 0 : _onEnterFinishRef$cur.call(onEnterFinishRef);
157
234
  }
158
- return runOnAnimationsSettled({
159
- element,
160
- onSettled: () => {
161
- var _onEnterFinishRef$cur;
162
- // Fire the consumer callback before transitioning phase so any
163
- // state the consumer reads (refs, DOM nodes) is still attached
164
- // in the same synchronous tick, regardless of React batching
165
- // semantics.
166
- (_onEnterFinishRef$cur = onEnterFinishRef.current) === null || _onEnterFinishRef$cur === void 0 ? void 0 : _onEnterFinishRef$cur.call(onEnterFinishRef);
167
- setPhase(current => current === 'entering' ? 'open' : current);
168
- }
169
- });
170
- }, [phase, elementRef]);
235
+ }, [phase]);
236
+ const isMounted = phase !== 'closed';
237
+ const cancelExitSettlementRef = useRef(() => {});
171
238
 
172
- // Non-animated entry callback. The lifecycle goes `closed → open`
173
- // directly with no `entering` phase; fire `onEnterFinish` on that jump.
174
- // A previous-phase ref avoids double-firing on the animated path.
175
- const prevPhaseForEntryRef = useRef('closed');
176
- useEffect(() => {
177
- const prevPhase = prevPhaseForEntryRef.current;
178
- prevPhaseForEntryRef.current = phase;
239
+ // Exit must notify consumers before `closed` unmounts the host.
240
+ const settleExit = useCallback(() => {
241
+ var _onExitFinishRef$curr;
242
+ (_onExitFinishRef$curr = onExitFinishRef.current) === null || _onExitFinishRef$curr === void 0 ? void 0 : _onExitFinishRef$curr.call(onExitFinishRef);
243
+ dispatch({
244
+ type: 'exit-settled'
245
+ });
246
+ }, []);
179
247
 
180
- // Animated entry settle goes through `entering` and already fired
181
- // onEnterFinish above; only handle the non-animated direct jumps.
182
- if (prevPhase !== 'open' && phase === 'open' && prevPhase !== 'entering') {
183
- var _onEnterFinishRef$cur2;
184
- (_onEnterFinishRef$cur2 = onEnterFinishRef.current) === null || _onEnterFinishRef$cur2 === void 0 ? void 0 : _onEnterFinishRef$cur2.call(onEnterFinishRef);
248
+ // Primitives bind these stable callbacks to their native lifecycle events.
249
+ // This keeps event ownership at the primitive while the hook owns state transitions.
250
+ const onBeforeToggle = useCallback(event => {
251
+ // Any native transition supersedes a previous exit snapshot. This prevents
252
+ // a stale settlement from closing a host that is reopening or closing again.
253
+ cancelExitSettlementRef.current();
254
+ // Snapshot currentTarget because the DOM clears it after event dispatch.
255
+ const element = event.currentTarget;
256
+ if (element instanceof HTMLElement) {
257
+ if (event.newState === 'open') {
258
+ element.removeAttribute('inert');
259
+ element.removeAttribute('aria-hidden');
260
+ } else {
261
+ // We use a microtask to let native focus restoration happen before making the element inert.
262
+ // The browser restores focus after beforetoggle returns, during its close steps.
263
+ queueMicrotask(() => {
264
+ // A controlled close can be interrupted by isOpen changing back to true,
265
+ // which reopens the element before this microtask runs.
266
+ if (isNativeElementOpen({
267
+ element
268
+ })) {
269
+ return;
270
+ }
271
+ element.setAttribute('inert', '');
272
+ // Tooling does not consistently treat inert content as hidden, even though the browser does.
273
+ element.setAttribute('aria-hidden', 'true');
274
+ });
275
+ }
185
276
  }
186
- }, [phase]);
187
-
188
- // Animated exit: wait for all active animations, fire `onExitFinish`,
189
- // then move to `closed` to unmount the host.
190
- useEffect(() => {
191
- if (phase !== 'exiting' || !willAnimate) {
277
+ if (event.newState === 'closed') {
278
+ dispatch({
279
+ type: 'exit-started'
280
+ });
281
+ }
282
+ }, []);
283
+ const onToggle = useCallback(event => {
284
+ if (event.newState !== 'closed') {
285
+ return;
286
+ }
287
+ if (!willAnimateRef.current) {
288
+ cancelExitSettlementRef.current = runCancellableSettlement({
289
+ schedule: queueMicrotask,
290
+ onSettled: settleExit
291
+ });
192
292
  return;
193
293
  }
194
294
  const element = elementRef.current;
195
295
  if (!element) {
196
296
  return;
197
297
  }
198
- return runOnAnimationsSettled({
298
+
299
+ // The closed `toggle` is task-queued after synchronous `beforetoggle`.
300
+ // Snapshot here so the exiting phase styles have committed and the list
301
+ // represents the animations that actually govern exit settlement.
302
+ cancelExitSettlementRef.current = runOnAnimationsSettled({
199
303
  element,
200
- onSettled: () => {
201
- var _onExitFinishRef$curr;
202
- // Fire the consumer callback before transitioning phase to
203
- // `closed`. The phase change drives the host element unmount,
204
- // and consumers expect to be able to read the element (or a
205
- // forwarded ref to it) inside `onExitFinish`. Doing this in
206
- // the safe order avoids relying on React's automatic batching
207
- // to keep the element attached across the callback.
208
- (_onExitFinishRef$curr = onExitFinishRef.current) === null || _onExitFinishRef$curr === void 0 ? void 0 : _onExitFinishRef$curr.call(onExitFinishRef);
209
- setPhase(current => current === 'exiting' ? 'closed' : current);
210
- }
304
+ onSettled: settleExit
211
305
  });
212
- }, [phase, willAnimate, elementRef]);
306
+ }, [elementRef, settleExit]);
307
+ useLayoutEffect(() => () => {
308
+ // Prevent a pending animation or microtask from notifying after unmount.
309
+ cancelExitSettlementRef.current();
310
+ }, []);
213
311
 
214
- // Native dismissal is authoritative. Its toggle can arrive while controlled
215
- // state still says open, so remember that native state and do not
216
- // reopen until `isOpen` has first moved to false.
217
- useLayoutEffect(() => {
218
- if (phase === 'exiting' && !willAnimate && isNativeClosedRef.current) {
219
- setPhase('closed');
312
+ // Entry settlement only removes entering styles. Its callback runs after the
313
+ // resulting `open` commit in the effect above.
314
+ useEffect(function settleEntry() {
315
+ if (phase !== 'entering') {
316
+ return;
220
317
  }
221
- }, [phase, willAnimate]);
222
- const onToggle = useCallback(event => {
223
- if (event.newState === 'open') {
224
- isNativeClosedRef.current = false;
318
+ if (!willAnimate) {
319
+ dispatch({
320
+ type: 'entry-settled'
321
+ });
225
322
  return;
226
323
  }
227
- if (event.newState !== 'closed') {
324
+ const element = elementRef.current;
325
+ if (!element) {
228
326
  return;
229
327
  }
230
- isNativeClosedRef.current = true;
231
- setPhase(current => {
232
- if (current === 'open' || current === 'entering') {
233
- return 'exiting';
234
- }
235
- if (current === 'exiting' && !willAnimate) {
236
- return 'closed';
328
+ return runOnAnimationsSettled({
329
+ element,
330
+ onSettled() {
331
+ dispatch({
332
+ type: 'entry-settled'
333
+ });
237
334
  }
238
- return current;
239
335
  });
240
- }, [willAnimate]);
241
-
242
- // Non-animated exit callback. There are no animations to wait for, so fire
243
- // `onExitFinish` on the transition into `exiting` (the unmount itself
244
- // is gated by the closing toggle handshake above).
245
- const prevPhaseForExitRef = useRef('closed');
246
- useEffect(() => {
247
- const prevPhase = prevPhaseForExitRef.current;
248
- prevPhaseForExitRef.current = phase;
249
-
250
- // Only fire on the non-animated transition into `exiting`. The
251
- // animated path's `exiting → closed` settle already fires
252
- // `onExitFinish` from `runOnAnimationsSettled`.
253
- if (prevPhase !== 'exiting' && phase === 'exiting' && !willAnimate) {
254
- var _onExitFinishRef$curr2;
255
- (_onExitFinishRef$curr2 = onExitFinishRef.current) === null || _onExitFinishRef$curr2 === void 0 ? void 0 : _onExitFinishRef$curr2.call(onExitFinishRef);
256
- }
257
- }, [phase, willAnimate]);
336
+ }, [phase, willAnimate, elementRef]);
258
337
  return {
259
338
  phase,
339
+ isMounted,
340
+ onBeforeToggle,
260
341
  onToggle
261
342
  };
262
343
  }