Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions packages/headless/README.md
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.
75 changes: 75 additions & 0 deletions packages/headless/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"name": "@clerk/headless",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
"./select": {
"import": "./dist/primitives/select/index.js",
"types": "./dist/primitives/select/index.d.ts"
},
"./menu": {
"import": "./dist/primitives/menu/index.js",
"types": "./dist/primitives/menu/index.d.ts"
},
"./dialog": {
"import": "./dist/primitives/dialog/index.js",
"types": "./dist/primitives/dialog/index.d.ts"
},
"./popover": {
"import": "./dist/primitives/popover/index.js",
"types": "./dist/primitives/popover/index.d.ts"
},
"./tooltip": {
"import": "./dist/primitives/tooltip/index.js",
"types": "./dist/primitives/tooltip/index.d.ts"
},
"./autocomplete": {
"import": "./dist/primitives/autocomplete/index.js",
"types": "./dist/primitives/autocomplete/index.d.ts"
},
"./tabs": {
"import": "./dist/primitives/tabs/index.js",
"types": "./dist/primitives/tabs/index.d.ts"
},
"./accordion": {
"import": "./dist/primitives/accordion/index.js",
"types": "./dist/primitives/accordion/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",
"@vitest/browser": "4.1.4",
"@vitest/browser-playwright": "4.1.4",
"axe-core": "^4.11.3",
"playwright": "^1.59.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 packages/headless/src/hooks/use-animations-finished.test.ts
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();
});
});
91 changes: 91 additions & 0 deletions packages/headless/src/hooks/use-animations-finished.ts
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],
);
}
Loading
Loading