antd-mobile
Version:
<img src="https://gw.alipayobjects.com/mdn/rms_ee68a8/afts/img/A*hjjDS5Yy-ooAAAAAAAAAAAAAARQnAQ" alt="logo" width="100%" />
89 lines (86 loc) • 2.84 kB
JavaScript
import { withNativeProps } from '../../utils/native-props';
import React, { useMemo, useRef, useState } from 'react';
import { useUnmountedRef } from 'ahooks';
import { useLockScroll } from '../../utils/use-lock-scroll';
import { useSpring, animated } from '@react-spring/web';
import { renderToContainer } from '../../utils/render-to-container';
import { mergeProps } from '../../utils/with-default-props';
import { useConfig } from '../config-provider';
import { useShouldRender } from '../../utils/should-render';
import { withStopPropagation } from '../../utils/with-stop-propagation';
const classPrefix = `adm-mask`;
const opacityRecord = {
default: 0.55,
thin: 0.35,
thick: 0.75
};
const defaultProps = {
visible: true,
destroyOnClose: false,
forceRender: false,
color: 'black',
opacity: 'default',
disableBodyScroll: true,
getContainer: null,
stopPropagation: ['click']
};
export const Mask = p => {
const props = mergeProps(defaultProps, p);
const {
locale
} = useConfig();
const ref = useRef(null);
useLockScroll(ref, props.visible && props.disableBodyScroll);
const background = useMemo(() => {
var _a;
const opacity = (_a = opacityRecord[props.opacity]) !== null && _a !== void 0 ? _a : props.opacity;
const rgb = props.color === 'white' ? '255, 255, 255' : '0, 0, 0';
return `rgba(${rgb}, ${opacity})`;
}, [props.color, props.opacity]);
const [active, setActive] = useState(props.visible);
const unmountedRef = useUnmountedRef();
const {
opacity
} = useSpring({
opacity: props.visible ? 1 : 0,
config: {
precision: 0.01,
mass: 1,
tension: 200,
friction: 30,
clamp: true
},
onStart: () => {
setActive(true);
},
onRest: () => {
var _a, _b;
if (unmountedRef.current) return;
setActive(props.visible);
if (props.visible) {
(_a = props.afterShow) === null || _a === void 0 ? void 0 : _a.call(props);
} else {
(_b = props.afterClose) === null || _b === void 0 ? void 0 : _b.call(props);
}
}
});
const shouldRender = useShouldRender(active, props.forceRender, props.destroyOnClose);
const node = withStopPropagation(props.stopPropagation, withNativeProps(props, React.createElement(animated.div, {
className: classPrefix,
ref: ref,
style: Object.assign(Object.assign({
background,
opacity
}, props.style), {
display: active ? 'unset' : 'none'
})
}, props.onMaskClick && React.createElement("div", {
className: `${classPrefix}-aria-button`,
role: 'button',
"aria-label": locale.Mask.name,
onClick: props.onMaskClick
}), React.createElement("div", {
className: `${classPrefix}-content`
}, shouldRender && props.children))));
return renderToContainer(props.getContainer, node);
};