-
Notifications
You must be signed in to change notification settings - Fork 474
feat(headless): add combobox primitive #9702
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5eb6c20
feat(headless): add combobox primitive
austincalvelage 283bb35
refactor(headless): make combobox independent of autocomplete
austincalvelage 873e09c
refactor(headless): remove combobox-specific code from autocomplete
austincalvelage 38c2625
docs(swingset): add combobox primitive page
austincalvelage 5cd0e15
fix(swingset): sort combobox primitive registry import
austincalvelage b1465cd
refactor(headless): keep combobox changes out of autocomplete
austincalvelage e352c8c
fix(headless): correct combobox refs and option cleanup
austincalvelage 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,2 @@ | ||
| --- | ||
| --- |
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
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,38 @@ | ||
| # Combobox | ||
|
|
||
| A headless single-selection input. Typing searches options; choosing one remembers its value. | ||
|
|
||
| ```tsx | ||
| import { Combobox } from '@clerk/headless/combobox'; | ||
|
|
||
| <Combobox.Root> | ||
| <Combobox.Input aria-label='Fruit' /> | ||
| <Combobox.Trigger aria-label='Show fruits' /> | ||
| <Combobox.Positioner> | ||
| <Combobox.Popup> | ||
| <Combobox.Collection | ||
| items={['Apple', 'Banana']} | ||
| itemToStringLabel={item => item} | ||
| > | ||
| {item => ( | ||
| <Combobox.Option | ||
| key={item} | ||
| value={item} | ||
| > | ||
| {item} | ||
| <Combobox.OptionIndicator>✓</Combobox.OptionIndicator> | ||
| </Combobox.Option> | ||
| )} | ||
| </Combobox.Collection> | ||
| </Combobox.Popup> | ||
| </Combobox.Positioner> | ||
| </Combobox.Root>; | ||
| ``` | ||
|
|
||
| `value`, `defaultValue`, and `onValueChange` control the selected option. Clearing the input clears selection with `null`. `inputValue`, `defaultInputValue`, and `onInputValueChange` control search text separately. | ||
|
|
||
| Dismissal restores the selected label. Reopening shows all options until typing starts. Hover and keyboard highlighting do not change selection. | ||
|
|
||
| For search inside another popup, use `inline` with `List` and bind `open` to the outer popup. Closing clears search without clearing selection. Supply `defaultInputValue` when an initial selection's label differs from its value. | ||
|
|
||
| Combobox owns its selection state and rendering parts independently of Autocomplete. Both use general headless utilities for rendering, controllable state, and transitions. Mosaic adds styling separately. |
23 changes: 23 additions & 0 deletions
23
packages/headless/src/primitives/combobox/combobox-arrow.tsx
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,23 @@ | ||
| 'use client'; | ||
|
|
||
| import { FloatingArrow, useMergeRefs } from '@floating-ui/react'; | ||
| import React from 'react'; | ||
|
|
||
| import { useComboboxContext } from './combobox-context'; | ||
|
|
||
| export type ComboboxArrowProps = Omit<React.ComponentPropsWithoutRef<typeof FloatingArrow>, 'context'>; | ||
|
|
||
| export const ComboboxArrow = React.forwardRef<SVGSVGElement, ComboboxArrowProps>(function ComboboxArrow(props, ref) { | ||
| const { floatingContext, arrowRef, placement } = useComboboxContext(); | ||
| const mergedRef = useMergeRefs([arrowRef, ref]); | ||
| const side = placement.split('-')[0]; | ||
|
|
||
| return ( | ||
| <FloatingArrow | ||
| data-side={side} | ||
| {...props} | ||
| ref={mergedRef} | ||
| context={floatingContext} | ||
| /> | ||
| ); | ||
| }); |
20 changes: 20 additions & 0 deletions
20
packages/headless/src/primitives/combobox/combobox-collection.tsx
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,20 @@ | ||
| 'use client'; | ||
|
|
||
| import type { ReactNode } from 'react'; | ||
|
|
||
| import { useComboboxContext } from './combobox-context'; | ||
|
|
||
| export interface ComboboxCollectionProps<Item> { | ||
| items: readonly Item[]; | ||
| itemToStringLabel: (item: Item) => string; | ||
| children: (item: Item) => ReactNode; | ||
| empty?: ReactNode; | ||
| } | ||
|
|
||
| /** Filters items using the search query rather than the selected label. */ | ||
| export function ComboboxCollection<Item>({ items, itemToStringLabel, children, empty }: ComboboxCollectionProps<Item>) { | ||
| const { filterQuery } = useComboboxContext(); | ||
| const query = filterQuery.trim().toLocaleLowerCase(); | ||
| const filtered = query ? items.filter(item => itemToStringLabel(item).toLocaleLowerCase().includes(query)) : items; | ||
| return <>{filtered.length ? filtered.map(children) : empty}</>; | ||
| } |
51 changes: 51 additions & 0 deletions
51
packages/headless/src/primitives/combobox/combobox-context.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,51 @@ | ||
| import type { | ||
| ExtendedRefs, | ||
| FloatingContext, | ||
| Placement, | ||
| ReferenceType, | ||
| UseInteractionsReturn, | ||
| } from '@floating-ui/react'; | ||
| import { createContext, type CSSProperties, useContext } from 'react'; | ||
|
|
||
| import type { TransitionProps } from '../../hooks/use-transition'; | ||
|
|
||
| export interface ComboboxContextValue { | ||
| open: boolean; | ||
| inputValue: string; | ||
| filterQuery: string; | ||
| selectedValue: string | null; | ||
| floatingContext: FloatingContext; | ||
| refs: ExtendedRefs<ReferenceType>; | ||
| floatingStyles: CSSProperties; | ||
| placement: Placement; | ||
| getReferenceProps: UseInteractionsReturn['getReferenceProps']; | ||
| getFloatingProps: UseInteractionsReturn['getFloatingProps']; | ||
| getItemProps: UseInteractionsReturn['getItemProps']; | ||
| activeIndex: number | null; | ||
| selectedIndex: number | null; | ||
| elementsRef: React.MutableRefObject<Array<HTMLElement | null>>; | ||
| labelsRef: React.MutableRefObject<Array<string | null>>; | ||
| popupRef: React.RefObject<HTMLDivElement | null>; | ||
| triggerRef: React.MutableRefObject<HTMLButtonElement | null>; | ||
| arrowRef: React.MutableRefObject<SVGSVGElement | null>; | ||
| valuesByIndexRef: React.MutableRefObject<Map<number, string>>; | ||
| setInlineMode: React.Dispatch<React.SetStateAction<boolean>>; | ||
| handleSelect: (value: string, index: number, label: string) => void; | ||
| handleInputChange: (value: string) => void; | ||
| setOpen: (open: boolean) => void; | ||
| focusInput: () => void; | ||
| popupId: string | undefined; | ||
| registerSelectedIndex: (index: number, value: string, label: string) => (() => void) | undefined; | ||
| mounted: boolean; | ||
| transitionProps: TransitionProps; | ||
| } | ||
|
|
||
| export const ComboboxContext = createContext<ComboboxContextValue | null>(null); | ||
|
|
||
| export function useComboboxContext() { | ||
| const ctx = useContext(ComboboxContext); | ||
| if (!ctx) { | ||
| throw new Error('Combobox compound components must be used within <Combobox>'); | ||
| } | ||
| return ctx; | ||
| } |
60 changes: 60 additions & 0 deletions
60
packages/headless/src/primitives/combobox/combobox-input.tsx
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,60 @@ | ||
| 'use client'; | ||
|
|
||
| import React from 'react'; | ||
|
|
||
| import { type ComponentProps, mergeProps, useRender } from '../../utils'; | ||
| import { useComboboxContext } from './combobox-context'; | ||
|
|
||
| export type ComboboxInputProps = ComponentProps<'input'>; | ||
|
|
||
| export const ComboboxInput = React.forwardRef<HTMLInputElement, ComboboxInputProps>(function ComboboxInput(props, ref) { | ||
| const { render, ...otherProps } = props; | ||
| const { | ||
| open, | ||
| inputValue, | ||
| activeIndex, | ||
| refs, | ||
| getReferenceProps, | ||
| handleInputChange, | ||
| handleSelect, | ||
| labelsRef, | ||
| valuesByIndexRef, | ||
| } = useComboboxContext(); | ||
|
|
||
| const state = { open }; | ||
|
|
||
| const defaultProps = { | ||
| ...getReferenceProps({ | ||
| value: inputValue, | ||
| 'aria-autocomplete': 'list' as const, | ||
| onChange(event: React.ChangeEvent<HTMLInputElement>) { | ||
| handleInputChange(event.target.value); | ||
| }, | ||
| onKeyDown(event: React.KeyboardEvent<HTMLInputElement>) { | ||
| if (event.key === 'Enter' && activeIndex != null) { | ||
| const value = valuesByIndexRef.current.get(activeIndex); | ||
| const label = labelsRef.current[activeIndex]; | ||
| if (value != null) { | ||
| event.preventDefault(); | ||
| handleSelect(value, activeIndex, label ?? value); | ||
| } | ||
| } | ||
| }, | ||
| }), | ||
| }; | ||
|
|
||
| return useRender({ | ||
| defaultTagName: 'input', | ||
| render, | ||
| // floating-ui types `setReference` as a method signature, but at runtime it's | ||
| // a stable callback that doesn't use `this`, so the unbound-method check is a | ||
| // false positive here. | ||
| // eslint-disable-next-line @typescript-eslint/unbound-method | ||
| ref: [refs.setReference, ref], | ||
| state, | ||
| stateAttributesMapping: { | ||
| open: (v: boolean): Record<string, string> | null => (v ? { 'data-open': '' } : { 'data-closed': '' }), | ||
| }, | ||
| props: mergeProps<'input'>(defaultProps, otherProps), | ||
| }); | ||
| }); |
51 changes: 51 additions & 0 deletions
51
packages/headless/src/primitives/combobox/combobox-list.tsx
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,51 @@ | ||
| 'use client'; | ||
|
|
||
| import { FloatingList } from '@floating-ui/react'; | ||
| import React, { useEffect } from 'react'; | ||
|
|
||
| import { type ComponentProps, type DefaultProps, mergeProps, useRender } from '../../utils'; | ||
| import { useComboboxContext } from './combobox-context'; | ||
|
|
||
| export type ComboboxListProps = ComponentProps<'div'>; | ||
|
|
||
| export const ComboboxList = React.forwardRef<HTMLDivElement, ComboboxListProps>(function ComboboxList(props, ref) { | ||
| const { render, ...otherProps } = props; | ||
| const { elementsRef, labelsRef, refs, getFloatingProps, setInlineMode } = useComboboxContext(); | ||
|
|
||
| useEffect(() => { | ||
| setInlineMode(true); | ||
| return () => setInlineMode(false); | ||
| }, [setInlineMode]); | ||
|
|
||
| const floatingProps = getFloatingProps(); | ||
| const wiredId = floatingProps.id; | ||
|
|
||
| const ownProps = {} satisfies DefaultProps<'div'>; | ||
|
|
||
| const defaultProps = { ...ownProps, ...floatingProps }; | ||
|
|
||
| const merged = mergeProps<'div'>(defaultProps, otherProps); | ||
| // The wired id is owned by the primitive: a consumer-supplied id must not | ||
| // override it, or the aria-controls pairing would silently break. | ||
| if (wiredId != null) { | ||
| merged.id = wiredId; | ||
| } | ||
|
|
||
| return ( | ||
| <FloatingList | ||
| elementsRef={elementsRef} | ||
| labelsRef={labelsRef} | ||
| > | ||
| {useRender({ | ||
| defaultTagName: 'div', | ||
| render, | ||
| // floating-ui types `setFloating` as a method signature, but at runtime it's | ||
| // a stable callback that doesn't use `this`, so the unbound-method check is a | ||
| // false positive here. | ||
| // eslint-disable-next-line @typescript-eslint/unbound-method | ||
| ref: [refs.setFloating, ref], | ||
| props: merged, | ||
| })} | ||
| </FloatingList> | ||
| ); | ||
| }); |
3 changes: 3 additions & 0 deletions
3
packages/headless/src/primitives/combobox/combobox-option-context.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,3 @@ | ||
| import { createContext } from 'react'; | ||
|
|
||
| export const ComboboxOptionContext = createContext<boolean | null>(null); |
24 changes: 24 additions & 0 deletions
24
packages/headless/src/primitives/combobox/combobox-option-indicator.tsx
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,24 @@ | ||
| 'use client'; | ||
|
|
||
| import React, { useContext } from 'react'; | ||
|
|
||
| import { type ComponentProps, mergeProps, useRender } from '../../utils'; | ||
| import { ComboboxOptionContext } from './combobox-option-context'; | ||
|
|
||
| export type ComboboxOptionIndicatorProps = ComponentProps<'span'>; | ||
|
|
||
| export const ComboboxOptionIndicator = React.forwardRef<HTMLSpanElement, ComboboxOptionIndicatorProps>( | ||
| function ComboboxOptionIndicator({ render, ...props }, ref) { | ||
| const selected = useContext(ComboboxOptionContext); | ||
| if (selected === null) { | ||
| throw new Error('Combobox.OptionIndicator must be used within Combobox.Option'); | ||
| } | ||
| return useRender({ | ||
| defaultTagName: 'span', | ||
| render, | ||
| ref, | ||
| enabled: selected, | ||
| props: mergeProps<'span'>({ 'aria-hidden': true }, props), | ||
| }); | ||
| }, | ||
| ); | ||
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.
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.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: clerk/javascript
Length of output: 6435
🏁 Script executed:
Repository: clerk/javascript
Length of output: 16284
🏁 Script executed:
Repository: clerk/javascript
Length of output: 2738
🏁 Script executed:
Repository: clerk/javascript
Length of output: 22064
🏁 Script executed:
Repository: clerk/javascript
Length of output: 2692
Call
useRenderbefore the context guard.useRenderis a hook and callsuseMergeRefs. The current guard skips both hooks whenselected === null, which violates the hook's unconditional-call contract.♻️ Proposed reorder
🤖 Prompt for AI Agents
Source: Coding guidelines