For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

November 15, 2026

Label drops radix, message consolidates, marker/attachment/switch/progress/slider/tooltip ship native, and dialog/item/checkbox/hover-card/tabs join them with docs migration to web paths.

Nine components ship native today, alongside the earlier consolidations in this date. Label drops radix, Message consolidates four primitives into one, Marker, Attachment, Switch, Progress, Slider, Tooltip drop to native implementations, and Dialog, Item, Checkbox, Hover Card, Tabs join them with a full native rewrite. Four already-native components move their docs to /docs/components/web/.


Label

label.tsx
"use client";

import type * as React from "react";
import { cn } from "@/lib/utils";

function Label({
  className,
  onMouseDown,
  ...props
}: React.ComponentProps<"label">) {
  return (
    <label
      className={cn(
        "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
        className
      )}
      data-slot="label"
      onMouseDown={(event) => {
        onMouseDown?.(event);
        if (!event.defaultPrevented && event.detail > 1) {
          event.preventDefault();
        }
      }}
      {...props}
    />
  );
}

export { Label };

Label renders a native <label> that forwards clicks to its associated control via htmlFor. Behavior is unchanged for consumers using htmlFor and className. The mousedown guard that prevents double-click text selection is preserved. The as prop is intentionally not added: a polymorphic label would lose the htmlFor association.

Installation

$ npx frakment@latest add label

Message consolidation

ME
Deploying to prod real quick.
OL
It is 4:55 PM. On a Friday.
ME
It is a one-line change.
Delivered
OL
It is always a one-line change.
Alright, let me take a look.
👍
Oliver is typing...
message.tsx
"use client";

import { cva, type VariantProps } from "class-variance-authority";
import { ArrowDownIcon } from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import {
  getTransition,
  parseMotion,
  useMotionGuard,
  useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";

interface UIMessagePart {
  text?: string;
  type: string;
}

interface UIMessage {
  id: string;
  metadata?: unknown;
  parts: UIMessagePart[];
  role: "user" | "assistant" | "system";
}

function getMessageText(message: UIMessage): string {
  if (!Array.isArray(message.parts)) {
    return "";
  }
  return message.parts
    .filter(
      (part): part is { type: "text"; text: string } =>
        part.type === "text" && typeof part.text === "string"
    )
    .map((part) => part.text)
    .join("");
}

function MessageGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex min-w-0 flex-col gap-2", className)}
      data-slot="message-group"
      {...props}
    />
  );
}

function Message({
  className,
  align = "start",
  ...props
}: React.ComponentProps<"div"> & { align?: "start" | "end" }) {
  return (
    <div
      className={cn(
        "group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse",
        className
      )}
      data-align={align}
      data-slot="message"
      {...props}
    />
  );
}

function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "bg-muted flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full group-has-data-[slot=message-footer]/message:-translate-y-8",
        className
      )}
      data-slot="message-avatar"
      {...props}
    />
  );
}
function MessageContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full min-w-0 flex-col gap-2.5 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end",
        className
      )}
      data-slot="message-content"
      {...props}
    />
  );
}

function MessageHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0",
        className
      )}
      data-slot="message-header"
      {...props}
    />
  );
}

function MessageFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "text-muted-foreground flex max-w-full min-w-0 items-center px-3 text-xs font-medium group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end",
        className
      )}
      data-slot="message-footer"
      {...props}
    />
  );
}

function BubbleGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex min-w-0 flex-col gap-2", className)}
      data-slot="bubble-group"
      {...props}
    />
  );
}

const bubbleVariants = cva(
  "group/bubble relative flex w-fit max-w-[80%] min-w-0 flex-col gap-1 group-data-[align=end]/message:self-end data-[align=end]:self-end data-[variant=ghost]:max-w-full",
  {
    defaultVariants: {
      variant: "default",
    },
    variants: {
      variant: {
        default:
          "*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80",
        destructive:
          "*:data-[slot=bubble-content]:bg-destructive/10 *:data-[slot=bubble-content]:text-destructive dark:*:data-[slot=bubble-content]:bg-destructive/20 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30",
        ghost:
          "[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50 border-none *:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0",
        muted:
          "*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]",
        outline:
          "*:data-[slot=bubble-content]:border-border *:data-[slot=bubble-content]:bg-background [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30",
        secondary:
          "*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]",
        tinted:
          "*:data-[slot=bubble-content]:text-foreground *:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]",
      },
    },
  }
);
function Bubble({
  variant = "default",
  align = "start",
  className,
  ...props
}: React.ComponentProps<"div"> &
  VariantProps<typeof bubbleVariants> & {
    align?: "start" | "end";
  }) {
  return (
    <div
      className={cn(bubbleVariants({ variant }), className)}
      data-align={align}
      data-slot="bubble"
      data-variant={variant}
      {...props}
    />
  );
}

type BubbleContentProps = Omit<React.ComponentProps<"div">, "ref"> & {
  as?: React.ElementType;
  ref?: React.Ref<HTMLDivElement>;
} & Record<string, unknown>;

function BubbleContent({ as, className, ref, ...props }: BubbleContentProps) {
  const Comp = as ?? "div";

  return (
    <Comp
      className={cn(
        "[button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-ring/50 w-fit max-w-full min-w-0 overflow-hidden rounded-xl border border-transparent px-3 py-2 text-sm leading-relaxed wrap-break-word group-data-[align=end]/bubble:self-end [button]:text-left [button,a]:transition-colors [button,a]:outline-none [button,a]:focus-visible:ring-3",
        className
      )}
      data-slot="bubble-content"
      ref={ref}
      {...props}
    />
  );
}
const bubbleReactionsVariants = cva(
  "bg-muted ring-card absolute z-10 flex w-fit shrink-0 items-center justify-center gap-1 rounded-full px-1.5 py-0.5 text-sm ring-3 has-[button]:p-0",
  {
    defaultVariants: {
      align: "end",
      side: "bottom",
    },
    variants: {
      align: {
        end: "right-3",
        start: "left-3",
      },
      side: {
        bottom: "bottom-0 translate-y-3/4",
        top: "top-0 -translate-y-3/4",
      },
    },
  }
);

function BubbleReactions({
  side = "bottom",
  align = "end",
  className,
  ...props
}: React.ComponentProps<"div"> & {
  align?: "start" | "end";
  side?: "top" | "bottom";
}) {
  return (
    <div
      className={cn(bubbleReactionsVariants({ align, side }), className)}
      data-align={align}
      data-side={side}
      data-slot="bubble-reactions"
      {...props}
    />
  );
}

type ScrollDefaultPosition = "start" | "end" | "last-anchor";
type ScrollButtonDirection = "start" | "end";
type ScrollAlign = "start" | "center" | "end" | "nearest";

interface ScrollOptions {
  align?: ScrollAlign;
  behavior?: ScrollBehavior;
  scrollMargin?: number;
}
interface Scrollable {
  end: boolean;
  start: boolean;
}
interface VisibilityState {
  currentAnchorId: string | null;
  visibleMessageIds: string[];
}
interface ScrollerProviderProps {
  autoScroll?: boolean;
  children?: React.ReactNode;
  defaultScrollPosition?: ScrollDefaultPosition;
  scrollEdgeThreshold?: number;
  scrollMargin?: number;
  scrollPreviousItemPeek?: number;
}
type ScrollerProps = React.ComponentProps<"div">;
type ScrollerViewportProps = React.ComponentProps<"div"> & {
  preserveScrollOnPrepend?: boolean;
};
type ScrollerContentProps = React.ComponentProps<"div"> & {
  spacerClassName?: string;
};
type ScrollerItemProps = React.ComponentProps<"div"> & {
  messageId?: string;
  scrollAnchor?: boolean;
};
type ScrollerButtonDirection = ScrollButtonDirection;
type ScrollerButtonProps = Omit<
  React.ComponentProps<"button">,
  "children" | "render"
> & {
  children?: React.ReactNode;
  behavior?: ScrollBehavior;
  direction?: ScrollerButtonDirection;
  render?: React.ReactElement;
};
interface ScrollerContextValue {
  autoScroll: boolean;
  contentRef: React.RefObject<HTMLDivElement | null>;
  defaultScrollPosition: ScrollDefaultPosition;
  itemElements: Map<string, HTMLDivElement>;
  preserveScrollOnPrependRef: React.MutableRefObject<boolean>;
  registerItem: (id: string, el: HTMLDivElement) => () => void;
  scrollable: Scrollable;
  scrollEdgeThreshold: number;
  scrollMargin: number;
  scrollPreviousItemPeek: number;
  scrollToEnd: (opts?: ScrollOptions) => boolean;
  scrollToMessage: (messageId: string, opts?: ScrollOptions) => boolean;
  scrollToStart: (opts?: ScrollOptions) => boolean;
  setContentPresent: (present: boolean) => void;
  setPreserveScrollOnPrepend: (v: boolean) => void;
  setViewportPresent: (present: boolean) => void;
  viewportRef: React.RefObject<HTMLDivElement | null>;
  visibility: VisibilityState;
}

const ScrollerContext = React.createContext<ScrollerContextValue | null>(null);

function useScrollerContext(): ScrollerContextValue {
  const ctx = React.useContext(ScrollerContext);
  if (!ctx) {
    throw new Error(
      "MessageScroller components must be used within <MessageScroller.Provider>"
    );
  }
  return ctx;
}

function ScrollerProvider({
  children,
  autoScroll = true,
  defaultScrollPosition = "end",
  scrollEdgeThreshold = 16,
  scrollPreviousItemPeek = 40,
  scrollMargin = 0,
}: ScrollerProviderProps) {
  const viewportRef = React.useRef<HTMLDivElement | null>(null);
  const contentRef = React.useRef<HTMLDivElement | null>(null);
  const itemElements = React.useRef<Map<string, HTMLDivElement>>(new Map());
  const preserveScrollOnPrependRef = React.useRef(false);
  const [contentPresent, setContentPresent] = React.useState(false);
  const [viewportPresent, setViewportPresent] = React.useState(false);
  const [scrollable, setScrollable] = React.useState<Scrollable>({
    end: false,
    start: false,
  });
  const [visibility, setVisibility] = React.useState<VisibilityState>({
    currentAnchorId: null,
    visibleMessageIds: [],
  });

  const setPreserveScrollOnPrepend = React.useCallback((v: boolean) => {
    preserveScrollOnPrependRef.current = v;
  }, []);

  const registerItem = React.useCallback((id: string, el: HTMLDivElement) => {
    itemElements.current.set(id, el);
    return () => {
      itemElements.current.delete(id);
    };
  }, []);

  const computeScrollable = React.useCallback(() => {
    const vp = viewportRef.current;
    if (!vp) {
      return;
    }
    const start = vp.scrollTop > scrollEdgeThreshold;
    const end =
      vp.scrollHeight - vp.clientHeight - vp.scrollTop > scrollEdgeThreshold;
    setScrollable((prev) =>
      prev.start === start && prev.end === end ? prev : { end, start }
    );
  }, [scrollEdgeThreshold]);

  const computeVisibility = React.useCallback(() => {
    const vp = viewportRef.current;
    if (!vp) {
      return;
    }
    const vpRect = vp.getBoundingClientRect();
    const visible: string[] = [];
    let currentAnchorId: string | null = null;
    let bestTop = Number.POSITIVE_INFINITY;
    itemElements.current.forEach((el, id) => {
      const r = el.getBoundingClientRect();
      if (r.bottom > vpRect.top && r.top < vpRect.bottom) {
        visible.push(id);
        if (r.top >= vpRect.top - 1 && r.top < bestTop) {
          bestTop = r.top;
          currentAnchorId = id;
        }
      }
    });
    setVisibility((prev) => {
      if (
        prev.currentAnchorId === currentAnchorId &&
        prev.visibleMessageIds.length === visible.length &&
        prev.visibleMessageIds.every((v, i) => v === visible[i])
      ) {
        return prev;
      }
      return { currentAnchorId, visibleMessageIds: visible };
    });
  }, []);

  const onScroll = React.useCallback(() => {
    computeScrollable();
    computeVisibility();
  }, [computeScrollable, computeVisibility]);
  const scrollToEnd = React.useCallback((opts?: ScrollOptions) => {
    const vp = viewportRef.current;
    if (!vp) {
      return false;
    }
    vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: vp.scrollHeight });
    return true;
  }, []);

  const scrollToStart = React.useCallback((opts?: ScrollOptions) => {
    const vp = viewportRef.current;
    if (!vp) {
      return false;
    }
    vp.scrollTo({ behavior: opts?.behavior ?? "smooth", top: 0 });
    return true;
  }, []);

  const scrollToMessage = React.useCallback(
    (messageId: string, opts?: ScrollOptions) => {
      const el = itemElements.current.get(messageId);
      if (!el) {
        return false;
      }
      el.scrollIntoView({
        behavior: opts?.behavior ?? "smooth",
        block: opts?.align ?? "start",
        inline: "nearest",
      });
      return true;
    },
    []
  );

  React.useEffect(() => {
    const vp = viewportRef.current;
    if (!vp) {
      return;
    }
    vp.addEventListener("scroll", onScroll, { passive: true });
    computeScrollable();
    computeVisibility();
    return () => vp.removeEventListener("scroll", onScroll);
  }, [onScroll, computeScrollable, computeVisibility, viewportPresent]);

  React.useEffect(() => {
    if (!contentPresent) {
      return;
    }
    const vp = viewportRef.current;
    if (!vp) {
      return;
    }
    if (defaultScrollPosition === "start") {
      vp.scrollTop = 0;
    } else if (defaultScrollPosition === "end") {
      vp.scrollTop = vp.scrollHeight;
    }
  }, [contentPresent, defaultScrollPosition]);

  React.useEffect(() => {
    if (!autoScroll) {
      return;
    }
    const vp = viewportRef.current;
    const content = contentRef.current;
    if (!(vp && content)) {
      return;
    }
    if (typeof ResizeObserver === "undefined") {
      return;
    }
    const observer = new ResizeObserver(() => {
      const distance = vp.scrollHeight - vp.clientHeight - vp.scrollTop;
      if (distance <= scrollEdgeThreshold) {
        vp.scrollTop = vp.scrollHeight;
      }
      computeScrollable();
    });
    observer.observe(content);
    return () => observer.disconnect();
  }, [autoScroll, scrollEdgeThreshold, computeScrollable, viewportPresent]);

  const value: ScrollerContextValue = {
    autoScroll,
    contentRef,
    defaultScrollPosition,
    itemElements: itemElements.current,
    preserveScrollOnPrependRef,
    registerItem,
    scrollable,
    scrollEdgeThreshold,
    scrollMargin,
    scrollPreviousItemPeek,
    scrollToEnd,
    scrollToMessage,
    scrollToStart,
    setContentPresent,
    setPreserveScrollOnPrepend,
    setViewportPresent,
    viewportRef,
    visibility,
  };

  return (
    <ScrollerContext.Provider value={value}>
      {children}
    </ScrollerContext.Provider>
  );
}
function ScrollerRoot({ children, ...props }: ScrollerProps) {
  return <div {...props}>{children}</div>;
}

