Merged in chore/sw-3145-move-tooltip (pull request #2514)
chore(SW-3145): Move Tooltip to design-system * Move Tooltip to design-system Approved-by: Joakim Jäderberg
This commit is contained in:
75
packages/design-system/lib/components/Tooltip/index.tsx
Normal file
75
packages/design-system/lib/components/Tooltip/index.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import { type PropsWithChildren, useState } from 'react'
|
||||
|
||||
import { tooltipVariants } from './variants'
|
||||
|
||||
import styles from './tooltip.module.css'
|
||||
import Caption from '../Caption'
|
||||
|
||||
type TooltipPosition = 'left' | 'right' | 'top' | 'bottom'
|
||||
type VerticalArrow = 'top' | 'bottom' | 'center'
|
||||
type HorizontalArrow = 'left' | 'right' | 'center'
|
||||
|
||||
type ValidArrowMap = {
|
||||
left: VerticalArrow
|
||||
right: VerticalArrow
|
||||
top: HorizontalArrow
|
||||
bottom: HorizontalArrow
|
||||
}
|
||||
|
||||
type ValidArrow<P extends TooltipPosition> = P extends keyof ValidArrowMap
|
||||
? ValidArrowMap[P]
|
||||
: never
|
||||
|
||||
interface TooltipProps<P extends TooltipPosition = TooltipPosition> {
|
||||
heading?: string
|
||||
text?: string
|
||||
position: P
|
||||
arrow: ValidArrow<P>
|
||||
isTouchable?: boolean
|
||||
}
|
||||
|
||||
export function Tooltip<P extends TooltipPosition>({
|
||||
heading,
|
||||
text,
|
||||
position,
|
||||
arrow,
|
||||
children,
|
||||
isTouchable = false,
|
||||
}: PropsWithChildren<TooltipProps<P>>) {
|
||||
const className = tooltipVariants({ position, arrow })
|
||||
const [isActive, setIsActive] = useState(false)
|
||||
|
||||
function handleToggle() {
|
||||
setIsActive((prevState) => !prevState)
|
||||
}
|
||||
|
||||
function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
handleToggle()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={styles.tooltipContainer}
|
||||
role="tooltip"
|
||||
aria-label={text}
|
||||
tabIndex={0}
|
||||
onClick={isTouchable ? undefined : handleToggle}
|
||||
onTouchStart={isTouchable ? handleToggle : undefined}
|
||||
onKeyDown={handleKeyDown}
|
||||
data-active={isActive}
|
||||
>
|
||||
<div className={className}>
|
||||
{heading && (
|
||||
<Caption type="bold" color="white">
|
||||
{heading}
|
||||
</Caption>
|
||||
)}
|
||||
{text && <Caption color="white">{text}</Caption>}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user