Skip to content

Commit

Permalink
[add] Modal component
Browse files Browse the repository at this point in the history
This adds support for the React Native Modal on web.

The app content is hidden from screen readers by setting the aria-modal flag on
the modal. This focus is trapped within the modal, both when attempting to
focus elsewhere using the mouse as well as when attempting to focus elsewhere
using the keyboard. A built-in "Escape to close" mechanism is been implemented
that calls 'onRequestClose' for the active modal.

Close necolas#1646
Fix necolas#1020
  • Loading branch information
imnotjames authored and necolas committed Oct 9, 2020
1 parent 2b6e3be commit f7ee33e
Show file tree
Hide file tree
Showing 6 changed files with 952 additions and 2 deletions.
131 changes: 131 additions & 0 deletions src/exports/Modal/ModalAnimation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import { useEffect, useCallback, useState, useRef } from 'react';
import StyleSheet from '../StyleSheet';
import createElement from '../createElement';

const ANIMATION_DURATION = 300;

function getAnimationStyle(animationType, visible) {
if (animationType === 'slide') {
return visible ? animatedSlideInStyles : animatedSlideOutStyles;
}
if (animationType === 'fade') {
return visible ? animatedFadeInStyles : animatedFadeOutStyles;
}
return visible ? styles.container : styles.hidden;
}

export type ModalAnimationProps = {|
animationType?: ?('none' | 'slide' | 'fade'),
children?: any,
onDismiss?: ?() => void,
onShow?: ?() => void,
visible?: ?boolean
|};

function ModalAnimation(props: ModalAnimationProps) {
const { animationType, children, onDismiss, onShow, visible } = props;

const [isRendering, setIsRendering] = useState(false);
const wasVisible = useRef(false);

const isAnimated = animationType && animationType !== 'none';

const animationEndCallback = useCallback(() => {
if (visible) {
if (onShow) {
onShow();
}
} else {
setIsRendering(false);
if (onDismiss) {
onDismiss();
}
}
}, [onDismiss, onShow, visible]);

useEffect(() => {
if (visible) {
setIsRendering(true);
}
if (visible !== wasVisible.current && !isAnimated) {
// Manually call `animationEndCallback` if no animation is used
animationEndCallback();
}
wasVisible.current = visible;
}, [isAnimated, visible, animationEndCallback]);

return isRendering || visible
? createElement('div', {
style: isRendering ? getAnimationStyle(animationType, visible) : styles.hidden,
onAnimationEnd: animationEndCallback,
children
})
: null;
}

const styles = StyleSheet.create({
container: {
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
left: 0
},
animatedIn: {
animationDuration: `${ANIMATION_DURATION}ms`,
animationTimingFunction: 'ease-in'
},
animatedOut: {
pointerEvents: 'none',
animationDuration: `${ANIMATION_DURATION}ms`,
animationTimingFunction: 'ease-out'
},
fadeIn: {
opacity: 1,
animationKeyframes: {
'0%': { opacity: 0 },
'100%': { opacity: 1 }
}
},
fadeOut: {
opacity: 0,
animationKeyframes: {
'0%': { opacity: 1 },
'100%': { opacity: 0 }
}
},
slideIn: {
transform: [{ translateY: '0%' }],
animationKeyframes: {
'0%': { transform: [{ translateY: '100%' }] },
'100%': { transform: [{ translateY: '0%' }] }
}
},
slideOut: {
transform: [{ translateY: '100%' }],
animationKeyframes: {
'0%': { transform: [{ translateY: '0%' }] },
'100%': { transform: [{ translateY: '100%' }] }
}
},
hidden: {
display: 'none'
}
});

const animatedSlideInStyles = [styles.container, styles.animatedIn, styles.slideIn];
const animatedSlideOutStyles = [styles.container, styles.animatedOut, styles.slideOut];
const animatedFadeInStyles = [styles.container, styles.animatedIn, styles.fadeIn];
const animatedFadeOutStyles = [styles.container, styles.animatedOut, styles.fadeOut];

export default ModalAnimation;
73 changes: 73 additions & 0 deletions src/exports/Modal/ModalContent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import React, { forwardRef, useMemo, useEffect } from 'react';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import View from '../View';
import StyleSheet from '../StyleSheet';

export type ModalContentProps = {|
active?: ?(boolean | (() => boolean)),
children?: any,
onRequestClose?: ?() => void,
transparent?: ?boolean
|};

const ModalContent = forwardRef<ModalContentProps, *>((props, forwardedRef) => {
const { active, children, onRequestClose, transparent } = props;

useEffect(() => {
if (canUseDOM) {
const closeOnEscape = (e: KeyboardEvent) => {
if (active && e.key === 'Escape') {
e.stopPropagation();
if (onRequestClose) {
onRequestClose();
}
}
};
document.addEventListener('keyup', closeOnEscape, false);
return () => document.removeEventListener('keyup', closeOnEscape, false);
}
}, [active, onRequestClose]);

const style = useMemo(() => {
return [styles.modal, transparent ? styles.modalTransparent : styles.modalOpaque];
}, [transparent]);

return (
<View accessibilityRole={active ? 'dialog' : null} aria-modal ref={forwardedRef} style={style}>
<View style={styles.container}>{children}</View>
</View>
);
});

