feat(ui): Dialog with backdrop + escape + motion fade

This commit is contained in:
Bastien Chanot committed 2026-05-18 21:18:18 +02:00
1 parent a1453ec32e
commit afd58b386b
2 files changed
+101 -2

No files matched your search

+66 -2
View File
@@ -1,3 +1,67 @@
export default function Dialog() {
return <div>Dialog placeholder</div>
import { useEffect, type ReactNode } from 'react'
import { AnimatePresence, motion } from 'motion/react'
export interface DialogProps {
open: boolean
onClose: () => void
title: string
children: ReactNode
size?: 'sm' | 'md' | 'lg' | 'xl'
}
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
sm: 'max-w-sm',
md: 'max-w-md',
lg: 'max-w-2xl',
xl: 'max-w-4xl',
}
export default function Dialog({ open, onClose, title, children, size = 'md' }: DialogProps) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onClose])
return (
<AnimatePresence>
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<motion.div
data-testid="dialog-backdrop"
className="absolute inset-0 bg-black/40"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
onClick={onClose}
/>
<motion.div
role="dialog"
aria-modal="true"
aria-label={title}
initial={{ opacity: 0, scale: 0.96 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.96 }}
transition={{ duration: 0.18 }}
className={`relative w-full ${SIZE[size]} max-h-[90vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
>
<header className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)]">
<h2 className="text-lg font-semibold text-[var(--color-ink)]">{title}</h2>
<button
type="button"
aria-label="Fermer"
onClick={onClose}
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
>
✕
</button>
</header>
<div className="px-6 py-4">{children}</div>
</motion.div>
</div>
)}
</AnimatePresence>
)
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Dialog from '@/components/ui/Dialog'
describe('Dialog', () => {
it('renders nothing when open=false', () => {
render(
<Dialog open={false} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(screen.queryByText('body')).toBeNull()
})
it('renders content when open=true', () => {
render(
<Dialog open={true} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(screen.getByText('body')).toBeInTheDocument()
})
it('calls onClose on backdrop click', async () => {
const onClose = vi.fn()
render(
<Dialog open onClose={onClose} title="X">
body
</Dialog>,
)
await userEvent.click(screen.getByTestId('dialog-backdrop'))
expect(onClose).toHaveBeenCalled()
})
})