Completely updated React, fixed #11, (hopefully)

This commit is contained in:
2018-03-04 19:11:49 -05:00
parent 6e0afd6e2a
commit 34e5f5139a
13674 changed files with 333464 additions and 473223 deletions

View File

@@ -0,0 +1,21 @@
import * as React from 'react';
import { StandardProps } from '..';
import { FadeProps } from '../transitions/Fade';
import { TransitionProps } from '../transitions/transition';
export interface BackdropProps
extends StandardProps<
React.HTMLAttributes<HTMLDivElement> & Partial<FadeProps>,
BackdropClassKey
> {
invisible?: boolean;
onClick?: React.ReactEventHandler<{}>;
open: boolean;
transitionDuration?: TransitionProps['timeout'];
}
export type BackdropClassKey = 'root' | 'invisible';
declare const Backdrop: React.ComponentType<BackdropProps>;
export default Backdrop;

View File

@@ -0,0 +1,67 @@
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import Fade from '../transitions/Fade';
export const styles = {
root: {
zIndex: -1,
width: '100%',
height: '100%',
position: 'fixed',
top: 0,
left: 0,
// Remove grey highlight
WebkitTapHighlightColor: 'transparent',
willChange: 'opacity',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
},
invisible: {
backgroundColor: 'transparent'
}
};
function Backdrop(props) {
const { classes, invisible, open, transitionDuration } = props,
other = _objectWithoutProperties(props, ['classes', 'invisible', 'open', 'transitionDuration']);
const className = classNames(classes.root, {
[classes.invisible]: invisible
});
return React.createElement(
Fade,
_extends({ appear: true, 'in': open, timeout: transitionDuration }, other),
React.createElement('div', { className: className, 'aria-hidden': 'true' })
);
}
Backdrop.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* If `true`, the backdrop is invisible.
* It can be used when rendering a popover or a custom select component.
*/
invisible: PropTypes.bool,
/**
* If `true`, the backdrop is open.
*/
open: PropTypes.bool.isRequired,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
*/
transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })])
} : {};
Backdrop.defaultProps = {
invisible: false
};
export default withStyles(styles, { name: 'MuiBackdrop' })(Backdrop);

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import { StandardProps, ModalManager } from '..';
import { BackdropProps } from './Backdrop';
import { PortalProps } from '../Portal';
export interface ModalProps
extends StandardProps<
React.HtmlHTMLAttributes<HTMLDivElement> & Partial<PortalProps>,
ModalClassKey
> {
BackdropComponent?: React.ReactType<BackdropProps>;
BackdropProps?: Partial<BackdropProps>;
disableAutoFocus?: boolean;
disableBackdropClick?: boolean;
disableEnforceFocus?: boolean;
disableEscapeKeyDown?: boolean;
disableRestoreFocus?: boolean;
hideBackdrop?: boolean;
keepMounted?: boolean;
manager?: ModalManager;
onBackdropClick?: React.ReactEventHandler<{}>;
onClose?: React.ReactEventHandler<{}>;
onEscapeKeyDown?: React.ReactEventHandler<{}>;
open: boolean;
}
export type ModalClassKey = 'root' | 'hidden';
declare const Modal: React.ComponentType<ModalProps>;
export default Modal;

View File