const styles = StyleSheet.create({
modal: {
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
left: 0,
zIndex: 9999
},
modalTransparent: {
backgroundColor: 'transparent'
},
modalOpaque: {
backgroundColor: 'white'
},
container: {
top: 0,
flex: 1
}
});

export default ModalContent;
141 changes: 141 additions & 0 deletions src/exports/Modal/ModalFocusTrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import React, { useRef, useEffect } from 'react';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import View from '../View';
import createElement from '../createElement';
import StyleSheet from '../StyleSheet';
import UIManager from '../UIManager';

/**
* This Component is used to "wrap" the modal we're opening
* so that changing focus via tab will never leave the document.
*
* This allows us to properly trap the focus within a modal
* even if the modal is at the start or end of a document.
*/

const FocusBracket = () => {
return createElement('div', {
accessibilityRole: 'none',
tabIndex: 0,
style: styles.focusBracket
});
};

function attemptFocus(element: any) {
if (!canUseDOM) {
return false;
}

try {
element.focus();
} catch (e) {
// Do nothing
}

return document.activeElement === element;
}

function focusFirstDescendant(element: any) {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes[i];
if (attemptFocus(child) || focusFirstDescendant(child)) {
return true;
}
}
return false;
}

function focusLastDescendant(element: any) {
for (let i = element.childNodes.length - 1; i >= 0; i--) {
const child = element.childNodes[i];
if (attemptFocus(child) || focusLastDescendant(child)) {
return true;
}
}
return false;
}

export type ModalFocusTrapProps = {|
active?: boolean | (() => boolean),
children?: any
|};

const ModalFocusTrap = ({ active, children }: ModalFocusTrapProps) => {
const trapElementRef = useRef<?HTMLElement>();
const focusRef = useRef<{ trapFocusInProgress: boolean, lastFocusedElement: ?HTMLElement }>({
trapFocusInProgress: false,
lastFocusedElement: null
});

useEffect(() => {
if (canUseDOM) {
const trapFocus = () => {
// We should not trap focus if:
// - The modal hasn't fully initialized with an HTMLElement ref
// - Focus is already in the process of being trapped (e.g., we're refocusing)
// - isTrapActive prop being falsey tells us to do nothing
if (trapElementRef.current == null || focusRef.current.trapFocusInProgress || !active) {
return;
}

try {
focusRef.current.trapFocusInProgress = true;
if (
document.activeElement instanceof Node &&
!trapElementRef.current.contains(document.activeElement)
) {
// To handle keyboard focusing we can make an assumption here.
// If you're tabbing through the focusable elements, the previously
// active element will either be the first or the last.
// If the previously selected element is the "first" descendant
// and we're leaving it - this means that we should be looping
// around to the other side of the modal.
let hasFocused = focusFirstDescendant(trapElementRef.current);
if (focusRef.current.lastFocusedElement === document.activeElement) {
hasFocused = focusLastDescendant(trapElementRef.current);
}
// If we couldn't focus a new element then we need to focus onto the trap target
if (!hasFocused && trapElementRef.current != null && document.activeElement) {
UIManager.focus(trapElementRef.current);
}
}
} finally {
focusRef.current.trapFocusInProgress = false;
}
focusRef.current.lastFocusedElement = document.activeElement;
};

// Call the trapFocus callback at least once when this modal has been activated.
trapFocus();

document.addEventListener('focus', trapFocus, true);
return () => document.removeEventListener('focus', trapFocus, true);
}
}, [active]);

return (
<>
<FocusBracket />
<View ref={trapElementRef}>{children}</View>
<FocusBracket />
</>
);
};

export default ModalFocusTrap;

const styles = StyleSheet.create({
focusBracket: {
outlineStyle: 'none'
}
});
48 changes: 48 additions & 0 deletions src/exports/Modal/ModalPortal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import { useEffect, useRef } from 'react';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import ReactDOM from 'react-dom';

export type ModalPortalProps = {|
children: any
|};

function ModalPortal(props: ModalPortalProps) {
const { children } = props;
const elementRef = useRef(null);

if (canUseDOM && !elementRef.current) {
const element = document.createElement('div');

if (element && document.body) {
document.body.appendChild(element);
elementRef.current = element;
}
}

useEffect(() => {
if (canUseDOM) {
return () => {
if (document.body && elementRef.current) {
document.body.removeChild(elementRef.current);
elementRef.current = null;
}
};
}
}, []);

return elementRef.current && canUseDOM
? ReactDOM.createPortal(children, elementRef.current)
: null;
}

export default ModalPortal;
Loading

0 comments on commit f7ee33e

Please sign in to comment.