function ScrollerViewport({
  children,
  onScroll,
  preserveScrollOnPrepend,
  ref,
  ...props
}: ScrollerViewportProps) {
  const ctx = useScrollerContext();
  const setRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      ctx.viewportRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
      }
    },
    [ctx.viewportRef, ref]
  );

  React.useEffect(() => {
    if (preserveScrollOnPrepend !== undefined) {
      ctx.setPreserveScrollOnPrepend(preserveScrollOnPrepend);
    }
  }, [preserveScrollOnPrepend, ctx]);

  const ctxRef = React.useRef(ctx);
  ctxRef.current = ctx;
  React.useEffect(() => {
    ctxRef.current.setViewportPresent(true);
    return () => ctxRef.current.setViewportPresent(false);
  }, []);

  return (
    <div onScroll={onScroll} ref={setRef} {...props}>
      {children}
    </div>
  );
}

function ScrollerContent({ children, ...props }: ScrollerContentProps) {
  const ctx = useScrollerContext();

  React.useEffect(() => {
    ctx.setContentPresent(true);
    return () => ctx.setContentPresent(false);
  }, [ctx]);

  return (
    <div ref={ctx.contentRef} {...props}>
      {children}
    </div>
  );
}

function ScrollerItem({
  messageId,
  scrollAnchor,
  children,
  ref,
  ...props
}: ScrollerItemProps) {
  const ctx = useScrollerContext();
  const localRef = React.useRef<HTMLDivElement | null>(null);
  const setRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      localRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
      }
    },
    [ref]
  );

  React.useEffect(() => {
    if (!(messageId && localRef.current)) {
      return;
    }
    return ctx.registerItem(messageId, localRef.current);
  }, [messageId, ctx]);

  return (
    <div
      data-scroll-anchor={scrollAnchor ? "true" : undefined}
      ref={setRef}
      {...props}
    >
      {children}
    </div>
  );
}
function ScrollerButton({
  direction = "end",
  behavior = "smooth",
  onClick,
  render,
  children,
  type = "button",
  ...props
}: ScrollerButtonProps) {
  const ctx = useScrollerContext();
  const active =
    direction === "end" ? ctx.scrollable.end : ctx.scrollable.start;

  const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
    onClick?.(e);
    if (e.defaultPrevented) {
      return;
    }
    if (direction === "end") {
      ctx.scrollToEnd({ behavior });
    } else {
      ctx.scrollToStart({ behavior });
    }
  };

  const mergedProps = {
    ...props,
    children,
    "data-active": active ? "true" : "false",
    "data-direction": direction,
    onClick: handleClick,
    type,
  } as React.ButtonHTMLAttributes<HTMLButtonElement> & Record<string, unknown>;

  if (render && React.isValidElement(render)) {
    return React.cloneElement(
      render as React.ReactElement<Record<string, unknown>>,
      mergedProps
    );
  }

  return <button {...mergedProps} />;
}

function useMessageScroller() {
  const ctx = useScrollerContext();
  return {
    scrollToEnd: ctx.scrollToEnd,
    scrollToMessage: ctx.scrollToMessage,
    scrollToStart: ctx.scrollToStart,
  };
}

function useMessageScrollerScrollable() {
  return useScrollerContext().scrollable;
}

function useMessageScrollerVisibility() {
  return useScrollerContext().visibility;
}

function MessageScrollerProvider(props: ScrollerProviderProps) {
  return <ScrollerProvider {...props} />;
}

function MessageScroller({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <ScrollerRoot
      className={cn(
        "group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",
        className
      )}
      data-slot="message-scroller"
      {...props}
    />
  );
}

function MessageScrollerViewport({
  className,
  ...props
}: React.ComponentProps<"div"> & { preserveScrollOnPrepend?: boolean }) {
  return (
    <ScrollerViewport
      className={cn(
        "scroll-fade-b size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain contain-content data-pending-scroll:invisible",
        className
      )}
      data-slot="message-scroller-viewport"
      {...props}
    />
  );
}

function MessageScrollerContent({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <ScrollerContent
      className={cn("flex h-max min-h-full flex-col gap-6", className)}
      data-slot="message-scroller-content"
      {...props}
    />
  );
}

function MessageScrollerItem({
  className,
  scrollAnchor = false,
  ...props
}: React.ComponentProps<"div"> & {
  messageId?: string;
  scrollAnchor?: boolean;
}) {
  return (
    <ScrollerItem
      className={cn(
        "min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",
        className
      )}
      data-slot="message-scroller-item"
      scrollAnchor={scrollAnchor}
      {...props}
    />
  );
}

function MessageScrollerButton({
  direction = "end",
  className,
  children,
  render,
  variant = "secondary",
  size = "icon-sm",
  ...props
}: React.ComponentProps<"button"> &
  Pick<React.ComponentProps<typeof Button>, "variant" | "size"> & {
    direction?: "start" | "end";
    render?: React.ReactElement;
    behavior?: ScrollBehavior;
  }) {
  return (
    <ScrollerButton
      className={cn(
        "border-border bg-muted text-foreground hover:bg-muted/80 hover:text-foreground absolute inset-s-1/2 -translate-x-1/2 rounded-full transition-[translate,scale,opacity] duration-200 data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",
        className
      )}
      data-direction={direction}
      data-size={size}
      data-slot="message-scroller-button"
      data-variant={variant}
      direction={direction}
      render={render ?? <Button size={size} variant={variant} />}
      {...props}
    >
      {children ?? (
        <>
          <ArrowDownIcon />
          <span className="sr-only">
            {direction === "end" ? "Scroll to end" : "Scroll to start"}
          </span>
        </>
      )}
    </ScrollerButton>
  );
}

const defaultMessageAnimatedMotion = "200 ease-out";

interface MessageAnimatedProps {
  message: UIMessage;
  motion?: string;
  scrollAnchor?: boolean;
}

function MessageAnimated({
  message,
  motion,
  scrollAnchor,
}: MessageAnimatedProps) {
  const text = getMessageText(message);
  const isUser = message.role === "user";
  const reduce = useReducedMotion();
  const motionValue = motion ?? defaultMessageAnimatedMotion;
  const internalRef = React.useRef<HTMLDivElement | null>(null);
  const [entered, setEntered] = React.useState(false);

  React.useEffect(() => {
    let raf1 = 0;
    let raf2 = 0;
    raf1 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(() => setEntered(true));
    });
    return () => {
      if (raf1) {
        cancelAnimationFrame(raf1);
      }
      if (raf2) {
        cancelAnimationFrame(raf2);
      }
    };
  }, []);

  let resolvedStyle: React.CSSProperties = {
    opacity: reduce ? 1 : entered ? 1 : 0,
    transform: reduce ? "none" : entered ? "translateY(0)" : "translateY(8px)",
  };

  if (reduce) {
    resolvedStyle.transition = "none";
  } else {
    const transition = getTransition(parseMotion(motionValue));
    if (transition) {
      resolvedStyle.transition = transition;
    }
  }

  const motionEnabled = !reduce;
  const styleFingerprint = JSON.stringify(resolvedStyle);
  const yielded = useMotionGuard(internalRef, motionEnabled, styleFingerprint);
  if (yielded && !reduce) {
    resolvedStyle = { ...resolvedStyle, transition: "none" };
  }

  return (
    <MessageScrollerItem scrollAnchor={scrollAnchor}>
      <div className="flex flex-col" ref={internalRef} style={resolvedStyle}>
        <Bubble
          align={isUser ? "end" : "start"}
          variant={isUser ? "muted" : "ghost"}
        >
          <BubbleContent className="whitespace-pre-wrap">{text}</BubbleContent>
        </Bubble>
      </div>
    </MessageScrollerItem>
  );
}

export type { UIMessage, UIMessagePart };
export {
  Bubble,
  BubbleContent,
  BubbleGroup,
  BubbleReactions,
  Message,
  MessageAnimated,
  MessageAvatar,
  MessageContent,
  MessageFooter,
  MessageGroup,
  MessageHeader,
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScroller,
  useMessageScrollerScrollable,
  useMessageScrollerVisibility,
};

Message, Bubble, MessageScroller, and MessageAnimated now ship as a single registry component. npx frakment add message installs all four primitives: layout (Message, MessageGroup, MessageContent), bubble (Bubble, BubbleContent, BubbleReactions), scroll behavior (MessageScroller* + three hooks), and animated message (MessageAnimated).

The scroll engine is inlined. The @frakment/react package is no longer published. Imports from @frakment/react/message-scroller must migrate to @/components/ui/message after running npx frakment@latest add message.

No runtime dependencies beyond class-variance-authority and lucide-react. The radix-ui and ai dependencies are removed from the bubble and animated parts.

Migration from the old registry names

  • npx frakment add bubble → npx frakment add message
  • npx frakment add message-scroller → npx frakment add message
  • npx frakment add message-animated → npx frakment add message
  • import ... from "@/components/ui/bubble" → import ... from "@/components/ui/message"