@@ -0,0 +1,400 @@
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
// @inheritedComponent Portal
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import warning from 'warning';
import keycode from 'keycode';
import activeElement from 'dom-helpers/activeElement';
import contains from 'dom-helpers/query/contains';
import inDOM from 'dom-helpers/util/inDOM';
import ownerDocument from 'dom-helpers/ownerDocument';
import RefHolder from '../internal/RefHolder';
import Portal from '../Portal';
import addEventListener from '../utils/addEventListener';
import { createChainedFunction } from '../utils/helpers';
import withStyles from '../styles/withStyles';
import ModalManager from './ModalManager';
import Backdrop from './Backdrop';
function getContainer(container, defaultContainer) {
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container) || defaultContainer;
}
function getHasTransition(props) {
return props.children ? props.children.props.hasOwnProperty('in') : false;
}
export const styles = theme => ({
root: {
display: 'flex',
width: '100%',
height: '100%',
position: 'fixed',
zIndex: theme.zIndex.modal,
top: 0,
left: 0
},
hidden: {
visibility: 'hidden'
}
});
class Modal extends React.Component {
constructor(props, context) {
super(props, context);
this.dialog = null;
this.mounted = false;
this.mountNode = null;
this.handleRendered = () => {
this.autoFocus();
if (this.props.onRendered) {
this.props.onRendered();
}
};
this.handleOpen = () => {
const doc = ownerDocument(this.mountNode);
const container = getContainer(this.props.container, doc.body);
this.props.manager.add(this, container);
this.onDocumentKeydownListener = addEventListener(doc, 'keydown', this.handleDocumentKeyDown);
this.onFocusinListener = addEventListener(doc, 'focus', this.enforceFocus, true);
};
this.handleClose = () => {
this.props.manager.remove(this);
this.onDocumentKeydownListener.remove();
this.onFocusinListener.remove();
this.restoreLastFocus();
};
this.handleExited = () => {
this.setState({ exited: true });
this.handleClose();
};
this.handleBackdropClick = event => {
if (event.target !== event.currentTarget) {
return;
}
if (this.props.onBackdropClick) {
this.props.onBackdropClick(event);
}
if (!this.props.disableBackdropClick && this.props.onClose) {
this.props.onClose(event, 'backdropClick');
}
};
this.handleDocumentKeyDown = event => {
if (!this.isTopModal() || keycode(event) !== 'esc') {
return;
}
if (this.props.onEscapeKeyDown) {
this.props.onEscapeKeyDown(event);
}
if (!this.props.disableEscapeKeyDown && this.props.onClose) {
this.props.onClose(event, 'escapeKeyDown');
}
};
this.checkForFocus = () => {
if (inDOM) {
this.lastFocus = activeElement();
}
};
this.enforceFocus = () => {
if (this.props.disableEnforceFocus || !this.mounted || !this.isTopModal()) {
return;
}
const dialogElement = this.getDialogElement();
const currentActiveElement = activeElement(ownerDocument(this.mountNode));
if (dialogElement && !contains(dialogElement, currentActiveElement)) {
dialogElement.focus();
}
};
this.state = {
exited: !this.props.open
};
}
componentDidMount() {
this.mounted = true;
if (this.props.open) {
this.handleOpen();
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.open) {
this.setState({ exited: false });
} else if (!getHasTransition(nextProps)) {
// Otherwise let handleExited take care of marking exited.
this.setState({ exited: true });
}
}
componentWillUpdate(nextProps) {
if (!this.props.open && nextProps.open) {
this.checkForFocus();
}
}
componentDidUpdate(prevProps) {
if (prevProps.open && !this.props.open && !getHasTransition(this.props)) {
// Otherwise handleExited will call this.
this.handleClose();
} else if (!prevProps.open && this.props.open) {
this.handleOpen();
}
}
componentWillUnmount() {
this.mounted = false;
if (this.props.open || getHasTransition(this.props) && !this.state.exited) {
this.handleClose();
}
}
getDialogElement() {
return ReactDOM.findDOMNode(this.dialog);
}
autoFocus() {
if (this.props.disableAutoFocus) {
return;
}
const dialogElement = this.getDialogElement();
const currentActiveElement = activeElement(ownerDocument(this.mountNode));
if (dialogElement && !contains(dialogElement, currentActiveElement)) {
this.lastFocus = currentActiveElement;
if (!dialogElement.hasAttribute('tabIndex')) {
process.env.NODE_ENV !== "production" ? warning(false, ['Material-UI: the modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to "-1".'].join('\n')) : void 0;
dialogElement.setAttribute('tabIndex', -1);
}
dialogElement.focus();
}
}
restoreLastFocus() {
if (this.props.disableRestoreFocus) {
return;
}
if (this.lastFocus) {
this.lastFocus.focus();
this.lastFocus = null;
}
}
isTopModal() {
return this.props.manager.isTopModal(this);
}
render() {
const _props = this.props,
{
BackdropComponent,
BackdropProps,
children,
classes,
className,
container,
disableAutoFocus,
disableBackdropClick,
disableEnforceFocus,
disableEscapeKeyDown,
disableRestoreFocus,
hideBackdrop,
keepMounted,
onBackdropClick,
onClose,
onEscapeKeyDown,
onRendered,
open,
manager
} = _props,
other = _objectWithoutProperties(_props, ['BackdropComponent', 'BackdropProps', 'children', 'classes', 'className', 'container', 'disableAutoFocus', 'disableBackdropClick', 'disableEnforceFocus', 'disableEscapeKeyDown', 'disableRestoreFocus', 'hideBackdrop', 'keepMounted', 'onBackdropClick', 'onClose', 'onEscapeKeyDown', 'onRendered', 'open', 'manager']);
const { exited } = this.state;
const hasTransition = getHasTransition(this.props);
const childProps = {};
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
// It's a Transition like component
if (hasTransition) {
childProps.onExited = createChainedFunction(this.handleExited, children.props.onExited);
}
if (children.props.role === undefined) {
childProps.role = children.props.role || 'document';
}
if (children.props.tabIndex === undefined) {
childProps.tabIndex = children.props.tabIndex || '-1';
}
return React.createElement(
Portal,
{
ref: node => {
this.mountNode = node ? node.getMountNode() : node;
},
container: container,
onRendered: this.handleRendered
},
React.createElement(
'div',
_extends({
className: classNames(classes.root, className, {
[classes.hidden]: exited
})
}, other),
hideBackdrop ? null : React.createElement(BackdropComponent, _extends({ open: open, onClick: this.handleBackdropClick }, BackdropProps)),
React.createElement(
RefHolder,
{
ref: node => {
this.dialog = node;
}
},
React.cloneElement(children, childProps)
)
)
);
}
}
Modal.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* A backdrop component. Useful for custom backdrop rendering.
*/
BackdropComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Properties applied to the `Backdrop` element.
*/
BackdropProps: PropTypes.object,
/**
* A single child content element.
*/
children: PropTypes.element,
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* A node, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*/
container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, clicking the backdrop will not fire any callback.
*/
disableBackdropClick: PropTypes.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, hitting escape will not fire any callback.
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
*/
disableRestoreFocus: PropTypes.bool,
/**
* If `true`, the backdrop is not rendered.
*/
hideBackdrop: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This property can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
*/
keepMounted: PropTypes.bool,
/**
* A modal manager used to track and manage the state of open
* Modals. Useful when customizing how modals interact within a container.
*/
manager: PropTypes.object,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback
* @param {string} reason Can be:`"escapeKeyDown"`, `"backdropClick"`
*/
onClose: PropTypes.func,
/**
* Callback fired when the escape key is pressed,
* `disableEscapeKeyDown` is false and the modal is in focus.
*/
onEscapeKeyDown: PropTypes.func,
/**
* Callback fired once the children has been mounted into the `container`.
* It signals that the `open={true}` property took effect.
*/
onRendered: PropTypes.func,
/**
* If `true`, the modal is open.
*/
open: PropTypes.bool.isRequired
} : {};
Modal.defaultProps = {
disableAutoFocus: false,
disableBackdropClick: false,
disableEnforceFocus: false,
disableEscapeKeyDown: false,
disableRestoreFocus: false,
hideBackdrop: false,
keepMounted: false,
// Modals don't open on the server so this won't conflict with concurrent requests.
manager: new ModalManager(),
BackdropComponent: Backdrop
};
export default withStyles(styles, { flip: false, name: 'MuiModal' })(Modal);

