Skip to content

Commit

Permalink
Try to add types for Scrim. This is crazy :/
Browse files Browse the repository at this point in the history
  • Loading branch information
wenche authored and vnys committed Nov 13, 2020
1 parent 531b841 commit d00e7b4
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 87 deletions.
87 changes: 0 additions & 87 deletions libraries/core-react/src/Scrim/Scrim.jsx

This file was deleted.

88 changes: 88 additions & 0 deletions libraries/core-react/src/Scrim/Scrim.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React, { forwardRef, useEffect, MouseEvent } from 'react'
import styled from 'styled-components'
import { scrim as tokens } from './Scrim.tokens'

const { height, width, background } = tokens

type StyledScrimProps = {
onClose: (event: React.KeyboardEvent, open: boolean) => void
onClick: (event: MouseEvent, open: boolean) => void
isDismissable?: boolean
}

const StyledScrim = styled.div<StyledScrimProps>`
width: ${width};
height: ${height};
background: ${background};
position: fixed;
z-index: 11;
top: 0;
left: 0;
align-items: center;
justify-content: center;
display: flex;
`

const ScrimContent = styled.div`
width: auto;
height: auto;
`
type Props = {
children?: React.ReactNode
/** Whether scrim can be dismissed with esc key */
isDismissable?: boolean
/** Function to handle closing scrim */
onClose?: (
event: React.KeyboardEvent | MouseEvent | KeyboardEvent,
open: boolean,
) => void
}
export const Scrim = forwardRef<HTMLDivElement, Props>(
({ children, onClose, isDismissable = false, ...rest }, ref) => {
const handleKeyboardClose = (
event: React.KeyboardEvent | KeyboardEvent,
) => {
if (event) {
if (event.key === 'Escape' && isDismissable) {
onClose && onClose(event, false)
}
}
}
const handleMouseClose = (event: MouseEvent) => {
if (event) {
if (event.type === 'click' && isDismissable) {
onClose && onClose(event, false)
}
}
}

const handleContentClick = (event: MouseEvent) => {
// Avoid event bubbling inside dialog/content inside scrim
event.stopPropagation()
}

useEffect(() => {
if (isDismissable) {
document.addEventListener('keydown', handleKeyboardClose, false)
}

return () => {
document.removeEventListener('keydown', handleKeyboardClose, false)
}
}, [])

return (
<StyledScrim
onClose={handleKeyboardClose}
onClick={handleMouseClose}
isDismissable={isDismissable}
{...rest}
ref={ref}
>
<ScrimContent onClick={handleContentClick}>{children}</ScrimContent>
</StyledScrim>
)
},
)

Scrim.displayName = 'Scrim'

0 comments on commit d00e7b4

Please sign in to comment.