Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 470
feat(headless): add package foundation with Dialog primitive#8474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
27fa431823c47d056f8ed061bcf5abc32732dc023e3d3d5d64430af5c3d5f6bca8388107b96d4e21a76e40e78a975b95bbb8ec1222f4d101b0f09119dbdee97c130afb5c1bddFile filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| # @clerk/headless | ||
| Headless UI primitives for Clerk's component library. These are unstyled, accessible React components built on [Floating UI](https://floating-ui.com/) that handle positioning, keyboard navigation, focus management, and ARIA attributes. | ||
| This package is **internal** (`private: true`) and consumed by `@clerk/ui`. It exists as a separate package because `@clerk/ui` uses `@emotion/react` as its JSX source, which conflicts with the standard `react-jsx` transform these primitives require. | ||
Ephem marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| ## Primitives | ||
| | Primitive | Import | Description | | ||
| | ------------ | ------------------------------ | ------------------------------------------------------------- | | ||
| | Accordion | `@clerk/headless/accordion` | Expandable content sections with single/multiple mode | | ||
| | Autocomplete | `@clerk/headless/autocomplete` | Combobox input with filterable option list | | ||
| | Dialog | `@clerk/headless/dialog` | Modal dialog with focus trapping and scroll lock | | ||
| | Menu | `@clerk/headless/menu` | Dropdown and nested context menus with safe hover zones | | ||
| | Popover | `@clerk/headless/popover` | Non-modal floating content triggered by click | | ||
| | Select | `@clerk/headless/select` | Dropdown select with typeahead and keyboard navigation | | ||
| | Tabs | `@clerk/headless/tabs` | Tab navigation with animated indicator | | ||
| | Tooltip | `@clerk/headless/tooltip` | Hover/focus tooltip with configurable delay and group support | | ||
coderabbitai[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| Shared utilities are available at `@clerk/headless/utils` (includes `renderElement` and `mergeProps`). | ||
| Each primitive has its own README in `src/primitives/<name>/` with full API docs, props tables, keyboard navigation, and data attributes. | ||
| ## Usage | ||
| ```tsx | ||
| import { Select } from '@clerk/headless/select'; | ||
| <Select> | ||
| <Select.Trigger>Choose...</Select.Trigger> | ||
| <Select.Positioner> | ||
| <Select.Popup> | ||
| <Select.Option | ||
| value='a' | ||
| label='Option A' | ||
| /> | ||
| <Select.Option | ||
| value='b' | ||
| label='Option B' | ||
| /> | ||
| </Select.Popup> | ||
| </Select.Positioner> | ||
| </Select>; | ||
| ``` | ||
| All primitives follow the same compound component pattern. They emit zero styles — all visual styling is applied externally via `data-cl-*` attribute selectors. | ||
| ## Architecture | ||
| - **Compound components** — each primitive exports a namespace (e.g. `Select.Trigger`, `Select.Popup`) backed by per-part files so unused parts tree-shake out | ||
| - **`renderElement`** — every part uses this instead of returning JSX directly, enabling consumer `render` prop overrides and automatic state-to-data-attribute mapping | ||
| - **`data-cl-*` attributes** — structural (`data-cl-slot`), state (`data-cl-open`, `data-cl-selected`, `data-cl-active`), and animation lifecycle (`data-cl-starting-style`, `data-cl-ending-style`) | ||
Ephem marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| - **CSS-driven animations** — the transition system uses `data-cl-*` attributes and the Web Animations API (`getAnimations().finished`) so all timing lives in CSS | ||
| - **Floating UI** — positioning, interactions, focus management, dismiss handling, list navigation, and ARIA are all delegated to `@floating-ui/react` | ||
| ## Consuming from `@clerk/ui` | ||
| `@clerk/ui` uses `jsxImportSource: '@emotion/react'`, which automatically gives every component that accepts `className: string` a working `css` prop at runtime. Headless parts already declare `className` (via `ComponentProps<Tag>`), so **the emotion `css` prop works out of the box**: | ||
| ```tsx | ||
| import { Dialog } from '@clerk/headless/dialog'; | ||
| <Dialog.Popup css={{ padding: 24, borderRadius: 8 }} />; | ||
| ``` | ||
| For Clerk's theme-aware **`sx` prop**, each part must be wrapped with `makeCustomizable` (the HOC that resolves `descriptors`/`elementId` and forwards `css={sx}` down). Create a thin wrapper module in `@clerk/ui`: | ||
| ```tsx | ||
| // packages/ui/src/primitives/Dialog.tsx | ||
| import { Dialog as HeadlessDialog } from '@clerk/headless/dialog'; | ||
| import type { | ||
| DialogBackdropProps, | ||
| DialogCloseProps, | ||
| DialogDescriptionProps, | ||
| DialogPopupProps, | ||
| DialogPortalProps, | ||
| DialogProps, | ||
| DialogTitleProps, | ||
| DialogTriggerProps, | ||
| } from '@clerk/headless/dialog'; | ||
| import type { FunctionComponent } from 'react'; | ||
| import { makeCustomizable } from '../customizables/makeCustomizable'; | ||
| import type { ThemableCssProp } from '../styledSystem'; | ||
| type Customizable<T> = T & { sx?: ThemableCssProp }; | ||
| export const Dialog: { | ||
| Root: FunctionComponent<DialogProps>; | ||
| Trigger: FunctionComponent<Customizable<DialogTriggerProps>>; | ||
| Portal: FunctionComponent<DialogPortalProps>; | ||
| Backdrop: FunctionComponent<Customizable<DialogBackdropProps>>; | ||
| Popup: FunctionComponent<Customizable<DialogPopupProps>>; | ||
| Title: FunctionComponent<Customizable<DialogTitleProps>>; | ||
| Description: FunctionComponent<Customizable<DialogDescriptionProps>>; | ||
| Close: FunctionComponent<Customizable<DialogCloseProps>>; | ||
| } = { | ||
| Root: HeadlessDialog.Root, | ||
| Trigger: makeCustomizable(HeadlessDialog.Trigger), | ||
| Portal: HeadlessDialog.Portal, | ||
| Backdrop: makeCustomizable(HeadlessDialog.Backdrop), | ||
| Popup: makeCustomizable(HeadlessDialog.Popup), | ||
| Title: makeCustomizable(HeadlessDialog.Title), | ||
| Description: makeCustomizable(HeadlessDialog.Description), | ||
| Close: makeCustomizable(HeadlessDialog.Close), | ||
| }; | ||
| ``` | ||
| Consumers can then style with the theme: | ||
| ```tsx | ||
| <Dialog.Popup sx={t => ({ backgroundColor: t.colors.$colorBackground, padding: t.space.$6 })} /> | ||
| ``` | ||
| ### Why the explicit type annotation is required | ||
| Without the annotation, `tsc` emits **TS2742**: | ||
| > The inferred type of `Dialog` cannot be named without a reference to `@clerk/headless/dist/utils/render-element`. This is likely not portable. | ||
| `makeCustomizable<P>` returns an internal `CustomizablePrimitive<P>` type. When TS rolls up `.d.ts`, it resolves `DialogTriggerProps = ComponentProps<'button'>` back to its source file (`headless/dist/utils/render-element`), which **isn't in the package `exports` map**. The explicit `FunctionComponent<Customizable<DialogXProps>>` annotation forces TS to reference the named `DialogXProps` type from `@clerk/headless/dialog` (a public entry) instead of expanding it. | ||
| This applies to **every** headless primitive consumed through `makeCustomizable` — Popover, Tooltip, Menu, Select, etc. Each gets its own wrapper module under `packages/ui/src/primitives/<Name>.tsx` following the pattern above. | ||
| ### Pass-through parts | ||
| Parts that don't render a DOM element (e.g. `Root`, `Portal`) should **not** be wrapped — pass them through directly. `makeCustomizable` only adds value for parts that render an element with a `className`. | ||
| ### Skipping the wrapper | ||
| If you only need one-off styling and don't want a wrapper module, headless's `render` prop is the escape hatch: | ||
| ```tsx | ||
| <HeadlessDialog.Popup render={props => <Box sx={{ ... }} {...props} />} /> | ||
| ``` | ||
| Trade-off: verbose at the call site and loses automatic `descriptors`/`elementId` plumbing. Prefer the wrapper for any primitive used more than once. | ||
| ## Development | ||
| ```sh | ||
| pnpm dev # watch mode build | ||
| pnpm build # production build | ||
| pnpm test # run tests (vitest + playwright browser mode) | ||
| ``` | ||
| Tests run in a real Chromium browser via `@vitest/browser-playwright`, not jsdom. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| { | ||
alexcarpenter marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| "name": "@clerk/headless", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "sideEffects": false, | ||
| "type": "module", | ||
| "exports": { | ||
| "./dialog": { | ||
| "import": "./dist/primitives/dialog/index.js", | ||
| "types": "./dist/primitives/dialog/index.d.ts" | ||
| }, | ||
| "./hooks": { | ||
| "import": "./dist/hooks/index.js", | ||
| "types": "./dist/hooks/index.d.ts" | ||
| }, | ||
| "./utils": { | ||
| "import": "./dist/utils/index.js", | ||
| "types": "./dist/utils/index.d.ts" | ||
| } | ||
| }, | ||
Ephem marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| "scripts": { | ||
| "build": "rm -rf dist && vite build", | ||
| "dev": "vite build --watch", | ||
| "lint": "eslint src", | ||
| "test": "vitest" | ||
| }, | ||
| "dependencies": { | ||
| "@floating-ui/react": "catalog:repo" | ||
| }, | ||
| "devDependencies": { | ||
| "@testing-library/dom": "^10.4.1", | ||
| "@testing-library/jest-dom": "^6.9.1", | ||
| "@testing-library/react": "^16.3.2", | ||
| "@testing-library/user-event": "^14.6.1", | ||
| "@types/react": "catalog:react", | ||
| "@types/react-dom": "catalog:react", | ||
| "axe-core": "^4.11.3", | ||
| "happy-dom": "^18.0.1", | ||
| "react": "catalog:react", | ||
| "react-dom": "catalog:react", | ||
| "typescript": "catalog:repo", | ||
| "vite": "6.4.1", | ||
| "vite-plugin-dts": "^4.5.4", | ||
| "vitest": "4.1.4", | ||
| "vitest-axe": "^0.1.0" | ||
| }, | ||
| "peerDependencies": { | ||
| "react": "catalog:peer-react", | ||
| "react-dom": "catalog:peer-react" | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| export { useAnimationsFinished } from './use-animations-finished'; | ||
| export { useControllableState } from './use-controllable-state'; | ||
| export { | ||
| type TransitionProps, | ||
| useTransition, | ||
| type UseTransitionOptions, | ||
| type UseTransitionReturn, | ||
| } from './use-transition'; | ||
| export { type TransitionStatus, useTransitionStatus } from './use-transition-status'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| import { act, renderHook } from '@testing-library/react'; | ||
| import { createRef, type RefObject } from 'react'; | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
| import { useAnimationsFinished } from './use-animations-finished'; | ||
| function createMockElement( | ||
| animations: Array<{ finished: Promise<void> }> = [], | ||
| attributes: Record<string, string> = {}, | ||
| ): HTMLElement { | ||
| const el = document.createElement('div'); | ||
| Object.entries(attributes).forEach(([k, v]) => el.setAttribute(k, v)); | ||
| el.getAnimations = vi.fn(() => animations as unknown as Animation[]); | ||
| return el; | ||
| } | ||
| describe('useAnimationsFinished', () => { | ||
| it('fires callback immediately when ref.current is null', () => { | ||
| const ref = createRef<HTMLElement>() as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('fires callback immediately when getAnimations is not supported', () => { | ||
| const ref = { current: document.createElement('div') } as RefObject<HTMLElement | null>; | ||
| // Don't add getAnimations | ||
| delete (ref.current as unknown as Record<string, unknown>).getAnimations; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('fires callback immediately when no animations are running', () => { | ||
| const el = createMockElement([]); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('waits for all animations to finish before firing callback', async () => { | ||
| let resolveAnim!: () => void; | ||
| const animPromise = new Promise<void>(r => { | ||
| resolveAnim = r; | ||
| }); | ||
| const el = createMockElement([{ finished: animPromise }]); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| expect(callback).not.toHaveBeenCalled(); | ||
| // After animations finish, change getAnimations to return empty | ||
| el.getAnimations = vi.fn(() => [] as unknown as Animation[]); | ||
| await act(() => resolveAnim()); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('aborts previous pending wait when called again', async () => { | ||
| let resolveFirst!: () => void; | ||
| const firstAnim = new Promise<void>(r => { | ||
| resolveFirst = r; | ||
| }); | ||
| const el = createMockElement([{ finished: firstAnim }]); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const firstCallback = vi.fn(); | ||
| act(() => result.current(firstCallback)); | ||
| // Call again — should abort the first | ||
| const secondCallback = vi.fn(); | ||
| el.getAnimations = vi.fn(() => [] as unknown as Animation[]); | ||
| act(() => result.current(secondCallback)); | ||
| expect(secondCallback).toHaveBeenCalledTimes(1); | ||
| // Resolve first animation — its callback should NOT fire | ||
| await act(() => resolveFirst()); | ||
| expect(firstCallback).not.toHaveBeenCalled(); | ||
| }); | ||
| it('re-checks animations when one is cancelled', async () => { | ||
| let rejectAnim!: () => void; | ||
| const cancelledAnim = new Promise<void>((_, reject) => { | ||
| rejectAnim = reject; | ||
| }); | ||
| const el = createMockElement([{ finished: cancelledAnim }]); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| expect(callback).not.toHaveBeenCalled(); | ||
| // Cancel the animation — hook should re-check and find no new animations | ||
| el.getAnimations = vi.fn(() => [] as unknown as Animation[]); | ||
| await act(async () => { | ||
| rejectAnim(); | ||
| // Let microtask queue flush | ||
| await new Promise(r => setTimeout(r, 0)); | ||
| }); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('waits for starting-style attribute removal when open=true', async () => { | ||
| const el = createMockElement([], { 'data-cl-starting-style': '' }); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result } = renderHook(() => useAnimationsFinished(ref, true)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| // Should not fire yet — waiting for attribute removal | ||
| expect(callback).not.toHaveBeenCalled(); | ||
| // Remove the attribute — MutationObserver should fire | ||
| await act(async () => { | ||
| el.removeAttribute('data-cl-starting-style'); | ||
| // MutationObserver is async; wait a tick | ||
| await new Promise(r => setTimeout(r, 0)); | ||
| }); | ||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| }); | ||
| it('cleans up on unmount', () => { | ||
| let resolveAnim!: () => void; | ||
| const animPromise = new Promise<void>(r => { | ||
| resolveAnim = r; | ||
| }); | ||
| const el = createMockElement([{ finished: animPromise }]); | ||
| const ref = { current: el } as RefObject<HTMLElement | null>; | ||
| const { result, unmount } = renderHook(() => useAnimationsFinished(ref, false)); | ||
| const callback = vi.fn(); | ||
| act(() => result.current(callback)); | ||
| // Unmount should abort | ||
| unmount(); | ||
| // Resolve animation — callback should not fire because abort was called | ||
| resolveAnim(); | ||
| expect(callback).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.