View File

@@ -0,0 +1,8 @@
declare class ModalManager {
constructor(opts?: { hideSiblingNodes?: boolean; handleContainerOverflow?: boolean });
add(modal: any, container: any): number;
remove(modal: any): void;
isTopModal(modal: any): boolean;
}
export default ModalManager;

View File

@@ -0,0 +1,163 @@
import _Object$keys from 'babel-runtime/core-js/object/keys';
import css from 'dom-helpers/style';
import ownerDocument from 'dom-helpers/ownerDocument';
import getScrollbarSize from 'dom-helpers/util/scrollbarSize';
import isOverflowing from './isOverflowing';
import { ariaHidden, hideSiblings, showSiblings } from './manageAriaHidden';
function findIndexOf(data, callback) {
let idx = -1;
data.some((item, index) => {
if (callback(item)) {
idx = index;
return true;
}
return false;
});
return idx;
}
function findContainer(data, modal) {
return findIndexOf(data, item => item.modals.indexOf(modal) !== -1);
}
function getPaddingRight(node) {
return parseInt(css(node, 'paddingRight') || 0, 10);
}
function setContainerStyle(data, container) {
const style = { overflow: 'hidden' };
// We are only interested in the actual `style` here because we will override it.
data.style = {
overflow: container.style.overflow,
paddingRight: container.style.paddingRight
};
if (data.overflowing) {
const scrollbarSize = getScrollbarSize();
// Use computed style, here to get the real padding to add our scrollbar width.
style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;
// .mui-fixed is a global helper.
const fixedNodes = ownerDocument(container).querySelectorAll('.mui-fixed');
for (let i = 0; i < fixedNodes.length; i += 1) {
const paddingRight = getPaddingRight(fixedNodes[i]);
data.prevPaddings.push(paddingRight);
fixedNodes[i].style.paddingRight = `${paddingRight + scrollbarSize}px`;
}
}
_Object$keys(style).forEach(key => {
container.style[key] = style[key];
});
}
function removeContainerStyle(data, container) {
_Object$keys(data.style).forEach(key => {
container.style[key] = data.style[key];
});
const fixedNodes = ownerDocument(container).querySelectorAll('.mui-fixed');
for (let i = 0; i < fixedNodes.length; i += 1) {
fixedNodes[i].style.paddingRight = `${data.prevPaddings[i]}px`;
}
}
/**
* @ignore - do not document.
*
* Proper state managment for containers and the modals in those containers.
* Simplified, but inspired by react-overlay's ModalManager class
* Used by the Modal to ensure proper styling of containers.
*/
class ModalManager {
constructor({ hideSiblingNodes = true, handleContainerOverflow = true } = {}) {
this.add = (modal, container) => {
let modalIdx = this.modals.indexOf(modal);
const containerIdx = this.containers.indexOf(container);
if (modalIdx !== -1) {
return modalIdx;
}
modalIdx = this.modals.length;
this.modals.push(modal);
if (this.hideSiblingNodes) {
hideSiblings(container, modal.mountNode);
}
if (containerIdx !== -1) {
this.data[containerIdx].modals.push(modal);
return modalIdx;
}
const data = {
modals: [modal],
overflowing: isOverflowing(container),
prevPaddings: []
};
if (this.handleContainerOverflow) {
setContainerStyle(data, container);
}
this.containers.push(container);
this.data.push(data);
return modalIdx;
};
this.remove = modal => {
const modalIdx = this.modals.indexOf(modal);
if (modalIdx === -1) {
return modalIdx;
}
const containerIdx = findContainer(this.data, modal);
const data = this.data[containerIdx];
const container = this.containers[containerIdx];
data.modals.splice(data.modals.indexOf(modal), 1);
this.modals.splice(modalIdx, 1);
// If that was the last modal in a container, clean up the container.
if (data.modals.length === 0) {
if (this.handleContainerOverflow) {
removeContainerStyle(data, container);
}
if (this.hideSiblingNodes) {
showSiblings(container, modal.mountNode);
}
this.containers.splice(containerIdx, 1);
this.data.splice(containerIdx, 1);
} else if (this.hideSiblingNodes) {
// Otherwise make sure the next top modal is visible to a SR.
ariaHidden(false, data.modals[data.modals.length - 1].mountNode);
}
return modalIdx;
};
this.isTopModal = modal => {
return !!this.modals.length && this.modals[this.modals.length - 1] === modal;
};
this.hideSiblingNodes = hideSiblingNodes;
this.handleContainerOverflow = handleContainerOverflow;
// this.modals[modalIdx] = modal
this.modals = [];
// this.containers[containerIdx] = container
this.containers = [];
// this.data[containerIdx] = {
// modals: [],
// }
this.data = [];
}
}
export default ModalManager;

