-
Notifications
You must be signed in to change notification settings - Fork 453
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| --- | ||
| --- | ||
|
|
||
| Introduce `@clerk/headless` package with Dialog primitive, hooks, and utilities. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # @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. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this intended to be private forever? I'm guessing yes and that anything we want public we export through I'm trying to think through the public parts, the css Are there any cases for our public components where you think C1s will pass through render props, or any other decisions here that are going to shape public facing APIs down the line? |
||
|
|
||
| ## 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.
|
||
|
|
||
| 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** via `Object.assign` — each primitive is a single export with dot-accessed parts (`Select.Trigger`, `Select.Popup`, etc.) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this approach entirely disables tree-shaking? Maybe not a huge deal but since we are setting this up from scratch and now is the best time to fix it if we want to, I wanted to raise it. If we still want compound components, I think |
||
| - **`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`) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I love the Did you consider also namespacing these per primitive? Maybe that's not necessary? |
||
| - **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` | ||
|
|
||
| ## 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,45 @@ | ||
| { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this have |
||
| "name": "@clerk/headless", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "type": "module", | ||
| "exports": { | ||
| "./dialog": { | ||
| "import": "./dist/primitives/dialog/index.js", | ||
| "types": "./dist/primitives/dialog/index.d.ts" | ||
| }, | ||
| "./utils": { | ||
| "import": "./dist/utils/index.js", | ||
| "types": "./dist/utils/index.d.ts" | ||
| } | ||
| }, | ||
| "scripts": { | ||
| "build": "rm -rf dist && vite build", | ||
| "dev": "vite build --watch", | ||
| "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,165 @@ | ||
| 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(async () => 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(async () => 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(); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| 'use client'; | ||
|
|
||
| import { type RefObject, useCallback, useEffect, useRef } from 'react'; | ||
| import { flushSync } from 'react-dom'; | ||
|
|
||
| /** | ||
| * Returns a function that waits for all CSS animations/transitions on the | ||
| * referenced element to finish, then invokes a callback. | ||
| * | ||
| * Uses the Web Animations API (`element.getAnimations()` + `animation.finished`) | ||
| * so we're duration-agnostic — CSS owns all timing. | ||
| * | ||
| * When `open` is true, waits for `[data-cl-starting-style]` to be removed | ||
| * before polling animations. This avoids a race where `getAnimations()` returns | ||
| * an empty array before the enter transition has been registered. | ||
| * | ||
| * Each call aborts any pending wait from a previous call, so rapid open/close | ||
| * toggles don't leak stale callbacks. | ||
| */ | ||
| export function useAnimationsFinished(ref: RefObject<HTMLElement | null>, open: boolean) { | ||
| const abortRef = useRef<AbortController | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| return () => { | ||
| abortRef.current?.abort(); | ||
| }; | ||
| }, []); | ||
|
|
||
| return useCallback( | ||
| (callback: () => void) => { | ||
| const element = ref.current; | ||
|
|
||
| abortRef.current?.abort(); | ||
| const controller = new AbortController(); | ||
| abortRef.current = controller; | ||
| const { signal } = controller; | ||
|
|
||
| if (!element || typeof element.getAnimations !== 'function') { | ||
| callback(); | ||
| return; | ||
| } | ||
|
|
||
| const runCheck = () => { | ||
| if (signal.aborted) return; | ||
| const animations = element.getAnimations(); | ||
| if (animations.length === 0) { | ||
| // Called synchronously (from useEffect or MutationObserver) — | ||
| // plain callback is fine, React will batch the state update. | ||
| callback(); | ||
| return; | ||
| } | ||
| Promise.all(animations.map(a => a.finished)) | ||
| .then(() => { | ||
| if (signal.aborted) return; | ||
| // Called from a microtask — flushSync forces synchronous unmount | ||
| // so there's no flash of the element in its final animated state. | ||
| flushSync(callback); | ||
| }) | ||
| .catch(() => { | ||
| if (signal.aborted) return; | ||
| // An animation was cancelled. If new animations are running, wait | ||
| // for those instead; otherwise we're done. | ||
| const current = element.getAnimations(); | ||
| if (current.length > 0) { | ||
| runCheck(); | ||
| } else { | ||
| flushSync(callback); | ||
| } | ||
| }); | ||
| }; | ||
|
|
||
| if (open && element.hasAttribute('data-cl-starting-style')) { | ||
| const observer = new MutationObserver(() => { | ||
| if (!element.hasAttribute('data-cl-starting-style')) { | ||
| observer.disconnect(); | ||
| runCheck(); | ||
| } | ||
| }); | ||
| observer.observe(element, { | ||
| attributes: true, | ||
| attributeFilter: ['data-cl-starting-style'], | ||
| }); | ||
| signal.addEventListener('abort', () => observer.disconnect()); | ||
| return; | ||
| } | ||
|
|
||
| runCheck(); | ||
| }, | ||
| [ref, open], | ||
| ); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure if this would help, or if we even want to have
/headlessas a folder inuiinstead, but did you try adding a/ui/src/headless/tsconfig.jsonwith"jsx": "react-jsx"? I think most tools resolve the nested one?