- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
This release adds Popover, migrates Select, Separator, Badge, Avatar, Accordion, Collapsible, Breadcrumb, and Input OTP off radix-ui and input-otp, ships first-party Button Group, and standardizes the polymorphic as prop across Button, Badge, Collapsible, Breadcrumb, and Button Group Text.
- Popover: Floating panel anchored to a trigger.
- Select: Floating UI listbox with item-aligned and popper modes.
- Badge: Smaller height,
asprop,iconOnlymode. - Avatar: Own primitive, destructive error fallback, soft destructive token.
- Button
asprop: Render router links and custom components. asprop rollout: RemovesasChildfrom Badge and Collapsible Trigger, addsasto Button Group Text.- Separator: No more
radix-ui. - Button Group: Own primitive replaces the Radix Slot.
- Native Separator & Button Group: Native ports.
Popover
"use client";
import {
autoUpdate,
flip,
offset,
shift,
useFloating,
} from "@floating-ui/react-dom";
import * as React from "react";
import { createPortal } from "react-dom";
import { getTransition, parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
const defaultPopoverMotion = "150 cubic-bezier(0.16, 1, 0.3, 1)";
function useControllableState<T>({
prop,
defaultProp,
onChange,
}: {
prop: T | undefined;
defaultProp: T;
onChange?: (value: T) => void;
}): [T, (next: T | ((prev: T) => T)) => void] {
const [uncontrolled, setUncontrolled] = React.useState<T>(defaultProp);
const isControlled = prop !== undefined;
const value = isControlled ? prop : uncontrolled;
const onChangeRef = React.useRef(onChange);
onChangeRef.current = onChange;
const setValue = React.useCallback(
(next: T | ((prev: T) => T)) => {
const resolved =
typeof next === "function"
? (next as (prev: T) => T)(isControlled ? (prop as T) : uncontrolled)
: next;
if (!isControlled) {
setUncontrolled(resolved);
}
onChangeRef.current?.(resolved);
},
[isControlled, prop, uncontrolled]
);
return [value, setValue];
}
function setRef<T>(ref: React.Ref<T> | undefined, node: T | null) {
if (!ref) {
return;
}
if (typeof ref === "function") {
ref(node);
} else {
(ref as React.MutableRefObject<T | null>).current = node;
}
}
function useComposedRefs<T>(...refs: Array<React.Ref<T> | undefined>) {
const refsRef = React.useRef(refs);
refsRef.current = refs;
return React.useCallback((node: T | null) => {
for (const ref of refsRef.current) {
setRef(ref, node);
}
}, []);
}
function composeEventHandlers<E extends { defaultPrevented: boolean }>(
theirHandler: ((event: E) => void) | undefined,
ourHandler: (event: E) => void
) {
return (event: E) => {
theirHandler?.(event);
if (!event.defaultPrevented) {
ourHandler(event);
}
};
}
interface PopoverContextValue {
anchor: HTMLElement | null;
contentId: string;
descriptionId: string;
descriptionPresent: boolean;
onOpenChange: (open: boolean) => void;
onOpenToggle: () => void;
open: boolean;
setAnchor: (node: HTMLElement | null) => void;
setDescriptionCount: React.Dispatch<React.SetStateAction<number>>;
setTitleCount: React.Dispatch<React.SetStateAction<number>>;
titleId: string;
titlePresent: boolean;
}
const PopoverContext = React.createContext<PopoverContextValue | null>(null);
function usePopoverContext(component: string): PopoverContextValue {
const ctx = React.useContext(PopoverContext);
if (!ctx) {
throw new Error(`${component} must be used within Popover`);
}
return ctx;
}
export interface PopoverProps {
children?: React.ReactNode;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
open?: boolean;
}
function Popover({
children,
open: openProp,
defaultOpen,
onOpenChange,
}: PopoverProps) {
const [anchor, setAnchor] = React.useState<HTMLElement | null>(null);
const [titleCount, setTitleCount] = React.useState(0);
const [descriptionCount, setDescriptionCount] = React.useState(0);
const [open, setOpen] = useControllableState({
defaultProp: defaultOpen ?? false,
onChange: onOpenChange,
prop: openProp,
});
const contentId = React.useId();
const titleId = React.useId();
const descriptionId = React.useId();
const context = React.useMemo<PopoverContextValue>(
() => ({
anchor,
contentId,
descriptionId,
descriptionPresent: descriptionCount > 0,
onOpenChange: setOpen,
onOpenToggle: () => setOpen((prev) => !prev),
open,
setAnchor,
setDescriptionCount,
setTitleCount,
titleId,
titlePresent: titleCount > 0,
}),
[
anchor,
contentId,
descriptionCount,
descriptionId,
open,
setOpen,
titleCount,
titleId,
]
);
return (
<PopoverContext.Provider value={context}>
{children}
</PopoverContext.Provider>
);
}
export type PopoverTriggerProps = Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
"ref"
> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
} & Record<string, unknown>;
function PopoverTrigger({ as, onClick, ref, ...props }: PopoverTriggerProps) {
const { open, contentId, onOpenToggle, setAnchor } =
usePopoverContext("PopoverTrigger");
const composedRef = useComposedRefs<HTMLButtonElement>(
ref as React.Ref<HTMLButtonElement> | undefined,
setAnchor as unknown as React.Ref<HTMLButtonElement>
);
const Component = as ?? "button";
const finalProps: Record<string, unknown> = {
...props,
"aria-controls": open ? contentId : undefined,
"aria-expanded": open,
"aria-haspopup": "dialog",
"data-state": open ? "open" : "closed",
onClick: composeEventHandlers(onClick, onOpenToggle),
ref: composedRef,
};
if (!(as || "type" in props)) {
finalProps.type = "button";
}
return React.createElement(Component, finalProps);
}
function useDismissablePopover({
open,
contentRef,
anchor,
onDismiss,
}: {
open: boolean;
contentRef: React.RefObject<HTMLElement | null>;
anchor: HTMLElement | null;
onDismiss: () => void;
}) {
React.useEffect(() => {
if (!open) {
return;
}
const ownerDocument = contentRef.current?.ownerDocument ?? document;
let isPointerInsideReactTree = false;
const handlePointerDown = (event: PointerEvent) => {
if (event.target && !isPointerInsideReactTree) {
const target = event.target as Node;
if (contentRef.current?.contains(target)) {
isPointerInsideReactTree = false;
return;
}
if (anchor?.contains(target)) {
isPointerInsideReactTree = false;
return;
}
onDismiss();
}
isPointerInsideReactTree = false;
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape") {
return;
}
if (event.isComposing || event.keyCode === 229) {
return;
}
event.preventDefault();
onDismiss();
};
ownerDocument.addEventListener("pointerdown", handlePointerDown);
ownerDocument.addEventListener("keydown", handleKeyDown, { capture: true });
return () => {
ownerDocument.removeEventListener("pointerdown", handlePointerDown);
ownerDocument.removeEventListener("keydown", handleKeyDown, {
capture: true,
});
};
}, [open, contentRef, anchor, onDismiss]);
}
export interface PopoverContentProps extends React.ComponentProps<"div"> {
align?: "start" | "center" | "end";
alignOffset?: number;
avoidCollisions?: boolean;
motion?: string;
side?: "top" | "right" | "bottom" | "left";
sideOffset?: number;
}
function PopoverContent({
align = "center",
alignOffset = 0,
avoidCollisions = true,
className,
motion,
side = "bottom",
sideOffset = 4,
style,
...props
}: PopoverContentProps) {
const {
anchor,
contentId,
descriptionId,
descriptionPresent,
onOpenChange,
open,
titleId,
titlePresent,
} = usePopoverContext("PopoverContent");
const contentRef = React.useRef<HTMLDivElement>(null);
const [present, setPresent] = React.useState(open);
const exitTimerRef = React.useRef<number | undefined>(undefined);
const { floatingStyles, isPositioned, placement, refs } = useFloating({
elements: { reference: anchor },
middleware: [
offset({ alignmentAxis: alignOffset, mainAxis: sideOffset }),
avoidCollisions && shift({ padding: 0 }),
avoidCollisions && flip(),
],
placement: `${side}${align === "center" ? "" : `-${align}`}` as never,
strategy: "fixed",
whileElementsMounted: autoUpdate,
});
const [entered, setEntered] = React.useState(false);
React.useEffect(() => {
if (!open) {
setEntered(false);
return;
}
if (!isPositioned) {
return;
}
let id2: number | undefined;
const id1 = requestAnimationFrame(() => {
id2 = requestAnimationFrame(() => setEntered(true));
});
return () => {
cancelAnimationFrame(id1);
if (id2 !== undefined) {
cancelAnimationFrame(id2);
}
};
}, [open, isPositioned]);
React.useEffect(
() => () => {
if (exitTimerRef.current !== undefined) {
window.clearTimeout(exitTimerRef.current);
}
},
[]
);
const reduce = useReducedMotion();
const motionValue = motion ?? defaultPopoverMotion;
const motionTransition =
reduce || motion === "off"
? "none"
: getTransition(parseMotion(motionValue));
React.useEffect(() => {
if (open) {
if (exitTimerRef.current !== undefined) {
window.clearTimeout(exitTimerRef.current);
exitTimerRef.current = undefined;
}
setPresent(true);
return;
}
if (!present) {
return;
}
const parsed = reduce || motion === "off" ? null : parseMotion(motionValue);
const duration = parsed && !parsed.disabled ? parsed.duration : 0;
exitTimerRef.current = window.setTimeout(() => {
setPresent(false);
exitTimerRef.current = undefined;
}, duration + 50);
}, [open, present, reduce, motion, motionValue]);
useDismissablePopover({
anchor,
contentRef,
onDismiss: () => onOpenChange(false),
open,
});
React.useEffect(() => {
if (!open) {
return;
}
const content = contentRef.current;
if (!content) {
return;
}
const previousFocus = document.activeElement as HTMLElement | null;
const focusable = content.querySelector<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
if (focusable) {
focusable.focus({ preventScroll: true });
}
return () => {
if (previousFocus?.focus) {
previousFocus.focus({ preventScroll: true });
}
};
}, [open]);
if (!present) {
return null;
}
const [placedSide, placedAlign = "center"] = placement.split("-");
const originBySide: Record<string, string> = {
bottom: "top center",
left: "center right",
right: "center left",
top: "bottom center",
};
const innerStyle: React.CSSProperties = {
opacity: entered ? 1 : 0,
transform: entered ? "scale(1)" : "scale(0.95)",
transformOrigin: originBySide[placedSide] ?? "center",
transition: motionTransition ?? "none",
...style,
};
const node = (
<div
data-popper-wrapper=""
ref={refs.setFloating}
style={{
...floatingStyles,
minWidth: "max-content",
transform: isPositioned
? floatingStyles.transform
: "translate(0, -200%)",
}}
>
<div
aria-describedby={descriptionPresent ? descriptionId : undefined}
aria-labelledby={titlePresent ? titleId : undefined}
data-align={placedAlign}
data-side={placedSide}
data-slot="popover-content"
data-state={open ? "open" : "closed"}
id={contentId}
ref={contentRef}
role="dialog"
style={innerStyle}
{...props}
className={cn(
"bg-popover text-popover-foreground z-50 w-72 rounded-md border p-4 shadow-md outline-none",
className
)}
/>
</div>
);
return createPortal(node, document.body);
}
function PopoverHeader({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("flex flex-col gap-1.5", className)} {...props} />;
}
function PopoverTitle({
className,
...props
}: React.HTMLAttributes<HTMLHeadingElement>) {
const { setTitleCount, titleId } = usePopoverContext("PopoverTitle");
React.useEffect(() => {
setTitleCount((count) => count + 1);
return () => setTitleCount((count) => count - 1);
}, [setTitleCount]);
return (
<h2
className={cn("leading-none font-medium", className)}
id={titleId}
{...props}
/>
);
}
function PopoverDescription({
className,
...props
}: React.HTMLAttributes<HTMLParagraphElement>) {
const { setDescriptionCount, descriptionId } =
usePopoverContext("PopoverDescription");
React.useEffect(() => {
setDescriptionCount((count) => count + 1);
return () => setDescriptionCount((count) => count - 1);
}, [setDescriptionCount]);
return (
<p
className={cn("text-muted-foreground text-sm", className)}
id={descriptionId}
{...props}
/>
);
}
export type PopoverCloseProps = Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
"ref"
> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
} & Record<string, unknown>;
function PopoverClose({ as, onClick, ref, ...props }: PopoverCloseProps) {
const { onOpenChange } = usePopoverContext("PopoverClose");
const Component = as ?? "button";
const finalProps: Record<string, unknown> = {
...props,
onClick: composeEventHandlers(onClick, () => onOpenChange(false)),
ref,
};
if (!(as || "type" in props)) {
finalProps.type = "button";
}
return React.createElement(Component, finalProps);
}
export {
Popover,
PopoverClose,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
};Popover renders a floating panel anchored to a trigger. Position is resolved with Floating UI, so the panel flips and shifts automatically when it would overflow the viewport. Opens on trigger click, closes on outside click or Escape. Non-modal: focus returns to the trigger, no focus trap. PopoverHeader, PopoverTitle, and PopoverDescription wire aria-labelledby and aria-describedby for you.
Installation
Install
$ bunx --bun frakment add popover$ npx frakment add popover$ pnpm dlx frakment add popover$ yarn dlx frakment add popover
Use it
import { Button } from "@/components/ui/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";Minimal usage
<Popover>
<PopoverTrigger as={Button} variant="outline">Open</PopoverTrigger>
<PopoverContent>Content</PopoverContent>
</Popover>See the Popover docs for the full API reference.
Button as prop
< ButtonDemo />
Button accepts as to render a different root element or component. Pass as={Link} for router links, as={CustomComponent} for a wrapped surface, or omit to keep the default <button> / <a> behavior based on href.
import Link from "next/link";
import { Button } from "@/components/ui/button";
<Button as={Link} href="/pricing" variant="outline">Pricing</Button>No API breaking changes. href and onClick continue to work as before. See the Button docs for the updated router link guidance.
Separator
< SeparatorDemo />
Separator no longer depends on radix-ui. It renders as a div with role="none" by default, or role="separator" with aria-orientation when decorative={false}.
Changed:
- Removed
radix-uifromdependencies. No npm install needed. decorativeprop now controlsroledirectly.
No API breaking changes. See the Separator docs.
Button Group
< ButtonGroupDemo />
Button Group now uses Frakment's own Slot primitive instead of the Radix Slot. All ten compositions (dropdown, input, input group, nested, select, separator, split, size, orientation, demo) continue to work without changes.
Changed:
- Removed
radix-uifromdependencies. - New
registryDependency:slot.
See the Button Group docs.
Select
"use client";
import {
autoUpdate,
flip,
offset,
shift,
size as sizeMiddleware,
useFloating,
} from "@floating-ui/react-dom";
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import * as React from "react";
import { createPortal } from "react-dom";
import { getTransition, parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
const defaultSelectMotion = "150 cubic-bezier(0.16, 1, 0.3, 1)";
const contentMargin = 10;
const openKeys = [" ", "Enter", "ArrowUp", "ArrowDown"];
const selectionKeys = [" ", "Enter"];
function composeEventHandlers<E extends { defaultPrevented: boolean }>(
theirHandler: ((event: E) => void) | undefined,
ourHandler: (event: E) => void
) {
return (event: E) => {
theirHandler?.(event);
if (!event.defaultPrevented) {
ourHandler(event);
}
};
}
function setRef<T>(ref: React.Ref<T> | undefined, node: T | null) {
if (!ref) {
return;
}
if (typeof ref === "function") {
ref(node);
} else {
(ref as React.MutableRefObject<T | null>).current = node;
}
}
function useComposedRefs<T>(...refs: Array<React.Ref<T> | undefined>) {
const refsRef = React.useRef(refs);
refsRef.current = refs;
return React.useCallback((node: T | null) => {
for (const ref of refsRef.current) {
setRef(ref, node);
}
}, []);
}
function useCallbackRef<T extends (...args: never[]) => unknown>(
callback: T | undefined
): T {
const ref = React.useRef(callback);
React.useEffect(() => {
ref.current = callback;
});
return React.useCallback(((...args) => ref.current?.(...args)) as T, []);
}
function useControllableState<T>({
prop,
defaultProp,
onChange,
}: {
prop: T | undefined;
defaultProp: T;
onChange?: ((value: T) => void) | undefined;
}): [T, (next: T | ((prev: T) => T)) => void] {
const [uncontrolled, setUncontrolled] = React.useState<T>(defaultProp);
const isControlled = prop !== undefined;
const value = isControlled ? prop : uncontrolled;
const onChangeRef = React.useRef(onChange);
onChangeRef.current = onChange;
const setValue = React.useCallback(
(next: T | ((prev: T) => T)) => {
const resolved =
typeof next === "function"
? (next as (prev: T) => T)(isControlled ? (prop as T) : uncontrolled)
: next;
if (!isControlled) {
setUncontrolled(resolved);
}
onChangeRef.current?.(resolved);
},
[isControlled, prop, uncontrolled]
);
return [value, setValue];
}
const visuallyHiddenStyles: React.CSSProperties = {
border: 0,
clip: "rect(0, 0, 0, 0)",
height: 1,
margin: -1,
overflow: "hidden",
padding: 0,
position: "absolute",
whiteSpace: "nowrap",
width: 1,
wordWrap: "normal",
};
function useTypeaheadSearch(onSearchChange: (search: string) => void) {
const handleSearchChange = useCallbackRef(onSearchChange);
const searchRef = React.useRef("");
const timerRef = React.useRef(0);
const handleTypeaheadSearch = React.useCallback(
(key: string) => {
const search = searchRef.current + key;
handleSearchChange(search);
const updateSearch = (value: string) => {
searchRef.current = value;
window.clearTimeout(timerRef.current);
if (value !== "") {
timerRef.current = window.setTimeout(() => updateSearch(""), 1000);
}
};
updateSearch(search);
},
[handleSearchChange]
);
const resetTypeahead = React.useCallback(() => {
searchRef.current = "";
window.clearTimeout(timerRef.current);
}, []);
React.useEffect(() => () => window.clearTimeout(timerRef.current), []);
return [searchRef, handleTypeaheadSearch, resetTypeahead] as const;
}
function wrapArray<T>(array: T[], startIndex: number) {
return array.map<T>((_, i) => array[(startIndex + i) % array.length] as T);
}
function findNextItem<T extends { textValue: string }>(
items: T[],
search: string,
currentItem?: T
) {
const isRepeated =
search.length > 1 && Array.from(search).every((c) => c === search[0]);
const normalizedSearch = isRepeated ? (search[0] as string) : search;
const currentItemIndex = currentItem ? items.indexOf(currentItem) : -1;
let wrappedItems = wrapArray(items, Math.max(currentItemIndex, 0));
if (normalizedSearch.length === 1) {
wrappedItems = wrappedItems.filter((v) => v !== currentItem);
}
const nextItem = wrappedItems.find((item) =>
item.textValue.toLowerCase().startsWith(normalizedSearch.toLowerCase())
);
return nextItem === currentItem ? undefined : nextItem;
}
function shouldShowPlaceholder(value?: string) {
return value === "" || value === undefined;
}
function getOpenState(open: boolean) {
return open ? "open" : "closed";
}
interface SelectContextValue {
autoComplete: string | undefined;
contentId: string;
disabled: boolean;
form: string | undefined;
isFormControl: boolean;
name: string | undefined;
nativeOptions: Set<React.ReactElement<React.ComponentProps<"option">>>;
nativeSelectKey: string;
onNativeOptionAdd: (
option: React.ReactElement<React.ComponentProps<"option">>
) => void;
onNativeOptionRemove: (
option: React.ReactElement<React.ComponentProps<"option">>
) => void;
onOpenChange: (open: boolean) => void;
onTriggerChange: (node: HTMLButtonElement | null) => void;
onValueChange: (value: string) => void;
onValueNodeChange: (node: HTMLSpanElement | null) => void;
onValueNodeHasChildrenChange: (hasChildren: boolean) => void;
open: boolean;
required: boolean;
trigger: HTMLButtonElement | null;
triggerPointerDownPosRef: React.MutableRefObject<{
x: number;
y: number;
} | null>;
value: string | undefined;
valueNode: HTMLSpanElement | null;
valueNodeHasChildren: boolean;
}
const SelectContext = React.createContext<SelectContextValue | null>(null);
function useSelectContext(component: string): SelectContextValue {
const ctx = React.useContext(SelectContext);
if (!ctx) {
throw new Error(`${component} must be used within Select`);
}
return ctx;
}
interface ItemData {
disabled: boolean;
ref: React.RefObject<HTMLDivElement | null>;
textValue: string;
value: string;
}
const ItemsContext = React.createContext<{
registerItem: (value: string, data: ItemData) => void;
unregisterItem: (value: string) => void;
getItems: () => ItemData[];
} | null>(null);
function useItemsContext(component: string) {
const ctx = React.useContext(ItemsContext);
if (!ctx) {
throw new Error(`${component} must be used within Select`);
}
return ctx;
}
export interface SelectProps {
autoComplete?: string;
children?: React.ReactNode;
defaultOpen?: boolean;
defaultValue?: string;
disabled?: boolean;
form?: string;
name?: string;
onOpenChange?: (open: boolean) => void;
onValueChange?: (value: string) => void;
open?: boolean;
required?: boolean;
value?: string;
}
function Select({
children,
open: openProp,
defaultOpen,
onOpenChange,
value: valueProp,
defaultValue,
onValueChange,
disabled = false,
required = false,
name,
form,
autoComplete,
}: SelectProps) {
const [trigger, setTrigger] = React.useState<HTMLButtonElement | null>(null);
const [valueNode, setValueNode] = React.useState<HTMLSpanElement | null>(
null
);
const [valueNodeHasChildren, setValueNodeHasChildren] = React.useState(false);
const [open, setOpen] = useControllableState({
defaultProp: defaultOpen ?? false,
onChange: onOpenChange,
prop: openProp,
});
const [internalValue, setInternalValue] = React.useState<string | undefined>(
defaultValue
);
const value = valueProp === undefined ? internalValue : valueProp;
const triggerPointerDownPosRef = React.useRef<{
x: number;
y: number;
} | null>(null);
const [nativeOptionsSet, setNativeOptionsSet] = React.useState<
Set<React.ReactElement<React.ComponentProps<"option">>>
>(new Set());
const itemsMap = React.useRef(new Map<string, ItemData>());
const contentId = React.useId();
const handleValueChange = React.useCallback(
(next: string) => {
if (valueProp === undefined) {
setInternalValue(next);
}
onValueChange?.(next);
},
[valueProp, onValueChange]
);
const initialValueRef = React.useRef(value);
React.useEffect(() => {
const associatedForm = form
? trigger?.ownerDocument.getElementById(form)
: trigger?.form;
if (associatedForm instanceof HTMLFormElement) {
const reset = () => setInternalValue(initialValueRef.current);
associatedForm.addEventListener("reset", reset);
return () => associatedForm.removeEventListener("reset", reset);
}
}, [form, trigger]);
const isFormControl = trigger ? !!form || !!trigger.closest("form") : true;
const nativeSelectKey = Array.from(nativeOptionsSet)
.map((option) => option.props.value)
.join(";");
const onNativeOptionAdd = React.useCallback(
(option: React.ReactElement<React.ComponentProps<"option">>) => {
setNativeOptionsSet((prev) => {
if (prev.has(option)) {
return prev;
}
const next = new Set(prev);
next.add(option);
return next;
});
},
[]
);
const onNativeOptionRemove = React.useCallback(
(option: React.ReactElement<React.ComponentProps<"option">>) => {
setNativeOptionsSet((prev) => {
if (!prev.has(option)) {
return prev;
}
const next = new Set(prev);
next.delete(option);
return next;
});
},
[]
);
const itemsApi = React.useMemo(
() => ({
getItems: () => Array.from(itemsMap.current.values()),
registerItem: (v: string, data: ItemData) => {
itemsMap.current.set(v, data);
},
unregisterItem: (v: string) => {
itemsMap.current.delete(v);
},
}),
[]
);
const ctx = React.useMemo<SelectContextValue>(
() => ({
autoComplete,
contentId,
disabled,
form,
isFormControl,
name,
nativeOptions: nativeOptionsSet,
nativeSelectKey,
onNativeOptionAdd,
onNativeOptionRemove,
onOpenChange: setOpen,
onTriggerChange: setTrigger,
onValueChange: handleValueChange,
onValueNodeChange: setValueNode,
onValueNodeHasChildrenChange: setValueNodeHasChildren,
open,
required,
trigger,
triggerPointerDownPosRef,
value,
valueNode,
valueNodeHasChildren,
}),
[
trigger,
valueNode,
valueNodeHasChildren,
contentId,
value,
handleValueChange,
open,
setOpen,
disabled,
required,
name,
form,
autoComplete,
nativeOptionsSet,
nativeSelectKey,
onNativeOptionAdd,
onNativeOptionRemove,
isFormControl,
]
);
return (
<SelectContext.Provider value={ctx}>
<ItemsContext.Provider value={itemsApi}>
{children}
{isFormControl ? <SelectBubbleInput /> : null}
</ItemsContext.Provider>
</SelectContext.Provider>
);
}
function SelectBubbleInput() {
const ctx = useSelectContext("SelectBubbleInput");
const ref = React.useRef<HTMLSelectElement>(null);
const selectValue = ctx.value ?? "";
const prevValueRef = React.useRef(selectValue);
const hasEmptyValueOption = Array.from(ctx.nativeOptions).some(
(option) => (option.props.value ?? "") === ""
);
React.useEffect(() => {
const select = ref.current;
if (!select) {
return;
}
const descriptor = Object.getOwnPropertyDescriptor(
window.HTMLSelectElement.prototype,
"value"
) as PropertyDescriptor;
const setValue = descriptor.set;
const valueChanged = prevValueRef.current !== selectValue;
prevValueRef.current = selectValue;
if (valueChanged && setValue) {
const event = new Event("change", { bubbles: true });
setValue.call(select, selectValue);
select.dispatchEvent(event);
}
}, [selectValue]);
return (
<select
aria-hidden
autoComplete={ctx.autoComplete}
defaultValue={selectValue}
disabled={ctx.disabled}
form={ctx.form}
key={ctx.nativeSelectKey}
name={ctx.name}
onChange={(event) => ctx.onValueChange(event.target.value)}
ref={ref}
required={ctx.required}
style={{ ...visuallyHiddenStyles }}
tabIndex={-1}
>
{shouldShowPlaceholder(ctx.value) && !hasEmptyValueOption ? (
<option value="" />
) : null}
{Array.from(ctx.nativeOptions)}
</select>
);
}
export type SelectTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
size?: "sm" | "default";
} & Record<string, unknown>;
function SelectTrigger({
as,
className,
disabled: disabledProp = false,
onClick,
onKeyDown,
onPointerDown,
ref,
size = "default",
...props
}: SelectTriggerProps) {
const context = useSelectContext("SelectTrigger");
const itemsApi = useItemsContext("SelectTrigger");
const isDisabled = context.disabled || disabledProp;
const pointerTypeRef =
React.useRef<React.PointerEvent["pointerType"]>("touch");
const composedRefs = useComposedRefs(
ref as React.Ref<HTMLButtonElement> | undefined,
context.onTriggerChange as (node: HTMLButtonElement | null) => void
);
const [searchRef, handleTypeaheadSearch, resetTypeahead] = useTypeaheadSearch(
(search) => {
const enabledItems = itemsApi.getItems().filter((item) => !item.disabled);
const currentItem = enabledItems.find(
(item) => item.value === context.value
);
const nextItem = findNextItem(enabledItems, search, currentItem);
if (nextItem !== undefined) {
context.onValueChange(nextItem.value);
}
}
);
const handleOpen = (pointerEvent?: React.MouseEvent | React.PointerEvent) => {
if (!isDisabled) {
context.onOpenChange(true);
resetTypeahead();
}
if (pointerEvent) {
context.triggerPointerDownPosRef.current = {
x: Math.round(pointerEvent.pageX),
y: Math.round(pointerEvent.pageY),
};
}
};
const Component = as ?? "button";
const triggerClassName = cn(
"border-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 flex w-fit items-center justify-between gap-1.5 rounded-lg border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 data-[size=default]:h-9 data-[size=sm]:h-8 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
);
const finalProps: Record<string, unknown> = {
...props,
"aria-autocomplete": "none",
"aria-controls": context.open ? context.contentId : undefined,
"aria-expanded": context.open,
"aria-haspopup": "listbox",
"aria-required": context.required,
className: triggerClassName,
"data-disabled": isDisabled ? "" : undefined,
"data-placeholder": shouldShowPlaceholder(context.value) ? "" : undefined,
"data-size": size,
"data-slot": "select-trigger",
"data-state": getOpenState(context.open),
disabled: isDisabled,
onClick: composeEventHandlers(
onClick as
| ((event: React.MouseEvent<HTMLButtonElement>) => void)
| undefined,
(event) => {
event.currentTarget.focus();
if (pointerTypeRef.current !== "mouse") {
handleOpen(event);
}
}
),
onKeyDown: composeEventHandlers(
onKeyDown as
| ((event: React.KeyboardEvent<HTMLButtonElement>) => void)
| undefined,
(event) => {
const isTypingAhead = searchRef.current !== "";
const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
if (!isModifierKey && event.key.length === 1) {
handleTypeaheadSearch(event.key);
}
if (isTypingAhead && event.key === " ") {
return;
}
if (openKeys.includes(event.key)) {
handleOpen();
event.preventDefault();
}
}
),
onPointerDown: composeEventHandlers(
onPointerDown as
| ((event: React.PointerEvent<HTMLButtonElement>) => void)
| undefined,
(event) => {
pointerTypeRef.current = event.pointerType;
const target = event.target as HTMLElement;
if (target.hasPointerCapture(event.pointerId)) {
target.releasePointerCapture(event.pointerId);
}
if (
event.button === 0 &&
event.ctrlKey === false &&
event.pointerType === "mouse"
) {
handleOpen(event);
event.preventDefault();
}
}
),
ref: composedRefs,
role: "combobox",
};
if (!(as || "type" in props)) {
finalProps.type = "button";
}
const renderedChildren = (
<>
{props.children as React.ReactNode}
<span
aria-hidden
className="text-muted-foreground pointer-events-none flex size-4 shrink-0 items-center justify-center"
>
<ChevronDownIcon className="size-4" />
</span>
</>
);
return React.createElement(Component, finalProps, renderedChildren);
}
export type SelectValueProps = Omit<
React.ComponentProps<"span">,
"ref" | "placeholder"
> & {
placeholder?: React.ReactNode;
ref?: React.Ref<HTMLSpanElement>;
};
function SelectValue({
className,
style,
children,
placeholder = "",
ref,
...props
}: SelectValueProps) {
const context = useSelectContext("SelectValue");
const hasChildren = children !== undefined;
const composedRefs = useComposedRefs(
ref as React.Ref<HTMLSpanElement> | undefined,
context.onValueNodeChange as (node: HTMLSpanElement | null) => void
);
React.useLayoutEffect(() => {
context.onValueNodeHasChildrenChange(hasChildren);
}, [context, hasChildren]);
const showPlaceholder = shouldShowPlaceholder(context.value);
return (
<span
{...props}
className={cn(className)}
data-slot="select-value"
ref={composedRefs}
style={{ pointerEvents: "none", ...style }}
>
<React.Fragment key={showPlaceholder ? "placeholder" : "value"}>
{showPlaceholder ? placeholder : children}
</React.Fragment>
</span>
);
}
export interface SelectIconProps extends React.ComponentProps<"span"> {}
function SelectIcon({ children, className, ...props }: SelectIconProps) {
return (
<span
aria-hidden
className={cn(
"text-muted-foreground pointer-events-none flex size-4 shrink-0 items-center justify-center",
className
)}
{...props}
>
{children || <ChevronDownIcon className="size-4" />}
</span>
);
}
export interface SelectPortalProps {
children?: React.ReactNode;
}
function SelectPortal({ children }: SelectPortalProps) {
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return null;
}
return createPortal(children, document.body);
}
interface SelectContentContextValue {
content: HTMLDivElement | null;
focusSelectedItem: () => void;
isPositioned: boolean;
itemRefCallback: (
node: HTMLDivElement | null,
value: string,
disabled: boolean
) => void;
itemTextRefCallback: (
node: HTMLSpanElement | null,
value: string,
disabled: boolean
) => void;
onItemLeave: () => void;
onViewportChange: (node: HTMLDivElement | null) => void;
position: "item-aligned" | "popper";
searchRef: React.RefObject<string>;
selectedItem: HTMLDivElement | null;
selectedItemText: HTMLSpanElement | null;
viewport: HTMLDivElement | null;
}
const SelectContentContext =
React.createContext<SelectContentContextValue | null>(null);
const noopContentContext: SelectContentContextValue = {
content: null,
focusSelectedItem: () => undefined,
isPositioned: false,
itemRefCallback: () => undefined,
itemTextRefCallback: () => undefined,
onItemLeave: () => undefined,
onViewportChange: () => undefined,
position: "popper",
searchRef: { current: "" },
selectedItem: null,
selectedItemText: null,
viewport: null,
};
function useSelectContentContext(
_component: string
): SelectContentContextValue {
const ctx = React.useContext(SelectContentContext);
return ctx ?? noopContentContext;
}
const defaultContentClassName =
"bg-popover text-popover-foreground ring-foreground/10 relative z-50 max-h-(--frakment-select-content-available-height) min-w-(--frakment-select-trigger-width) overflow-x-hidden overflow-y-auto rounded-lg shadow-md ring-1";
const defaultViewportClassName =
"p-1 data-[position=popper]:w-full data-[position=popper]:min-w-(--frakment-select-trigger-width)";
export type SelectContentProps = React.ComponentProps<"div"> & {
align?: "start" | "center" | "end";
alignOffset?: number;
avoidCollisions?: boolean;
collisionPadding?: number;
motion?: string;
onEscapeKeyDown?: (event: KeyboardEvent) => void;
onPointerDownOutside?: (event: Event) => void;
position?: "item-aligned" | "popper";
side?: "top" | "right" | "bottom" | "left";
sideOffset?: number;
};
function SelectContent(props: SelectContentProps) {
const context = useSelectContext("SelectContent");
const [fragment, setFragment] = React.useState<DocumentFragment>();
React.useLayoutEffect(() => {
setFragment(new DocumentFragment());
}, []);
if (context.open) {
return (
<SelectPortal>
<SelectContentImpl {...props} />
</SelectPortal>
);
}
return <SelectContentFragment {...props} fragment={fragment} />;
}
function SelectContentFragment(
props: SelectContentProps & { fragment?: DocumentFragment }
) {
const { fragment, children } = props;
if (!fragment) {
return null;
}
return createPortal(
<SelectContentContext.Provider value={noopContentContext}>
<div>{children}</div>
</SelectContentContext.Provider>,
fragment
);
}
function SelectContentImpl({
align = "start",
alignOffset = 0,
avoidCollisions = true,
children,
className,
collisionPadding = contentMargin,
motion,
onEscapeKeyDown,
onPointerDownOutside,
position = "item-aligned",
side = "bottom",
sideOffset = 4,
style,
onKeyDown,
...props
}: SelectContentProps) {
const context = useSelectContext("SelectContentImpl");
const itemsApi = useItemsContext("SelectContentImpl");
const contentRef = React.useRef<HTMLDivElement>(null);
const [contentEl, setContentEl] = React.useState<HTMLDivElement | null>(null);
const [viewport, setViewport] = React.useState<HTMLDivElement | null>(null);
const [selectedItem, setSelectedItem] = React.useState<HTMLDivElement | null>(
null
);
const [selectedItemText, setSelectedItemText] =
React.useState<HTMLSpanElement | null>(null);
const [isPositioned, setIsPositioned] = React.useState(false);
const firstValidItemFoundRef = React.useRef(false);
const [entered, setEntered] = React.useState(false);
React.useLayoutEffect(() => {
if (!isPositioned) {
return;
}
const frame = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(frame);
}, [isPositioned]);
const reduce = useReducedMotion();
const motionValue = motion ?? defaultSelectMotion;
const motionTransition =
reduce || motion === "off"
? "none"
: getTransition(parseMotion(motionValue));
const originBySide: Record<string, string> = {
bottom: "top center",
left: "center right",
right: "center left",
top: "bottom center",
};
const transformOrigin = originBySide[side] ?? "center";
React.useEffect(() => {
const content = contentRef.current;
if (!(content && viewport)) {
return;
}
const prevent = (event: Event) => {
const target = event.target;
if (target instanceof Node && viewport.contains(target)) {
return;
}
if (event.cancelable) {
event.preventDefault();
}
};
document.addEventListener("wheel", prevent, { passive: false });
document.addEventListener("touchmove", prevent, { passive: false });
return () => {
document.removeEventListener("wheel", prevent);
document.removeEventListener("touchmove", prevent);
};
}, [viewport]);
const [searchRef, handleTypeaheadSearch] = useTypeaheadSearch((search) => {
const enabledItems = itemsApi.getItems().filter((item) => !item.disabled);
const currentItem = enabledItems.find(
(item) => item.ref.current === document.activeElement
);
const nextItem = findNextItem(enabledItems, search, currentItem);
if (nextItem) {
setTimeout(() => nextItem.ref.current?.focus());
}
});
React.useEffect(() => {
const content = contentRef.current;
if (!content) {
return;
}
const selector =
'[tabindex]:not([tabindex="-1"]), button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled])';
const handler = (event: KeyboardEvent) => {
if (event.key !== "Tab") {
return;
}
const focusables = Array.from(
content.querySelectorAll<HTMLElement>(selector)
);
const first = focusables[0];
const last = focusables.at(-1);
if (!(first && last)) {
return;
}
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
content.addEventListener("keydown", handler);
return () => content.removeEventListener("keydown", handler);
}, []);
React.useEffect(() => {
const content = contentRef.current;
if (!content) {
return;
}
const ownerDocument = content.ownerDocument;
const pointerdown = (event: PointerEvent) => {
const target = event.target as Node;
if (!(content.contains(target) || context.trigger?.contains(target))) {
context.onOpenChange(false);
onPointerDownOutside?.(event as unknown as Event);
}
};
const keydown = (event: KeyboardEvent) => {
if (event.key !== "Escape") {
return;
}
if (event.isComposing || event.keyCode === 229) {
return;
}
onEscapeKeyDown?.(event);
if (!event.defaultPrevented) {
event.preventDefault();
context.onOpenChange(false);
}
};
ownerDocument.addEventListener("pointerdown", pointerdown);
ownerDocument.addEventListener("keydown", keydown, { capture: true });
return () => {
ownerDocument.removeEventListener("pointerdown", pointerdown);
ownerDocument.removeEventListener("keydown", keydown, { capture: true });
};
}, [context, onPointerDownOutside, onEscapeKeyDown]);
React.useEffect(
() => () => {
context.trigger?.focus({ preventScroll: true });
},
[context]
);
const focusFirst = React.useCallback(
(candidates: Array<HTMLElement | null>) => {
const allItems = itemsApi.getItems().map((item) => item.ref.current);
const [firstItem, ...restItems] = allItems;
const [lastItem] = restItems.slice(-1);
const PREV = document.activeElement;
for (const candidate of candidates) {
if (candidate === PREV) {
return;
}
candidate?.scrollIntoView({ block: "nearest" });
if (candidate === firstItem && viewport) {
viewport.scrollTop = 0;
}
if (candidate === lastItem && viewport) {
viewport.scrollTop = viewport.scrollHeight;
}
candidate?.focus();
if (document.activeElement !== PREV) {
return;
}
}
},
[itemsApi, viewport]
);
const focusSelectedItem = React.useCallback(
() => focusFirst([selectedItem, contentRef.current]),
[focusFirst, selectedItem]
);
React.useEffect(() => {
if (!context.open) {
return;
}
const handle = requestAnimationFrame(() => {
const el = contentRef.current;
if (el && !el.contains(document.activeElement)) {
el.focus({ preventScroll: true });
}
});
return () => cancelAnimationFrame(handle);
}, [context.open]);
React.useEffect(() => {
if (isPositioned) {
focusSelectedItem();
}
}, [isPositioned, focusSelectedItem]);
const firstItemFoundRef = React.useRef(false);
const firstItemTextFoundRef = React.useRef(false);
const itemRefCallback = React.useCallback(
(node: HTMLDivElement | null, value: string, disabled: boolean) => {
const isFirstItem = !firstItemFoundRef.current;
if (isFirstItem) {
firstItemFoundRef.current = true;
}
const isFirstValid = !(firstValidItemFoundRef.current || disabled);
const isSelected = context.value !== undefined && context.value === value;
if (isSelected || isFirstValid) {
setSelectedItem(node);
if (isFirstValid) {
firstValidItemFoundRef.current = true;
}
} else if (isFirstItem) {
setSelectedItem(node);
}
},
[context.value]
);
const itemTextRefCallback = React.useCallback(
(node: HTMLSpanElement | null, value: string, disabled: boolean) => {
if (!node) {
return;
}
const isFirstItem = !firstItemTextFoundRef.current;
if (isFirstItem) {
firstItemTextFoundRef.current = true;
}
const isFirstValid = !(firstValidItemFoundRef.current || disabled);
const isSelected = context.value !== undefined && context.value === value;
if (isSelected || isFirstValid) {
setSelectedItemText(node);
} else if (isFirstItem) {
setSelectedItemText(node);
}
},
[context.value]
);
const handleItemLeave = React.useCallback(
() => contentRef.current?.focus(),
[]
);
const handleContentKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event);
const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
if (event.key === "Tab") {
event.preventDefault();
}
if (!isModifierKey && event.key.length === 1) {
handleTypeaheadSearch(event.key);
}
if (["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {
const items = itemsApi.getItems().filter((item) => !item.disabled);
let candidates = items
.map((item) => item.ref.current)
.filter((n): n is HTMLDivElement => n !== null);
if (["ArrowUp", "End"].includes(event.key)) {
candidates = candidates.slice().reverse();
}
if (["ArrowUp", "ArrowDown"].includes(event.key)) {
const currentIndex = candidates.indexOf(event.target as HTMLDivElement);
candidates = candidates.slice(currentIndex + 1);
}
setTimeout(() => focusFirst(candidates));
event.preventDefault();
}
};
const contentContext: SelectContentContextValue = {
content: contentEl,
focusSelectedItem,
isPositioned,
itemRefCallback,
itemTextRefCallback,
onItemLeave: handleItemLeave,
onViewportChange: setViewport,
position,
searchRef,
selectedItem,
selectedItemText,
viewport,
};
const contentClassName = cn(
defaultContentClassName,
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
);
const contentStyle: React.CSSProperties = {
display: "flex",
flexDirection: "column",
opacity: entered ? 1 : 0,
outline: "none",
transform: entered ? "scale(1)" : "scale(0.95)",
transformOrigin,
transition: motionTransition ?? "none",
...style,
};
const contentProps = {
...props,
"aria-labelledby": context.trigger?.id,
className: contentClassName,
"data-slot": "select-content",
"data-state": getOpenState(context.open),
id: context.contentId,
onContextMenu: (event: React.MouseEvent<HTMLDivElement>) =>
event.preventDefault(),
onKeyDown: handleContentKeyDown,
role: "listbox" as const,
style: contentStyle,
tabIndex: -1,
};
return (
<SelectContentContext.Provider value={contentContext}>
{position === "popper" ? (
<SelectPopperPosition
align={align}
alignOffset={alignOffset}
avoidCollisions={avoidCollisions}
collisionPadding={collisionPadding}
contentProps={contentProps}
contentRef={contentRef}
contentSetRef={setContentEl}
onPlaced={() => setIsPositioned(true)}
side={side}
sideOffset={sideOffset}
>
<SelectViewport>{children}</SelectViewport>
</SelectPopperPosition>
) : (
<SelectItemAlignedPosition
contentProps={contentProps}
contentRef={contentRef}
contentSetRef={setContentEl}
onPlaced={() => setIsPositioned(true)}
>
<SelectViewport>{children}</SelectViewport>
</SelectItemAlignedPosition>
)}
</SelectContentContext.Provider>
);
}
interface SelectPopperPositionProps {
align?: "start" | "center" | "end";
alignOffset?: number;
avoidCollisions?: boolean;
children?: React.ReactNode;
collisionPadding?: number;
contentProps: Record<string, unknown>;
contentRef: React.RefObject<HTMLDivElement | null>;
contentSetRef: (node: HTMLDivElement | null) => void;
onPlaced?: () => void;
side?: "top" | "right" | "bottom" | "left";
sideOffset?: number;
}
function SelectPopperPosition({
align = "start",
alignOffset = 0,
avoidCollisions = true,
children,
collisionPadding = contentMargin,
contentProps,
contentRef,
contentSetRef,
onPlaced,
side = "bottom",
sideOffset = 4,
}: SelectPopperPositionProps) {
const context = useSelectContext("SelectPopperPosition");
const { refs, floatingStyles, isPositioned, placement } = useFloating({
elements: { reference: context.trigger },
middleware: [
offset({ alignmentAxis: alignOffset, mainAxis: sideOffset }),
avoidCollisions && shift({ padding: collisionPadding }),
avoidCollisions && flip({ padding: collisionPadding }),
sizeMiddleware({
apply: ({ elements, rects, availableWidth, availableHeight }) => {
elements.floating.style.setProperty(
"--frakment-select-content-available-width",
`${availableWidth}px`
);
elements.floating.style.setProperty(
"--frakment-select-content-available-height",
`${availableHeight}px`
);
elements.floating.style.setProperty(
"--frakment-select-trigger-width",
`${rects.reference.width}px`
);
elements.floating.style.setProperty(
"--frakment-select-trigger-height",
`${rects.reference.height}px`
);
},
}),
],
placement: (side + (align === "center" ? "" : `-${align}`)) as never,
strategy: "fixed",
whileElementsMounted: autoUpdate,
});
React.useEffect(() => {
if (context.open && context.trigger) {
refs.setReference(context.trigger);
}
}, [context.open, refs, context.trigger]);
React.useEffect(() => {
if (isPositioned) {
onPlaced?.();
}
}, [isPositioned, onPlaced]);
const placedSide = placement.split("-")[0];
const placedAlign = placement.split("-")[1] ?? "center";
return (
<div
data-align={placedAlign}
data-popper-wrapper=""
data-side={placedSide}
ref={refs.setFloating}
style={{
...floatingStyles,
minWidth: "max-content",
transform: isPositioned
? floatingStyles.transform
: "translate(0, -200%)",
}}
>
<div
{...contentProps}
data-align={placedAlign}
data-side={placedSide}
ref={(node) => {
contentRef.current = node;
contentSetRef(node);
}}
>
{children}
</div>
</div>
);
}
export interface SelectViewportProps extends React.ComponentProps<"div"> {}
interface SelectViewportContextValue {
contentWrapper: HTMLDivElement | null;
onScrollButtonChange: ((node: HTMLDivElement | null) => void) | null;
shouldExpandOnScrollRef: React.RefObject<boolean> | null;
}
const SelectViewportContext =
React.createContext<SelectViewportContextValue | null>(null);
function useSelectViewportContext(): SelectViewportContextValue {
const ctx = React.useContext(SelectViewportContext);
return (
ctx ?? {
contentWrapper: null,
onScrollButtonChange: null,
shouldExpandOnScrollRef: null,
}
);
}
function clamp(value: number, [min, max]: [number, number]): number {
return Math.min(Math.max(value, min), max);
}
interface SelectItemAlignedPositionProps {
children?: React.ReactNode;
contentProps: Record<string, unknown>;
contentRef: React.RefObject<HTMLDivElement | null>;
contentSetRef: (node: HTMLDivElement | null) => void;
onPlaced?: () => void;
}
function SelectItemAlignedPosition({
children,
contentProps,
contentRef,
contentSetRef,
onPlaced,
}: SelectItemAlignedPositionProps) {
const context = useSelectContext("SelectItemAlignedPosition");
const contentCtx = useSelectContentContext("SelectItemAlignedPosition");
const itemsApi = useItemsContext("SelectItemAlignedPosition");
const [contentWrapper, setContentWrapper] =
React.useState<HTMLDivElement | null>(null);
const [content, setContent] = React.useState<HTMLDivElement | null>(null);
const [contentZIndex, setContentZIndex] = React.useState<string>();
const shouldExpandOnScrollRef = React.useRef(false);
const shouldRepositionRef = React.useRef(true);
const { viewport, selectedItem, selectedItemText } = contentCtx;
const position = React.useCallback(() => {
if (
!(
context.trigger &&
context.valueNode &&
contentWrapper &&
content &&
viewport &&
selectedItem &&
selectedItemText
)
) {
return;
}
const triggerRect = context.trigger.getBoundingClientRect();
const contentRect = content.getBoundingClientRect();
const valueNodeRect = context.valueNode.getBoundingClientRect();
const itemTextRect = selectedItemText.getBoundingClientRect();
const itemTextOffset = itemTextRect.left - contentRect.left;
const left = valueNodeRect.left - itemTextOffset;
const leftDelta = triggerRect.left - left;
const minContentWidth = triggerRect.width + leftDelta;
const contentWidth = Math.max(minContentWidth, contentRect.width);
const rightEdge = window.innerWidth - contentMargin;
const clampedLeft = clamp(left, [
contentMargin,
Math.max(contentMargin, rightEdge - contentWidth),
]);
contentWrapper.style.minWidth = `${minContentWidth}px`;
contentWrapper.style.left = `${clampedLeft}px`;
const items = itemsApi.getItems();
const availableHeight = window.innerHeight - contentMargin * 2;
const itemsHeight = viewport.scrollHeight;
const contentStyles = window.getComputedStyle(content);
const contentBorderTopWidth = Number.parseInt(
contentStyles.borderTopWidth,
10
);
const contentPaddingTop = Number.parseInt(contentStyles.paddingTop, 10);
const contentBorderBottomWidth = Number.parseInt(
contentStyles.borderBottomWidth,
10
);
const contentPaddingBottom = Number.parseInt(
contentStyles.paddingBottom,
10
);
const fullContentHeight =
contentBorderTopWidth +
contentPaddingTop +
itemsHeight +
contentPaddingBottom +
contentBorderBottomWidth;
const minContentHeight = Math.min(
selectedItem.offsetHeight * 5,
fullContentHeight
);
const viewportStyles = window.getComputedStyle(viewport);
const viewportPaddingTop = Number.parseInt(viewportStyles.paddingTop, 10);
const viewportPaddingBottom = Number.parseInt(
viewportStyles.paddingBottom,
10
);
const topEdgeToTriggerMiddle =
triggerRect.top + triggerRect.height / 2 - contentMargin;
const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle;
const selectedItemHalfHeight = selectedItem.offsetHeight / 2;
const itemOffsetMiddle = selectedItem.offsetTop + selectedItemHalfHeight;
const contentTopToItemMiddle =
contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle;
const itemMiddleToContentBottom =
fullContentHeight - contentTopToItemMiddle;
const willAlignWithoutTopOverflow =
contentTopToItemMiddle <= topEdgeToTriggerMiddle;
if (willAlignWithoutTopOverflow) {
const isLastItem =
items.length > 0 && selectedItem === items.at(-1)?.ref.current;
contentWrapper.style.bottom = "0px";
const viewportOffsetBottom =
content.clientHeight - viewport.offsetTop - viewport.offsetHeight;
const clampedTriggerMiddleToBottomEdge = Math.max(
triggerMiddleToBottomEdge,
selectedItemHalfHeight +
(isLastItem ? viewportPaddingBottom : 0) +
viewportOffsetBottom +
contentBorderBottomWidth
);
const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge;
contentWrapper.style.height = `${height}px`;
} else {
const isFirstItem =
items.length > 0 && selectedItem === items[0]?.ref.current;
contentWrapper.style.top = "0px";
const clampedTopEdgeToTriggerMiddle = Math.max(
topEdgeToTriggerMiddle,
contentBorderTopWidth +
viewport.offsetTop +
(isFirstItem ? viewportPaddingTop : 0) +
selectedItemHalfHeight
);
const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom;
contentWrapper.style.height = `${height}px`;
viewport.scrollTop =
contentTopToItemMiddle - topEdgeToTriggerMiddle + viewport.offsetTop;
}
contentWrapper.style.margin = `${contentMargin}px 0`;
contentWrapper.style.minHeight = `${minContentHeight}px`;
contentWrapper.style.maxHeight = `${availableHeight}px`;
onPlaced?.();
requestAnimationFrame(() => {
shouldExpandOnScrollRef.current = true;
});
}, [
context.trigger,
context.valueNode,
contentWrapper,
content,
viewport,
selectedItem,
selectedItemText,
itemsApi,
onPlaced,
]);
React.useLayoutEffect(() => position(), [position]);
React.useLayoutEffect(() => {
if (content) {
setContentZIndex(window.getComputedStyle(content).zIndex);
}
}, [content]);
const handleScrollButtonChange = React.useCallback(
(node: HTMLDivElement | null) => {
if (node && shouldRepositionRef.current) {
position();
contentCtx.focusSelectedItem();
shouldRepositionRef.current = false;
}
},
[position, contentCtx]
);
return (
<SelectViewportContext.Provider
value={{
contentWrapper,
onScrollButtonChange: handleScrollButtonChange,
shouldExpandOnScrollRef,
}}
>
<div
ref={setContentWrapper}
style={{
display: "flex",
flexDirection: "column",
position: "fixed",
zIndex: contentZIndex,
}}
>
<div
{...contentProps}
ref={(node) => {
setContent(node);
contentRef.current = node;
contentSetRef(node);
}}
style={{
boxSizing: "border-box",
maxHeight: "100%",
...((contentProps.style as React.CSSProperties) ?? {}),
}}
>
{children}
</div>
</div>
</SelectViewportContext.Provider>
);
}
function SelectViewport({
children,
className,
onScroll,
style,
ref,
...props
}: SelectViewportProps & { ref?: React.Ref<HTMLDivElement> }) {
const contentCtx = useSelectContentContext("SelectViewport");
const viewportCtx = useSelectViewportContext();
const viewportRef = React.useRef<HTMLDivElement>(null);
const prevScrollTopRef = React.useRef(0);
const composedRefs = useComposedRefs(
ref as React.Ref<HTMLDivElement> | undefined,
viewportRef,
(node: HTMLDivElement | null) => contentCtx.onViewportChange(node)
);
const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
onScroll?.(event);
const viewport = event.currentTarget;
const { contentWrapper, shouldExpandOnScrollRef } = viewportCtx;
if (shouldExpandOnScrollRef?.current && contentWrapper) {
const scrolledBy = Math.abs(
prevScrollTopRef.current - viewport.scrollTop
);
if (scrolledBy > 0) {
const availableHeight = window.innerHeight - contentMargin * 2;
const cssMinHeight = Number.parseFloat(contentWrapper.style.minHeight);
const cssHeight = Number.parseFloat(contentWrapper.style.height);
const prevHeight = Math.max(cssMinHeight, cssHeight);
if (prevHeight < availableHeight) {
const nextHeight = prevHeight + scrolledBy;
const clampedNextHeight = Math.min(availableHeight, nextHeight);
const heightDiff = nextHeight - clampedNextHeight;
contentWrapper.style.height = `${clampedNextHeight}px`;
if (contentWrapper.style.bottom === "0px") {
viewport.scrollTop = Math.max(heightDiff, 0);
contentWrapper.style.justifyContent = "flex-end";
}
}
}
}
prevScrollTopRef.current = viewport.scrollTop;
};
return (
<div
className={cn(defaultViewportClassName, className)}
data-position={contentCtx.position}
data-slot="select-viewport"
{...props}
onScroll={handleScroll}
ref={composedRefs}
role="presentation"
style={{
flex: 1,
overflowX: "hidden",
overflowY: "auto",
overscrollBehavior: "contain",
position: "relative",
...style,
}}
>
{children}
</div>
);
}
interface SelectGroupContextValue {
id: string;
}
const SelectGroupContext = React.createContext<SelectGroupContextValue | null>(
null
);
function useSelectGroupContext(component: string): SelectGroupContextValue {
const ctx = React.useContext(SelectGroupContext);
if (!ctx) {
throw new Error(`${component} must be used within SelectGroup`);
}
return ctx;
}
export interface SelectGroupProps extends React.ComponentProps<"div"> {}
function SelectGroup({ className, ...props }: SelectGroupProps) {
const groupId = React.useId();
return (
<SelectGroupContext.Provider value={{ id: groupId }}>
<div
aria-labelledby={groupId}
className={cn("scroll-my-1 p-1", className)}
data-slot="select-group"
role="group"
{...props}
/>
</SelectGroupContext.Provider>
);
}
export interface SelectLabelProps extends React.ComponentProps<"div"> {}
function SelectLabel({ className, ...props }: SelectLabelProps) {
const ctx = useSelectGroupContext("SelectLabel");
return (
<div
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
data-slot="select-label"
id={ctx.id}
{...props}
/>
);
}
interface SelectItemContextValue {
disabled: boolean;
isSelected: boolean;
onItemTextChange: (node: HTMLSpanElement | null) => void;
textId: string;
value: string;
}
const SelectItemContext = React.createContext<SelectItemContextValue | null>(
null
);
function useSelectItemContext(component: string): SelectItemContextValue {
const ctx = React.useContext(SelectItemContext);
if (!ctx) {
throw new Error(`${component} must be used within SelectItem`);
}
return ctx;
}
export type SelectItemProps = React.ComponentProps<"div"> & {
value: string;
disabled?: boolean;
textValue?: string;
};
function SelectItem({
children,
className,
disabled = false,
onClick,
onKeyDown,
onPointerDown,
onPointerLeave,
onPointerMove,
onPointerUp,
textValue: textValueProp,
value,
...props
}: SelectItemProps) {
const context = useSelectContext("SelectItem");
const contentCtx = useSelectContentContext("SelectItem");
const itemsApi = useItemsContext("SelectItem");
const isSelected = context.value === value;
const [textValue, setTextValue] = React.useState(textValueProp ?? "");
const [isFocused, setIsFocused] = React.useState(false);
const ref = React.useRef<HTMLDivElement>(null);
const textId = React.useId();
const pointerTypeRef =
React.useRef<React.PointerEvent["pointerType"]>("touch");
React.useEffect(() => {
itemsApi.registerItem(value, {
disabled,
ref,
textValue: textValueProp ?? textValue,
value,
});
return () => itemsApi.unregisterItem(value);
}, [itemsApi, value, textValueProp, textValue, disabled]);
React.useEffect(() => {
if (ref.current) {
contentCtx.itemRefCallback(ref.current, value, disabled);
}
}, [contentCtx, value, disabled]);
const handleSelect = () => {
if (disabled) {
return;
}
context.onValueChange(value);
context.onOpenChange(false);
};
return (
<SelectItemContext.Provider
value={{
disabled,
isSelected,
onItemTextChange: React.useCallback((node) => {
setTextValue((prev) => prev || (node?.textContent ?? "").trim());
}, []),
textId,
value,
}}
>
<div
aria-disabled={disabled || undefined}
aria-labelledby={textId}
aria-selected={isSelected && isFocused}
className={cn(
"focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
data-disabled={disabled ? "" : undefined}
data-highlighted={isFocused ? "" : undefined}
data-slot="select-item"
data-state={isSelected ? "checked" : "unchecked"}
{...props}
onBlur={(event) => {
setIsFocused(false);
props.onBlur?.(event);
}}
onClick={(event) => {
onClick?.(event);
if (disabled) {
return;
}
if (pointerTypeRef.current !== "mouse") {
handleSelect();
}
}}
onFocus={(event) => {
setIsFocused(true);
props.onFocus?.(event);
}}
onKeyDown={(event) => {
onKeyDown?.(event);
if (disabled || event.target !== event.currentTarget) {
return;
}
const isTypingAhead = contentCtx.searchRef.current !== "";
if (isTypingAhead && event.key === " ") {
return;
}
if (selectionKeys.includes(event.key)) {
handleSelect();
}
if (event.key === " ") {
event.preventDefault();
}
}}
onPointerDown={(event) => {
onPointerDown?.(event);
pointerTypeRef.current = event.pointerType;
}}
onPointerLeave={(event) => {
onPointerLeave?.(event);
if (event.currentTarget === document.activeElement) {
contentCtx.onItemLeave();
}
}}
onPointerMove={(event) => {
onPointerMove?.(event);
pointerTypeRef.current = event.pointerType;
if (disabled) {
contentCtx.onItemLeave();
} else if (pointerTypeRef.current === "mouse") {
event.currentTarget.focus({ preventScroll: true });
}
}}
onPointerUp={(event) => {
onPointerUp?.(event);
if (disabled) {
return;
}
if (pointerTypeRef.current !== "mouse") {
return;
}
const pointerDownPos = context.triggerPointerDownPosRef.current;
if (pointerDownPos !== null) {
context.triggerPointerDownPosRef.current = null;
const dx = Math.abs(Math.round(event.pageX) - pointerDownPos.x);
const dy = Math.abs(Math.round(event.pageY) - pointerDownPos.y);
if (dx <= 10 && dy <= 10) {
return;
}
}
handleSelect();
}}
ref={ref}
role="option"
tabIndex={disabled ? undefined : -1}
>
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
<SelectItemIndicator>
<CheckIcon className="pointer-events-none" />
</SelectItemIndicator>
</span>
<SelectItemText>{children}</SelectItemText>
</div>
</SelectItemContext.Provider>
);
}
export interface SelectItemTextProps extends React.ComponentProps<"span"> {}
function SelectItemText({ children, ...props }: SelectItemTextProps) {
const context = useSelectContext("SelectItemText");
const contentCtx = useSelectContentContext("SelectItemText");
const itemCtx = useSelectItemContext("SelectItemText");
const [itemTextNode, setItemTextNode] =
React.useState<HTMLSpanElement | null>(null);
React.useEffect(() => {
if (itemTextNode) {
itemCtx.onItemTextChange(itemTextNode);
contentCtx.itemTextRefCallback(
itemTextNode,
itemCtx.value,
itemCtx.disabled
);
}
}, [itemTextNode, itemCtx, contentCtx]);
const textContent = itemTextNode?.textContent;
const nativeOption = React.useMemo(
() => (
<option
disabled={itemCtx.disabled}
key={itemCtx.value}
value={itemCtx.value}
>
{textContent}
</option>
),
[itemCtx.disabled, itemCtx.value, textContent]
);
const onNativeOptionAdd = context.onNativeOptionAdd;
const onNativeOptionRemove = context.onNativeOptionRemove;
React.useLayoutEffect(() => {
onNativeOptionAdd(nativeOption);
return () => onNativeOptionRemove(nativeOption);
}, [onNativeOptionAdd, onNativeOptionRemove, nativeOption]);
return (
<>
<span id={itemCtx.textId} {...props} ref={setItemTextNode}>
{children}
</span>
{itemCtx.isSelected &&
context.valueNode &&
!context.valueNodeHasChildren &&
!shouldShowPlaceholder(context.value)
? createPortal(children, context.valueNode)
: null}
</>
);
}
export interface SelectItemIndicatorProps
extends React.ComponentProps<"span"> {}
function SelectItemIndicator({ children, ...props }: SelectItemIndicatorProps) {
const itemCtx = useSelectItemContext("SelectItemIndicator");
return itemCtx.isSelected ? (
<span aria-hidden {...props}>
{children}
</span>
) : null;
}
export interface SelectSeparatorProps extends React.ComponentProps<"div"> {}
function SelectSeparator({ className, ...props }: SelectSeparatorProps) {
return (
<div
aria-hidden
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
data-slot="select-separator"
{...props}
/>
);
}
type SelectScrollButtonImplProps = React.ComponentProps<"div"> & {
onAutoScroll: () => void;
ref?: React.Ref<HTMLDivElement>;
};
function SelectScrollButtonImpl({
children,
onAutoScroll,
onPointerDown,
onPointerLeave,
onPointerMove,
ref,
style,
...props
}: SelectScrollButtonImplProps) {
const contentCtx = useSelectContentContext("SelectScrollButtonImpl");
const itemsApi = useItemsContext("SelectScrollButtonImpl");
const autoScrollTimerRef = React.useRef<number | null>(null);
const clearAutoScrollTimer = React.useCallback(() => {
if (autoScrollTimerRef.current !== null) {
window.clearInterval(autoScrollTimerRef.current);
autoScrollTimerRef.current = null;
}
}, []);
React.useEffect(() => clearAutoScrollTimer, [clearAutoScrollTimer]);
React.useLayoutEffect(() => {
const activeItem = itemsApi
.getItems()
.find((item) => item.ref.current === document.activeElement);
activeItem?.ref.current?.scrollIntoView({ block: "nearest" });
}, [itemsApi]);
return (
<div
aria-hidden
{...props}
onPointerDown={(event) => {
onPointerDown?.(event);
if (autoScrollTimerRef.current === null) {
autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
}
}}
onPointerLeave={(event) => {
onPointerLeave?.(event);
clearAutoScrollTimer();
}}
onPointerMove={(event) => {
onPointerMove?.(event);
contentCtx.onItemLeave();
if (autoScrollTimerRef.current === null) {
autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
}
}}
ref={ref}
style={{ flexShrink: 0, ...style }}
>
{children}
</div>
);
}
export interface SelectScrollUpButtonProps
extends React.ComponentProps<"div"> {}
function SelectScrollUpButton(props: SelectScrollUpButtonProps) {
const contentCtx = useSelectContentContext("SelectScrollUpButton");
const viewportCtx = useSelectViewportContext();
const [canScrollUp, setCanScrollUp] = React.useState(false);
const composedRef = React.useCallback(
(node: HTMLDivElement | null) => {
viewportCtx.onScrollButtonChange?.(node);
},
[viewportCtx]
);
React.useLayoutEffect(() => {
const viewport = contentCtx.viewport;
if (!(viewport && contentCtx.isPositioned)) {
return;
}
const handleScroll = () => setCanScrollUp(viewport.scrollTop > 0);
handleScroll();
viewport.addEventListener("scroll", handleScroll);
return () => viewport.removeEventListener("scroll", handleScroll);
}, [contentCtx.viewport, contentCtx.isPositioned]);
if (!canScrollUp) {
return null;
}
return (
<SelectScrollButtonImpl
{...props}
onAutoScroll={() => {
const { viewport, selectedItem } = contentCtx;
if (viewport && selectedItem) {
viewport.scrollTop -= selectedItem.offsetHeight;
}
}}
ref={composedRef}
/>
);
}
export interface SelectScrollDownButtonProps
extends React.ComponentProps<"div"> {}
function SelectScrollDownButton(props: SelectScrollDownButtonProps) {
const contentCtx = useSelectContentContext("SelectScrollDownButton");
const viewportCtx = useSelectViewportContext();
const [canScrollDown, setCanScrollDown] = React.useState(false);
const composedRef = React.useCallback(
(node: HTMLDivElement | null) => {
viewportCtx.onScrollButtonChange?.(node);
},
[viewportCtx]
);
React.useLayoutEffect(() => {
const viewport = contentCtx.viewport;
if (!(viewport && contentCtx.isPositioned)) {
return;
}
const handleScroll = () => {
const maxScroll = viewport.scrollHeight - viewport.clientHeight;
setCanScrollDown(Math.ceil(viewport.scrollTop) < maxScroll);
};
handleScroll();
viewport.addEventListener("scroll", handleScroll);
return () => viewport.removeEventListener("scroll", handleScroll);
}, [contentCtx.viewport, contentCtx.isPositioned]);
if (!canScrollDown) {
return null;
}
return (
<SelectScrollButtonImpl
{...props}
onAutoScroll={() => {
const { viewport, selectedItem } = contentCtx;
if (viewport && selectedItem) {
viewport.scrollTop += selectedItem.offsetHeight;
}
}}
ref={composedRef}
/>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectIcon,
SelectItem,
SelectItemIndicator,
SelectItemText,
SelectLabel,
SelectPortal,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};Select no longer depends on radix-ui. The listbox runs on Floating UI with two placement modes: item-aligned (default, overlaps the selected item with the trigger) and popper (anchors below the trigger). Keyboard navigation, type-ahead, and form submission follow the native select contract.
Changed:
- Removed
radix-uifromdependencies. Added@floating-ui/react-dom. - New
positionprop onSelectContent:item-aligned(default) orpopper. - Controlled
openandvaluenow honor the prop instead of the initial state. - New
SelectScrollUpButtonandSelectScrollDownButtonfor long lists. - Scroll inside the listbox is locked; the page beneath does not scroll while open.
No API breaking changes. See the Select docs.
Badge
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 text-xs leading-none font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] data-[icon-only]:aspect-square data-[icon-only]:px-0 [&_[data-slot=spinner]]:size-2.5 [&_[data-slot=spinner][data-variant=default]]:border [&>svg]:pointer-events-none [&>svg]:size-3",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
destructive:
"bg-destructive focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90 text-white",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
},
},
}
);
type BadgeProps = Omit<React.ComponentProps<"span">, "ref"> &
VariantProps<typeof badgeVariants> & {
as?: React.ElementType;
iconOnly?: boolean;
ref?: React.Ref<HTMLSpanElement>;
} & Record<string, unknown>;
function Badge({
className,
variant = "default",
as,
iconOnly = false,
...props
}: BadgeProps) {
const Comp = as ?? "span";
return (
<Comp
className={cn(badgeVariants({ variant }), className)}
data-icon-only={iconOnly ? "" : undefined}
data-inline
data-slot="badge"
{...props}
/>
);
}
export { Badge, badgeVariants };Badge no longer depends on radix-ui. The surface height drops from h-6 to h-5 to match the shadcn/ui baseline, and the primitive gains an as prop and an iconOnly mode.
Changed:
- Removed
radix-uifromdependencies. - New
registryDependency:slot. - Height
h-6→h-5, horizontal paddingpx-2.5→px-2, icon sizesize-3.5→size-3. - New
asprop for router links and custom components.asChildstays for backward compatibility. - New
iconOnlyprop renders a square badge with no horizontal padding. Use when the badge wraps only an icon. - Spinner inside a badge now renders at
size-2.5with a 1px ring.
See the Badge docs.
Avatar
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
type ImageLoadingStatus = "idle" | "loading" | "loaded" | "error";
function useImageLoadingStatus(
src: string | undefined,
referrerPolicy: React.HTMLAttributeReferrerPolicy | undefined
): ImageLoadingStatus {
const [status, setStatus] = React.useState<ImageLoadingStatus>("idle");
React.useEffect(() => {
if (!src) {
setStatus("error");
return;
}
let isMounted = true;
const image = new window.Image();
const update = (next: ImageLoadingStatus) => () => {
if (isMounted) {
setStatus(next);
}
};
setStatus("loading");
image.onload = update("loaded");
image.onerror = update("error");
if (referrerPolicy) {
image.referrerPolicy = referrerPolicy;
}
image.src = src;
return () => {
isMounted = false;
};
}, [src, referrerPolicy]);
return status;
}
interface AvatarContextValue {
imageLoadingStatus: ImageLoadingStatus;
onImageLoadingStatusChange: (status: ImageLoadingStatus) => void;
}
const AvatarContext = React.createContext<AvatarContextValue | null>(null);
function useAvatarContext(component: string): AvatarContextValue {
const ctx = React.useContext(AvatarContext);
if (!ctx) {
throw new Error(`${component} must be used within Avatar`);
}
return ctx;
}
type AvatarProps = React.ComponentProps<"span"> & {
size?: "default" | "sm" | "lg";
};
function Avatar({
className,
size = "default",
children,
...props
}: AvatarProps) {
const [imageLoadingStatus, setImageLoadingStatus] =
React.useState<ImageLoadingStatus>("idle");
const ctxValue = React.useMemo<AvatarContextValue>(
() => ({
imageLoadingStatus,
onImageLoadingStatusChange: setImageLoadingStatus,
}),
[imageLoadingStatus]
);
return (
<AvatarContext.Provider value={ctxValue}>
<span
className={cn(
"group/avatar after:border-border relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
)}
data-size={size}
data-slot="avatar"
{...props}
>
{children}
</span>
</AvatarContext.Provider>
);
}
type AvatarImageProps = React.ComponentProps<"img"> & {
onLoadingStatusChange?: (status: ImageLoadingStatus) => void;
};
function AvatarImage({
alt,
className,
onLoadingStatusChange,
referrerPolicy,
src,
...props
}: AvatarImageProps) {
const { onImageLoadingStatusChange } = useAvatarContext("AvatarImage");
const isStringSrc = typeof src === "string";
const imageLoadingStatus = useImageLoadingStatus(
isStringSrc ? src : undefined,
referrerPolicy
);
React.useEffect(() => {
onImageLoadingStatusChange(imageLoadingStatus);
}, [imageLoadingStatus, onImageLoadingStatusChange]);
React.useEffect(() => {
onLoadingStatusChange?.(imageLoadingStatus);
}, [imageLoadingStatus, onLoadingStatusChange]);
if (isStringSrc && imageLoadingStatus !== "loaded") {
return null;
}
return (
<img
alt={alt}
className={cn(
"aspect-square size-full rounded-full object-cover",
className
)}
data-slot="avatar-image"
referrerPolicy={referrerPolicy}
src={src}
{...props}
/>
);
}
function AvatarFallback({ className, ...props }: React.ComponentProps<"span">) {
const { imageLoadingStatus } = useAvatarContext("AvatarFallback");
if (imageLoadingStatus === "loaded") {
return null;
}
return (
<span
className={cn(
"bg-muted text-muted-foreground data-[status=error]:bg-destructive flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs data-[status=error]:text-white",
className
)}
data-slot="avatar-fallback"
data-status={imageLoadingStatus}
{...props}
/>
);
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"bg-primary text-primary-foreground ring-background absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-blend-color ring-2 select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
data-slot="avatar-badge"
{...props}
/>
);
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"group/avatar-group *:data-[slot=avatar]:ring-background flex -space-x-2 *:data-[slot=avatar]:ring-2",
className
)}
data-slot="avatar-group"
{...props}
/>
);
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
data-slot="avatar-group-count"
{...props}
/>
);
}
export {
Avatar,
AvatarBadge,
AvatarFallback,
AvatarGroup,
AvatarGroupCount,
AvatarImage,
type AvatarImageProps,
};Avatar no longer depends on radix-ui. The image loading state lives in a small context hook, so AvatarImage and AvatarFallback share it. A failed load auto-styles the fallback with the destructive token — distinguishable from a missing image without extra state.
Changed:
- Removed
radix-uifromdependencies. - New
data-statusattribute onAvatarFallback:idle,loading,loaded,error. - Failed
AvatarImageloads auto-render the fallback withbg-destructiveandtext-white. --destructivein light mode drops chroma from0.245to0.18for a softer surface across Button, Badge, and Input.
See the Avatar docs.
Collapsible
Order #4189
Shipping address
100 Market St, San Francisco
Items
2x Studio Headphones
"use client";
import * as React from "react";
import { getTransition, parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";
const defaultCollapsibleMotion = "450 cubic-bezier(0.32, 0.72, 0, 1)";
interface CollapsibleContextValue {
contentId: string;
disabled: boolean;
motion: string | undefined;
onOpenChange: (open: boolean) => void;
open: boolean;
triggerId: string;
}
const CollapsibleContext = React.createContext<CollapsibleContextValue | null>(
null
);
function useCollapsibleContext(component: string): CollapsibleContextValue {
const ctx = React.useContext(CollapsibleContext);
if (!ctx) {
throw new Error(`${component} must be used within Collapsible`);
}
return ctx;
}
interface CollapsibleProps
extends Omit<React.ComponentProps<"div">, "onChange"> {
defaultOpen?: boolean;
disabled?: boolean;
motion?: string;
onOpenChange?: (open: boolean) => void;
open?: boolean;
}
function Collapsible({
children,
className,
defaultOpen,
disabled = false,
motion,
onOpenChange,
open: openProp,
...props
}: CollapsibleProps) {
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(
defaultOpen ?? false
);
const isControlled = openProp !== undefined;
const open = isControlled ? openProp : uncontrolledOpen;
const triggerId = React.useId();
const contentId = React.useId();
const setOpen = React.useCallback(
(next: boolean) => {
if (!isControlled) {
setUncontrolledOpen(next);
}
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const context = React.useMemo<CollapsibleContextValue>(
() => ({
contentId,
disabled,
motion,
onOpenChange: setOpen,
open,
triggerId,
}),
[contentId, disabled, motion, setOpen, open, triggerId]
);
return (
<CollapsibleContext.Provider value={context}>
<div
className={className}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible"
data-state={open ? "open" : "closed"}
{...props}
>
{children}
</div>
</CollapsibleContext.Provider>
);
}
type CollapsibleTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
as?: React.ElementType;
ref?: React.Ref<HTMLButtonElement>;
} & Record<string, unknown>;
function CollapsibleTrigger({
as,
children,
className,
onClick,
ref,
...props
}: CollapsibleTriggerProps) {
const { contentId, disabled, onOpenChange, open, triggerId } =
useCollapsibleContext("CollapsibleTrigger");
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented || disabled) {
return;
}
onOpenChange(!open);
};
const finalProps: Record<string, unknown> = {
...props,
"aria-controls": contentId,
"aria-expanded": open,
className: cn(className),
"data-disabled": disabled ? "" : undefined,
"data-slot": "collapsible-trigger",
"data-state": open ? "open" : "closed",
id: triggerId,
onClick: handleClick,
ref,
};
if (!(as || "type" in props)) {
finalProps.type = "button";
finalProps.disabled = disabled;
}
const Comp = as ?? "button";
return <Comp {...finalProps}>{children}</Comp>;
}
interface CollapsibleContentProps extends React.ComponentProps<"div"> {
motion?: string | false;
}
function CollapsibleContent({
children,
className,
motion: localMotion,
style,
...props
}: CollapsibleContentProps) {
const {
contentId,
disabled,
motion: contextMotion,
open,
triggerId,
} = useCollapsibleContext("CollapsibleContent");
const reduce = useReducedMotion();
const motionProp =
localMotion === false ? "off" : (localMotion ?? contextMotion);
const motionValue = motionProp ?? defaultCollapsibleMotion;
const gridStyle: React.CSSProperties = {
display: "grid",
gridTemplateRows: open ? "1fr" : "0fr",
opacity: open ? 1 : 0,
...style,
};
if (reduce) {
gridStyle.transition = "none";
} else {
const transition = getTransition(parseMotion(motionValue));
if (transition) {
gridStyle.transition = transition;
}
}
return (
<div
aria-labelledby={triggerId}
data-disabled={disabled ? "" : undefined}
data-slot="collapsible-content"
data-state={open ? "open" : "closed"}
id={contentId}
role="region"
{...props}
>
<div inert={!open} style={gridStyle}>
<div style={{ minHeight: 0, overflow: "hidden" }}>
<div className={cn(className)}>{children}</div>
</div>
</div>
</div>
);
}
export { Collapsible, CollapsibleContent, CollapsibleTrigger };Collapsible no longer depends on radix-ui or motion/react. The reveal runs through Frakment's motion engine, and the height animates via CSS grid rows.
Changed:
- Removed
radix-uiandmotionfromdependencies. - New
motionprop accepts"off","150","150 ease-out", or"150 cubic-bezier(...)". Default is a 450ms smooth-out curve. - Per-content override on
CollapsibleContent. - Height animates via CSS grid rows (
0frto1fr). CollapsibleTriggeracceptsasfor custom trigger elements.asChildstays for backward compatibility.
See the Collapsible docs.
as prop rollout (Badge, Collapsible, Button Group Text)
Badge, Collapsible Trigger, and Button Group Text now accept a single polymorphic as prop instead of asChild. Pass as={Link} to render a router link, as={Button} to slot a custom surface, or omit to keep the default element.
Changed:
Badgeacceptsas.asChildis removed; useas={Link}for anchors oras={Custom}for other elements.CollapsibleTriggeracceptsas.asChildis removed.ButtonGroupTextacceptsas.asChildis deprecated and kept for backward compatibility.
See the Badge, Collapsible, and Button Group docs.
Breadcrumb
import { ChevronRightIcon, MoreHorizontalIcon } from "lucide-react";
import type * as React from "react";
import { Slot } from "@/components/ui/slot";
import { cn } from "@/lib/utils";
function Breadcrumb({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
aria-label="breadcrumb"
className={cn(className)}
data-slot="breadcrumb"
{...props}
/>
);
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm wrap-break-word",
className
)}
data-slot="breadcrumb-list"
{...props}
/>
);
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
className={cn("inline-flex items-center gap-1", className)}
data-slot="breadcrumb-item"
{...props}
/>
);
}
type BreadcrumbLinkProps = Omit<React.ComponentProps<"a">, "ref"> & {
as?: React.ElementType;
asChild?: boolean;
ref?: React.Ref<HTMLAnchorElement>;
} & Record<string, unknown>;
function BreadcrumbLink({
as,
asChild = false,
className,
...props
}: BreadcrumbLinkProps) {
const Comp = as ?? (asChild ? Slot : "a");
return (
<Comp
className={cn("hover:text-foreground transition-colors", className)}
data-slot="breadcrumb-link"
{...props}
/>
);
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
aria-current="page"
aria-disabled="true"
className={cn("text-foreground font-normal", className)}
data-slot="breadcrumb-page"
{...props}
/>
);
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
data-slot="breadcrumb-separator"
role="presentation"
{...props}
>
{children ?? <ChevronRightIcon />}
</li>
);
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden="true"
className={cn(
"flex size-5 items-center justify-center [&>svg]:size-4",
className
)}
data-slot="breadcrumb-ellipsis"
role="presentation"
{...props}
>
<MoreHorizontalIcon />
<span className="sr-only">More</span>
</span>
);
}
export {
Breadcrumb,
BreadcrumbEllipsis,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
};Breadcrumb no longer depends on radix-ui. The link part accepts a single as prop instead of asChild.
Changed:
- Removed
radix-uifromdependencies. - New
registryDependency:slot. BreadcrumbLinkacceptsasfor router links.asChildis deprecated and kept for backward compatibility.
See the Breadcrumb docs.
Input OTP
"use client";
import { MinusIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const digits = "^\\d+$";
const chars = "^[a-zA-Z]+$";
const alphanumeric = "^[a-zA-Z0-9]+$";
interface SlotProps {
char: string | null;
hasFakeCaret: boolean;
isActive: boolean;
placeholderChar: string | null;
}
interface RenderProps {
isFocused: boolean;
isHovering: boolean;
slots: SlotProps[];
}
const OTPInputContext = React.createContext<RenderProps>({
isFocused: false,
isHovering: false,
slots: [],
});
type OTPInputBaseProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"value" | "onChange" | "maxLength" | "pattern" | "placeholder"
> & {
containerClassName?: string;
maxLength: number;
onChange?: (value: string) => void;
pattern?: string;
placeholder?: string;
value?: string;
};
type OTPInputProps = OTPInputBaseProps & {
children?: React.ReactNode;
};
const InputOTP = React.forwardRef<HTMLInputElement, OTPInputProps>(
function InputOTP(
{
children,
className,
containerClassName,
defaultValue,
disabled,
id,
inputMode = "numeric",
maxLength,
onChange,
onFocus,
onBlur,
pattern,
placeholder,
value: valueProp,
...props
},
forwardedRef
) {
const isControlled = valueProp !== undefined;
const [uncontrolled, setUncontrolled] = React.useState<string>(
typeof defaultValue === "string" ? defaultValue : ""
);
const value = isControlled ? valueProp : uncontrolled;
const [isFocused, setIsFocused] = React.useState(false);
const [isHovering, setIsHovering] = React.useState(false);
const [selectionStart, setSelectionStart] = React.useState(0);
const [selectionEnd, setSelectionEnd] = React.useState(0);
const inputRef = React.useRef<HTMLInputElement>(null);
const setRef = React.useCallback(
(node: HTMLInputElement | null) => {
inputRef.current = node;
if (typeof forwardedRef === "function") {
forwardedRef(node);
} else if (forwardedRef) {
(
forwardedRef as React.MutableRefObject<HTMLInputElement | null>
).current = node;
}
},
[forwardedRef]
);
const filterValue = React.useCallback(
(raw: string): string => {
let next = raw.slice(0, maxLength);
if (pattern) {
const re = new RegExp(pattern);
if (!re.test(next)) {
next = next
.split("")
.filter((c) => new RegExp(pattern.replace(/[+*]$/, "")).test(c))
.join("");
}
}
return next;
},
[maxLength, pattern]
);
const commit = React.useCallback(
(next: string) => {
const filtered = filterValue(next);
if (!isControlled) {
setUncontrolled(filtered);
}
onChange?.(filtered);
},
[filterValue, isControlled, onChange]
);
const updateSelection = React.useCallback(() => {
const el = inputRef.current;
if (!el) {
return;
}
setSelectionStart(el.selectionStart ?? 0);
setSelectionEnd(el.selectionEnd ?? 0);
}, []);
const slots = React.useMemo<SlotProps[]>(
() =>
Array.from({ length: maxLength }).map((_, i) => {
const char = value[i] ?? null;
const active =
isFocused &&
((selectionStart === selectionEnd && i === selectionStart) ||
(i >= selectionStart && i < selectionEnd));
return {
char,
hasFakeCaret: active && char === null,
isActive: active,
placeholderChar: null,
};
}),
[value, maxLength, isFocused, selectionStart, selectionEnd]
);
const contextValue = React.useMemo<RenderProps>(
() => ({ isFocused, isHovering, slots }),
[isFocused, isHovering, slots]
);
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
commit(event.currentTarget.value);
updateSelection();
};
const handleSelect = () => updateSelection();
const handleClick = () => {
inputRef.current?.focus();
updateSelection();
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
props.onKeyDown?.(event);
if (event.defaultPrevented) {
return;
}
requestAnimationFrame(updateSelection);
};
return (
<OTPInputContext.Provider value={contextValue}>
<div
className={cn("cn-input-otp flex items-center", containerClassName)}
data-slot="input-otp"
onClick={handleClick}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
<input
aria-label={props["aria-label"] ?? "One-time password"}
autoComplete="one-time-code"
className={cn(
"pointer-events-none absolute inset-0 -z-10 opacity-0",
className
)}
data-input-otp=""
defaultValue={
isControlled ? undefined : (defaultValue as string | undefined)
}
disabled={disabled}
id={id}
inputMode={inputMode}
maxLength={maxLength}
onBlur={(e) => {
setIsFocused(false);
onBlur?.(e);
}}
onChange={handleInput}
onFocus={(e) => {
setIsFocused(true);
updateSelection();
onFocus?.(e);
}}
onKeyDown={handleKeyDown}
onSelect={handleSelect}
pattern={pattern}
placeholder={placeholder}
ref={setRef}
value={isControlled ? value : undefined}
{...props}
/>
{children}
</div>
</OTPInputContext.Provider>
);
}
);
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"has-aria-invalid:border-destructive has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40 flex items-center rounded-lg has-aria-invalid:ring-3",
className
)}
data-slot="input-otp-group"
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & { index: number }) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index] ?? {};
return (
<div
className={cn(
"border-input aria-invalid:border-destructive data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40 relative flex size-8 items-center justify-center border-y border-r text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg data-[active=true]:z-10 data-[active=true]:ring-3",
className
)}
data-active={isActive}
data-slot="input-otp-slot"
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div
className="flex items-center [&_svg:not([class*='size-'])]:size-4"
data-slot="input-otp-separator"
role="separator"
{...props}
>
<MinusIcon />
</div>
);
}
export {
alphanumeric,
chars,
digits,
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
};Input OTP no longer depends on input-otp. The field renders a real hidden <input> so paste, backspace, arrow navigation, and form submission work natively. Each slot is a styled sibling driven by the input value.
Changed:
- Removed
input-otpfromdependencies. - Exports
digits,chars, andalphanumericregex patterns instead ofREGEXP_*constants. - Pattern filtering runs on
onChangeso pasted values are sanitized against the pattern.
See the Input OTP docs.
Native Separator & Button Group
import { View, type ViewProps, type ViewStyle } from "react-native";
import { useThemeColors } from "@/lib/theme";
import { cn } from "@/lib/utils";
export interface SeparatorProps extends Omit<ViewProps, "style"> {
decorative?: boolean;
orientation?: "horizontal" | "vertical";
style?: ViewStyle;
}
function Separator({
decorative = true,
orientation = "horizontal",
className,
style,
...props
}: SeparatorProps) {
const colors = useThemeColors();
const isHorizontal = orientation === "horizontal";
const baseStyle: ViewStyle = {
backgroundColor: colors.border,
flexShrink: 0,
...(isHorizontal
? { height: 1, width: "100%" }
: { alignSelf: "stretch", width: 1 }),
...style,
};
return (
<View
accessibilityRole={decorative ? "none" : undefined}
accessible={!decorative}
className={cn(className)}
style={baseStyle}
{...props}
/>
);
}
export { Separator };import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import {
Text,
type TextStyle,
View,
type ViewProps,
type ViewStyle,
} from "react-native";
import { Separator } from "@/components/ui/separator";
import { useThemeColors } from "@/lib/theme";
import { cn } from "@/lib/utils";
const buttonGroupVariants = cva("flex w-fit", {
defaultVariants: {
orientation: "horizontal",
},
variants: {
orientation: {
horizontal: "flex-row items-stretch",
vertical: "flex-col items-stretch",
},
},
});
function ButtonGroup({
className,
orientation = "horizontal",
style,
children,
...props
}: Omit<ViewProps, "style"> &
VariantProps<typeof buttonGroupVariants> & { style?: ViewStyle }) {
const isHorizontal = orientation !== "vertical";
const items = React.Children.toArray(children);
const validIndexes = items
.map((c, i) => (React.isValidElement(c) ? i : -1))
.filter((i) => i >= 0);
const getChildTypeName = (c: React.ReactNode): string | undefined => {
if (!React.isValidElement(c)) {
return undefined;
}
const t = (c as React.ReactElement).type;
if (typeof t === "function") {
return (t as { name?: string }).name;
}
return undefined;
};
const firstIdx = validIndexes[0];
const lastIdx = validIndexes.at(-1);
const hasNestedGroups = items.some(
(c) =>
React.isValidElement(c) && (c as React.ReactElement).type === ButtonGroup
);
return (
<View
className={cn(
buttonGroupVariants({ orientation }),
hasNestedGroups && "gap-2",
className
)}
style={style}
{...props}
>
{items.map((child, index) => {
if (!React.isValidElement(child)) {
return child;
}
const typeName = getChildTypeName(child);
if (typeName === "ButtonGroup" || typeName === "ButtonGroupSeparator") {
return child;
}
const isFirst = index === firstIdx;
const isLast = index === lastIdx;
const overrides: Record<string, number> = {};
if (!isFirst) {
if (isHorizontal) {
overrides.borderLeftWidth = 0;
overrides.borderTopLeftRadius = 0;
overrides.borderBottomLeftRadius = 0;
} else {
overrides.borderTopWidth = 0;
overrides.borderTopLeftRadius = 0;
overrides.borderTopRightRadius = 0;
}
}
if (!isLast) {
if (isHorizontal) {
overrides.borderTopRightRadius = 0;
overrides.borderBottomRightRadius = 0;
} else {
overrides.borderBottomLeftRadius = 0;
overrides.borderBottomRightRadius = 0;
}
}
const childProps = child.props as { style?: ViewStyle };
const mergedStyle: ViewStyle = {
...overrides,
...childProps.style,
} as ViewStyle;
return React.cloneElement(
child as React.ReactElement<{ style?: ViewStyle }>,
{ style: mergedStyle }
);
})}
</View>
);
}
function ButtonGroupText({
className,
style,
children,
...props
}: Omit<ViewProps, "style"> & { style?: ViewStyle }) {
const colors = useThemeColors();
const baseStyle: ViewStyle = {
alignItems: "center",
backgroundColor: colors.secondary,
borderColor: colors.border,
borderRadius: 10,
borderWidth: 1,
flexDirection: "row",
gap: 8,
paddingHorizontal: 10,
...style,
};
const textStyle: TextStyle = {
color: colors.secondaryForeground,
fontSize: 14,
fontWeight: "500",
};
return (
<View className={cn(className)} style={baseStyle} {...props}>
{React.Children.map(children, (child) =>
typeof child === "string" || typeof child === "number" ? (
<Text style={textStyle}>{child}</Text>
) : (
child
)
)}
</View>
);
}
function ButtonGroupSeparator({
orientation = "vertical",
style,
...props
}: Omit<React.ComponentProps<typeof Separator>, "style"> & {
style?: ViewStyle;
}) {
const marginStyle: ViewStyle =
orientation === "vertical"
? { marginVertical: 1 }
: { marginHorizontal: 1 };
return (
<Separator
orientation={orientation}
style={{
alignSelf: "stretch",
backgroundColor: "transparent",
...marginStyle,
...style,
}}
{...props}
/>
);
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
};Separator and Button Group are now available for React Native via Expo. Separator renders as a View with a 1px line. Button Group lays out children in a row or column, strips the inner border and radius on adjacent children, and paints the separator variant with the input token so it matches the web composition.
Both read colors from useThemeColors(), so light and dark mode track the device system preference.
Installation
Install Separator first
Copy from the Separator docs. No CLI flag for native yet.
Install Button Group
Copy from the Button Group docs.
Minimal usage
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import { ButtonDemo } from "@/examples/button-demo";
import { ButtonGroupDemo } from "@/examples/button-group-demo";
import { SeparatorDemo } from "@/examples/separator-demo";
<Separator />
<ButtonGroup>
<Button variant="outline">Archive</Button>
<Button variant="outline">Report</Button>
</ButtonGroup>