View File

@@ -0,0 +1,6 @@
export { default } from './Modal';
export * from './Modal';
export { default as Backdrop } from './Backdrop';
export * from './Backdrop';
export { default as ModalManager } from './ModalManager';
export * from './ModalManager';

View File

@@ -0,0 +1,3 @@
export { default } from './Modal';
export { default as Backdrop } from './Backdrop';
export { default as ModalManager } from './ModalManager';

View File

@@ -0,0 +1,25 @@
import isWindow from 'dom-helpers/query/isWindow';
import ownerDocument from 'dom-helpers/ownerDocument';
import ownerWindow from 'dom-helpers/ownerWindow';
export function isBody(node) {
return node && node.tagName.toLowerCase() === 'body';
}
// Do we have a scroll bar?
export default function isOverflowing(container) {
const doc = ownerDocument(container);
const win = ownerWindow(doc);
/* istanbul ignore next */
if (!isWindow(doc) && !isBody(container)) {
return container.scrollHeight > container.clientHeight;
}
// Takes in account potential non zero margin on the body.
const style = win.getComputedStyle(doc.body);
const marginLeft = parseInt(style.getPropertyValue('margin-left'), 10);
const marginRight = parseInt(style.getPropertyValue('margin-right'), 10);
return marginLeft + doc.body.clientWidth + marginRight < win.innerWidth;
}

View File

@@ -0,0 +1,3 @@
export function ariaHidden(show: boolean, node: Node): never;
export function hideSiblings(container: Element, mountNode: Node): never;
export function showSiblings(container: Element, mountNode: Node): never;

View File

@@ -0,0 +1,33 @@
const BLACKLIST = ['template', 'script', 'style'];
function isHidable(node) {
return node.nodeType === 1 && BLACKLIST.indexOf(node.tagName.toLowerCase()) === -1;
}
function siblings(container, mount, callback) {
mount = [].concat(mount); // eslint-disable-line no-param-reassign
[].forEach.call(container.children, node => {
if (mount.indexOf(node) === -1 && isHidable(node)) {
callback(node);
}
});
}
export function ariaHidden(show, node) {
if (!node) {
return;
}
if (show) {
node.setAttribute('aria-hidden', 'true');
} else {
node.removeAttribute('aria-hidden');
}
}
export function hideSiblings(container, mountNode) {
siblings(container, mountNode, node => ariaHidden(true, node));
}
export function showSiblings(container, mountNode) {
siblings(container, mountNode, node => ariaHidden(false, node));
}