The BubbleContent asChild prop is replaced by as. Pass as={Link} or `as="a" for clickable bubbles.

Installation

$ npx frakment@latest add message

Minimal usage

tsx
<MessageScrollerProvider>
  <MessageScroller>
    <MessageScrollerViewport>
      <MessageScrollerContent>
        <MessageAnimated message={message} scrollAnchor={message.role === "user"} />
      </MessageScrollerContent>
    </MessageScrollerViewport>
    <MessageScrollerButton />
  </MessageScroller>
</MessageScrollerProvider>

Marker, Attachment, Switch, Progress

Switched to a new branch
Thinking...
Conversation compacted
Explored 4 files
marker.tsx
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import type * as React from "react";

import { cn } from "@/lib/utils";

const markerVariants = cva(
  "group/marker text-muted-foreground [a]:hover:text-foreground relative flex min-h-4 w-full items-center gap-2 text-left text-sm [&_svg:not([class*='size-'])]:size-4 [a]:underline [a]:underline-offset-3",
  {
    variants: {
      variant: {
        border: "border-border border-b pb-2",
        default: "",
        separator:
          "before:bg-border after:bg-border before:mr-1 before:h-px before:min-w-0 before:flex-1 after:ml-1 after:h-px after:min-w-0 after:flex-1",
      },
    },
  }
);

type MarkerProps = Omit<React.ComponentProps<"div">, "ref"> &
  VariantProps<typeof markerVariants> & {
    as?: React.ElementType;
    ref?: React.Ref<HTMLDivElement>;
  } & Record<string, unknown>;

function Marker({
  className,
  variant = "default",
  as,
  ref,
  ...props
}: MarkerProps) {
  const Comp = as ?? "div";
  return (
    <Comp
      className={cn(markerVariants({ className, variant }))}
      data-slot="marker"
      data-variant={variant}
      ref={ref}
      {...props}
    />
  );
}

function MarkerIcon({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      aria-hidden="true"
      className={cn(
        "size-4 shrink-0 [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      data-slot="marker-icon"
      {...props}
    />
  );
}

function MarkerContent({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      className={cn(
        "*:[a]:hover:text-foreground min-w-0 wrap-break-word group-data-[variant=separator]/marker:flex-none group-data-[variant=separator]/marker:text-center *:[a]:underline *:[a]:underline-offset-3",
        className
      )}
      data-slot="marker-content"
      {...props}
    />
  );
}

export { Marker, MarkerContent, MarkerIcon, markerVariants };
Workspace
workspace.avifAVIF · 42 KB
Desk
desk-reference.avifAVIF · 14 KB
Office
office-reference.avifAVIF · 38 KB
sales-dashboard.pdfUploading · 64%
message-renderer.tsxTypeScript · 12 KB
attachment.tsx
"use client";

import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import * as React from "react";

import { Button } from "@/components/ui/button";
import { Shimmer } from "@/components/ui/shimmer";
import { cn } from "@/lib/utils";

const attachmentVariants = cva(
  "group/attachment bg-card text-card-foreground focus-within:ring-ring/50 has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-xl border transition-colors focus-within:ring-1 data-[state=idle]:border-dashed",
  {
    variants: {
      orientation: {
        horizontal: "min-w-40 items-center",
        vertical: "w-24 flex-col has-data-[slot=attachment-content]:w-30",
      },
      size: {
        default:
          "gap-2 text-sm has-data-[slot=attachment-content]:px-2.5 has-data-[slot=attachment-content]:py-2 has-data-[slot=attachment-media]:p-2",
        sm: "gap-2.5 text-xs has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5",
        xs: "gap-1.5 rounded-lg text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
      },
    },
  }
);

const AttachmentContext = React.createContext<{
  state?: "idle" | "uploading" | "processing" | "error" | "done";
}>({});

function Attachment({
  className,
  state = "done",
  size = "default",
  orientation = "horizontal",
  ...props
}: React.ComponentProps<"div"> &
  VariantProps<typeof attachmentVariants> & {
    state?: "idle" | "uploading" | "processing" | "error" | "done";
  }) {
  return (
    <AttachmentContext.Provider value={{ state }}>
      <div
        className={cn(attachmentVariants({ orientation, size }), className)}
        data-orientation={orientation}
        data-size={size}
        data-slot="attachment"
        data-state={state}
        {...props}
      />
    </AttachmentContext.Provider>
  );
}

const attachmentMediaVariants = cva(
  "bg-muted text-foreground group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-md group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5",
  {
    defaultVariants: {
      variant: "icon",
    },
    variants: {
      variant: {
        icon: "",
        image:
          "opacity-60 group-data-[state=done]/attachment:opacity-100 group-data-[state=idle]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover",
      },
    },
  }
);

function AttachmentMedia({
  className,
  variant = "icon",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof attachmentMediaVariants>) {
  return (
    <div
      className={cn(attachmentMediaVariants({ variant }), className)}
      data-slot="attachment-media"
      data-variant={variant}
      {...props}
    />
  );
}

function AttachmentContent({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "max-w-full min-w-0 flex-1 text-sm leading-tight group-data-[orientation=vertical]/attachment:px-1",
        className
      )}
      data-slot="attachment-content"
      {...props}
    />
  );
}

function AttachmentTitle({
  className,
  children,
  ...props
}: React.ComponentProps<"span">) {
  const { state } = React.useContext(AttachmentContext);
  const shimmering = state === "processing" || state === "uploading";
  const content = shimmering ? <Shimmer>{children}</Shimmer> : children;
  return (
    <span
      className={cn("block max-w-full min-w-0 truncate font-medium", className)}
      data-slot="attachment-title"
      {...props}
    >
      {content}
    </span>
  );
}

function AttachmentDescription({
  className,
  ...props
}: React.ComponentProps<"span">) {
  return (
    <span
      className={cn(
        "text-muted-foreground group-data-[state=error]/attachment:text-destructive/80 mt-0.5 block min-w-0 truncate text-xs",
        "max-w-full",
        className
      )}
      data-slot="attachment-description"
      {...props}
    />
  );
}

function AttachmentActions({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "relative z-20 flex shrink-0 items-center group-data-[orientation=vertical]/attachment:absolute group-data-[orientation=vertical]/attachment:top-3 group-data-[orientation=vertical]/attachment:right-3 group-data-[orientation=vertical]/attachment:gap-1",
        className
      )}
      data-slot="attachment-actions"
      {...props}
    />
  );
}

function AttachmentAction({
  className,
  variant,
  size = "icon-xs",
  ...props
}: React.ComponentProps<typeof Button>) {
  return (
    <Button
      className={cn(className)}
      data-slot="attachment-action"
      size={size}
      variant={variant ?? "ghost"}
      {...props}
    />
  );
}

function AttachmentTrigger({
  className,
  as,
  ref,
  type,
  ...props
}: React.ComponentProps<"button"> & {
  as?: React.ElementType;
  ref?: React.Ref<HTMLButtonElement>;
}) {
  const Comp = as ?? "button";

  return (
    <Comp
      className={cn("absolute inset-0 z-10 outline-none", className)}
      data-slot="attachment-trigger"
      ref={ref}
      type={as ? undefined : (type ?? "button")}
      {...props}
    />
  );
}

function AttachmentGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex min-w-0 snap-x snap-mandatory scroll-px-1 scrollbar-none gap-3 overflow-x-auto overscroll-x-contain py-1 *:data-[slot=attachment]:flex-none *:data-[slot=attachment]:snap-start",
        className
      )}
      data-slot="attachment-group"
      {...props}
    />
  );
}

export {
  Attachment,
  AttachmentAction,
  AttachmentActions,
  AttachmentContent,
  AttachmentDescription,
  AttachmentGroup,
  AttachmentMedia,
  AttachmentTitle,
  AttachmentTrigger,
};
switch.tsx
"use client";

import * as React from "react";

import {
  getTransition,
  parseMotion,
  useMotionGuard,
  useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";

type SwitchSize = "sm" | "default";

type SwitchProps = Omit<
  React.ComponentProps<"button">,
  "onChange" | "role" | "aria-checked" | "type"
> & {
  checked?: boolean;
  defaultChecked?: boolean;
  disabled?: boolean;
  motion?: string;
  onCheckedChange?: (checked: boolean) => void;
  size?: SwitchSize;
};

function Switch({
  checked: checkedProp,
  className,
  defaultChecked = false,
  disabled = false,
  motion,
  onClick,
  onCheckedChange,
  ref,
  size = "default",
  ...props
}: SwitchProps) {
  const isControlled = checkedProp !== undefined;
  const [uncontrolledChecked, setUncontrolledChecked] =
    React.useState(defaultChecked);
  const checked = isControlled ? checkedProp : uncontrolledChecked;
  const reduce = useReducedMotion();
  const internalRef = React.useRef<HTMLButtonElement | null>(null);

  const setRef = React.useCallback(
    (node: HTMLButtonElement | null) => {
      internalRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLButtonElement | null>).current =
          node;
      }
    },
    [ref]
  );

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || disabled) {
      return;
    }
    const next = !checked;
    if (!isControlled) {
      setUncontrolledChecked(next);
    }
    onCheckedChange?.(next);
  };

  const motionValue = motion;
  const thumbStyle: React.CSSProperties = {};
  if (reduce) {
    thumbStyle.transition = "none";
  } else if (motionValue !== undefined) {
    const transition = getTransition(parseMotion(motionValue));
    if (transition) {
      thumbStyle.transition = transition;
    }
  }

  const motionEnabled = motionValue !== undefined && !reduce;
  const styleFingerprint = JSON.stringify(thumbStyle);
  const yielded = useMotionGuard(
    internalRef as React.RefObject<HTMLElement | null>,
    motionEnabled,
    styleFingerprint
  );
  if (yielded && !reduce) {
    thumbStyle.transition = "none";
  }

  return (
    <button
      aria-checked={checked}
      className={cn(
        "peer group/switch focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80 relative inline-flex shrink-0 items-center rounded-full border border-transparent outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px]",
        className
      )}
      data-size={size}
      data-slot="switch"
      data-state={checked ? "checked" : "unchecked"}
      disabled={disabled}
      onClick={handleClick}
      ref={setRef}
      role="switch"
      type="button"
      {...props}
    >
      <span
        className={cn(
          "bg-background dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground pointer-events-none block rounded-full ring-0",
          "group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3",
          "transition-transform group-data-[size=default]/switch:data-[state=checked]:translate-x-[calc(100%-2px)] group-data-[size=default]/switch:data-[state=unchecked]:translate-x-0",
          "group-data-[size=sm]/switch:data-[state=checked]:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-[state=unchecked]:translate-x-0"
        )}
        data-slot="switch-thumb"
        data-state={checked ? "checked" : "unchecked"}
        style={thumbStyle}
      />
    </button>
  );
}

export { Switch };
progress.tsx
"use client";

import * as React from "react";

import {
  getTransition,
  parseMotion,
  useMotionGuard,
  useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";

const ProgressContext = React.createContext<{ value?: number }>({});

type ProgressProps = Omit<React.ComponentProps<"div">, "role"> & {
  "aria-label"?: string;
  children?: React.ReactNode;
  max?: number;
  min?: number;
  motion?: string;
  value?: number;
};

function useProgressIndicatorStyle(
  value: number,
  min: number,
  max: number,
  motion: string | undefined,
  internalRef: React.RefObject<HTMLDivElement | null>
): React.CSSProperties {
  const reduce = useReducedMotion();
  const clamped = Math.min(Math.max(value, min), max);
  const range = Math.max(max - min, 1);
  const percent = ((clamped - min) / range) * 100;

  let style: React.CSSProperties = {
    transform: `translateX(-${100 - percent}%)`,
  };

  if (reduce) {
    style.transition = "none";
  } else if (motion !== undefined) {
    const transition = getTransition(parseMotion(motion));
    if (transition) {
      style.transition = transition;
    }
  }

  const motionEnabled = motion !== undefined && !reduce;
  const fingerprint = JSON.stringify(style);
  const yielded = useMotionGuard(internalRef, motionEnabled, fingerprint);
  if (yielded && !reduce) {
    style = { ...style, transition: "none" };
  }

  return style;
}

function ProgressBar({
  className,
  max = 100,
  min = 0,
  motion,
  value,
  ...props
}: ProgressProps) {
  const internalRef = React.useRef<HTMLDivElement | null>(null);
  const safeValue = value ?? 0;
  const indicatorStyle = useProgressIndicatorStyle(
    safeValue,
    min,
    max,
    motion,
    internalRef
  );

  return (
    <div
      aria-valuemax={max}
      aria-valuemin={min}
      aria-valuenow={safeValue}
      className={cn(
        "bg-primary/20 relative flex h-1 w-full items-center overflow-x-hidden rounded-full",
        className
      )}
      data-slot="progress"
      role="progressbar"
      {...props}
    >
      <div
        className={cn(
          "bg-primary size-full flex-1",
          motion === undefined && "transition-transform duration-500 ease-out"
        )}
        data-slot="progress-indicator"
        ref={internalRef}
        style={indicatorStyle}
      />
    </div>
  );
}

function Progress({ className, value, children, ...props }: ProgressProps) {
  const normalizedValue = value ?? 0;

  if (!children) {
    return (
      <ProgressBar className={className} value={normalizedValue} {...props} />
    );
  }

  return (
    <ProgressContext.Provider value={{ value: normalizedValue }}>
      <div className={cn("flex flex-col gap-2", className)}>
        <div className="flex items-center justify-between gap-2">
          {children}
        </div>
        <ProgressBar value={normalizedValue} {...props} />
      </div>
    </ProgressContext.Provider>
  );
}

function ProgressLabel({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      className={cn("text-sm font-medium", className)}
      data-slot="progress-label"
      {...props}
    />
  );
}

function ProgressValue({ className, ...props }: React.ComponentProps<"span">) {
  const { value } = React.useContext(ProgressContext);
  return (
    <span
      className={cn("text-muted-foreground text-sm tabular-nums", className)}
      data-slot="progress-value"
      {...props}
    >
      {value ?? 0}%
    </span>
  );
}

export { Progress, ProgressLabel, ProgressValue };

Four more components drop radix-ui and ship as native primitives. Marker and Attachment replace the asChild prop with as for polymorphic rendering. Switch and Progress expose a motion prop so you can override the CSS transition without editing the file.

All four now render with role=switch / role=progressbar / native <div> + aria-* attributes directly, so the shipped file has no external primitive dependency. prefers-reduced-motion disables transitions automatically, and third-party animation libraries that write inline styles suppress the internal transition via useMotionGuard.

$ npx frakment@latest add marker attachment switch progress

Motion prop

tsx
<Switch motion="300 cubic-bezier(0.34, 1.56, 0.64, 1)" />
<Progress motion="500 ease-out" value={60} />

as prop (R16)

tsx
<Marker as="a" href="/branch">View branch</Marker>
<Attachment>
  <AttachmentTrigger as="a" href="/report.pdf" aria-label="Open report" />
</Attachment>

asChild on AttachmentTrigger is no longer supported. Migrate to as:

diff
- <AttachmentTrigger asChild><a href="..." /></AttachmentTrigger>
+ <AttachmentTrigger as="a" href="..." />

Slider, Tooltip

slider.tsx
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

type SliderOrientation = "horizontal" | "vertical";

interface SliderProps {
  "aria-label"?: string;
  className?: string;
  defaultValue?: number[];
  disabled?: boolean;
  id?: string;
  max?: number;
  min?: number;
  onValueChange?: (value: number[]) => void;
  orientation?: SliderOrientation;
  step?: number;
  value?: number[];
}

function decimalsFor(step: number): number {
  const text = String(step);
  const dot = text.indexOf(".");
  return dot < 0 ? 0 : text.length - dot - 1;
}

function snapToStep(raw: number, step: number): number {
  const decimals = decimalsFor(step);
  const factor = 10 ** decimals;
  return Math.round(raw * factor) / factor;
}

function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max);
}

function Slider({
  "aria-label": ariaLabel,
  className,
  defaultValue,
  disabled = false,
  id,
  max = 100,
  min = 0,
  onValueChange,
  orientation = "horizontal",
  step = 1,
  value: valueProp,
}: SliderProps) {
  const isControlled = valueProp !== undefined;
  const [uncontrolled, setUncontrolled] = React.useState<number[]>(
    () => defaultValue ?? [min, max]
  );
  const values = isControlled ? valueProp : uncontrolled;
  const trackRef = React.useRef<HTMLDivElement | null>(null);

  const commit = React.useCallback(
    (next: number[]) => {
      if (!isControlled) {
        setUncontrolled(next);
      }
      onValueChange?.(next);
    },
    [isControlled, onValueChange]
  );

  const percentOf = (v: number) => {
    const range = Math.max(max - min, Number.EPSILON);
    return ((v - min) / range) * 100;
  };

  const valueFromPointer = (clientX: number, clientY: number): number => {
    const track = trackRef.current;
    if (!track) {
      return min;
    }
    const rect = track.getBoundingClientRect();
    let ratio: number;
    if (orientation === "horizontal") {
      ratio = rect.width === 0 ? 0 : (clientX - rect.left) / rect.width;
    } else {
      ratio = rect.height === 0 ? 0 : 1 - (clientY - rect.top) / rect.height;
    }
    ratio = clamp(ratio, 0, 1);
    return snapToStep(min + ratio * (max - min), step);
  };

  const boundsFor = (index: number): [number, number] => {
    const lower = index === 0 ? min : values[index - 1];
    const upper = index === values.length - 1 ? max : values[index + 1];
    return [lower, upper];
  };

  const updateThumb = (index: number, raw: number) => {
    const [lo, hi] = boundsFor(index);
    const next = values.slice();
    next[index] = clamp(raw, lo, hi);
    if (next[index] !== values[index]) {
      commit(next);
    }
  };

  const handlePointerDown =
    (index: number) => (event: React.PointerEvent<HTMLSpanElement>) => {
      if (disabled) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      const target = event.currentTarget;
      try {
        target.setPointerCapture(event.pointerId);
      } catch {
        // noop
      }
      updateThumb(index, valueFromPointer(event.clientX, event.clientY));
      const onMove = (ev: PointerEvent) => {
        updateThumb(index, valueFromPointer(ev.clientX, ev.clientY));
      };
      const onUp = () => {
        target.removeEventListener("pointermove", onMove);
        target.removeEventListener("pointerup", onUp);
        target.removeEventListener("pointercancel", onUp);
      };
      target.addEventListener("pointermove", onMove);
      target.addEventListener("pointerup", onUp);
      target.addEventListener("pointercancel", onUp);
    };

  const handleKeyDown =
    (index: number) => (event: React.KeyboardEvent<HTMLSpanElement>) => {
      if (disabled) {
        return;
      }
      const [lo, hi] = boundsFor(index);
      const current = values[index];
      let next = current;
      switch (event.key) {
        case "ArrowRight":
        case "ArrowUp":
          next = clamp(snapToStep(current + step, step), lo, hi);
          break;
        case "ArrowLeft":
        case "ArrowDown":
          next = clamp(snapToStep(current - step, step), lo, hi);
          break;
        case "Home":
          next = lo;
          break;
        case "End":
          next = hi;
          break;
        case "PageUp":
          next = clamp(snapToStep(current + step * 10, step), lo, hi);
          break;
        case "PageDown":
          next = clamp(snapToStep(current - step * 10, step), lo, hi);
          break;
        default:
          return;
      }
      event.preventDefault();
      if (next !== current) {
        const arr = values.slice();
        arr[index] = next;
        commit(arr);
      }
    };

  const rangeStart = percentOf(values[0]);
  const rangeEnd = percentOf(values.at(-1) ?? min);
  const rangeStyle: React.CSSProperties =
    orientation === "horizontal"
      ? { left: `${rangeStart}%`, right: `${100 - rangeEnd}%` }
      : { bottom: `${rangeStart}%`, top: `${100 - rangeEnd}%` };

  return (
    <div
      className={cn(
        "relative flex w-full touch-none select-none",
        orientation === "horizontal"
          ? "items-center"
          : "h-full min-h-40 flex-col items-center",
        disabled ? "opacity-50" : undefined,
        className
      )}
      data-disabled={disabled || undefined}
      data-orientation={orientation}
      data-slot="slider"
      id={id}
    >
      <div
        className={cn(
          "bg-muted relative grow overflow-hidden rounded-full",
          orientation === "horizontal" ? "h-1 w-full" : "h-full w-1"
        )}
        data-slot="slider-track"
        ref={trackRef}
      >
        <div
          className={cn(
            "bg-primary absolute select-none",
            orientation === "horizontal" ? "inset-y-0" : "inset-x-0"
          )}
          data-slot="slider-range"
          style={rangeStyle}
        />
      </div>
      {values.map((v, index) => {
        const percent = percentOf(v);
        const thumbStyle: React.CSSProperties =
          orientation === "horizontal"
            ? {
                left: `${percent}%`,
                top: "50%",
                transform: "translate(-50%, -50%)",
              }
            : {
                bottom: `${percent}%`,
                left: "50%",
                transform: "translate(-50%, 50%)",
              };
        return (
          <span
            aria-disabled={disabled || undefined}
            aria-label={ariaLabel}
            aria-orientation={orientation}
            aria-valuemax={max}
            aria-valuemin={min}
            aria-valuenow={v}
            className={cn(
              "border-primary bg-background ring-ring/50 absolute block size-3.5 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] select-none",
              "after:absolute after:-inset-2",
              "hover:ring-3 focus-visible:ring-3 focus-visible:outline-hidden active:ring-3",
              disabled ? "pointer-events-none opacity-50" : "cursor-grab"
            )}
            data-slot="slider-thumb"
            key={`slider-thumb-${index}`}
            onKeyDown={handleKeyDown(index)}
            onPointerDown={handlePointerDown(index)}
            role="slider"
            style={thumbStyle}
            tabIndex={disabled ? -1 : 0}
          />
        );
      })}
    </div>
  );
}

export { Slider };
tooltip.tsx
"use client";

import * as React from "react";
import { createPortal } from "react-dom";

import { parseMotion, useReducedMotion } from "@/lib/motion";
import { cn } from "@/lib/utils";

type TooltipSide = "top" | "right" | "bottom" | "left";
type TooltipAlign = "start" | "center" | "end";

interface TooltipProviderContextValue {
  delayDuration: number;
}

const TooltipProviderContext = React.createContext<TooltipProviderContextValue>(
  { delayDuration: 0 }
);

interface TooltipContextValue {
  contentId: string;
  contentRef: React.RefObject<HTMLDivElement | null>;
  onContentEnter: () => void;
  onContentLeave: () => void;
  onTriggerBlur: () => void;
  onTriggerEnter: () => void;
  onTriggerFocus: () => void;
  onTriggerLeave: () => void;
  open: boolean;
  setOpen: (open: boolean) => void;
  triggerRef: React.RefObject<HTMLElement | null>;
}

const TooltipContext = React.createContext<TooltipContextValue | null>(null);

function useTooltipContext(component: string): TooltipContextValue {
  const ctx = React.useContext(TooltipContext);
  if (!ctx) {
    throw new Error(`${component} must be used within Tooltip`);
  }
  return ctx;
}

function computeTooltipPosition(
  trigger: HTMLElement,
  content: HTMLElement,
  side: TooltipSide,
  align: TooltipAlign,
  sideOffset: number,
  avoidCollisions: boolean
): { x: number; y: number; side: TooltipSide } {
  const t = trigger.getBoundingClientRect();
  const c = content.getBoundingClientRect();
  const vw = window.innerWidth;
  const vh = window.innerHeight;

  const place = (s: TooltipSide): { x: number; y: number } => {
    let x = 0;
    let y = 0;
    if (s === "top") {
      x = t.left + (t.width - c.width) / 2;
      y = t.top - c.height - sideOffset;
    } else if (s === "bottom") {
      x = t.left + (t.width - c.width) / 2;
      y = t.bottom + sideOffset;
    } else if (s === "left") {
      x = t.left - c.width - sideOffset;
      y = t.top + (t.height - c.height) / 2;
    } else {
      x = t.right + sideOffset;
      y = t.top + (t.height - c.height) / 2;
    }
    if (s === "top" || s === "bottom") {
      if (align === "start") {
        x = t.left;
      } else if (align === "end") {
        x = t.right - c.width;
      }
    } else if (align === "start") {
      y = t.top;
    } else if (align === "end") {
      y = t.bottom - c.height;
    }
    return { x, y };
  };

  let resolvedSide = side;
  const placed = place(resolvedSide);
  let x = placed.x;
  let y = placed.y;

  if (avoidCollisions) {
    const pad = 8;
    const over = {
      bottom: y + c.height > vh - pad,
      left: x < pad,
      right: x + c.width > vw - pad,
      top: y < pad,
    };
    const flipMap: Record<TooltipSide, TooltipSide> = {
      bottom: "top",
      left: "right",
      right: "left",
      top: "bottom",
    };
    if (over[resolvedSide]) {
      const flipped = flipMap[resolvedSide];
      const fp = place(flipped);
      const flipOver =
        fp.y < pad ||
        fp.y + c.height > vh - pad ||
        fp.x < pad ||
        fp.x + c.width > vw - pad;
      if (!flipOver) {
        resolvedSide = flipped;
        x = fp.x;
        y = fp.y;
      }
    }
    if (x < pad) {
      x = pad;
    }
    if (x + c.width > vw - pad) {
      x = vw - c.width - pad;
    }
    if (y < pad) {
      y = pad;
    }
    if (y + c.height > vh - pad) {
      y = vh - c.height - pad;
    }
  }

  return { side: resolvedSide, x, y };
}

interface TooltipProviderProps {
  children?: React.ReactNode;
  delayDuration?: number;
}

function TooltipProvider({
  children,
  delayDuration = 0,
}: TooltipProviderProps) {
  const value = React.useMemo(() => ({ delayDuration }), [delayDuration]);
  return (
    <TooltipProviderContext.Provider value={value}>
      {children}
    </TooltipProviderContext.Provider>
  );
}

interface TooltipProps {
  children?: React.ReactNode;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  open?: boolean;
}

function Tooltip({
  children,
  defaultOpen = false,
  onOpenChange,
  open: openProp,
}: TooltipProps) {
  const provider = React.useContext(TooltipProviderContext);
  const isControlled = openProp !== undefined;
  const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen);
  const open = isControlled ? openProp : uncontrolledOpen;
  const contentId = React.useId();
  const triggerRef = React.useRef<HTMLButtonElement | null>(null);
  const contentRef = React.useRef<HTMLDivElement | null>(null);
  const openTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
  const closeTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  const clearTimers = React.useCallback(() => {
    if (openTimer.current !== null) {
      clearTimeout(openTimer.current);
      openTimer.current = null;
    }
    if (closeTimer.current !== null) {
      clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  }, []);

  const setOpen = React.useCallback(
    (next: boolean) => {
      if (!isControlled) {
        setUncontrolledOpen(next);
      }
      onOpenChange?.(next);
    },
    [isControlled, onOpenChange]
  );

  const onTriggerEnter = React.useCallback(() => {
    clearTimers();
    if (provider.delayDuration > 0) {
      openTimer.current = setTimeout(
        () => setOpen(true),
        provider.delayDuration
      );
    } else {
      setOpen(true);
    }
  }, [clearTimers, provider.delayDuration, setOpen]);

  const onTriggerLeave = React.useCallback(() => {
    clearTimers();
    closeTimer.current = setTimeout(() => setOpen(false), 80);
  }, [clearTimers, setOpen]);

  const onContentEnter = React.useCallback(() => {
    clearTimers();
  }, [clearTimers]);

  const onContentLeave = React.useCallback(() => {
    clearTimers();
    closeTimer.current = setTimeout(() => setOpen(false), 80);
  }, [clearTimers, setOpen]);

  const onTriggerFocus = React.useCallback(() => {
    clearTimers();
    setOpen(true);
  }, [clearTimers, setOpen]);

  const onTriggerBlur = React.useCallback(() => {
    clearTimers();
    closeTimer.current = setTimeout(() => setOpen(false), 0);
  }, [clearTimers, setOpen]);

  React.useEffect(
    () => () => {
      clearTimers();
    },
    [clearTimers]
  );

  React.useEffect(() => {
    if (!open) {
      return;
    }
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        clearTimers();
        setOpen(false);
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, clearTimers, setOpen]);

  const value = React.useMemo<TooltipContextValue>(
    () => ({
      contentId,
      contentRef,
      onContentEnter,
      onContentLeave,
      onTriggerBlur,
      onTriggerEnter,
      onTriggerFocus,
      onTriggerLeave,
      open,
      setOpen,
      triggerRef,
    }),
    [
      contentId,
      onContentEnter,
      onContentLeave,
      onTriggerBlur,
      onTriggerEnter,
      onTriggerFocus,
      onTriggerLeave,
      open,
      setOpen,
    ]
  );

  return (
    <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>
  );
}

type TooltipTriggerProps = Omit<React.ComponentProps<"button">, "ref"> & {
  as?: React.ElementType;
  asChild?: boolean;
  ref?: React.Ref<HTMLElement>;
} & Record<string, unknown>;

function TooltipTrigger({
  as,
  asChild = false,
  children,
  onBlur,
  onFocus,
  onPointerEnter,
  onPointerLeave,
  ref,
  ...props
}: TooltipTriggerProps) {
  const ctx = useTooltipContext("TooltipTrigger");

  const setRef = React.useCallback(
    (node: HTMLElement | null) => {
      ctx.triggerRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLElement | null>).current = node;
      }
    },
    [ctx.triggerRef, ref]
  );

  const handlers: Record<string, unknown> = {
    "aria-describedby": ctx.open ? ctx.contentId : undefined,
    "data-state": ctx.open ? "open" : "closed",
    onBlur: (event: React.FocusEvent<HTMLElement>) => {
      (onBlur as ((e: React.FocusEvent<HTMLElement>) => void) | undefined)?.(
        event
      );
      ctx.onTriggerBlur();
    },
    onFocus: (event: React.FocusEvent<HTMLElement>) => {
      (onFocus as ((e: React.FocusEvent<HTMLElement>) => void) | undefined)?.(
        event
      );
      ctx.onTriggerFocus();
    },
    onPointerEnter: (event: React.PointerEvent<HTMLElement>) => {
      (
        onPointerEnter as
          | ((e: React.PointerEvent<HTMLElement>) => void)
          | undefined
      )?.(event);
      ctx.onTriggerEnter();
    },
    onPointerLeave: (event: React.PointerEvent<HTMLElement>) => {
      (
        onPointerLeave as
          | ((e: React.PointerEvent<HTMLElement>) => void)
          | undefined
      )?.(event);
      ctx.onTriggerLeave();
    },
    ref: setRef,
  };

  if (asChild && React.isValidElement(children)) {
    return React.cloneElement(
      children as React.ReactElement<Record<string, unknown>>,
      handlers
    );
  }

  const Comp = (as ?? "button") as React.ElementType;
  const isNativeButton = Comp === "button";

  return (
    <Comp
      data-slot="tooltip-trigger"
      type={isNativeButton ? ((props.type as string) ?? "button") : undefined}
      {...props}
      {...handlers}
    >
      {children}
    </Comp>
  );
}

interface TooltipContentProps extends Omit<React.ComponentProps<"div">, "ref"> {
  align?: TooltipAlign;
  avoidCollisions?: boolean;
  motion?: string;
  ref?: React.Ref<HTMLDivElement>;
  side?: TooltipSide;
  sideOffset?: number;
}

const defaultTooltipMotion = "120 ease-out";

function TooltipContent({
  align = "center",
  avoidCollisions = true,
  children,
  className,
  motion,
  ref,
  side = "bottom",
  sideOffset = 10,
  style,
  ...props
}: TooltipContentProps) {
  const ctx = useTooltipContext("TooltipContent");
  const reduce = useReducedMotion();
  const motionValue = motion ?? defaultTooltipMotion;
  const internalRef = React.useRef<HTMLDivElement | null>(null);
  const [entered, setEntered] = React.useState(false);
  const [present, setPresent] = React.useState(false);
  const [resolvedSide, setResolvedSide] = React.useState<TooltipSide>(side);
  const [pos, setPos] = React.useState<{ x: number; y: number }>({
    x: 0,
    y: 0,
  });

  const setRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      internalRef.current = node;
      ctx.contentRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
      }
    },
    [ctx.contentRef, ref]
  );

  React.useLayoutEffect(() => {
    if (!present) {
      return;
    }
    const trigger = ctx.triggerRef.current;
    const content = internalRef.current;
    if (!(trigger && content)) {
      return;
    }
    const update = () => {
      const t = ctx.triggerRef.current;
      const c = internalRef.current;
      if (!(t && c)) {
        return;
      }
      const next = computeTooltipPosition(
        t,
        c,
        side,
        align,
        sideOffset,
        avoidCollisions
      );
      setPos({ x: next.x, y: next.y });
      setResolvedSide(next.side);
    };
    update();
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    let observer: ResizeObserver | undefined;
    if (typeof ResizeObserver !== "undefined") {
      observer = new ResizeObserver(update);
      observer.observe(trigger);
      observer.observe(content);
    }
    return () => {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
      observer?.disconnect();
    };
  }, [present, side, align, sideOffset, avoidCollisions, ctx.triggerRef]);

  const parsedMotion = parseMotion(motionValue);
  const exitDuration =
    reduce || parsedMotion?.disabled ? 0 : (parsedMotion?.duration ?? 120);

  React.useEffect(() => {
    if (ctx.open) {
      setPresent(true);
      let raf1 = 0;
      let raf2 = 0;
      raf1 = requestAnimationFrame(() => {
        raf2 = requestAnimationFrame(() => setEntered(true));
      });
      return () => {
        if (raf1) {
          cancelAnimationFrame(raf1);
        }
        if (raf2) {
          cancelAnimationFrame(raf2);
        }
      };
    }
    setEntered(false);
    const timer = setTimeout(() => setPresent(false), exitDuration);
    return () => clearTimeout(timer);
  }, [ctx.open, exitDuration]);

  if (!present) {
    return null;
  }

  const baseStyle: React.CSSProperties = {
    left: pos.x,
    opacity: reduce ? 1 : entered ? 1 : 0,
    position: "fixed",
    top: pos.y,
    ...style,
  };

  if (reduce) {
    baseStyle.transition = "none";
  } else {
    const parsed = parseMotion(motionValue);
    if (parsed?.disabled) {
      baseStyle.transition = "none";
    } else if (parsed) {
      baseStyle.transition = `opacity ${parsed.duration}ms ${parsed.easing}`;
    } else {
      baseStyle.transition = "opacity 120ms ease-out, transform 120ms ease-out";
    }
  }

  const arrowSize = 8;
  const arrowStyle: React.CSSProperties = {
    background: "var(--foreground)",
    height: arrowSize,
    position: "absolute",
    transform: "rotate(45deg)",
    width: arrowSize,
  };
  if (resolvedSide === "top") {
    arrowStyle.bottom = -arrowSize / 4;
    if (align === "start") {
      arrowStyle.left = 12;
    } else if (align === "end") {
      arrowStyle.right = 12;
    } else {
      arrowStyle.left = "50%";
      arrowStyle.marginLeft = -arrowSize / 2;
    }
  } else if (resolvedSide === "bottom") {
    arrowStyle.top = -arrowSize / 4;
    if (align === "start") {
      arrowStyle.left = 12;
    } else if (align === "end") {
      arrowStyle.right = 12;
    } else {
      arrowStyle.left = "50%";
      arrowStyle.marginLeft = -arrowSize / 2;
    }
  } else if (resolvedSide === "left") {
    arrowStyle.right = -arrowSize / 4;
    if (align === "start") {
      arrowStyle.top = 12;
    } else if (align === "end") {
      arrowStyle.bottom = 12;
    } else {
      arrowStyle.top = "50%";
      arrowStyle.marginTop = -arrowSize / 2;
    }
  } else {
    arrowStyle.left = -arrowSize / 4;
    if (align === "start") {
      arrowStyle.top = 12;
    } else if (align === "end") {
      arrowStyle.bottom = 12;
    } else {
      arrowStyle.top = "50%";
      arrowStyle.marginTop = -arrowSize / 2;
    }
  }

  return createPortal(
    <div
      className={cn(
        "bg-foreground text-background z-50 inline-flex w-fit max-w-xs items-center gap-1.5 overflow-visible rounded-md px-3 py-1.5 text-xs",
        className
      )}
      data-align={align}
      data-side={resolvedSide}
      data-slot="tooltip-content"
      data-state={ctx.open ? "open" : "closed"}
      id={ctx.contentId}
      onPointerEnter={ctx.onContentEnter}
      onPointerLeave={ctx.onContentLeave}
      ref={setRef}
      role="tooltip"
      style={baseStyle}
      {...props}
    >
      <span aria-hidden="true" style={arrowStyle} />
      {children}
    </div>,
    document.body
  );
}

export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };

The last two Radix primitives drop to native implementations. Slider renders <div role="slider"> per thumb with pointer and keyboard handling in a single file. Tooltip renders <div role="tooltip"> with floating-ui positioning, hover/focus trigger, and portal. radix-ui is no longer a runtime dependency for either.

TooltipTrigger replaces the Radix asChild pattern with an as prop (R16). asChild stays for backward compat (deprecated) but as={Button} is the recommended call.

$ npx frakment@latest add slider tooltip

Tooltip as prop

tsx
<Tooltip>
  <TooltipTrigger as={Button} variant="outline">Hover</TooltipTrigger>
  <TooltipContent>Add to library</TooltipContent>
</Tooltip>

Slider keyboard support

Arrow keys step, Home/End jump, Page Up/Down step × 10. Multi-thumb sliders respect thumb ordering automatically.

motion prop on TooltipContent overrides the entrance transition. Slider keeps its color/box-shadow hover transition and does not expose a motion prop (no positioning animation to tune).


Native primitives (Dialog, Item, Checkbox, Hover Card, Tabs)

dialog.tsx
"use client";

import { XIcon } 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";

interface DialogContextValue {
  contentRef: React.RefObject<HTMLDivElement | null>;
  descriptionId: string | null;
  open: boolean;
  setDescriptionId: (id: string | null) => void;
  setOpen: (open: boolean) => void;
  setTitleId: (id: string | null) => void;
  titleId: string | null;
  triggerRef: React.RefObject<HTMLElement | null>;
}

const DialogContext = React.createContext<DialogContextValue | null>(null);

function useDialogContext(): DialogContextValue {
  const ctx = React.useContext(DialogContext);
  if (!ctx) {
    throw new Error("Dialog components must be used within <Dialog>.");
  }
  return ctx;
}

const FOCUSABLE_SELECTOR =
  'a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])';

function getFocusable(root: HTMLElement | null): HTMLElement[] {
  if (!root) {
    return [];
  }
  return Array.from(
    root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
  ).filter((el) => !el.hasAttribute("disabled") && el.offsetParent !== null);
}

interface DialogProps {
  children?: React.ReactNode;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  open?: boolean;
}

function Dialog({
  children,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
}: DialogProps) {
  const isControlled = openProp !== undefined;
  const [uncontrolled, setUncontrolled] = React.useState(defaultOpen);
  const open = isControlled ? openProp : uncontrolled;
  const triggerRef = React.useRef<HTMLElement | null>(null);
  const contentRef = React.useRef<HTMLDivElement | null>(null);
  const [titleId, setTitleId] = React.useState<string | null>(null);
  const [descriptionId, setDescriptionId] = React.useState<string | null>(null);
  const setOpen = React.useCallback(
    (next: boolean) => {
      if (!isControlled) {
        setUncontrolled(next);
      }
      onOpenChange?.(next);
    },
    [isControlled, onOpenChange]
  );
  const ctx = React.useMemo<DialogContextValue>(
    () => ({
      contentRef,
      descriptionId,
      open,
      setDescriptionId,
      setOpen,
      setTitleId,
      titleId,
      triggerRef,
    }),
    [open, setOpen, titleId, descriptionId]
  );
  return (
    <DialogContext.Provider value={ctx}>
      <div data-slot="dialog" data-state={open ? "open" : "closed"}>
        {children}
      </div>
    </DialogContext.Provider>
  );
}

type DialogTriggerProps = Omit<
  React.ComponentPropsWithoutRef<"button">,
  "ref"
> &
  Record<string, unknown> & {
    as?: React.ElementType;
    asChild?: boolean;
    ref?: React.Ref<HTMLElement>;
  };

function DialogTrigger({
  as,
  asChild,
  children,
  onClick,
  ref,
  ...props
}: DialogTriggerProps) {
  const ctx = useDialogContext();
  const setRef = React.useCallback(
    (node: HTMLElement | null) => {
      ctx.triggerRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLElement | null>).current = node;
      }
    },
    [ctx.triggerRef, ref]
  );
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    onClick?.(event as never);
    if (event.defaultPrevented) {
      return;
    }
    ctx.setOpen(true);
  };
  if (asChild && React.isValidElement(children)) {
    const child = children as React.ReactElement<{
      onClick?: (e: React.MouseEvent<HTMLElement>) => void;
      ref?: React.Ref<HTMLElement>;
    }>;
    return React.cloneElement(child, {
      ...props,
      onClick: (event: React.MouseEvent<HTMLElement>) => {
        child.props.onClick?.(event);
        handleClick(event);
      },
      ref: setRef,
    } as never);
  }
  const Component = (as ?? "button") as React.ElementType;
  const isNativeButton = !as;
  return (
    <Component
      data-slot="dialog-trigger"
      {...props}
      {...(isNativeButton ? { type: "button" as const } : {})}
      onClick={handleClick}
      ref={setRef}
    >
      {children}
    </Component>
  );
}

function DialogPortal({ children }: { children?: React.ReactNode }) {
  return <>{children}</>;
}

type DialogCloseProps = Omit<React.ComponentPropsWithoutRef<"button">, "ref"> &
  Record<string, unknown> & {
    as?: React.ElementType;
    asChild?: boolean;
    ref?: React.Ref<HTMLElement>;
  };

function DialogClose({
  as,
  asChild,
  children,
  onClick,
  ref,
  ...props
}: DialogCloseProps) {
  const ctx = useDialogContext();
  const setRef = React.useCallback(
    (node: HTMLElement | null) => {
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLElement | null>).current = node;
      }
    },
    [ref]
  );
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    onClick?.(event as never);
    if (event.defaultPrevented) {
      return;
    }
    ctx.setOpen(false);
  };
  if (asChild && React.isValidElement(children)) {
    const child = children as React.ReactElement<{
      onClick?: (e: React.MouseEvent<HTMLElement>) => void;
      ref?: React.Ref<HTMLElement>;
    }>;
    return React.cloneElement(child, {
      ...props,
      onClick: (event: React.MouseEvent<HTMLElement>) => {
        child.props.onClick?.(event);
        handleClick(event);
      },
      ref: setRef,
    } as never);
  }
  const Component = (as ?? "button") as React.ElementType;
  const isNativeButton = !as;
  return (
    <Component
      data-slot="dialog-close"
      {...props}
      {...(isNativeButton ? { type: "button" as const } : {})}
      onClick={handleClick}
      ref={setRef}
    >
      {children}
    </Component>
  );
}

type DialogOverlayProps = React.ComponentPropsWithoutRef<"div"> & {
  motion?: string;
};

function DialogOverlay({
  className,
  motion,
  style,
  ...props
}: DialogOverlayProps) {
  const ctx = useDialogContext();
  const reduce = useReducedMotion();
  const transition = reduce
    ? "none"
    : (getTransition(parseMotion(motion)) ?? "opacity 150ms ease-out");
  return (
    <div
      aria-hidden="true"
      className={className}
      data-slot="dialog-overlay"
      data-state={ctx.open ? "open" : "closed"}
      {...props}
      onClick={(event) => {
        if (event.target === event.currentTarget) {
          ctx.setOpen(false);
        }
      }}
      style={{
        background: "rgba(0,0,0,0.5)",
        inset: 0,
        opacity: ctx.open ? 1 : 0,
        position: "fixed",
        transition,
        zIndex: 50,
        ...style,
      }}
    />
  );
}

type DialogContentProps = React.ComponentPropsWithoutRef<"div"> & {
  showCloseButton?: boolean;
  motion?: string;
};

function DialogContent({
  children,
  className,
  motion,
  showCloseButton = true,
  style,
  ...props
}: DialogContentProps) {
  const ctx = useDialogContext();
  const { open, setOpen, contentRef, triggerRef, titleId, descriptionId } = ctx;
  const reduce = useReducedMotion();
  const [mounted, setMounted] = React.useState(false);
  const [entered, setEntered] = React.useState(false);
  const transition = reduce
    ? "none"
    : (getTransition(parseMotion(motion)) ??
      "opacity 150ms ease-out, transform 150ms ease-out");
  React.useEffect(() => {
    if (open) {
      setMounted(true);
      const r1 = requestAnimationFrame(() => {
        const r2 = requestAnimationFrame(() => setEntered(true));
        return () => cancelAnimationFrame(r2);
      });
      return () => cancelAnimationFrame(r1);
    }
    setEntered(false);
    const t = setTimeout(() => setMounted(false), 150);
    return () => clearTimeout(t);
  }, [open]);
  React.useEffect(() => {
    if (!(open && mounted)) {
      return;
    }
    const prev = document.activeElement as HTMLElement | null;
    const root = contentRef.current;
    if (root) {
      const f = getFocusable(root);
      (f[0] ?? root).focus();
    }
    return () => {
      if (prev && typeof prev.focus === "function") {
        prev.focus();
      } else {
        triggerRef.current?.focus?.();
      }
    };
  }, [open, mounted, contentRef, triggerRef]);
  React.useEffect(() => {
    if (!open) {
      return;
    }
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.stopPropagation();
        setOpen(false);
        return;
      }
      if (event.key !== "Tab") {
        return;
      }
      const root = contentRef.current;
      if (!root) {
        return;
      }
      const f = getFocusable(root);
      if (f.length === 0) {
        event.preventDefault();
        root.focus();
        return;
      }
      const first = f[0];
      const last = f.at(-1);
      if (!last) {
        return;
      }
      const active = document.activeElement as HTMLElement | null;
      if (event.shiftKey && active === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && active === last) {
        event.preventDefault();
        first.focus();
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, setOpen, contentRef]);
  if (!mounted) {
    return null;
  }
  if (typeof document === "undefined") {
    return null;
  }
  const content = (
    <>
      <DialogOverlay motion={motion} />
      <div
        aria-describedby={descriptionId ?? undefined}
        aria-labelledby={titleId ?? undefined}
        aria-modal="true"
        className={cn(
          "bg-background fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] gap-4 rounded-lg border p-6 shadow-lg sm:max-w-lg",
          className
        )}
        data-slot="dialog-content"
        data-state={open ? "open" : "closed"}
        ref={contentRef}
        role="dialog"
        tabIndex={-1}
        {...props}
        style={{
          opacity: entered ? 1 : 0,
          overscrollBehavior: "contain",
          transform: `translate(-50%, -50%) scale(${entered ? 1 : 0.95})`,
          transition,
          ...style,
        }}
      >
        {children}
        {showCloseButton && (
          <DialogClose className="ring-offset-background focus:ring-ring absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=size-])]:size-4">
            <XIcon />
            <span className="sr-only">Close</span>
          </DialogClose>
        )}
      </div>
    </>
  );
  return createPortal(content, document.body);
}

const DialogHeader = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div
    className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
    data-slot="dialog-header"
    {...props}
  />
);

const DialogFooter = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div
    className={cn(
      "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
      className
    )}
    data-slot="dialog-footer"
    {...props}
  />
);

const DialogTitle = ({
  className,
  id,
  ...props
}: React.ComponentProps<"h2">) => {
  const ctx = useDialogContext();
  const generatedId = React.useId();
  const titleId = id ?? generatedId;
  React.useEffect(() => {
    ctx.setTitleId(titleId);
    return () => ctx.setTitleId(null);
  }, [ctx, titleId]);
  return (
    <h2
      className={cn("text-lg leading-none font-semibold", className)}
      data-slot="dialog-title"
      id={titleId}
      {...props}
    />
  );
};

const DialogDescription = ({
  className,
  id,
  ...props
}: React.ComponentProps<"p">) => {
  const ctx = useDialogContext();
  const generatedId = React.useId();
  const descId = id ?? generatedId;
  React.useEffect(() => {
    ctx.setDescriptionId(descId);
    return () => ctx.setDescriptionId(null);
  }, [ctx, descId]);
  return (
    <p
      className={cn("text-muted-foreground text-sm", className)}
      data-slot="dialog-description"
      id={descId}
      {...props}
    />
  );
};

export {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogOverlay,
  DialogPortal,
  DialogTitle,
  DialogTrigger,
};
AC
Aria Chen
aria@example.com
Admin
BO
Ben Ortiz
jane@example.com
CP
Cleo Park
cara@example.com
Member
item.tsx
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import * as React from "react";

import { cn } from "@/lib/utils";

const itemVariants = cva(
  "group/item flex w-full flex-wrap items-center gap-3 rounded-lg border px-4 py-3 text-sm transition-colors",
  {
    defaultVariants: {
      variant: "default",
    },
    variants: {
      variant: {
        default: "border-border bg-card text-card-foreground",
        muted: "bg-muted text-foreground border-transparent",
        outline: "border-border bg-transparent",
      },
    },
  }
);

type ItemProps = React.ComponentPropsWithoutRef<"div"> &
  VariantProps<typeof itemVariants> & {
    as?: React.ElementType;
    asChild?: boolean;
  };

function Item({
  as,
  asChild,
  children,
  className,
  variant,
  ...props
}: ItemProps) {
  const mergedClass = cn(itemVariants({ variant }), className);
  if (asChild && React.isValidElement(children)) {
    const child = children as React.ReactElement<{ className?: string }>;
    return React.cloneElement(child, {
      ...props,
      className: cn(mergedClass, child.props.className),
      "data-slot": "item",
      "data-variant": variant,
    } as never);
  }
  const Comp = (as ?? "div") as React.ElementType;
  return (
    <Comp
      className={mergedClass}
      data-slot="item"
      data-variant={variant}
      {...props}
    >
      {children}
    </Comp>
  );
}

function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex flex-col gap-2", className)}
      data-slot="item-group"
      {...props}
    />
  );
}

function ItemMedia({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex shrink-0 items-center justify-center [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      data-slot="item-media"
      {...props}
    />
  );
}

function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex min-w-0 flex-1 flex-col gap-0.5", className)}
      data-slot="item-content"
      {...props}
    />
  );
}

function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("truncate text-sm leading-tight font-medium", className)}
      data-slot="item-title"
      {...props}
    />
  );
}

function ItemDescription({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("text-muted-foreground text-sm", className)}
      data-slot="item-description"
      {...props}
    />
  );
}

function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex shrink-0 items-center gap-2", className)}
      data-slot="item-actions"
      {...props}
    />
  );
}

export {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemGroup,
  ItemMedia,
  ItemTitle,
};
checkbox.tsx
"use client";

import { CheckIcon } from "lucide-react";
import * as React from "react";

import { cn } from "@/lib/utils";

type CheckedState = boolean | "indeterminate";

type CheckboxProps = Omit<
  React.ComponentPropsWithoutRef<"button">,
  "onChange" | "role" | "aria-checked" | "type"
> & {
  checked?: CheckedState;
  defaultChecked?: CheckedState;
  disabled?: boolean;
  onCheckedChange?: (checked: CheckedState) => void;
  ref?: React.Ref<HTMLButtonElement>;
};

function Checkbox({
  checked: checkedProp,
  className,
  defaultChecked = false,
  disabled = false,
  onClick,
  onCheckedChange,
  ref,
  ...props
}: CheckboxProps) {
  const isControlled = checkedProp !== undefined;
  const [uncontrolled, setUncontrolled] =
    React.useState<CheckedState>(defaultChecked);
  const checked = isControlled ? checkedProp : uncontrolled;
  const isChecked = checked === true;
  const isIndeterminate = checked === "indeterminate";
  const isActive = isChecked || isIndeterminate;
  const dataState = isIndeterminate
    ? "indeterminate"
    : isChecked
      ? "checked"
      : "unchecked";
  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || disabled) {
      return;
    }
    const next: CheckedState = !isChecked;
    if (!isControlled) {
      setUncontrolled(next);
    }
    onCheckedChange?.(next);
  };
  return (
    <button
      aria-checked={isIndeterminate ? "mixed" : isChecked}
      className={cn(
        "peer border-input group-has-[:focus-visible]/field-label:not-data-checked:border-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors outline-none group-has-disabled/field:opacity-50 group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3",
        className
      )}
      data-checked={isActive ? "" : undefined}
      data-slot="checkbox"
      data-state={dataState}
      disabled={disabled}
      onClick={handleClick}
      ref={ref}
      role="checkbox"
      type="button"
      {...props}
    >
      {isActive ? (
        <span
          aria-hidden="true"
          className="grid place-content-center text-current [&>svg]:size-3.5"
          data-slot="checkbox-indicator"
        >
          {isIndeterminate ? (
            <span className="block h-px w-2 rounded-full bg-current" />
          ) : (
            <CheckIcon />
          )}
        </span>
      ) : null}
    </button>
  );
}

export { Checkbox };
hover-card.tsx
"use client";

import * as React from "react";
import { createPortal } from "react-dom";

import { cn } from "@/lib/utils";

type Side = "top" | "right" | "bottom" | "left";
type Align = "start" | "center" | "end";

interface HoverCardContextValue {
  contentRef: React.RefObject<HTMLDivElement | null>;
  open: boolean;
  scheduleClose: () => void;
  scheduleOpen: () => void;
  setOpen: (open: boolean) => void;
  triggerRef: React.RefObject<HTMLElement | null>;
}

const HoverCardContext = React.createContext<HoverCardContextValue | null>(
  null
);

function useHoverCardContext(): HoverCardContextValue {
  const ctx = React.useContext(HoverCardContext);
  if (!ctx) {
    throw new Error("HoverCard components must be used within <HoverCard>.");
  }
  return ctx;
}

interface HoverCardProps {
  children?: React.ReactNode;
  closeDelay?: number;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  open?: boolean;
  openDelay?: number;
}

function HoverCard({
  children,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  openDelay = 700,
  closeDelay = 300,
}: HoverCardProps) {
  const isControlled = openProp !== undefined;
  const [uncontrolled, setUncontrolled] = React.useState(defaultOpen);
  const open = isControlled ? openProp : uncontrolled;
  const triggerRef = React.useRef<HTMLElement | null>(null);
  const contentRef = React.useRef<HTMLDivElement | null>(null);
  const openTimerRef = React.useRef<number | null>(null);
  const closeTimerRef = React.useRef<number | null>(null);
  const clearTimers = React.useCallback(() => {
    if (openTimerRef.current !== null) {
      window.clearTimeout(openTimerRef.current);
      openTimerRef.current = null;
    }
    if (closeTimerRef.current !== null) {
      window.clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
  }, []);
  const setOpen = React.useCallback(
    (next: boolean) => {
      if (!isControlled) {
        setUncontrolled(next);
      }
      onOpenChange?.(next);
    },
    [isControlled, onOpenChange]
  );
  const scheduleOpen = React.useCallback(() => {
    if (closeTimerRef.current !== null) {
      window.clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
    if (open) {
      return;
    }
    openTimerRef.current = window.setTimeout(() => {
      openTimerRef.current = null;
      setOpen(true);
    }, openDelay);
  }, [open, openDelay, setOpen]);
  const scheduleClose = React.useCallback(() => {
    if (openTimerRef.current !== null) {
      window.clearTimeout(openTimerRef.current);
      openTimerRef.current = null;
    }
    if (!open) {
      return;
    }
    closeTimerRef.current = window.setTimeout(() => {
      closeTimerRef.current = null;
      setOpen(false);
    }, closeDelay);
  }, [open, closeDelay, setOpen]);
  React.useEffect(() => clearTimers, [clearTimers]);
  const ctx = React.useMemo<HoverCardContextValue>(
    () => ({
      contentRef,
      open,
      scheduleClose,
      scheduleOpen,
      setOpen,
      triggerRef,
    }),
    [open, setOpen, scheduleOpen, scheduleClose]
  );
  return (
    <HoverCardContext.Provider value={ctx}>
      {children}
    </HoverCardContext.Provider>
  );
}

type HoverCardTriggerProps = Omit<
  React.ComponentPropsWithoutRef<"button">,
  "ref"
> &
  Record<string, unknown> & {
    as?: React.ElementType;
    asChild?: boolean;
    ref?: React.Ref<HTMLElement>;
  };

function HoverCardTrigger({
  as,
  asChild,
  children,
  onBlur,
  onFocus,
  onPointerEnter,
  onPointerLeave,
  ref,
  ...props
}: HoverCardTriggerProps) {
  const ctx = useHoverCardContext();
  const setRef = React.useCallback(
    (node: HTMLElement | null) => {
      ctx.triggerRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLElement | null>).current = node;
      }
    },
    [ctx.triggerRef, ref]
  );
  const handlers = {
    onBlur: (e: React.FocusEvent<HTMLElement>) => {
      onBlur?.(e as never);
      if (!e.defaultPrevented) {
        ctx.scheduleClose();
      }
    },
    onFocus: (e: React.FocusEvent<HTMLElement>) => {
      onFocus?.(e as never);
      if (!e.defaultPrevented) {
        ctx.scheduleOpen();
      }
    },
    onPointerEnter: (e: React.PointerEvent<HTMLElement>) => {
      onPointerEnter?.(e as never);
      if (!e.defaultPrevented) {
        ctx.scheduleOpen();
      }
    },
    onPointerLeave: (e: React.PointerEvent<HTMLElement>) => {
      onPointerLeave?.(e as never);
      if (!e.defaultPrevented) {
        ctx.scheduleClose();
      }
    },
  };
  const state = ctx.open ? "open" : "closed";
  if (asChild && React.isValidElement(children)) {
    const child = children as React.ReactElement<Record<string, unknown>>;
    return React.cloneElement(child, {
      ...props,
      ...handlers,
      "data-slot": "hover-card-trigger",
      "data-state": state,
      ref: setRef,
    } as never);
  }
  const Component = (as ?? "button") as React.ElementType;
  const isNativeButton = !as;
  return (
    <Component
      data-slot="hover-card-trigger"
      data-state={state}
      {...props}
      {...(isNativeButton ? { type: "button" as const } : {})}
      {...handlers}
      ref={setRef}
    >
      {children}
    </Component>
  );
}

type HoverCardContentProps = React.ComponentPropsWithoutRef<"div"> & {
  align?: Align;
  side?: Side;
  sideOffset?: number;
  ref?: React.Ref<HTMLDivElement>;
};

interface Position {
  left: number;
  side: Side;
  top: number;
}

function computePosition(
  trigger: HTMLElement,
  content: HTMLElement,
  side: Side,
  align: Align,
  offset: number
): Position {
  const t = trigger.getBoundingClientRect();
  const c = content.getBoundingClientRect();
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  let actualSide: Side = side;
  if (
    side === "bottom" &&
    t.bottom + offset + c.height > vh &&
    t.top > vh - t.bottom
  ) {
    actualSide = "top";
  } else if (
    side === "top" &&
    t.top - offset - c.height < 0 &&
    vh - t.bottom > t.top
  ) {
    actualSide = "bottom";
  } else if (
    side === "right" &&
    t.right + offset + c.width > vw &&
    t.left > vw - t.right
  ) {
    actualSide = "left";
  } else if (
    side === "left" &&
    t.left - offset - c.width < 0 &&
    vw - t.right > t.left
  ) {
    actualSide = "right";
  }
  let top = 0;
  let left = 0;
  if (actualSide === "bottom") {
    top = t.bottom + offset;
  } else if (actualSide === "top") {
    top = t.top - c.height - offset;
  } else if (actualSide === "right") {
    top = t.top + (t.height - c.height) / 2;
  } else {
    top = t.top + (t.height - c.height) / 2;
  }
  if (actualSide === "bottom" || actualSide === "top") {
    if (align === "start") {
      left = t.left;
    } else if (align === "end") {
      left = t.right - c.width;
    } else {
      left = t.left + (t.width - c.width) / 2;
    }
  } else if (actualSide === "right") {
    left = t.right + offset;
  } else {
    left = t.left - c.width - offset;
  }
  left = Math.max(8, Math.min(left, vw - c.width - 8));
  top = Math.max(8, Math.min(top, vh - c.height - 8));
  return { left, side: actualSide, top };
}

function HoverCardContent({
  align = "center",
  children,
  className,
  ref,
  side = "bottom",
  sideOffset = 4,
  style,
  ...props
}: HoverCardContentProps) {
  const ctx = useHoverCardContext();
  const { open, setOpen, triggerRef, contentRef, scheduleOpen, scheduleClose } =
    ctx;
  const [mounted, setMounted] = React.useState(open);
  const [pos, setPos] = React.useState<Position>({ left: 0, side, top: 0 });
  const setRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      contentRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
      }
    },
    [contentRef, ref]
  );
  const [entered, setEntered] = React.useState(false);
  React.useEffect(() => {
    if (open) {
      setMounted(true);
      const raf1 = requestAnimationFrame(() => {
        const raf2 = requestAnimationFrame(() => setEntered(true));
        return () => cancelAnimationFrame(raf2);
      });
      return () => cancelAnimationFrame(raf1);
    }
    setEntered(false);
    const timer = window.setTimeout(() => setMounted(false), 100);
    return () => window.clearTimeout(timer);
  }, [open]);
  React.useLayoutEffect(() => {
    if (!mounted) {
      return;
    }
    const trigger = triggerRef.current;
    const content = contentRef.current;
    if (!(trigger && content)) {
      return;
    }
    const update = () =>
      setPos(computePosition(trigger, content, side, align, sideOffset));
    update();
    const ro = new ResizeObserver(update);
    ro.observe(trigger);
    ro.observe(content);
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    return () => {
      ro.disconnect();
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    };
  }, [mounted, align, side, sideOffset, triggerRef, contentRef]);

  React.useEffect(() => {
    if (!open) {
      return;
    }
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setOpen(false);
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, setOpen]);
  if (!mounted || typeof document === "undefined") {
    return null;
  }
  return createPortal(
    <div
      data-side={pos.side}
      data-slot="hover-card-content"
      data-state={open ? "open" : "closed"}
      {...props}
      className={cn(
        "bg-popover dark:bg-card text-popover-foreground ring-foreground/10 fixed z-50 w-64 rounded-lg p-3 text-sm shadow-sm ring-1 outline-hidden",
        className
      )}
      onPointerEnter={() => scheduleOpen()}
      onPointerLeave={() => scheduleClose()}
      ref={setRef}
      style={{
        left: pos.left,
        opacity: entered ? 1 : 0,
        top: pos.top,
        transform: `scale(${entered ? 1 : 0.95})`,
        transition: "opacity 100ms ease-out, transform 100ms ease-out",
        ...style,
      }}
    >
      {children}
    </div>,
    document.body
  );
}

export { HoverCard, HoverCardContent, HoverCardTrigger };
Overview
View your key metrics and recent project activity.
You have 12 active projects and 3 pending tasks.
tabs.tsx
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

interface TabsContextValue {
  baseId: string;
  orientation: "horizontal" | "vertical";
  setValue: (value: string) => void;
  value: string;
}

const TabsContext = React.createContext<TabsContextValue | null>(null);

function useTabsContext(): TabsContextValue {
  const ctx = React.useContext(TabsContext);
  if (!ctx) {
    throw new Error("Tabs components must be used within <Tabs>.");
  }
  return ctx;
}

interface TabsProps {
  children?: React.ReactNode;
  className?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  orientation?: "horizontal" | "vertical";
  value?: string;
}

function Tabs({
  children,
  className,
  value: valueProp,
  defaultValue = "",
  onValueChange,
  orientation = "horizontal",
}: TabsProps) {
  const isControlled = valueProp !== undefined;
  const [uncontrolled, setUncontrolled] = React.useState(defaultValue);
  const value = isControlled ? valueProp : uncontrolled;
  const baseId = React.useId();
  const setValue = React.useCallback(
    (next: string) => {
      if (!isControlled) {
        setUncontrolled(next);
      }
      onValueChange?.(next);
    },
    [isControlled, onValueChange]
  );
  const ctx = React.useMemo<TabsContextValue>(
    () => ({ baseId, orientation, setValue, value }),
    [value, setValue, baseId, orientation]
  );
  return (
    <TabsContext.Provider value={ctx}>
      <div
        className={cn(
          "flex flex-col gap-2",
          orientation === "vertical" && "flex-row",
          className
        )}
        data-orientation={orientation}
        data-slot="tabs"
      >
        {children}
      </div>
    </TabsContext.Provider>
  );
}

type TabsListProps = React.ComponentPropsWithoutRef<"div">;

function TabsList({ children, className, onKeyDown, ...props }: TabsListProps) {
  const ctx = useTabsContext();
  const listRef = React.useRef<HTMLDivElement>(null);
  const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(e);
    if (e.defaultPrevented) {
      return;
    }
    const root = listRef.current;
    if (!root) {
      return;
    }
    const triggers = Array.from(
      root.querySelectorAll<HTMLButtonElement>(
        "[data-slot=tabs-trigger]:not([disabled])"
      )
    );
    if (triggers.length === 0) {
      return;
    }
    const currentIdx = triggers.indexOf(
      document.activeElement as HTMLButtonElement
    );
    if (currentIdx < 0) {
      return;
    }
    let nextIdx = -1;
    const isVertical = ctx.orientation === "vertical";
    const prev = isVertical ? "ArrowUp" : "ArrowLeft";
    const next = isVertical ? "ArrowDown" : "ArrowRight";
    if (e.key === next) {
      nextIdx = (currentIdx + 1) % triggers.length;
    } else if (e.key === prev) {
      nextIdx = (currentIdx - 1 + triggers.length) % triggers.length;
    } else if (e.key === "Home") {
      nextIdx = 0;
    } else if (e.key === "End") {
      nextIdx = triggers.length - 1;
    }
    if (nextIdx < 0) {
      return;
    }
    e.preventDefault();
    triggers[nextIdx].focus();
    triggers[nextIdx].click();
  };
  return (
    <div
      {...props}
      className={cn(
        "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px] outline-none",
        className
      )}
      data-slot="tabs-list"
      onKeyDown={handleKeyDown}
      ref={listRef}
      role="tablist"
    >
      {children}
    </div>
  );
}

type TabsTriggerProps = Omit<
  React.ComponentPropsWithoutRef<"button">,
  "value" | "ref"
> & {
  value: string;
  ref?: React.Ref<HTMLButtonElement>;
};

function TabsTrigger({
  children,
  className,
  onClick,
  ref,
  value,
  ...props
}: TabsTriggerProps) {
  const ctx = useTabsContext();
  const isActive = ctx.value === value;
  const triggerId = `${ctx.baseId}-trigger-${value}`;
  const contentId = `${ctx.baseId}-content-${value}`;
  return (
    <button
      {...props}
      aria-controls={contentId}
      aria-selected={isActive}
      className={cn(
        "data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow,opacity] duration-150 focus-visible:outline-none active:opacity-60 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=size-])]:size-4",
        className
      )}
      data-slot="tabs-trigger"
      data-state={isActive ? "active" : "inactive"}
      id={triggerId}
      onClick={(e) => {
        onClick?.(e);
        if (e.defaultPrevented) {
          return;
        }
        ctx.setValue(value);
      }}
      ref={ref}
      role="tab"
      tabIndex={isActive ? 0 : -1}
      type="button"
    >
      {children}
    </button>
  );
}

type TabsContentProps = Omit<React.ComponentPropsWithoutRef<"div">, "value"> & {
  value: string;
  as?: React.ElementType;
  asChild?: boolean;
  ref?: React.Ref<HTMLDivElement>;
};

function TabsContent({
  as,
  asChild,
  children,
  className,
  ref,
  value,
  ...props
}: TabsContentProps) {
  const ctx = useTabsContext();
  const isActive = ctx.value === value;
  const triggerId = `${ctx.baseId}-trigger-${value}`;
  const contentId = `${ctx.baseId}-content-${value}`;
  const merged = {
    ...props,
    "aria-hidden": !isActive,
    "aria-labelledby": triggerId,
    className: cn("flex-1 outline-none", className),
    "data-slot": "tabs-content",
    "data-state": isActive ? "active" : "inactive",
    hidden: !isActive,
    id: contentId,
    role: "tabpanel",
    tabIndex: 0,
  };
  if (asChild && React.isValidElement(children)) {
    const child = children as React.ReactElement<Record<string, unknown>>;
    return React.cloneElement(child, { ...merged, ref } as never);
  }
  const Component = (as ?? "div") as React.ElementType;
  return (
    <Component {...merged} ref={ref}>
      {children}
    </Component>
  );
}

export { Tabs, TabsContent, TabsList, TabsTrigger };

Dialog, Item, Checkbox, Hover Card, and Tabs now ship as native implementations. Dialog renders a role="dialog" surface with aria-modal, focus trap, Escape close, click-outside close, focus restore, and a motion prop. Hover Card runs on a self-contained computePosition with portal, openDelay, and closeDelay. Tabs implements the WAI-ARIA tabs pattern with roving tabindex and arrow-key navigation. Checkbox and Item replace the Radix Slot with the polymorphic as prop (asChild stays for backward compatibility).

Changed:

  • Removed radix-ui from dependencies on all five.
  • New motion prop on DialogContent.
  • New openDelay / closeDelay props on HoverCard.
  • DialogTrigger, DialogClose, Item, HoverCardTrigger, and TabsContent accept as (asChild retained).
  • Checkbox now supports checked="indeterminate" with aria-checked="mixed".
  • Fixed class typo on Checkbox and Item: data-checked:bg-primary and data-checked:text-primary-foreground were missing a space.

Installation

$ npx frakment@latest add dialog item checkbox hover-card tabs

Docs migration (Empty, Field, Code Block, Textarea)

No projects yet
Get started by creating your first project.
empty.tsx
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";

function Empty({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance",
        className
      )}
      data-slot="empty"
      {...props}
    />
  );
}

function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex max-w-sm flex-col items-center gap-2", className)}
      data-slot="empty-header"
      {...props}
    />
  );
}

const emptyMediaVariants = cva(
  "mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
  {
    defaultVariants: {
      variant: "default",
    },
    variants: {
      variant: {
        default: "bg-transparent",
        icon: "bg-muted text-foreground flex size-8 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-4",
      },
    },
  }
);

function EmptyMedia({
  className,
  variant = "default",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
  return (
    <div
      className={cn(emptyMediaVariants({ className, variant }))}
      data-slot="empty-icon"
      data-variant={variant}
      {...props}
    />
  );
}

function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("text-sm font-medium tracking-tight", className)}
      data-slot="empty-title"
      {...props}
    />
  );
}

function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <div
      className={cn(
        "text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
        className
      )}
      data-slot="empty-description"
      {...props}
    />
  );
}

function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full max-w-sm min-w-0 flex-col items-center gap-2.5 text-sm text-balance",
        className
      )}
      data-slot="empty-content"
      {...props}
    />
  );
}

export {
  Empty,
  EmptyContent,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
};
Payment Method

All transactions are secure and encrypted

Enter your 16-digit card number

Billing Address

The billing address associated with your payment method

field.tsx
"use client";

import { cva, type VariantProps } from "class-variance-authority";
import { useMemo } from "react";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";

function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
  return (
    <fieldset
      className={cn(
        "flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
        className
      )}
      data-slot="field-set"
      {...props}
    />
  );
}

function FieldLegend({
  className,
  variant = "legend",
  ...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
  return (
    <legend
      className={cn(
        "mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
        className
      )}
      data-slot="field-legend"
      data-variant={variant}
      {...props}
    />
  );
}

function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
        className
      )}
      data-slot="field-group"
      {...props}
    />
  );
}

const fieldVariants = cva(
  "group/field data-[invalid=true]:text-destructive flex w-full gap-2",
  {
    defaultVariants: {
      orientation: "vertical",
    },
    variants: {
      orientation: {
        horizontal:
          "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
        responsive:
          "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
        vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
      },
    },
  }
);

function Field({
  className,
  orientation = "vertical",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
  return (
    <div
      className={cn(fieldVariants({ orientation }), className)}
      data-orientation={orientation}
      data-slot="field"
      role="group"
      {...props}
    />
  );
}

function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
        className
      )}
      data-slot="field-content"
      {...props}
    />
  );
}

function FieldLabel({
  className,
  ...props
}: React.ComponentProps<typeof Label>) {
  return (
    <Label
      className={cn(
        "group/field-label peer/field-label has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10 flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 *:data-[slot=field]:p-2.5",
        "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
        className
      )}
      data-slot="field-label"
      {...props}
    />
  );
}

function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",
        className
      )}
      data-slot="field-label"
      {...props}
    />
  );
}

function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      className={cn(
        "text-muted-foreground text-left text-sm leading-normal font-normal group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
        "last:mt-0 nth-last-2:-mt-1",
        "[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
        className
      )}
      data-slot="field-description"
      {...props}
    />
  );
}

function FieldSeparator({
  children,
  className,
  ...props
}: React.ComponentProps<"div"> & {
  children?: React.ReactNode;
}) {
  return (
    <div
      className={cn(
        "relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
        className
      )}
      data-content={!!children}
      data-slot="field-separator"
      {...props}
    >
      <Separator className="absolute inset-0 top-1/2" />
      {children && (
        <span
          className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
          data-slot="field-separator-content"
        >
          {children}
        </span>
      )}
    </div>
  );
}

function FieldError({
  className,
  children,
  errors,
  ...props
}: React.ComponentProps<"div"> & {
  errors?: Array<{ message?: string } | undefined>;
}) {
  const content = useMemo(() => {
    if (children) {
      return children;
    }

    if (!errors?.length) {
      return null;
    }

    const uniqueErrors = [
      ...new Map(errors.map((error) => [error?.message, error])).values(),
    ];

    if (uniqueErrors?.length === 1) {
      return uniqueErrors[0]?.message;
    }

    return (
      <ul className="ml-4 flex list-disc flex-col gap-1">
        {uniqueErrors.map(
          (error, index) =>
            error?.message && <li key={index}>{error.message}</li>
        )}
      </ul>
    );
  }, [children, errors]);

  if (!content) {
    return null;
  }

  return (
    <div
      className={cn("text-destructive text-sm font-normal", className)}
      data-slot="field-error"
      role="alert"
      {...props}
    >
      {content}
    </div>
  );
}

export {
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSeparator,
  FieldSet,
  FieldTitle,
};
app/api/chat/route.ts
import { streamText } from "ai"
export async function POST(request: Request) {  const { messages } = await request.json()
  const result = streamText({    model: "anthropic/claude-sonnet-4.5",    system: "You are a helpful assistant. Answer in one short paragraph.",    messages,  })
  return result.toUIMessageStreamResponse()}
code-block.tsx
"use client";

import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import {
  CheckIcon,
  CopyIcon,
  FileCode2Icon,
  FileJsonIcon,
  FileTextIcon,
  TerminalIcon,
} from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const codeBlockVariants = cva(
  "group/code-block has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/30 relative flex w-full min-w-0 flex-col overflow-hidden rounded-2xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 data-[size=sm]:rounded-xl data-[size=sm]:text-xs",
  {
    defaultVariants: {
      variant: "default",
    },
    variants: {
      variant: {
        default:
          "bg-muted text-foreground ring-foreground/5 dark:ring-foreground/10 ring-1",
        destructive:
          "bg-destructive/5 text-destructive ring-destructive/15 dark:bg-destructive/10 dark:ring-destructive/20 ring-1",
      },
    },
  }
);

function CodeBlock({
  className,
  variant = "default",
  size = "default",
  ...props
}: React.ComponentProps<"div"> &
  VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
  return (
    <div
      className={cn(codeBlockVariants({ variant }), className)}
      data-size={size}
      data-slot="code-block"
      data-variant={variant}
      {...props}
    />
  );
}

function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "text-muted-foreground group-data-[variant=destructive]/code-block:text-destructive flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 *:has-[>[data-slot=code-block-title]]:min-w-0",
        className
      )}
      data-slot="code-block-header"
      {...props}
    />
  );
}

const iconMap: Record<string, typeof FileCode2Icon> = {
  bash: TerminalIcon,
  cjs: FileCode2Icon,
  css: FileCode2Icon,
  fish: TerminalIcon,
  go: FileCode2Icon,
  html: FileCode2Icon,
  js: FileCode2Icon,
  json: FileJsonIcon,
  jsonc: FileJsonIcon,
  jsx: FileCode2Icon,
  less: FileCode2Icon,
  md: FileTextIcon,
  mdx: FileTextIcon,
  mjs: FileCode2Icon,
  php: FileCode2Icon,
  py: FileCode2Icon,
  rb: FileCode2Icon,
  rs: FileCode2Icon,
  sass: FileCode2Icon,
  scss: FileCode2Icon,
  sh: TerminalIcon,
  toml: FileCode2Icon,
  ts: FileCode2Icon,
  tsx: FileCode2Icon,
  yaml: FileCode2Icon,
  yml: FileCode2Icon,
  zsh: TerminalIcon,
};

function pickIcon(children: React.ReactNode): typeof FileCode2Icon | null {
  if (typeof children !== "string") {
    return null;
  }
  const trimmed = children.trim();
  const last = trimmed.split(/\s+/u).pop() ?? "";
  const dot = last.lastIndexOf(".");
  if (dot < 0 || dot === last.length - 1) {
    return FileCode2Icon;
  }
  const ext = last.slice(dot + 1).toLowerCase();
  return iconMap[ext] ?? FileCode2Icon;
}

function CodeBlockTitle({
  children,
  className,
  icon,
  ...props
}: React.ComponentProps<"div"> & { icon?: typeof FileCode2Icon | null }) {
  const Icon = icon === undefined ? pickIcon(children) : icon;
  return (
    <div
      className={cn(
        "text-foreground group-data-[variant=destructive]/code-block:text-destructive inline-flex min-w-0 items-center gap-1.5 truncate font-sans text-sm font-medium group-data-[size=sm]/code-block:text-xs [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5",
        className
      )}
      data-slot="code-block-title"
      {...props}
    >
      {Icon ? <Icon /> : null}
      <span className="min-w-0 truncate">{children}</span>
    </div>
  );
}

function CodeBlockActions({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "*:data-[slot=button]:hover:bg-foreground/5 dark:*:data-[slot=button]:hover:bg-foreground/10 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-foreground/10 -my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:ring-1",
        className
      )}
      data-slot="code-block-actions"
      {...props}
    />
  );
}

function CodeBlockCopyButton({
  value,
  variant = "ghost",
  size = "icon-xs",
  className,
  onClick,
  ...props
}: React.ComponentProps<typeof Button> & { value: string }) {
  const [copied, setCopied] = React.useState(false);

  React.useEffect(() => {
    if (!copied) {
      return;
    }

    const timeout = setTimeout(() => setCopied(false), 2000);
    return () => clearTimeout(timeout);
  }, [copied]);

  return (
    <>
      <Button
        aria-label={copied ? "Copied" : "Copy"}
        className={cn(
          "hover:bg-foreground/5 dark:hover:bg-foreground/10",
          className
        )}
        data-copied={copied || undefined}
        data-slot="code-block-copy-button"
        onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
          onClick?.(event);
          navigator.clipboard
            .writeText(value)
            .then(() => setCopied(true))
            .catch(() => {});
        }}
        size={size}
        variant={variant}
        {...props}
      >
        {copied ? <CheckIcon /> : <CopyIcon />}
      </Button>
      <span aria-live="polite" className="sr-only">
        {copied ? "Copied" : ""}
      </span>
    </>
  );
}

function CodeBlockContent({
  className,
  children,
  style,
  wrap = false,
  lineNumbers = false,
  startLine = 1,
  ...props
}: React.ComponentProps<"pre"> & {
  wrap?: boolean;
  lineNumbers?: boolean;
  startLine?: number;
}) {
  return (
    <pre
      className={cn(
        "scroll-fade-x data-wrap:scroll-fade-y min-h-0 min-w-0 scrollbar-thin overflow-auto px-4 py-4 text-start font-mono text-sm leading-relaxed outline-none group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
        className
      )}
      data-numbered={lineNumbers || undefined}
      data-slot="code-block-content"
      data-wrap={wrap || undefined}
      dir="ltr"
      style={{ counterReset: `line ${startLine - 1}`, ...style }}
      {...props}
    >
      <code
        className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
        data-slot="code-block-code"
      >
        {lineNumbers && typeof children === "string"
          ? children
              .replace(/\n$/u, "")
              .split("\n")
              .map((line, index) => (
                <CodeBlockLine key={index}>{line}</CodeBlockLine>
              ))
          : children}
      </code>
    </pre>
  );
}

const codeBlockLineVariants = cva(
  "before:text-muted-foreground after:text-muted-foreground relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end after:absolute after:start-1 after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:gap-x-3 in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
  {
    defaultVariants: {
      variant: "default",
    },
    variants: {
      variant: {
        added: "bg-foreground/5 after:content-['+']",
        default: "",
        highlighted: "bg-foreground/5",
        removed: "bg-destructive/10 after:text-destructive after:content-['−']",
      },
    },
  }
);

function CodeBlockLine({
  className,
  variant = "default",
  children,
  ...props
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
  const empty =
    children === undefined ||
    children === null ||
    children === "" ||
    (Array.isArray(children) && children.length === 0);

  return (
    <span
      className={cn(codeBlockLineVariants({ variant }), className)}
      data-slot="code-block-line"
      data-variant={variant}
      {...props}
    >
      <span className="min-w-0" data-slot="code-block-line-content">
        {empty ? "\n" : children}
      </span>
    </span>
  );
}

function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "text-muted-foreground flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
        className
      )}
      data-slot="code-block-footer"
      {...props}
    />
  );
}

export {
  CodeBlock,
  CodeBlockActions,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockFooter,
  CodeBlockHeader,
  CodeBlockLine,
  CodeBlockTitle,
};
textarea.tsx
import type * as React from "react";

import { cn } from "@/lib/utils";

function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
  return (
    <textarea
      className={cn(
        "border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 disabled:bg-input/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-2.5 py-2 text-base transition-colors outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 md:text-sm",
        className
      )}
      data-slot="textarea"
      {...props}
    />
  );
}

export { Textarea };

Empty, Field, Code Block, and Textarea move under the /docs/components/web/ path to match the base switcher used by the rest of the web components. Sources are unchanged and already free of radix-ui. Old URLs redirect.

Changed:

  • Docs moved from /docs/components/<name> to /docs/components/web/<name>.
  • Each page now renders <DocsBaseSwitcher base="web" component="<name>" />.
  • All install snippets and related-component links point to the new paths.