-
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
Open
alexcarpenter
wants to merge
3
commits into
main
Choose a base branch
from
carp/headless-foundation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| --- | ||
| --- | ||
|
|
||
| Introduce `@clerk/headless` package with Dialog primitive, hooks, and utilities. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
| ## 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 | | ||
|
|
||
| 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.) | ||
| - **`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`) | ||
| - **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. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| { | ||
| "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" | ||
| } | ||
| } |
165 changes: 165 additions & 0 deletions
165
packages/headless/src/hooks/use-animations-finished.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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], | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.