@charcuterie/ui 4.28.0 → 4.28.2

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.
@@ -12,7 +12,14 @@ import {
12
12
  useRole,
13
13
  } from "@floating-ui/react"
14
14
  import type { ReactNode, RefObject } from "react"
15
- import { useCallback, useEffect, useState } from "react"
15
+ import {
16
+ useCallback,
17
+ useEffect,
18
+ useLayoutEffect,
19
+ useMemo,
20
+ useRef,
21
+ useState,
22
+ } from "react"
16
23
  import {
17
24
  toOverlayMotionClass,
18
25
  usePresence,
@@ -22,6 +29,7 @@ import {
22
29
  AnchoredOverlayScopeContext,
23
30
  useAnchoredOverlayScope,
24
31
  } from "./AnchoredOverlayScope.ts"
32
+ import { findReturnFocusTarget } from "./focusHistory.ts"
25
33
  import { lockScrollBehind } from "./lockScrollBehind.ts"
26
34
  import { useOverlayStack } from "./OverlayStack.tsx"
27
35
  import { SharedBackdrop } from "./SharedBackdrop.tsx"
@@ -129,6 +137,56 @@ export const OverlayPanel = ({
129
137
  const { isExiting, isMounted, presenceRef } =
130
138
  usePresence(isVisible)
131
139
 
140
+ // Where focus goes when the panel closes: the element that had focus
141
+ // when it opened, or, if that has gone, the most recently focused
142
+ // element that is still there (`findReturnFocusTarget`).
143
+ //
144
+ // The focus manager's own memory is not enough. When a panel stacked
145
+ // on this one closes, this one's manager is enabled again and
146
+ // remembers whatever had focus then, which is a button INSIDE this
147
+ // panel. Unmounted at once, that button was gone and floating-ui fell
148
+ // back further; kept in the page for the exit motion, it is still
149
+ // there, but inert, so focus landed nowhere.
150
+ //
151
+ // Recorded in a layout effect, which never runs on the server, and
152
+ // which runs before the focus manager moves focus inside: it does
153
+ // that in a microtask.
154
+ const openerRef = useRef<HTMLElement | null>(null)
155
+
156
+ const panelElementRef = useRef<HTMLElement | null>(null)
157
+
158
+ useLayoutEffect(() => {
159
+ if (!isVisible) {
160
+ return
161
+ }
162
+
163
+ const focused = document.activeElement
164
+
165
+ openerRef.current =
166
+ focused instanceof HTMLElement ? focused : null
167
+ }, [isVisible])
168
+
169
+ useLayoutEffect(() => {
170
+ if (!isMounted) {
171
+ openerRef.current = null
172
+ }
173
+ }, [isMounted])
174
+
175
+ // The manager reads `returnFocus.current` as the panel closes, so a
176
+ // getter decides then, with the page as it is at that moment, rather
177
+ // than in an earlier render.
178
+ const returnFocus = useMemo(
179
+ () => ({
180
+ get current() {
181
+ return findReturnFocusTarget({
182
+ opener: openerRef.current,
183
+ panel: panelElementRef.current,
184
+ })
185
+ },
186
+ }),
187
+ [],
188
+ )
189
+
132
190
  const isTop =
133
191
  !isExiting && (!stack.isProvided || stack.topId === id)
134
192
  const anchors = useAnchoredOverlayScope()
@@ -221,6 +279,7 @@ export const OverlayPanel = ({
221
279
  const setPanelRef = useMergeRefs([
222
280
  refs.setFloating,
223
281
  presenceRef,
282
+ panelElementRef,
224
283
  ])
225
284
 
226
285
  useEffect(() => {
@@ -307,6 +366,7 @@ export const OverlayPanel = ({
307
366
  // anyway, and two live traps fight over one caret.
308
367
  disabled={!isTop}
309
368
  modal
369
+ returnFocus={returnFocus}
310
370
  >
311
371
  <div
312
372
  {...getFloatingProps()}
@@ -325,6 +385,14 @@ export const OverlayPanel = ({
325
385
  hasMotion &&
326
386
  toOverlayMotionClass(isExiting),
327
387
  )}
388
+ // Both read by `findReturnFocusTarget`: a closing panel
389
+ // does not send focus into another that is leaving, and
390
+ // an `inert` overlay panel, unlike other `inert` content,
391
+ // can still receive it once it is turned back on.
392
+ data-overlay-exiting={
393
+ isExiting ? "" : undefined
394
+ }
395
+ data-overlay-panel=""
328
396
  // The fallback the plan calls for: `inert` on every panel
329
397
  // but the top, so a lower modal is unreachable across the
330
398
  // portal boundary even where `FloatingFocusManager`'s
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The elements the user has focused, newest last, so a closing panel
3
+ * can find somewhere real to send focus when its opener has gone.
4
+ *
5
+ * floating-ui keeps a list like this, but it is private, and a panel
6
+ * that passes its own `returnFocus` target no longer falls back to it.
7
+ *
8
+ * Weak references, so a removed element is not kept alive by the list.
9
+ */
10
+ const LIMIT = 20
11
+
12
+ let history: WeakRef<HTMLElement>[] = []
13
+
14
+ const remember = (event: FocusEvent) => {
15
+ const { target } = event
16
+
17
+ if (
18
+ !(target instanceof HTMLElement) ||
19
+ target === target.ownerDocument.body
20
+ ) {
21
+ return
22
+ }
23
+
24
+ history = [
25
+ ...history.filter((entry) => {
26
+ const element = entry.deref()
27
+
28
+ return element !== undefined && element !== target
29
+ }),
30
+ new WeakRef(target),
31
+ ].slice(-LIMIT)
32
+ }
33
+
34
+ // Installed when the module first loads in a browser, so an element
35
+ // focused before any panel ever opened, such as a menu's trigger, is
36
+ // already in the list. Nothing runs on the server.
37
+ if (typeof document !== "undefined") {
38
+ document.addEventListener("focusin", remember, true)
39
+ }
40
+
41
+ /**
42
+ * Whether focus can land on `element` once `panel` has closed: it is
43
+ * still in the page, enabled, and rendered; it is outside the closing
44
+ * panel and outside any panel that is itself leaving; and it is not
45
+ * inside anything else that is `inert`, such as a menu that is still
46
+ * leaving.
47
+ *
48
+ * An `inert` overlay panel does not rule an element out: a lower panel
49
+ * that the closing one covered is still `inert` at the moment this is
50
+ * read, and is turned back on in the same commit.
51
+ */
52
+ const isReturnable = (
53
+ element: HTMLElement | null | undefined,
54
+ panel: HTMLElement | null,
55
+ ): element is HTMLElement => {
56
+ if (
57
+ element?.isConnected !== true ||
58
+ element === element.ownerDocument.body ||
59
+ (panel?.contains(element) ?? false) ||
60
+ element.closest("[data-overlay-exiting]") !== null ||
61
+ element.matches(":disabled")
62
+ ) {
63
+ return false
64
+ }
65
+
66
+ if (
67
+ typeof element.checkVisibility === "function" &&
68
+ !element.checkVisibility()
69
+ ) {
70
+ return false
71
+ }
72
+
73
+ const inertAncestor = element.closest("[inert]")
74
+
75
+ return (
76
+ inertAncestor === null ||
77
+ inertAncestor.hasAttribute("data-overlay-panel")
78
+ )
79
+ }
80
+
81
+ /**
82
+ * Input types that do not bring up an on-screen keyboard.
83
+ */
84
+ const KEYLESS_INPUT_TYPES = new Set([
85
+ "button",
86
+ "checkbox",
87
+ "color",
88
+ "file",
89
+ "image",
90
+ "radio",
91
+ "range",
92
+ "reset",
93
+ "submit",
94
+ ])
95
+
96
+ /**
97
+ * Whether focusing `element` brings up the keyboard on a phone. The
98
+ * history fallback skips these: the user left that field, and did not
99
+ * ask to type in it again.
100
+ */
101
+ const isTextEntry = (element: HTMLElement): boolean =>
102
+ element instanceof HTMLTextAreaElement ||
103
+ element.isContentEditable ||
104
+ (element instanceof HTMLInputElement &&
105
+ !KEYLESS_INPUT_TYPES.has(element.type))
106
+
107
+ /**
108
+ * Where a closing panel sends focus: the element that opened it if
109
+ * that still can take focus; otherwise, if there was an opener, the
110
+ * most recently focused element that can and is not a text field.
111
+ *
112
+ * A panel that opened while nothing had focus returns nothing, so
113
+ * focus stays where it was, as before. The history is only for an
114
+ * opener that has gone, not for a panel that never had one: sending
115
+ * focus to a field the user left minutes ago would open the keyboard
116
+ * on a phone.
117
+ */
118
+ export const findReturnFocusTarget = ({
119
+ opener,
120
+ panel,
121
+ }: {
122
+ opener: HTMLElement | null
123
+ panel: HTMLElement | null
124
+ }): HTMLElement | null => {
125
+ if (
126
+ opener === null ||
127
+ opener === opener.ownerDocument.body
128
+ ) {
129
+ return null
130
+ }
131
+
132
+ if (isReturnable(opener, panel)) {
133
+ return opener
134
+ }
135
+
136
+ for (
137
+ let index = history.length - 1;
138
+ index >= 0;
139
+ index -= 1
140
+ ) {
141
+ const element = history[index]?.deref()
142
+
143
+ if (
144
+ isReturnable(element, panel) &&
145
+ !isTextEntry(element)
146
+ ) {
147
+ return element
148
+ }
149
+ }
150
+
151
+ return null
152
+ }
@@ -0,0 +1,242 @@
1
+ import type { ReactNode } from "react"
2
+ import { useState } from "react"
3
+
4
+ import { Menu } from "../Menu/Menu.tsx"
5
+ import { Modal } from "../Modal/Modal.tsx"
6
+ import { OverlayStackProvider } from "./OverlayStack.tsx"
7
+
8
+ /**
9
+ * The page shapes `overlayReturnFocus.test.tsx` opens and closes.
10
+ *
11
+ * `.storyHelpers.tsx` rather than `.tsx` because `react/no-multi-comp`
12
+ * is switched off for that suffix, and it is excluded from the
13
+ * package build so none of this ships.
14
+ */
15
+
16
+ export const StackedModals = (): ReactNode => {
17
+ const [isOuterVisible, setIsOuterVisible] =
18
+ useState(false)
19
+
20
+ const [isInnerVisible, setIsInnerVisible] =
21
+ useState(false)
22
+
23
+ return (
24
+ <OverlayStackProvider>
25
+ <button
26
+ onClick={() => {
27
+ setIsOuterVisible(true)
28
+ }}
29
+ type="button"
30
+ >
31
+ Open outer
32
+ </button>
33
+
34
+ <Modal
35
+ aria-label="Outer"
36
+ isVisible={isOuterVisible}
37
+ onClose={() => {
38
+ setIsOuterVisible(false)
39
+ }}
40
+ >
41
+ <button
42
+ onClick={() => {
43
+ setIsInnerVisible(true)
44
+ }}
45
+ type="button"
46
+ >
47
+ Open inner
48
+ </button>
49
+ </Modal>
50
+
51
+ <Modal
52
+ aria-label="Inner"
53
+ isVisible={isInnerVisible}
54
+ onClose={() => {
55
+ setIsInnerVisible(false)
56
+ }}
57
+ >
58
+ <button type="button">Inside inner</button>
59
+ </Modal>
60
+ </OverlayStackProvider>
61
+ )
62
+ }
63
+
64
+ export const MenuThenModal = (): ReactNode => {
65
+ const [isMenuVisible, setIsMenuVisible] = useState(false)
66
+
67
+ const [isModalVisible, setIsModalVisible] =
68
+ useState(false)
69
+
70
+ return (
71
+ <>
72
+ <Menu
73
+ isVisible={isMenuVisible}
74
+ items={[
75
+ {
76
+ key: "rename",
77
+ label: "Rename",
78
+ onSelect: () => {
79
+ setIsModalVisible(true)
80
+ },
81
+ },
82
+ ]}
83
+ onDismiss={() => {
84
+ setIsMenuVisible(false)
85
+ }}
86
+ trigger={
87
+ <button
88
+ onClick={() => {
89
+ setIsMenuVisible((isVisible) => !isVisible)
90
+ }}
91
+ type="button"
92
+ >
93
+ Actions
94
+ </button>
95
+ }
96
+ />
97
+
98
+ <Modal
99
+ aria-label="Rename"
100
+ isVisible={isModalVisible}
101
+ onClose={() => {
102
+ setIsModalVisible(false)
103
+ }}
104
+ >
105
+ <button type="button">Inside rename</button>
106
+ </Modal>
107
+ </>
108
+ )
109
+ }
110
+
111
+ export const SwappedModals = (): ReactNode => {
112
+ const [isFirstVisible, setIsFirstVisible] =
113
+ useState(false)
114
+
115
+ const [isSecondVisible, setIsSecondVisible] =
116
+ useState(false)
117
+
118
+ return (
119
+ <OverlayStackProvider>
120
+ <button
121
+ onClick={() => {
122
+ setIsFirstVisible(true)
123
+ }}
124
+ type="button"
125
+ >
126
+ Open first
127
+ </button>
128
+
129
+ <Modal
130
+ aria-label="First"
131
+ isVisible={isFirstVisible}
132
+ onClose={() => {
133
+ setIsFirstVisible(false)
134
+ }}
135
+ >
136
+ <button
137
+ onClick={() => {
138
+ setIsFirstVisible(false)
139
+
140
+ setIsSecondVisible(true)
141
+ }}
142
+ type="button"
143
+ >
144
+ Next
145
+ </button>
146
+ </Modal>
147
+
148
+ <Modal
149
+ aria-label="Second"
150
+ isVisible={isSecondVisible}
151
+ onClose={() => {
152
+ setIsSecondVisible(false)
153
+ }}
154
+ >
155
+ <button type="button">Inside second</button>
156
+ </Modal>
157
+ </OverlayStackProvider>
158
+ )
159
+ }
160
+
161
+ /**
162
+ * A modal that opens on its own, with nothing focused, as a timeout
163
+ * warning does. A field the user focused earlier sits beside it.
164
+ */
165
+ export const ModalWithoutOpener = (): ReactNode => {
166
+ const [isVisible, setIsVisible] = useState(false)
167
+
168
+ return (
169
+ <>
170
+ <input aria-label="Search" type="search" />
171
+
172
+ <button
173
+ onClick={() => {
174
+ setIsVisible(true)
175
+ }}
176
+ type="button"
177
+ >
178
+ Open from a timer
179
+ </button>
180
+
181
+ <Modal
182
+ aria-label="Timer"
183
+ isVisible={isVisible}
184
+ onClose={() => {
185
+ setIsVisible(false)
186
+ }}
187
+ >
188
+ <button type="button">Inside timer</button>
189
+ </Modal>
190
+ </>
191
+ )
192
+ }
193
+
194
+ /**
195
+ * A row whose Delete button opens a confirm modal, and whose Confirm
196
+ * removes the row, and the button with it. A search field the user
197
+ * typed in earlier sits above.
198
+ */
199
+ export const DeleteRowWithConfirm = (): ReactNode => {
200
+ const [hasRow, setHasRow] = useState(true)
201
+
202
+ const [isConfirmVisible, setIsConfirmVisible] =
203
+ useState(false)
204
+
205
+ return (
206
+ <>
207
+ <input aria-label="Filter" type="search" />
208
+
209
+ <button type="button">Sort</button>
210
+
211
+ {hasRow ? (
212
+ <button
213
+ onClick={() => {
214
+ setIsConfirmVisible(true)
215
+ }}
216
+ type="button"
217
+ >
218
+ Delete row
219
+ </button>
220
+ ) : null}
221
+
222
+ <Modal
223
+ aria-label="Confirm"
224
+ isVisible={isConfirmVisible}
225
+ onClose={() => {
226
+ setIsConfirmVisible(false)
227
+ }}
228
+ >
229
+ <button
230
+ onClick={() => {
231
+ setHasRow(false)
232
+
233
+ setIsConfirmVisible(false)
234
+ }}
235
+ type="button"
236
+ >
237
+ Confirm
238
+ </button>
239
+ </Modal>
240
+ </>
241
+ )
242
+ }