@equinor/eds-core-react
Version:
The React implementation of the Equinor Design System
86 lines (81 loc) • 2.65 kB
JavaScript
import { forwardRef, useRef, useMemo, useEffect } from 'react';
import styled, { css, ThemeProvider } from 'styled-components';
import { typographyTemplate, bordersTemplate, useToken, mergeRefs, useHideBodyScroll, useGlobalKeyPress } from '@equinor/eds-utils';
import { dialog } from './Dialog.tokens.js';
import { jsx } from 'react/jsx-runtime';
import { Paper } from '../Paper/Paper.js';
import { useEds } from '../EdsProvider/eds.context.js';
const StyledDialog = styled(Paper).attrs({
'aria-labelledby': 'eds-dialog-title',
'aria-describedby': 'eds-dialog-customcontent',
elevation: 'above_scrim'
}).withConfig({
displayName: "Dialog__StyledDialog",
componentId: "sc-1mewo3f-0"
})(({
theme
}) => {
return css(["width:", ";background:", ";display:grid;grid-auto-columns:auto;", ";", ";grid-gap:", ";"], theme.width, theme.background, typographyTemplate(theme.typography), bordersTemplate(theme.border), theme.spacings.bottom);
});
const StyledNativeDialog = styled.dialog.withConfig({
displayName: "Dialog__StyledNativeDialog",
componentId: "sc-1mewo3f-1"
})(({
theme
}) => {
return css(["padding:0;border:0;overflow:visible;overscroll-behavior:contain;", ";&::backdrop{background-color:", ";}"], bordersTemplate(theme.border), theme.entities.scrim.background);
});
const Dialog = /*#__PURE__*/forwardRef(function Dialog({
children,
open,
onClose,
isDismissable = false,
dialogRef,
...props
}, ref) {
const {
density
} = useEds();
const localRef = useRef(null);
const token = useToken({
density
}, dialog);
const combinedDialogRef = useMemo(() => mergeRefs(localRef, dialogRef), [localRef, dialogRef]);
useEffect(() => {
if (open) {
localRef?.current?.showModal();
} else {
localRef?.current?.close();
}
}, [open]);
//This might become redundant in the future, see https://github.com/whatwg/html/issues/7732
useHideBodyScroll(open);
const handleDismiss = e => {
const {
target
} = e;
if (target instanceof HTMLElement) if (isDismissable && target.nodeName === 'DIALOG') {
onClose && onClose();
}
};
useGlobalKeyPress('Escape', e => {
e.preventDefault();
if (isDismissable && onClose && open) {
onClose && onClose();
}
});
return /*#__PURE__*/jsx(ThemeProvider, {
theme: token,
children: /*#__PURE__*/jsx(StyledNativeDialog, {
ref: combinedDialogRef,
onMouseDown: handleDismiss,
children: open && /*#__PURE__*/jsx(StyledDialog, {
...props,
ref: ref,
children: children
})
})
});
});
// Dialog.displayName = 'EdsDialog'
export { Dialog };