Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ module.exports = [
require: 'readonly',
console: 'readonly',
KeyboardEvent: 'readonly',
HTMLElement: 'readonly',
Element: 'readonly',
},
},
plugins: {
Expand Down
7 changes: 7 additions & 0 deletions src/FocusBracket.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { FC } from 'react';

// Invisible + focusable sentinels placed on each side of the dialog
// Tabbing past either edge lands on a bracket (outside the trap) and gets bounced back in
export const FocusBracket: FC = () => (
<div role='none' tabIndex={0} style={{ outline: 'none' }} />
);
9 changes: 9 additions & 0 deletions src/ModalView.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { FC } from 'react';
import { createPortal } from 'react-dom';
import { StyleSheet, View, Pressable } from 'react-native';

import { FocusBracket } from './FocusBracket';
import { useFocusTrap } from './hooks/useFocusTrap';
import { useModalStack } from './hooks/useModalStack';
import type { ModalViewProps } from './types';

Expand Down Expand Up @@ -40,6 +42,8 @@ export const ModalView: FC<ModalViewWebProps> = ({
const currentModalId = modalId ?? reactId;
const { isTopmost } = useModalStack(currentModalId);

const contentRef = useFocusTrap(isTopmost);

const [isOpen, setIsOpen] = useState(false);

useEffect(() => {
Expand Down Expand Up @@ -96,13 +100,18 @@ export const ModalView: FC<ModalViewWebProps> = ({
</BackdropPressableComponent>
)}

<FocusBracket />
<View
ref={contentRef}
role='dialog'
aria-modal={true}
tabIndex={-1}
pointerEvents='box-none'
style={[styles.content, animatedStyle, contentContainerStyle]}
>
{children}
</View>
<FocusBracket />
</View>,
document.body,
);
Expand Down
113 changes: 113 additions & 0 deletions src/focusHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
export const maybeGetElement = (node: unknown): HTMLElement | null =>
node instanceof HTMLElement ? node : null;

export const getModalRoot = (element: HTMLElement): HTMLElement => {
let root = element;

while (root.parentElement && root.parentElement !== document.body) {
root = root.parentElement;
}

return root;
};

export const inertBackground = (modalRoot: Element): (() => void) => {
const backgrounded = Array.from(document.body.children).filter(
node => node !== modalRoot && !node.hasAttribute('inert'),
);

backgrounded.forEach(node => node.setAttribute('inert', ''));

return () => {
backgrounded.forEach(node => node.removeAttribute('inert'));
};
};

export const onDocumentFocus = (handler: () => void): (() => void) => {
document.addEventListener('focus', handler, true);

return () => {
document.removeEventListener('focus', handler, true);
};
};

const attemptFocus = (element: HTMLElement): boolean => {
try {
element.focus();
} catch {
// .focus() can throw in rare cases (e.g. a detached node)
}

return document.activeElement === element;
};

export const focusFirstDescendant = (element: HTMLElement): boolean => {
const { children } = element;

for (let i = 0; i < children.length; i++) {
const child = children[i];

if (
child instanceof HTMLElement &&
(attemptFocus(child) || focusFirstDescendant(child))
) {
return true;
}
}

return false;
};

export const focusLastDescendant = (element: HTMLElement): boolean => {
const { children } = element;

for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];

if (
child instanceof HTMLElement &&
(attemptFocus(child) || focusLastDescendant(child))
) {
return true;
}
}

return false;
};

export const createFocusTrap = (
getModalContent: () => HTMLElement | null,
): (() => void) => {
let trapInProgress = false;
let lastFocused: Element | null = null;

return () => {
const modalContent = getModalContent();

if (!modalContent || trapInProgress) {
return;
}

trapInProgress = true;

try {
const activeElement = document.activeElement;

if (activeElement && !modalContent.contains(activeElement)) {
let hasFocused = focusFirstDescendant(modalContent);

if (lastFocused === document.activeElement) {
hasFocused = focusLastDescendant(modalContent);
}

if (!hasFocused) {
modalContent.focus();
}
}
} finally {
trapInProgress = false;
}

lastFocused = document.activeElement;
};
};
45 changes: 45 additions & 0 deletions src/hooks/useFocusTrap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useEffect, useRef } from 'react';
import type { View } from 'react-native';

import {
createFocusTrap,
getModalRoot,
inertBackground,
maybeGetElement,
onDocumentFocus,
} from '../focusHelpers';
import { useRestoreFocus } from './useRestoreFocus';

export function useFocusTrap(isTopmost: boolean) {
const contentRef = useRef<View>(null);

useRestoreFocus();

useEffect(() => {
if (!isTopmost) {
return;
}

const modalContent = maybeGetElement(contentRef.current);

if (!modalContent) {
return;
}

return inertBackground(getModalRoot(modalContent));
}, [isTopmost]);

useEffect(() => {
if (!isTopmost) {
return;
}

const trapFocus = createFocusTrap(() => maybeGetElement(contentRef.current));

trapFocus();

return onDocumentFocus(trapFocus);
}, [isTopmost]);

return contentRef;
}
17 changes: 17 additions & 0 deletions src/hooks/useRestoreFocus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect } from 'react';

import { maybeGetElement } from '../focusHelpers';

export function useRestoreFocus() {
useEffect(() => {
const previouslyFocused = maybeGetElement(document.activeElement);

return () => {
Promise.resolve().then(() => {
if (previouslyFocused && document.contains(previouslyFocused)) {
previouslyFocused.focus();
}
});
};
}, []);
}