@radix-ui/react-focus-scope 1.1.12 → 1.1.13-rc.1784074599772

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.
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
10
  var __export = (target, all) => {
10
11
  for (var name in all)
11
12
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -45,124 +46,129 @@ var import_jsx_runtime = require("react/jsx-runtime");
45
46
  var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount";
46
47
  var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount";
47
48
  var EVENT_OPTIONS = { bubbles: false, cancelable: true };
48
- var FOCUS_SCOPE_NAME = "FocusScope";
49
- var FocusScope = React.forwardRef((props, forwardedRef) => {
50
- const {
51
- loop = false,
52
- trapped = false,
53
- onMountAutoFocus: onMountAutoFocusProp,
54
- onUnmountAutoFocus: onUnmountAutoFocusProp,
55
- ...scopeProps
56
- } = props;
57
- const [container, setContainer] = React.useState(null);
58
- const onMountAutoFocus = (0, import_react_use_callback_ref.useCallbackRef)(onMountAutoFocusProp);
59
- const onUnmountAutoFocus = (0, import_react_use_callback_ref.useCallbackRef)(onUnmountAutoFocusProp);
60
- const lastFocusedElementRef = React.useRef(null);
61
- const composedRefs = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, setContainer);
62
- const focusScope = React.useRef({
63
- paused: false,
64
- pause() {
65
- this.paused = true;
66
- },
67
- resume() {
68
- this.paused = false;
69
- }
70
- }).current;
71
- React.useEffect(() => {
72
- if (trapped) {
73
- let handleFocusIn2 = function(event) {
74
- if (focusScope.paused || !container) return;
75
- const target = event.target;
76
- if (container.contains(target)) {
77
- lastFocusedElementRef.current = target;
78
- } else {
79
- focus(lastFocusedElementRef.current, { select: true });
80
- }
81
- }, handleFocusOut2 = function(event) {
82
- if (focusScope.paused || !container) return;
83
- const relatedTarget = event.relatedTarget;
84
- if (relatedTarget === null) return;
85
- if (!container.contains(relatedTarget)) {
86
- focus(lastFocusedElementRef.current, { select: true });
87
- }
88
- }, handleMutations2 = function(mutations) {
89
- const focusedElement = document.activeElement;
90
- if (focusedElement !== document.body) return;
91
- for (const mutation of mutations) {
92
- if (mutation.removedNodes.length > 0) focus(container);
93
- }
94
- };
95
- var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
96
- document.addEventListener("focusin", handleFocusIn2);
97
- document.addEventListener("focusout", handleFocusOut2);
98
- const mutationObserver = new MutationObserver(handleMutations2);
99
- if (container) mutationObserver.observe(container, { childList: true, subtree: true });
100
- return () => {
101
- document.removeEventListener("focusin", handleFocusIn2);
102
- document.removeEventListener("focusout", handleFocusOut2);
103
- mutationObserver.disconnect();
104
- };
105
- }
106
- }, [trapped, container, focusScope.paused]);
107
- React.useEffect(() => {
108
- if (container) {
109
- focusScopesStack.add(focusScope);
110
- const previouslyFocusedElement = document.activeElement;
111
- const hasFocusedCandidate = container.contains(previouslyFocusedElement);
112
- if (!hasFocusedCandidate) {
113
- const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
114
- container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
115
- container.dispatchEvent(mountEvent);
116
- if (!mountEvent.defaultPrevented) {
117
- focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
118
- if (document.activeElement === previouslyFocusedElement) {
119
- focus(container);
120
- }
121
- }
49
+ var FocusScope = /* @__PURE__ */ React.forwardRef(
50
+ // ignore prettier to reduce diff noise
51
+ // prettier-ignore
52
+ /* @__PURE__ */ __name(function FocusScope2(props, forwardedRef) {
53
+ const {
54
+ loop = false,
55
+ trapped = false,
56
+ onMountAutoFocus: onMountAutoFocusProp,
57
+ onUnmountAutoFocus: onUnmountAutoFocusProp,
58
+ ...scopeProps
59
+ } = props;
60
+ const [container, setContainer] = React.useState(null);
61
+ const onMountAutoFocus = (0, import_react_use_callback_ref.useCallbackRef)(onMountAutoFocusProp);
62
+ const onUnmountAutoFocus = (0, import_react_use_callback_ref.useCallbackRef)(onUnmountAutoFocusProp);
63
+ const lastFocusedElementRef = React.useRef(null);
64
+ const composedRefs = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, setContainer);
65
+ const focusScope = React.useRef({
66
+ paused: false,
67
+ pause() {
68
+ this.paused = true;
69
+ },
70
+ resume() {
71
+ this.paused = false;
122
72
  }
123
- return () => {
124
- container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
125
- setTimeout(() => {
126
- const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
127
- container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
128
- container.dispatchEvent(unmountEvent);
129
- if (!unmountEvent.defaultPrevented) {
130
- focus(previouslyFocusedElement ?? document.body, { select: true });
73
+ }).current;
74
+ React.useEffect(() => {
75
+ if (trapped) {
76
+ let handleFocusIn2 = function(event) {
77
+ if (focusScope.paused || !container) return;
78
+ const target = event.target;
79
+ if (container.contains(target)) {
80
+ lastFocusedElementRef.current = target;
81
+ } else {
82
+ focus(lastFocusedElementRef.current, { select: true });
131
83
  }
132
- container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
133
- focusScopesStack.remove(focusScope);
134
- }, 0);
135
- };
136
- }
137
- }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
138
- const handleKeyDown = React.useCallback(
139
- (event) => {
140
- if (!loop && !trapped) return;
141
- if (focusScope.paused) return;
142
- const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
143
- const focusedElement = document.activeElement;
144
- if (isTabKey && focusedElement) {
145
- const container2 = event.currentTarget;
146
- const [first, last] = getTabbableEdges(container2);
147
- const hasTabbableElementsInside = first && last;
148
- if (!hasTabbableElementsInside) {
149
- if (focusedElement === container2) event.preventDefault();
150
- } else {
151
- if (!event.shiftKey && focusedElement === last) {
152
- event.preventDefault();
153
- if (loop) focus(first, { select: true });
154
- } else if (event.shiftKey && focusedElement === first) {
155
- event.preventDefault();
156
- if (loop) focus(last, { select: true });
84
+ }, handleFocusOut2 = function(event) {
85
+ if (focusScope.paused || !container) return;
86
+ const relatedTarget = event.relatedTarget;
87
+ if (relatedTarget === null) return;
88
+ if (!container.contains(relatedTarget)) {
89
+ focus(lastFocusedElementRef.current, { select: true });
90
+ }
91
+ }, handleMutations2 = function(mutations) {
92
+ const focusedElement = document.activeElement;
93
+ if (focusedElement !== document.body) return;
94
+ for (const mutation of mutations) {
95
+ if (mutation.removedNodes.length > 0) focus(container);
96
+ }
97
+ };
98
+ var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
99
+ __name(handleFocusIn2, "handleFocusIn");
100
+ __name(handleFocusOut2, "handleFocusOut");
101
+ __name(handleMutations2, "handleMutations");
102
+ document.addEventListener("focusin", handleFocusIn2);
103
+ document.addEventListener("focusout", handleFocusOut2);
104
+ const mutationObserver = new MutationObserver(handleMutations2);
105
+ if (container) mutationObserver.observe(container, { childList: true, subtree: true });
106
+ return () => {
107
+ document.removeEventListener("focusin", handleFocusIn2);
108
+ document.removeEventListener("focusout", handleFocusOut2);
109
+ mutationObserver.disconnect();
110
+ };
111
+ }
112
+ }, [trapped, container, focusScope.paused]);
113
+ React.useEffect(() => {
114
+ if (container) {
115
+ focusScopesStack.add(focusScope);
116
+ const previouslyFocusedElement = document.activeElement;
117
+ const hasFocusedCandidate = container.contains(previouslyFocusedElement);
118
+ if (!hasFocusedCandidate) {
119
+ const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
120
+ container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
121
+ container.dispatchEvent(mountEvent);
122
+ if (!mountEvent.defaultPrevented) {
123
+ focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
124
+ if (document.activeElement === previouslyFocusedElement) {
125
+ focus(container);
126
+ }
157
127
  }
158
128
  }
129
+ return () => {
130
+ container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
131
+ setTimeout(() => {
132
+ const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
133
+ container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
134
+ container.dispatchEvent(unmountEvent);
135
+ if (!unmountEvent.defaultPrevented) {
136
+ focus(previouslyFocusedElement ?? document.body, { select: true });
137
+ }
138
+ container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
139
+ focusScopesStack.remove(focusScope);
140
+ }, 0);
141
+ };
159
142
  }
160
- },
161
- [loop, trapped, focusScope.paused]
162
- );
163
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_primitive.Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
164
- });
165
- FocusScope.displayName = FOCUS_SCOPE_NAME;
143
+ }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
144
+ const handleKeyDown = React.useCallback(
145
+ (event) => {
146
+ if (!loop && !trapped) return;
147
+ if (focusScope.paused) return;
148
+ const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
149
+ const focusedElement = document.activeElement;
150
+ if (isTabKey && focusedElement) {
151
+ const container2 = event.currentTarget;
152
+ const [first, last] = getTabbableEdges(container2);
153
+ const hasTabbableElementsInside = first && last;
154
+ if (!hasTabbableElementsInside) {
155
+ if (focusedElement === container2) event.preventDefault();
156
+ } else {
157
+ if (!event.shiftKey && focusedElement === last) {
158
+ event.preventDefault();
159
+ if (loop) focus(first, { select: true });
160
+ } else if (event.shiftKey && focusedElement === first) {
161
+ event.preventDefault();
162
+ if (loop) focus(last, { select: true });
163
+ }
164
+ }
165
+ }
166
+ },
167
+ [loop, trapped, focusScope.paused]
168
+ );
169
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_primitive.Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
170
+ }, "FocusScope")
171
+ );
166
172
  function focusFirst(candidates, { select = false } = {}) {
167
173
  const previouslyFocusedElement = document.activeElement;
168
174
  for (const candidate of candidates) {
@@ -170,24 +176,27 @@ function focusFirst(candidates, { select = false } = {}) {
170
176
  if (document.activeElement !== previouslyFocusedElement) return;
171
177
  }
172
178
  }
179
+ __name(focusFirst, "focusFirst");
173
180
  function getTabbableEdges(container) {
174
181
  const candidates = getTabbableCandidates(container);
175
182
  const first = findVisible(candidates, container);
176
183
  const last = findVisible(candidates.reverse(), container);
177
184
  return [first, last];
178
185
  }
186
+ __name(getTabbableEdges, "getTabbableEdges");
179
187
  function getTabbableCandidates(container) {
180
188
  const nodes = [];
181
189
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
182
- acceptNode: (node) => {
190
+ acceptNode: /* @__PURE__ */ __name((node) => {
183
191
  const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
184
192
  if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
185
193
  return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
186
- }
194
+ }, "acceptNode")
187
195
  });
188
196
  while (walker.nextNode()) nodes.push(walker.currentNode);
189
197
  return nodes;
190
198
  }
199
+ __name(getTabbableCandidates, "getTabbableCandidates");
191
200
  function findVisible(elements, container) {
192
201
  const canUseCheckVisibility = typeof container.checkVisibility === "function" && container.checkVisibility({ checkVisibilityCSS: true });
193
202
  for (const element of elements) {
@@ -197,6 +206,7 @@ function findVisible(elements, container) {
197
206
  }
198
207
  }
199
208
  }
209
+ __name(findVisible, "findVisible");
200
210
  function isHidden(node, { upTo }) {
201
211
  if (getComputedStyle(node).visibility === "hidden") return true;
202
212
  while (node) {
@@ -206,9 +216,11 @@ function isHidden(node, { upTo }) {
206
216
  }
207
217
  return false;
208
218
  }
219
+ __name(isHidden, "isHidden");
209
220
  function isSelectableInput(element) {
210
221
  return element instanceof HTMLInputElement && "select" in element;
211
222
  }
223
+ __name(isSelectableInput, "isSelectableInput");
212
224
  function focus(element, { select = false } = {}) {
213
225
  if (element && element.focus) {
214
226
  const previouslyFocusedElement = document.activeElement;
@@ -217,6 +229,7 @@ function focus(element, { select = false } = {}) {
217
229
  element.select();
218
230
  }
219
231
  }
232
+ __name(focus, "focus");
220
233
  var focusScopesStack = createFocusScopesStack();
221
234
  function createFocusScopesStack() {
222
235
  let stack = [];
@@ -235,6 +248,7 @@ function createFocusScopesStack() {
235
248
  }
236
249
  };
237
250
  }
251
+ __name(createFocusScopesStack, "createFocusScopesStack");
238
252
  function arrayRemove(array, item) {
239
253
  const updatedArray = [...array];
240
254
  const index = updatedArray.indexOf(item);
@@ -243,8 +257,10 @@ function arrayRemove(array, item) {
243
257
  }
244
258
  return updatedArray;
245
259
  }
260
+ __name(arrayRemove, "arrayRemove");
246
261
  function removeLinks(items) {
247
262
  return items.filter((item) => item.tagName !== "A");
248
263
  }
264
+ __name(removeLinks, "removeLinks");
249
265
  var Root = FocusScope;
250
266
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/focus-scope.tsx"],
4
- "sourcesContent": ["'use client';\nexport {\n FocusScope,\n //\n Root,\n} from './focus-scope';\nexport type { FocusScopeProps } from './focus-scope';\n", "import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\nconst FOCUS_SCOPE_NAME = 'FocusScope';\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n /**\n * When `true`, tabbing from last item will focus first tabbable\n * and shift+tab from first item will focus last tababble.\n * @defaultValue false\n */\n loop?: boolean;\n\n /**\n * When `true`, focus cannot escape the focus scope via keyboard,\n * pointer, or a programmatic focus.\n * @defaultValue false\n */\n trapped?: boolean;\n\n /**\n * Event handler called when auto-focusing on mount.\n * Can be prevented.\n */\n onMountAutoFocus?: (event: Event) => void;\n\n /**\n * Event handler called when auto-focusing on unmount.\n * Can be prevented.\n */\n onUnmountAutoFocus?: (event: Event) => void;\n}\n\nconst FocusScope = React.forwardRef<FocusScopeElement, FocusScopeProps>((props, forwardedRef) => {\n const {\n loop = false,\n trapped = false,\n onMountAutoFocus: onMountAutoFocusProp,\n onUnmountAutoFocus: onUnmountAutoFocusProp,\n ...scopeProps\n } = props;\n const [container, setContainer] = React.useState<HTMLElement | null>(null);\n const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, setContainer);\n\n const focusScope = React.useRef({\n paused: false,\n pause() {\n this.paused = true;\n },\n resume() {\n this.paused = false;\n },\n }).current;\n\n // Takes care of trapping focus if focus is moved outside programmatically for example\n React.useEffect(() => {\n if (trapped) {\n function handleFocusIn(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const target = event.target as HTMLElement | null;\n if (container.contains(target)) {\n lastFocusedElementRef.current = target;\n } else {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n function handleFocusOut(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n //\n // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n // 2. In Google Chrome, when the focused element is removed from the DOM.\n //\n // We let the browser do its thing here because:\n //\n // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n // throws the CPU to 100%, so we avoid doing anything for this reason here too.\n if (relatedTarget === null) return;\n\n // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n // that is outside the container, we move focus to the last valid focused element inside.\n if (!container.contains(relatedTarget)) {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n // When the focused element gets removed from the DOM, browsers move focus\n // back to the document.body. In this case, we move focus to the container\n // to keep focus trapped correctly.\n function handleMutations(mutations: MutationRecord[]) {\n const focusedElement = document.activeElement as HTMLElement | null;\n if (focusedElement !== document.body) return;\n for (const mutation of mutations) {\n if (mutation.removedNodes.length > 0) focus(container);\n }\n }\n\n document.addEventListener('focusin', handleFocusIn);\n document.addEventListener('focusout', handleFocusOut);\n const mutationObserver = new MutationObserver(handleMutations);\n if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n return () => {\n document.removeEventListener('focusin', handleFocusIn);\n document.removeEventListener('focusout', handleFocusOut);\n mutationObserver.disconnect();\n };\n }\n }, [trapped, container, focusScope.paused]);\n\n React.useEffect(() => {\n if (container) {\n focusScopesStack.add(focusScope);\n const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n if (!hasFocusedCandidate) {\n const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n container.dispatchEvent(mountEvent);\n if (!mountEvent.defaultPrevented) {\n focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n if (document.activeElement === previouslyFocusedElement) {\n focus(container);\n }\n }\n }\n\n return () => {\n container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n\n // We hit a react bug (fixed in v17) with focusing in unmount.\n // We need to delay the focus a little to get around it for now.\n // See: https://github.com/facebook/react/issues/17894\n setTimeout(() => {\n const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n container.dispatchEvent(unmountEvent);\n if (!unmountEvent.defaultPrevented) {\n focus(previouslyFocusedElement ?? document.body, { select: true });\n }\n // we need to remove the listener after we `dispatchEvent`\n container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n focusScopesStack.remove(focusScope);\n }, 0);\n };\n }\n }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n // Takes care of looping focus (when tabbing whilst at the edges)\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (!loop && !trapped) return;\n if (focusScope.paused) return;\n\n const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n const focusedElement = document.activeElement as HTMLElement | null;\n\n if (isTabKey && focusedElement) {\n const container = event.currentTarget as HTMLElement;\n const [first, last] = getTabbableEdges(container);\n const hasTabbableElementsInside = first && last;\n\n // we can only wrap focus if we have tabbable edges\n if (!hasTabbableElementsInside) {\n if (focusedElement === container) event.preventDefault();\n } else {\n if (!event.shiftKey && focusedElement === last) {\n event.preventDefault();\n if (loop) focus(first, { select: true });\n } else if (event.shiftKey && focusedElement === first) {\n event.preventDefault();\n if (loop) focus(last, { select: true });\n }\n }\n }\n },\n [loop, trapped, focusScope.paused],\n );\n\n return (\n <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n );\n});\n\nFocusScope.displayName = FOCUS_SCOPE_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n const previouslyFocusedElement = document.activeElement;\n for (const candidate of candidates) {\n focus(candidate, { select });\n if (document.activeElement !== previouslyFocusedElement) return;\n }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n const candidates = getTabbableCandidates(container);\n const first = findVisible(candidates, container);\n const last = findVisible(candidates.reverse(), container);\n return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n const nodes: HTMLElement[] = [];\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: any) => {\n const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';\n if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n // runtime's understanding of tabbability, so this automatically accounts\n // for any kind of element that could be tabbed to.\n return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n },\n });\n while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);\n // we do not take into account the order of nodes with positive `tabIndex` as it\n // hinders accessibility to have tab order different from visual order.\n return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n // `checkVisibility` performs a single native check for `visibility: hidden`\n // and `display: none` across the ancestor chain. This avoids the repeated\n // `getComputedStyle` calls per ancestor that the fallback path requires,\n // which reduces the cost of style resolution triggered by earlier DOM writes\n // (e.g. react-remove-scroll, DismissableLayer setting body styles).\n const canUseCheckVisibility =\n typeof container.checkVisibility === 'function' &&\n container.checkVisibility({ checkVisibilityCSS: true });\n\n for (const element of elements) {\n const hidden = canUseCheckVisibility\n ? !element.checkVisibility({ checkVisibilityCSS: true })\n : isHidden(element, { upTo: container });\n // we stop checking if it's hidden at the `container` level (excluding)\n if (!hidden) {\n return element;\n }\n }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n if (getComputedStyle(node).visibility === 'hidden') return true;\n while (node) {\n // we stop at `upTo` (excluding it)\n if (upTo !== undefined && node === upTo) return false;\n if (getComputedStyle(node).display === 'none') return true;\n node = node.parentElement as HTMLElement;\n }\n return false;\n}\n\nfunction isSelectableInput(element: any): element is FocusableTarget & { select: () => void } {\n return element instanceof HTMLInputElement && 'select' in element;\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n // only focus if that element is focusable\n if (element && element.focus) {\n const previouslyFocusedElement = document.activeElement;\n // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n element.focus({ preventScroll: true });\n // only select if its not the same element, it supports selection and we need to select\n if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n element.select();\n }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n /** A stack of focus scopes, with the active one at the top */\n let stack: FocusScopeAPI[] = [];\n\n return {\n add(focusScope: FocusScopeAPI) {\n // pause the currently active focus scope (at the top of the stack)\n const activeFocusScope = stack[0];\n if (focusScope !== activeFocusScope) {\n activeFocusScope?.pause();\n }\n // remove in case it already exists (because we'll re-add it at the top of the stack)\n stack = arrayRemove(stack, focusScope);\n stack.unshift(focusScope);\n },\n\n remove(focusScope: FocusScopeAPI) {\n stack = arrayRemove(stack, focusScope);\n stack[0]?.resume();\n },\n };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n const updatedArray = [...array];\n const index = updatedArray.indexOf(item);\n if (index !== -1) {\n updatedArray.splice(index, 1);\n }\n return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n return items.filter((item) => item.tagName !== 'A');\n}\n\nconst Root = FocusScope;\n\nexport {\n FocusScope,\n //\n Root,\n};\nexport type { FocusScopeProps };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,YAAuB;AACvB,gCAAgC;AAChC,6BAA0B;AAC1B,oCAA+B;AAwM3B;AAtMJ,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB,EAAE,SAAS,OAAO,YAAY,KAAK;AAQzD,IAAM,mBAAmB;AAgCzB,IAAM,aAAmB,iBAA+C,CAAC,OAAO,iBAAiB;AAC/F,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,UAAU;AAAA,IACV,kBAAkB;AAAA,IAClB,oBAAoB;AAAA,IACpB,GAAG;AAAA,EACL,IAAI;AACJ,QAAM,CAAC,WAAW,YAAY,IAAU,eAA6B,IAAI;AACzE,QAAM,uBAAmB,8CAAe,oBAAoB;AAC5D,QAAM,yBAAqB,8CAAe,sBAAsB;AAChE,QAAM,wBAA8B,aAA2B,IAAI;AACnE,QAAM,mBAAe,2CAAgB,cAAc,YAAY;AAE/D,QAAM,aAAmB,aAAO;AAAA,IAC9B,QAAQ;AAAA,IACR,QAAQ;AACN,WAAK,SAAS;AAAA,IAChB;AA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AAU;AACrC,YAAM,QAAQ,UAAU;AAAA,IAC1B;AAAA,IAEA,OAAO,YAA2B;AAChC,cAAQ,YAAY,OAAO,UAAU;AACrC,YAAM,CAAC,GAAG,OAAO;AAAA,IACnB;AAAA,EACF;AACF;AAEA,SAAS,YAAe,OAAY,MAAS;AAC3C,QAAM,eAAe,CAAC,GAAG,KAAK;AAC9B,QAAM,QAAQ,aAAa,QAAQ,IAAI;AACvC,MAAI,UAAU,IAAI;AAChB,iBAAa,OAAO,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAsB;AACzC,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,YAAY,GAAG;AACpD;AAEA,IAAM,OAAO;",
6
- "names": ["handleFocusIn", "handleFocusOut", "handleMutations", "container"]
4
+ "sourcesContent": ["'use client';\nexport {\n FocusScope,\n //\n Root,\n} from './focus-scope';\nexport type { FocusScopeProps } from './focus-scope';\n", "import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n /**\n * When `true`, tabbing from last item will focus first tabbable\n * and shift+tab from first item will focus last tababble.\n * @defaultValue false\n */\n loop?: boolean;\n\n /**\n * When `true`, focus cannot escape the focus scope via keyboard,\n * pointer, or a programmatic focus.\n * @defaultValue false\n */\n trapped?: boolean;\n\n /**\n * Event handler called when auto-focusing on mount.\n * Can be prevented.\n */\n onMountAutoFocus?: (event: Event) => void;\n\n /**\n * Event handler called when auto-focusing on unmount.\n * Can be prevented.\n */\n onUnmountAutoFocus?: (event: Event) => void;\n}\n\nconst FocusScope = /* @__PURE__ */ React.forwardRef<FocusScopeElement, FocusScopeProps>(\n // ignore prettier to reduce diff noise\n // prettier-ignore\n function FocusScope(props, forwardedRef) {\n const {\n loop = false,\n trapped = false,\n onMountAutoFocus: onMountAutoFocusProp,\n onUnmountAutoFocus: onUnmountAutoFocusProp,\n ...scopeProps\n } = props;\n const [container, setContainer] = React.useState<HTMLElement | null>(null);\n const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, setContainer);\n\n const focusScope = React.useRef({\n paused: false,\n pause() {\n this.paused = true;\n },\n resume() {\n this.paused = false;\n },\n }).current;\n\n // Takes care of trapping focus if focus is moved outside programmatically for example\n React.useEffect(() => {\n if (trapped) {\n function handleFocusIn(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const target = event.target as HTMLElement | null;\n if (container.contains(target)) {\n lastFocusedElementRef.current = target;\n } else {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n function handleFocusOut(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n //\n // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n // 2. In Google Chrome, when the focused element is removed from the DOM.\n //\n // We let the browser do its thing here because:\n //\n // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n // throws the CPU to 100%, so we avoid doing anything for this reason here too.\n if (relatedTarget === null) return;\n\n // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n // that is outside the container, we move focus to the last valid focused element inside.\n if (!container.contains(relatedTarget)) {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n // When the focused element gets removed from the DOM, browsers move focus\n // back to the document.body. In this case, we move focus to the container\n // to keep focus trapped correctly.\n function handleMutations(mutations: MutationRecord[]) {\n const focusedElement = document.activeElement as HTMLElement | null;\n if (focusedElement !== document.body) return;\n for (const mutation of mutations) {\n if (mutation.removedNodes.length > 0) focus(container);\n }\n }\n\n document.addEventListener('focusin', handleFocusIn);\n document.addEventListener('focusout', handleFocusOut);\n const mutationObserver = new MutationObserver(handleMutations);\n if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n return () => {\n document.removeEventListener('focusin', handleFocusIn);\n document.removeEventListener('focusout', handleFocusOut);\n mutationObserver.disconnect();\n };\n }\n }, [trapped, container, focusScope.paused]);\n\n React.useEffect(() => {\n if (container) {\n focusScopesStack.add(focusScope);\n const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n if (!hasFocusedCandidate) {\n const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n container.dispatchEvent(mountEvent);\n if (!mountEvent.defaultPrevented) {\n focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n if (document.activeElement === previouslyFocusedElement) {\n focus(container);\n }\n }\n }\n\n return () => {\n container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n\n // We hit a react bug (fixed in v17) with focusing in unmount.\n // We need to delay the focus a little to get around it for now.\n // See: https://github.com/facebook/react/issues/17894\n setTimeout(() => {\n const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n container.dispatchEvent(unmountEvent);\n if (!unmountEvent.defaultPrevented) {\n focus(previouslyFocusedElement ?? document.body, { select: true });\n }\n // we need to remove the listener after we `dispatchEvent`\n container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n focusScopesStack.remove(focusScope);\n }, 0);\n };\n }\n }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n // Takes care of looping focus (when tabbing whilst at the edges)\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (!loop && !trapped) return;\n if (focusScope.paused) return;\n\n const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n const focusedElement = document.activeElement as HTMLElement | null;\n\n if (isTabKey && focusedElement) {\n const container = event.currentTarget as HTMLElement;\n const [first, last] = getTabbableEdges(container);\n const hasTabbableElementsInside = first && last;\n\n // we can only wrap focus if we have tabbable edges\n if (!hasTabbableElementsInside) {\n if (focusedElement === container) event.preventDefault();\n } else {\n if (!event.shiftKey && focusedElement === last) {\n event.preventDefault();\n if (loop) focus(first, { select: true });\n } else if (event.shiftKey && focusedElement === first) {\n event.preventDefault();\n if (loop) focus(last, { select: true });\n }\n }\n }\n },\n [loop, trapped, focusScope.paused],\n );\n\n return (\n <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n );\n },\n);\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n const previouslyFocusedElement = document.activeElement;\n for (const candidate of candidates) {\n focus(candidate, { select });\n if (document.activeElement !== previouslyFocusedElement) return;\n }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n const candidates = getTabbableCandidates(container);\n const first = findVisible(candidates, container);\n const last = findVisible(candidates.reverse(), container);\n return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n const nodes: HTMLElement[] = [];\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: any) => {\n const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';\n if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n // runtime's understanding of tabbability, so this automatically accounts\n // for any kind of element that could be tabbed to.\n return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n },\n });\n while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);\n // we do not take into account the order of nodes with positive `tabIndex` as it\n // hinders accessibility to have tab order different from visual order.\n return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n // `checkVisibility` performs a single native check for `visibility: hidden`\n // and `display: none` across the ancestor chain. This avoids the repeated\n // `getComputedStyle` calls per ancestor that the fallback path requires,\n // which reduces the cost of style resolution triggered by earlier DOM writes\n // (e.g. react-remove-scroll, DismissableLayer setting body styles).\n const canUseCheckVisibility =\n typeof container.checkVisibility === 'function' &&\n container.checkVisibility({ checkVisibilityCSS: true });\n\n for (const element of elements) {\n const hidden = canUseCheckVisibility\n ? !element.checkVisibility({ checkVisibilityCSS: true })\n : isHidden(element, { upTo: container });\n // we stop checking if it's hidden at the `container` level (excluding)\n if (!hidden) {\n return element;\n }\n }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n if (getComputedStyle(node).visibility === 'hidden') return true;\n while (node) {\n // we stop at `upTo` (excluding it)\n if (upTo !== undefined && node === upTo) return false;\n if (getComputedStyle(node).display === 'none') return true;\n node = node.parentElement as HTMLElement;\n }\n return false;\n}\n\nfunction isSelectableInput(element: any): element is FocusableTarget & { select: () => void } {\n return element instanceof HTMLInputElement && 'select' in element;\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n // only focus if that element is focusable\n if (element && element.focus) {\n const previouslyFocusedElement = document.activeElement;\n // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n element.focus({ preventScroll: true });\n // only select if its not the same element, it supports selection and we need to select\n if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n element.select();\n }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n /** A stack of focus scopes, with the active one at the top */\n let stack: FocusScopeAPI[] = [];\n\n return {\n add(focusScope: FocusScopeAPI) {\n // pause the currently active focus scope (at the top of the stack)\n const activeFocusScope = stack[0];\n if (focusScope !== activeFocusScope) {\n activeFocusScope?.pause();\n }\n // remove in case it already exists (because we'll re-add it at the top of the stack)\n stack = arrayRemove(stack, focusScope);\n stack.unshift(focusScope);\n },\n\n remove(focusScope: FocusScopeAPI) {\n stack = arrayRemove(stack, focusScope);\n stack[0]?.resume();\n },\n };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n const updatedArray = [...array];\n const index = updatedArray.indexOf(item);\n if (index !== -1) {\n updatedArray.splice(index, 1);\n }\n return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n return items.filter((item) => item.tagName !== 'A');\n}\n\nconst Root = FocusScope;\n\nexport {\n FocusScope,\n //\n Root,\n};\nexport type { FocusScopeProps };\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;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C,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,YAAY,GAAG;AACpD;AAFS;AAIT,IAAM,OAAO;",
6
+ "names": ["FocusScope", "handleFocusIn", "handleFocusOut", "handleMutations", "container"]
7
7
  }
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  "use client";
2
+ var __defProp = Object.defineProperty;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
2
4
 
3
5
  // src/focus-scope.tsx
4
6
  import * as React from "react";
@@ -9,124 +11,129 @@ import { jsx } from "react/jsx-runtime";
9
11
  var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount";
10
12
  var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount";
11
13
  var EVENT_OPTIONS = { bubbles: false, cancelable: true };
12
- var FOCUS_SCOPE_NAME = "FocusScope";
13
- var FocusScope = React.forwardRef((props, forwardedRef) => {
14
- const {
15
- loop = false,
16
- trapped = false,
17
- onMountAutoFocus: onMountAutoFocusProp,
18
- onUnmountAutoFocus: onUnmountAutoFocusProp,
19
- ...scopeProps
20
- } = props;
21
- const [container, setContainer] = React.useState(null);
22
- const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
23
- const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
24
- const lastFocusedElementRef = React.useRef(null);
25
- const composedRefs = useComposedRefs(forwardedRef, setContainer);
26
- const focusScope = React.useRef({
27
- paused: false,
28
- pause() {
29
- this.paused = true;
30
- },
31
- resume() {
32
- this.paused = false;
33
- }
34
- }).current;
35
- React.useEffect(() => {
36
- if (trapped) {
37
- let handleFocusIn2 = function(event) {
38
- if (focusScope.paused || !container) return;
39
- const target = event.target;
40
- if (container.contains(target)) {
41
- lastFocusedElementRef.current = target;
42
- } else {
43
- focus(lastFocusedElementRef.current, { select: true });
44
- }
45
- }, handleFocusOut2 = function(event) {
46
- if (focusScope.paused || !container) return;
47
- const relatedTarget = event.relatedTarget;
48
- if (relatedTarget === null) return;
49
- if (!container.contains(relatedTarget)) {
50
- focus(lastFocusedElementRef.current, { select: true });
51
- }
52
- }, handleMutations2 = function(mutations) {
53
- const focusedElement = document.activeElement;
54
- if (focusedElement !== document.body) return;
55
- for (const mutation of mutations) {
56
- if (mutation.removedNodes.length > 0) focus(container);
57
- }
58
- };
59
- var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
60
- document.addEventListener("focusin", handleFocusIn2);
61
- document.addEventListener("focusout", handleFocusOut2);
62
- const mutationObserver = new MutationObserver(handleMutations2);
63
- if (container) mutationObserver.observe(container, { childList: true, subtree: true });
64
- return () => {
65
- document.removeEventListener("focusin", handleFocusIn2);
66
- document.removeEventListener("focusout", handleFocusOut2);
67
- mutationObserver.disconnect();
68
- };
69
- }
70
- }, [trapped, container, focusScope.paused]);
71
- React.useEffect(() => {
72
- if (container) {
73
- focusScopesStack.add(focusScope);
74
- const previouslyFocusedElement = document.activeElement;
75
- const hasFocusedCandidate = container.contains(previouslyFocusedElement);
76
- if (!hasFocusedCandidate) {
77
- const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
78
- container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
79
- container.dispatchEvent(mountEvent);
80
- if (!mountEvent.defaultPrevented) {
81
- focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
82
- if (document.activeElement === previouslyFocusedElement) {
83
- focus(container);
84
- }
85
- }
14
+ var FocusScope = /* @__PURE__ */ React.forwardRef(
15
+ // ignore prettier to reduce diff noise
16
+ // prettier-ignore
17
+ /* @__PURE__ */ __name(function FocusScope2(props, forwardedRef) {
18
+ const {
19
+ loop = false,
20
+ trapped = false,
21
+ onMountAutoFocus: onMountAutoFocusProp,
22
+ onUnmountAutoFocus: onUnmountAutoFocusProp,
23
+ ...scopeProps
24
+ } = props;
25
+ const [container, setContainer] = React.useState(null);
26
+ const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
27
+ const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
28
+ const lastFocusedElementRef = React.useRef(null);
29
+ const composedRefs = useComposedRefs(forwardedRef, setContainer);
30
+ const focusScope = React.useRef({
31
+ paused: false,
32
+ pause() {
33
+ this.paused = true;
34
+ },
35
+ resume() {
36
+ this.paused = false;
86
37
  }
87
- return () => {
88
- container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
89
- setTimeout(() => {
90
- const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
91
- container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
92
- container.dispatchEvent(unmountEvent);
93
- if (!unmountEvent.defaultPrevented) {
94
- focus(previouslyFocusedElement ?? document.body, { select: true });
38
+ }).current;
39
+ React.useEffect(() => {
40
+ if (trapped) {
41
+ let handleFocusIn2 = function(event) {
42
+ if (focusScope.paused || !container) return;
43
+ const target = event.target;
44
+ if (container.contains(target)) {
45
+ lastFocusedElementRef.current = target;
46
+ } else {
47
+ focus(lastFocusedElementRef.current, { select: true });
95
48
  }
96
- container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
97
- focusScopesStack.remove(focusScope);
98
- }, 0);
99
- };
100
- }
101
- }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
102
- const handleKeyDown = React.useCallback(
103
- (event) => {
104
- if (!loop && !trapped) return;
105
- if (focusScope.paused) return;
106
- const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
107
- const focusedElement = document.activeElement;
108
- if (isTabKey && focusedElement) {
109
- const container2 = event.currentTarget;
110
- const [first, last] = getTabbableEdges(container2);
111
- const hasTabbableElementsInside = first && last;
112
- if (!hasTabbableElementsInside) {
113
- if (focusedElement === container2) event.preventDefault();
114
- } else {
115
- if (!event.shiftKey && focusedElement === last) {
116
- event.preventDefault();
117
- if (loop) focus(first, { select: true });
118
- } else if (event.shiftKey && focusedElement === first) {
119
- event.preventDefault();
120
- if (loop) focus(last, { select: true });
49
+ }, handleFocusOut2 = function(event) {
50
+ if (focusScope.paused || !container) return;
51
+ const relatedTarget = event.relatedTarget;
52
+ if (relatedTarget === null) return;
53
+ if (!container.contains(relatedTarget)) {
54
+ focus(lastFocusedElementRef.current, { select: true });
55
+ }
56
+ }, handleMutations2 = function(mutations) {
57
+ const focusedElement = document.activeElement;
58
+ if (focusedElement !== document.body) return;
59
+ for (const mutation of mutations) {
60
+ if (mutation.removedNodes.length > 0) focus(container);
61
+ }
62
+ };
63
+ var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
64
+ __name(handleFocusIn2, "handleFocusIn");
65
+ __name(handleFocusOut2, "handleFocusOut");
66
+ __name(handleMutations2, "handleMutations");
67
+ document.addEventListener("focusin", handleFocusIn2);
68
+ document.addEventListener("focusout", handleFocusOut2);
69
+ const mutationObserver = new MutationObserver(handleMutations2);
70
+ if (container) mutationObserver.observe(container, { childList: true, subtree: true });
71
+ return () => {
72
+ document.removeEventListener("focusin", handleFocusIn2);
73
+ document.removeEventListener("focusout", handleFocusOut2);
74
+ mutationObserver.disconnect();
75
+ };
76
+ }
77
+ }, [trapped, container, focusScope.paused]);
78
+ React.useEffect(() => {
79
+ if (container) {
80
+ focusScopesStack.add(focusScope);
81
+ const previouslyFocusedElement = document.activeElement;
82
+ const hasFocusedCandidate = container.contains(previouslyFocusedElement);
83
+ if (!hasFocusedCandidate) {
84
+ const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
85
+ container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
86
+ container.dispatchEvent(mountEvent);
87
+ if (!mountEvent.defaultPrevented) {
88
+ focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
89
+ if (document.activeElement === previouslyFocusedElement) {
90
+ focus(container);
91
+ }
121
92
  }
122
93
  }
94
+ return () => {
95
+ container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
96
+ setTimeout(() => {
97
+ const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
98
+ container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
99
+ container.dispatchEvent(unmountEvent);
100
+ if (!unmountEvent.defaultPrevented) {
101
+ focus(previouslyFocusedElement ?? document.body, { select: true });
102
+ }
103
+ container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
104
+ focusScopesStack.remove(focusScope);
105
+ }, 0);
106
+ };
123
107
  }
124
- },
125
- [loop, trapped, focusScope.paused]
126
- );
127
- return /* @__PURE__ */ jsx(Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
128
- });
129
- FocusScope.displayName = FOCUS_SCOPE_NAME;
108
+ }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
109
+ const handleKeyDown = React.useCallback(
110
+ (event) => {
111
+ if (!loop && !trapped) return;
112
+ if (focusScope.paused) return;
113
+ const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
114
+ const focusedElement = document.activeElement;
115
+ if (isTabKey && focusedElement) {
116
+ const container2 = event.currentTarget;
117
+ const [first, last] = getTabbableEdges(container2);
118
+ const hasTabbableElementsInside = first && last;
119
+ if (!hasTabbableElementsInside) {
120
+ if (focusedElement === container2) event.preventDefault();
121
+ } else {
122
+ if (!event.shiftKey && focusedElement === last) {
123
+ event.preventDefault();
124
+ if (loop) focus(first, { select: true });
125
+ } else if (event.shiftKey && focusedElement === first) {
126
+ event.preventDefault();
127
+ if (loop) focus(last, { select: true });
128
+ }
129
+ }
130
+ }
131
+ },
132
+ [loop, trapped, focusScope.paused]
133
+ );
134
+ return /* @__PURE__ */ jsx(Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
135
+ }, "FocusScope")
136
+ );
130
137
  function focusFirst(candidates, { select = false } = {}) {
131
138
  const previouslyFocusedElement = document.activeElement;
132
139
  for (const candidate of candidates) {
@@ -134,24 +141,27 @@ function focusFirst(candidates, { select = false } = {}) {
134
141
  if (document.activeElement !== previouslyFocusedElement) return;
135
142
  }
136
143
  }
144
+ __name(focusFirst, "focusFirst");
137
145
  function getTabbableEdges(container) {
138
146
  const candidates = getTabbableCandidates(container);
139
147
  const first = findVisible(candidates, container);
140
148
  const last = findVisible(candidates.reverse(), container);
141
149
  return [first, last];
142
150
  }
151
+ __name(getTabbableEdges, "getTabbableEdges");
143
152
  function getTabbableCandidates(container) {
144
153
  const nodes = [];
145
154
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
146
- acceptNode: (node) => {
155
+ acceptNode: /* @__PURE__ */ __name((node) => {
147
156
  const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
148
157
  if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
149
158
  return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
150
- }
159
+ }, "acceptNode")
151
160
  });
152
161
  while (walker.nextNode()) nodes.push(walker.currentNode);
153
162
  return nodes;
154
163
  }
164
+ __name(getTabbableCandidates, "getTabbableCandidates");
155
165
  function findVisible(elements, container) {
156
166
  const canUseCheckVisibility = typeof container.checkVisibility === "function" && container.checkVisibility({ checkVisibilityCSS: true });
157
167
  for (const element of elements) {
@@ -161,6 +171,7 @@ function findVisible(elements, container) {
161
171
  }
162
172
  }
163
173
  }
174
+ __name(findVisible, "findVisible");
164
175
  function isHidden(node, { upTo }) {
165
176
  if (getComputedStyle(node).visibility === "hidden") return true;
166
177
  while (node) {
@@ -170,9 +181,11 @@ function isHidden(node, { upTo }) {
170
181
  }
171
182
  return false;
172
183
  }
184
+ __name(isHidden, "isHidden");
173
185
  function isSelectableInput(element) {
174
186
  return element instanceof HTMLInputElement && "select" in element;
175
187
  }
188
+ __name(isSelectableInput, "isSelectableInput");
176
189
  function focus(element, { select = false } = {}) {
177
190
  if (element && element.focus) {
178
191
  const previouslyFocusedElement = document.activeElement;
@@ -181,6 +194,7 @@ function focus(element, { select = false } = {}) {
181
194
  element.select();
182
195
  }
183
196
  }
197
+ __name(focus, "focus");
184
198
  var focusScopesStack = createFocusScopesStack();
185
199
  function createFocusScopesStack() {
186
200
  let stack = [];
@@ -199,6 +213,7 @@ function createFocusScopesStack() {
199
213
  }
200
214
  };
201
215
  }
216
+ __name(createFocusScopesStack, "createFocusScopesStack");
202
217
  function arrayRemove(array, item) {
203
218
  const updatedArray = [...array];
204
219
  const index = updatedArray.indexOf(item);
@@ -207,9 +222,11 @@ function arrayRemove(array, item) {
207
222
  }
208
223
  return updatedArray;
209
224
  }
225
+ __name(arrayRemove, "arrayRemove");
210
226
  function removeLinks(items) {
211
227
  return items.filter((item) => item.tagName !== "A");
212
228
  }
229
+ __name(removeLinks, "removeLinks");
213
230
  var Root = FocusScope;
214
231
  export {
215
232
  FocusScope,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/focus-scope.tsx"],
4
- "sourcesContent": ["import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\nconst FOCUS_SCOPE_NAME = 'FocusScope';\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n /**\n * When `true`, tabbing from last item will focus first tabbable\n * and shift+tab from first item will focus last tababble.\n * @defaultValue false\n */\n loop?: boolean;\n\n /**\n * When `true`, focus cannot escape the focus scope via keyboard,\n * pointer, or a programmatic focus.\n * @defaultValue false\n */\n trapped?: boolean;\n\n /**\n * Event handler called when auto-focusing on mount.\n * Can be prevented.\n */\n onMountAutoFocus?: (event: Event) => void;\n\n /**\n * Event handler called when auto-focusing on unmount.\n * Can be prevented.\n */\n onUnmountAutoFocus?: (event: Event) => void;\n}\n\nconst FocusScope = React.forwardRef<FocusScopeElement, FocusScopeProps>((props, forwardedRef) => {\n const {\n loop = false,\n trapped = false,\n onMountAutoFocus: onMountAutoFocusProp,\n onUnmountAutoFocus: onUnmountAutoFocusProp,\n ...scopeProps\n } = props;\n const [container, setContainer] = React.useState<HTMLElement | null>(null);\n const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, setContainer);\n\n const focusScope = React.useRef({\n paused: false,\n pause() {\n this.paused = true;\n },\n resume() {\n this.paused = false;\n },\n }).current;\n\n // Takes care of trapping focus if focus is moved outside programmatically for example\n React.useEffect(() => {\n if (trapped) {\n function handleFocusIn(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const target = event.target as HTMLElement | null;\n if (container.contains(target)) {\n lastFocusedElementRef.current = target;\n } else {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n function handleFocusOut(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n //\n // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n // 2. In Google Chrome, when the focused element is removed from the DOM.\n //\n // We let the browser do its thing here because:\n //\n // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n // throws the CPU to 100%, so we avoid doing anything for this reason here too.\n if (relatedTarget === null) return;\n\n // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n // that is outside the container, we move focus to the last valid focused element inside.\n if (!container.contains(relatedTarget)) {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n // When the focused element gets removed from the DOM, browsers move focus\n // back to the document.body. In this case, we move focus to the container\n // to keep focus trapped correctly.\n function handleMutations(mutations: MutationRecord[]) {\n const focusedElement = document.activeElement as HTMLElement | null;\n if (focusedElement !== document.body) return;\n for (const mutation of mutations) {\n if (mutation.removedNodes.length > 0) focus(container);\n }\n }\n\n document.addEventListener('focusin', handleFocusIn);\n document.addEventListener('focusout', handleFocusOut);\n const mutationObserver = new MutationObserver(handleMutations);\n if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n return () => {\n document.removeEventListener('focusin', handleFocusIn);\n document.removeEventListener('focusout', handleFocusOut);\n mutationObserver.disconnect();\n };\n }\n }, [trapped, container, focusScope.paused]);\n\n React.useEffect(() => {\n if (container) {\n focusScopesStack.add(focusScope);\n const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n if (!hasFocusedCandidate) {\n const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n container.dispatchEvent(mountEvent);\n if (!mountEvent.defaultPrevented) {\n focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n if (document.activeElement === previouslyFocusedElement) {\n focus(container);\n }\n }\n }\n\n return () => {\n container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n\n // We hit a react bug (fixed in v17) with focusing in unmount.\n // We need to delay the focus a little to get around it for now.\n // See: https://github.com/facebook/react/issues/17894\n setTimeout(() => {\n const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n container.dispatchEvent(unmountEvent);\n if (!unmountEvent.defaultPrevented) {\n focus(previouslyFocusedElement ?? document.body, { select: true });\n }\n // we need to remove the listener after we `dispatchEvent`\n container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n focusScopesStack.remove(focusScope);\n }, 0);\n };\n }\n }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n // Takes care of looping focus (when tabbing whilst at the edges)\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (!loop && !trapped) return;\n if (focusScope.paused) return;\n\n const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n const focusedElement = document.activeElement as HTMLElement | null;\n\n if (isTabKey && focusedElement) {\n const container = event.currentTarget as HTMLElement;\n const [first, last] = getTabbableEdges(container);\n const hasTabbableElementsInside = first && last;\n\n // we can only wrap focus if we have tabbable edges\n if (!hasTabbableElementsInside) {\n if (focusedElement === container) event.preventDefault();\n } else {\n if (!event.shiftKey && focusedElement === last) {\n event.preventDefault();\n if (loop) focus(first, { select: true });\n } else if (event.shiftKey && focusedElement === first) {\n event.preventDefault();\n if (loop) focus(last, { select: true });\n }\n }\n }\n },\n [loop, trapped, focusScope.paused],\n );\n\n return (\n <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n );\n});\n\nFocusScope.displayName = FOCUS_SCOPE_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n const previouslyFocusedElement = document.activeElement;\n for (const candidate of candidates) {\n focus(candidate, { select });\n if (document.activeElement !== previouslyFocusedElement) return;\n }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n const candidates = getTabbableCandidates(container);\n const first = findVisible(candidates, container);\n const last = findVisible(candidates.reverse(), container);\n return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n const nodes: HTMLElement[] = [];\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: any) => {\n const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';\n if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n // runtime's understanding of tabbability, so this automatically accounts\n // for any kind of element that could be tabbed to.\n return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n },\n });\n while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);\n // we do not take into account the order of nodes with positive `tabIndex` as it\n // hinders accessibility to have tab order different from visual order.\n return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n // `checkVisibility` performs a single native check for `visibility: hidden`\n // and `display: none` across the ancestor chain. This avoids the repeated\n // `getComputedStyle` calls per ancestor that the fallback path requires,\n // which reduces the cost of style resolution triggered by earlier DOM writes\n // (e.g. react-remove-scroll, DismissableLayer setting body styles).\n const canUseCheckVisibility =\n typeof container.checkVisibility === 'function' &&\n container.checkVisibility({ checkVisibilityCSS: true });\n\n for (const element of elements) {\n const hidden = canUseCheckVisibility\n ? !element.checkVisibility({ checkVisibilityCSS: true })\n : isHidden(element, { upTo: container });\n // we stop checking if it's hidden at the `container` level (excluding)\n if (!hidden) {\n return element;\n }\n }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n if (getComputedStyle(node).visibility === 'hidden') return true;\n while (node) {\n // we stop at `upTo` (excluding it)\n if (upTo !== undefined && node === upTo) return false;\n if (getComputedStyle(node).display === 'none') return true;\n node = node.parentElement as HTMLElement;\n }\n return false;\n}\n\nfunction isSelectableInput(element: any): element is FocusableTarget & { select: () => void } {\n return element instanceof HTMLInputElement && 'select' in element;\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n // only focus if that element is focusable\n if (element && element.focus) {\n const previouslyFocusedElement = document.activeElement;\n // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n element.focus({ preventScroll: true });\n // only select if its not the same element, it supports selection and we need to select\n if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n element.select();\n }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n /** A stack of focus scopes, with the active one at the top */\n let stack: FocusScopeAPI[] = [];\n\n return {\n add(focusScope: FocusScopeAPI) {\n // pause the currently active focus scope (at the top of the stack)\n const activeFocusScope = stack[0];\n if (focusScope !== activeFocusScope) {\n activeFocusScope?.pause();\n }\n // remove in case it already exists (because we'll re-add it at the top of the stack)\n stack = arrayRemove(stack, focusScope);\n stack.unshift(focusScope);\n },\n\n remove(focusScope: FocusScopeAPI) {\n stack = arrayRemove(stack, focusScope);\n stack[0]?.resume();\n },\n };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n const updatedArray = [...array];\n const index = updatedArray.indexOf(item);\n if (index !== -1) {\n updatedArray.splice(index, 1);\n }\n return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n return items.filter((item) => item.tagName !== 'A');\n}\n\nconst Root = FocusScope;\n\nexport {\n FocusScope,\n //\n Root,\n};\nexport type { FocusScopeProps };\n"],
5
- "mappings": ";;;AAAA,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAwM3B;AAtMJ,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB,EAAE,SAAS,OAAO,YAAY,KAAK;AAQzD,IAAM,mBAAmB;AAgCzB,IAAM,aAAmB,iBAA+C,CAAC,OAAO,iBAAiB;AAC/F,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,UAAU;AAAA,IACV,kBAAkB;AAAA,IAClB,oBAAoB;AAAA,IACpB,GAAG;AAAA,EACL,IAAI;AACJ,QAAM,CAAC,WAAW,YAAY,IAAU,eAA6B,IAAI;AACzE,QAAM,mBAAmB,eAAe,oBAAoB;AAC5D,QAAM,qBAAqB,eAAe,sBAAsB;AAChE,QAAM,wBAA8B,aAA2B,IAAI;AACnE,QAAM,eAAe,gBAAgB,cAAc,YAAY;AAE/D,QAAM,aAAmB,aAAO;AAAA,IAC9B,QAAQ;AAAA,IACR,QAAQ;AACN,WAAK,SAAS;AAAA,IAChB;AAAA,IACA,SAAS;AACP,WAAK,SAAS;AAAA,IAChB;AAAA,EACF,CAAC,EAAE;AAGH,EAAM,gBAAU,MAAM;AACpB,QAAI,SAAS;AACX,UAASA,iBAAT,SAAuB,OAAmB;AACxC,YAAI,WAAW,UAAU,CAAC,UAAW;AACrC,cAAM,SAAS,MAAM;AACrB,YAAI,UAAU,SAAS,MAAM,GAAG;AAC9B,gCAAsB,UAAU;AAAA,QAClC,OAAO;AACL,gBAAM,sBAAsB,SAAS,EAAE,QAAQ,KAAK,CAAC;AAAA,QACvD;AAAA,MACF,GAESC,kBAAT,SAAwB,OAAmB;AACzC,YAAI,WAAW,UAAU,CAAC,UAAW;AACrC,cAAM,gBAAgB,MAAM;AA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OAAO;",
6
- "names": ["handleFocusIn", "handleFocusOut", "handleMutations", "container"]
4
+ "sourcesContent": ["import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n /**\n * When `true`, tabbing from last item will focus first tabbable\n * and shift+tab from first item will focus last tababble.\n * @defaultValue false\n */\n loop?: boolean;\n\n /**\n * When `true`, focus cannot escape the focus scope via keyboard,\n * pointer, or a programmatic focus.\n * @defaultValue false\n */\n trapped?: boolean;\n\n /**\n * Event handler called when auto-focusing on mount.\n * Can be prevented.\n */\n onMountAutoFocus?: (event: Event) => void;\n\n /**\n * Event handler called when auto-focusing on unmount.\n * Can be prevented.\n */\n onUnmountAutoFocus?: (event: Event) => void;\n}\n\nconst FocusScope = /* @__PURE__ */ React.forwardRef<FocusScopeElement, FocusScopeProps>(\n // ignore prettier to reduce diff noise\n // prettier-ignore\n function FocusScope(props, forwardedRef) {\n const {\n loop = false,\n trapped = false,\n onMountAutoFocus: onMountAutoFocusProp,\n onUnmountAutoFocus: onUnmountAutoFocusProp,\n ...scopeProps\n } = props;\n const [container, setContainer] = React.useState<HTMLElement | null>(null);\n const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, setContainer);\n\n const focusScope = React.useRef({\n paused: false,\n pause() {\n this.paused = true;\n },\n resume() {\n this.paused = false;\n },\n }).current;\n\n // Takes care of trapping focus if focus is moved outside programmatically for example\n React.useEffect(() => {\n if (trapped) {\n function handleFocusIn(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const target = event.target as HTMLElement | null;\n if (container.contains(target)) {\n lastFocusedElementRef.current = target;\n } else {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n function handleFocusOut(event: FocusEvent) {\n if (focusScope.paused || !container) return;\n const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n //\n // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n // 2. In Google Chrome, when the focused element is removed from the DOM.\n //\n // We let the browser do its thing here because:\n //\n // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n // throws the CPU to 100%, so we avoid doing anything for this reason here too.\n if (relatedTarget === null) return;\n\n // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n // that is outside the container, we move focus to the last valid focused element inside.\n if (!container.contains(relatedTarget)) {\n focus(lastFocusedElementRef.current, { select: true });\n }\n }\n\n // When the focused element gets removed from the DOM, browsers move focus\n // back to the document.body. In this case, we move focus to the container\n // to keep focus trapped correctly.\n function handleMutations(mutations: MutationRecord[]) {\n const focusedElement = document.activeElement as HTMLElement | null;\n if (focusedElement !== document.body) return;\n for (const mutation of mutations) {\n if (mutation.removedNodes.length > 0) focus(container);\n }\n }\n\n document.addEventListener('focusin', handleFocusIn);\n document.addEventListener('focusout', handleFocusOut);\n const mutationObserver = new MutationObserver(handleMutations);\n if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n return () => {\n document.removeEventListener('focusin', handleFocusIn);\n document.removeEventListener('focusout', handleFocusOut);\n mutationObserver.disconnect();\n };\n }\n }, [trapped, container, focusScope.paused]);\n\n React.useEffect(() => {\n if (container) {\n focusScopesStack.add(focusScope);\n const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n if (!hasFocusedCandidate) {\n const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n container.dispatchEvent(mountEvent);\n if (!mountEvent.defaultPrevented) {\n focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n if (document.activeElement === previouslyFocusedElement) {\n focus(container);\n }\n }\n }\n\n return () => {\n container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n\n // We hit a react bug (fixed in v17) with focusing in unmount.\n // We need to delay the focus a little to get around it for now.\n // See: https://github.com/facebook/react/issues/17894\n setTimeout(() => {\n const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n container.dispatchEvent(unmountEvent);\n if (!unmountEvent.defaultPrevented) {\n focus(previouslyFocusedElement ?? document.body, { select: true });\n }\n // we need to remove the listener after we `dispatchEvent`\n container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n focusScopesStack.remove(focusScope);\n }, 0);\n };\n }\n }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n // Takes care of looping focus (when tabbing whilst at the edges)\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (!loop && !trapped) return;\n if (focusScope.paused) return;\n\n const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n const focusedElement = document.activeElement as HTMLElement | null;\n\n if (isTabKey && focusedElement) {\n const container = event.currentTarget as HTMLElement;\n const [first, last] = getTabbableEdges(container);\n const hasTabbableElementsInside = first && last;\n\n // we can only wrap focus if we have tabbable edges\n if (!hasTabbableElementsInside) {\n if (focusedElement === container) event.preventDefault();\n } else {\n if (!event.shiftKey && focusedElement === last) {\n event.preventDefault();\n if (loop) focus(first, { select: true });\n } else if (event.shiftKey && focusedElement === first) {\n event.preventDefault();\n if (loop) focus(last, { select: true });\n }\n }\n }\n },\n [loop, trapped, focusScope.paused],\n );\n\n return (\n <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n );\n },\n);\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n const previouslyFocusedElement = document.activeElement;\n for (const candidate of candidates) {\n focus(candidate, { select });\n if (document.activeElement !== previouslyFocusedElement) return;\n }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n const candidates = getTabbableCandidates(container);\n const first = findVisible(candidates, container);\n const last = findVisible(candidates.reverse(), container);\n return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n const nodes: HTMLElement[] = [];\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n acceptNode: (node: any) => {\n const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden';\n if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;\n // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n // runtime's understanding of tabbability, so this automatically accounts\n // for any kind of element that could be tabbed to.\n return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;\n },\n });\n while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);\n // we do not take into account the order of nodes with positive `tabIndex` as it\n // hinders accessibility to have tab order different from visual order.\n return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n // `checkVisibility` performs a single native check for `visibility: hidden`\n // and `display: none` across the ancestor chain. This avoids the repeated\n // `getComputedStyle` calls per ancestor that the fallback path requires,\n // which reduces the cost of style resolution triggered by earlier DOM writes\n // (e.g. react-remove-scroll, DismissableLayer setting body styles).\n const canUseCheckVisibility =\n typeof container.checkVisibility === 'function' &&\n container.checkVisibility({ checkVisibilityCSS: true });\n\n for (const element of elements) {\n const hidden = canUseCheckVisibility\n ? !element.checkVisibility({ checkVisibilityCSS: true })\n : isHidden(element, { upTo: container });\n // we stop checking if it's hidden at the `container` level (excluding)\n if (!hidden) {\n return element;\n }\n }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n if (getComputedStyle(node).visibility === 'hidden') return true;\n while (node) {\n // we stop at `upTo` (excluding it)\n if (upTo !== undefined && node === upTo) return false;\n if (getComputedStyle(node).display === 'none') return true;\n node = node.parentElement as HTMLElement;\n }\n return false;\n}\n\nfunction isSelectableInput(element: any): element is FocusableTarget & { select: () => void } {\n return element instanceof HTMLInputElement && 'select' in element;\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n // only focus if that element is focusable\n if (element && element.focus) {\n const previouslyFocusedElement = document.activeElement;\n // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n element.focus({ preventScroll: true });\n // only select if its not the same element, it supports selection and we need to select\n if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n element.select();\n }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n /** A stack of focus scopes, with the active one at the top */\n let stack: FocusScopeAPI[] = [];\n\n return {\n add(focusScope: FocusScopeAPI) {\n // pause the currently active focus scope (at the top of the stack)\n const activeFocusScope = stack[0];\n if (focusScope !== activeFocusScope) {\n activeFocusScope?.pause();\n }\n // remove in case it already exists (because we'll re-add it at the top of the stack)\n stack = arrayRemove(stack, focusScope);\n stack.unshift(focusScope);\n },\n\n remove(focusScope: FocusScopeAPI) {\n stack = arrayRemove(stack, focusScope);\n stack[0]?.resume();\n },\n };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n const updatedArray = [...array];\n const index = updatedArray.indexOf(item);\n if (index !== -1) {\n updatedArray.splice(index, 1);\n }\n return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n return items.filter((item) => item.tagName !== 'A');\n}\n\nconst Root = FocusScope;\n\nexport {\n FocusScope,\n //\n Root,\n};\nexport type { FocusScopeProps };\n"],
5
+ "mappings": ";;;;;AAAA,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAyM3B;AAvMJ,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB,EAAE,SAAS,OAAO,YAAY,KAAK;AAsCzD,IAAM,aAA6B,gBAAM;AAAA;AAAA;AAAA,EAGvC,gCAASA,YAAW,OAAO,cAAc;AACzC,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,UAAU;AAAA,MACV,kBAAkB;AAAA,MAClB,oBAAoB;AAAA,MACpB,GAAG;AAAA,IACL,IAAI;AACJ,UAAM,CAAC,WAAW,YAAY,IAAU,eAA6B,IAAI;AACzE,UAAM,mBAAmB,eAAe,oBAAoB;AAC5D,UAAM,qBAAqB,eAAe,sBAAsB;AAChE,UAAM,wBAA8B,aAA2B,IA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,OAAO;AAAA,EACnB;AACF;AAVS;AAiBT,IAAM,mBAAmB,uBAAuB;AAEhD,SAAS,yBAAyB;AAEhC,MAAI,QAAyB,CAAC;AAE9B,SAAO;AAAA,IACL,IAAI,YAA2B;AAE7B,YAAM,mBAAmB,MAAM,CAAC;AAChC,UAAI,eAAe,kBAAkB;AACnC,0BAAkB,MAAM;AAAA,MAC1B;AAEA,cAAQ,YAAY,OAAO,UAAU;AACrC,YAAM,QAAQ,UAAU;AAAA,IAC1B;AAAA,IAEA,OAAO,YAA2B;AAChC,cAAQ,YAAY,OAAO,UAAU;AACrC,YAAM,CAAC,GAAG,OAAO;AAAA,IACnB;AAAA,EACF;AACF;AArBS;AAuBT,SAAS,YAAe,OAAY,MAAS;AAC3C,QAAM,eAAe,CAAC,GAAG,KAAK;AAC9B,QAAM,QAAQ,aAAa,QAAQ,IAAI;AACvC,MAAI,UAAU,IAAI;AAChB,iBAAa,OAAO,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;AAPS;AAST,SAAS,YAAY,OAAsB;AACzC,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,YAAY,GAAG;AACpD;AAFS;AAIT,IAAM,OAAO;",
6
+ "names": ["FocusScope", "handleFocusIn", "handleFocusOut", "handleMutations", "container"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radix-ui/react-focus-scope",
3
- "version": "1.1.12",
3
+ "version": "1.1.13-rc.1784074599772",
4
4
  "license": "MIT",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./dist/index.js",
@@ -21,8 +21,8 @@
21
21
  "react": "^19.2.0",
22
22
  "react-dom": "^19.2.0",
23
23
  "typescript": "^5.9.3",
24
- "@repo/builder": "0.0.0",
25
24
  "@repo/test-utils": "0.0.0",
25
+ "@repo/builder": "0.0.1-rc.1784074599772",
26
26
  "@repo/typescript-config": "0.0.0"
27
27
  },
28
28
  "peerDependencies": {