{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "drawer",
  "title": "Drawer",
  "description": "A panel that slides in from any edge, start and end following the text direction, and is dragged back to it to close, on the feel’s spring. On the bottom edge it has a handle, follows its content when that changes height and rests at snap points. A drawer opened on top dims or steps back the one below, and an outlet steps the page back with the finger.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/grip.json",
    "https://kinoui.com/r/panel.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/sheet-physics.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/drawer.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { gripClassName } from '@/registry/lib/grip'\nimport {\n  PanelCloseIcon,\n  PanelHandle,\n  panelBodyClassName,\n  panelBodyContentClassName,\n  panelBodyFrameClassName,\n  panelCloseClassName,\n  panelCloseRoomClassName,\n  panelDescriptionClassName,\n  panelDimClassName,\n  panelFooterClassName,\n  panelFooterTint,\n  panelHeaderClassName,\n  panelTitleClassName,\n  useFollowHeight,\n  useScrollRegion,\n} from '@/registry/lib/panel'\nimport { mergeRefs } from '@/registry/lib/refs'\nimport { useSheetPhysics } from '@/registry/lib/sheet-physics'\nimport {\n  Drawer as DrawerPrimitive,\n  DrawerBackdrop as DrawerBackdropPrimitive,\n  DrawerClose as DrawerClosePrimitive,\n  DrawerContent as DrawerContentPrimitive,\n  type DrawerContentState,\n  DrawerDescription as DrawerDescriptionPrimitive,\n  DrawerHandle as DrawerHandlePrimitive,\n  type DrawerKeyframes,\n  DrawerOutlet as DrawerOutletPrimitive,\n  DrawerTitle as DrawerTitlePrimitive,\n  DrawerTrigger as DrawerTriggerPrimitive,\n} from '@ui-sdk/react/drawer'\nimport { type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  type RefObject,\n  use,\n  useCallback,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { cn } from '@/lib/utils'\n\n/**\n * `default` docks the panel to its edge while the page stays still. `recede`\n * also steps it back and up while another drawer is open on top of it.\n */\ntype DrawerVariant = 'default' | 'recede'\n\nconst DrawerContext = createContext<{\n  snaps: boolean\n  trigger?: RefObject<HTMLElement | null>\n  content?: RefObject<HTMLElement | null>\n  onDrag?: (dragging: boolean) => void\n}>({ snaps: false })\n\n/** The panel of the drawer this one was opened from, which reads its height to step back. */\nconst PanelBelowContext = createContext<RefObject<HTMLElement | null> | null>(null)\n\n/** Whether the drawer around rests at its largest snap point, which names its handle. */\nconst ExpandedContext = createContext(false)\n\n/**\n * A panel that slides in from an edge of the screen, `bottom` unless `side`\n * says another, and is dragged back to it to close. `start` and `end`\n * follow the text direction. With `snapPoints` it rests at the first and is\n * dragged, or its handle pressed, to the next. ui-sdk moves it on a spring\n * of its own, timed by the feel's `enter` spring while it opens and rests\n * and its `exit` spring while it closes or is let go, where it is: a\n * `data-feel` or `data-motion='reduce'` around it re-times or stops it.\n */\nfunction Drawer({\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  ...props\n}: Omit<ComponentProps<typeof DrawerPrimitive>, 'physics'>) {\n  // Held here, so the spring can change to `exit` in the render that closes it.\n  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)\n  const trigger = useRef<HTMLElement | null>(null)\n  const content = useRef<HTMLElement | null>(null)\n  const [dragging, setDragging] = useState(false)\n  const at = useCallback(() => content.current ?? trigger.current, [])\n  // ui-sdk works out a release's spring as the finger lifts, before the render that closes it.\n  const physics = useSheetPhysics(open && !dragging ? 'enter' : 'exit', at)\n  const snaps = (props.snapPoints?.length ?? 0) > 1\n  return (\n    <DrawerContext value={{ snaps, trigger, content, onDrag: setDragging }}>\n      <DrawerPrimitive\n        open={open}\n        onOpenChange={setOpen}\n        physics={physics}\n        // At its first snap point, a peek, the page stays undimmed and usable.\n        modalAbove={snaps ? props.snapPoints?.[0] : undefined}\n        {...props}\n      />\n    </DrawerContext>\n  )\n}\n\nfunction DrawerTrigger({ ref, ...props }: ComponentProps<typeof DrawerTriggerPrimitive>) {\n  const { trigger } = use(DrawerContext)\n  const own = useMemo(() => mergeRefs(ref, trigger), [ref, trigger])\n  return <DrawerTriggerPrimitive ref={own} {...props} />\n}\n\nfunction DrawerClose(props: ComponentProps<typeof DrawerClosePrimitive>) {\n  return <DrawerClosePrimitive {...props} />\n}\n\n/**\n * The dim behind the drawer, which follows it as it is dragged. A drawer\n * opened from another one leaves its dim out: the one below already dims the\n * page, and dims itself.\n */\nfunction DrawerBackdrop({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof DrawerBackdropPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <DrawerBackdropPrimitive\n      className={cn(panelDimClassName, 'data-nested:invisible', className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * The bar on a bottom drawer's top edge that shows it can be dragged. With\n * snap points it is a button: pressing it moves the drawer to the next, so\n * it can be resized without dragging, and the arrow keys, Home and End step.\n */\nfunction DrawerHandle({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof DrawerHandlePrimitive>, 'className'> & {\n  className?: string\n}) {\n  const { snaps } = use(DrawerContext)\n  const expanded = use(ExpandedContext)\n  if (!snaps) return <PanelHandle className={className} />\n  return (\n    // A press walks on to the next snap point, back to the first after the last.\n    <DrawerHandlePrimitive\n      data-panel='handle'\n      aria-label={expanded ? 'Collapse' : 'Expand'}\n      className={cn(\n        'group/grip focus-visible:ring-ring/50 mx-auto flex h-6 w-16 shrink-0 items-end justify-center rounded-full focus-visible:ring-3 focus-visible:outline-hidden',\n        className,\n      )}\n      {...props}\n    >\n      <span className={cn(gripClassName, 'h-1 w-10')} />\n    </DrawerHandlePrimitive>\n  )\n}\n\n/**\n * The panel's box. A panel on the top or bottom edge is as tall as its\n * content, and follows it when that changes height while it is open; one on\n * a side is as tall as the screen.\n */\nfunction DrawerSurface({\n  vertical,\n  closeButton,\n  children,\n}: {\n  vertical: boolean\n  closeButton: ReactNode\n  children: ReactNode\n}) {\n  const surfaceRef = useRef<HTMLDivElement>(null)\n  const innerRef = useRef<HTMLDivElement>(null)\n  useFollowHeight(surfaceRef, innerRef, vertical)\n\n  return (\n    <div\n      ref={surfaceRef}\n      data-close-button={closeButton ? '' : undefined}\n      className={cn(\n        // Not a flex box: the inner box keeps its own height while this one animates to it.\n        'group/panel-surface @container relative min-h-0 overflow-clip rounded-[inherit] transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n        panelCloseRoomClassName,\n        vertical ? 'max-h-full' : 'h-full',\n      )}\n    >\n      <div\n        ref={innerRef}\n        className={cn(\n          'relative flex min-h-0 flex-col pb-[env(safe-area-inset-bottom)] *:[form]:contents',\n          vertical ? 'max-h-[calc(100cqh-(--spacing(12)))]' : 'h-full',\n        )}\n      >\n        {children}\n        {closeButton}\n      </div>\n    </div>\n  )\n}\n\n/**\n * The panel, with its dim, and the handle on a bottom drawer. ui-sdk moves\n * it on `translate` and sets the dim's opacity, so neither is styled here.\n * `children` are its parts, or a function of its state that returns them,\n * such as to read the `payload` a trigger passed.\n */\nfunction DrawerContent<Payload = unknown>({\n  className,\n  children,\n  showCloseButton = true,\n  variant = 'default',\n  initialFocus = 'content',\n  ref,\n  ...props\n}: Omit<\n  ComponentProps<typeof DrawerContentPrimitive<Payload>>,\n  'className' | 'children' | 'container'\n> & {\n  className?: string\n  children?: ReactNode | ((state: DrawerContentState<Payload>) => ReactNode)\n  showCloseButton?: boolean\n  variant?: DrawerVariant\n}) {\n  const { content, onDrag } = use(DrawerContext)\n  const below = use(PanelBelowContext)\n  const own = useMemo(\n    () =>\n      mergeRefs(ref, content, holdFocusedStill, stackHeights(below), followDrag(onDrag)),\n    [ref, content, below, onDrag],\n  )\n  return (\n    <>\n      <DrawerBackdrop />\n      <DrawerContentPrimitive<Payload>\n        ref={own}\n        initialFocus={initialFocus}\n        data-variant={variant}\n        className={cn(\n          /*\n           * A strip past the edge, in the colour the panel ends in, covers\n           * the gap when a spring overshoots or the panel is pulled past its\n           * size. While a drawer is open on top, this one dims, on that\n           * drawer's `enter` and `exit` roles.\n           */\n          'group/drawer bg-background text-foreground relative flex flex-col text-sm shadow-xl focus-visible:outline-hidden after:absolute after:bg-inherit forced-colors:outline',\n          'before:pointer-events-none before:absolute before:inset-0 before:z-20 before:rounded-[inherit] before:bg-black/10 before:opacity-0 before:transition-opacity before:duration-(--motion-exit-duration) before:ease-(--motion-exit-fade-easing) data-nested-open:before:opacity-100 data-nested-open:before:duration-(--motion-enter-duration) data-nested-open:before:ease-(--motion-enter-fade-easing) data-[variant=recede]:before:bg-black/15 dark:before:bg-black/40',\n          /*\n           * `recede`: it steps back and up the way a page does, lifted to the\n           * top of a taller drawer in front and past it by\n           * `--drawer-recede-offset`, so its top shows above that one.\n           */\n          'data-[variant=recede]:origin-top data-[variant=recede]:transition-transform data-[variant=recede]:duration-(--motion-exit-duration) data-[variant=recede]:ease-(--motion-exit-easing) data-[variant=recede]:data-nested-open:duration-(--motion-enter-duration) data-[variant=recede]:data-nested-open:ease-(--motion-enter-easing) data-[variant=recede]:data-nested-open:[transform:translateY(calc(min(0px,var(--drawer-height,0px)-var(--drawer-front-height,0px))-var(--drawer-recede-offset,0.75rem)))_scale(var(--drawer-recede,0.94))] motion-reduce:data-[variant=recede]:transition-none motion-reduce:data-[variant=recede]:data-nested-open:[transform:none]',\n          // A panel on a side is 26rem wide, never closer than 3rem to the far edge, one on the bottom edge no wider than 40rem, and one on the top edge as wide as the screen, unless `className` sets another width.\n          'w-[min(26rem,calc(100%-(--spacing(12))))] max-w-160',\n          'data-[side=left]:h-full data-[side=left]:border-e data-[side=left]:after:inset-y-0 data-[side=left]:after:right-full data-[side=left]:after:w-12',\n          'data-[side=right]:h-full data-[side=right]:border-s data-[side=right]:after:inset-y-0 data-[side=right]:after:left-full data-[side=right]:after:w-12',\n          'data-[side=bottom]:mx-auto data-[side=bottom]:w-full data-[side=bottom]:rounded-t-(--surface-radius-lg) data-[side=bottom]:border-t data-[side=bottom]:after:inset-x-0 data-[side=bottom]:after:top-full data-[side=bottom]:after:h-12 data-[side=bottom]:has-data-[panel=footer]:after:bg-(--panel-footer)',\n          'data-[side=top]:w-full data-[side=top]:max-w-none data-[side=top]:rounded-b-(--surface-radius-lg) data-[side=top]:border-b data-[side=top]:after:inset-x-0 data-[side=top]:after:bottom-full data-[side=top]:after:h-12',\n          panelFooterTint,\n          className,\n        )}\n        {...props}\n      >\n        {(state) => (\n          <PanelBelowContext value={content ?? null}>\n            <ExpandedContext value={state.expanded}>\n              <DrawerSurface\n                vertical={state.side === 'top' || state.side === 'bottom'}\n                closeButton={\n                  showCloseButton ? (\n                    <DrawerClosePrimitive\n                      render={\n                        <Button\n                          variant='ghost'\n                          size='icon-sm'\n                          className={panelCloseClassName}\n                        />\n                      }\n                      aria-label='Close'\n                    >\n                      <PanelCloseIcon />\n                    </DrawerClosePrimitive>\n                  ) : null\n                }\n              >\n                {state.side === 'bottom' ? <DrawerHandle /> : null}\n                {typeof children === 'function' ? children(state) : children}\n              </DrawerSurface>\n            </ExpandedContext>\n          </PanelBelowContext>\n        )}\n      </DrawerContentPrimitive>\n    </>\n  )\n}\n\nfunction DrawerHeader({\n  className,\n  render,\n  ...props\n}: Omit<PartProps<'div'>, 'className'> & { className?: string }) {\n  return renderElement(\n    'div',\n    {\n      'data-slot': 'drawer-header',\n      className: cn(panelHeaderClassName, className),\n      ...props,\n    },\n    render,\n  )\n}\n\nfunction DrawerTitle({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof DrawerTitlePrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <DrawerTitlePrimitive className={cn(panelTitleClassName, className)} {...props} />\n  )\n}\n\nfunction DrawerDescription({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof DrawerDescriptionPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <DrawerDescriptionPrimitive\n      className={cn(panelDescriptionClassName, className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * What scrolls between the header and the footer. `className` goes to its\n * content, every other prop to the element that scrolls. Dragging it down\n * once it is scrolled to the top moves the drawer. While it scrolls it takes\n * focus, so the keyboard can scroll it, as a region named by the title.\n */\n/**\n * What scrolls between the header and the footer. A finger drags the drawer\n * from it; a mouse selects its text, and drags from the header or the handle.\n */\nfunction DrawerBody({ className, children, ref, ...props }: ComponentProps<'div'>) {\n  const scrollerRef = useRef<HTMLDivElement>(null)\n  const contentRef = useRef<HTMLDivElement>(null)\n  const scrollRegion = useScrollRegion(scrollerRef, contentRef)\n  const own = useMemo(() => mergeRefs(scrollerRef, ref), [ref])\n  const mouse = useSyncExternalStore(watchMouse, pointsWithMouse, () => false)\n\n  return (\n    <div data-panel='body' className={panelBodyFrameClassName}>\n      <div\n        ref={own}\n        data-slot='drawer-body'\n        data-drawer-no-drag={mouse ? '' : undefined}\n        {...scrollRegion}\n        className={panelBodyClassName}\n        {...props}\n      >\n        <div\n          ref={contentRef}\n          data-slot='drawer-body-content'\n          className={cn(panelBodyContentClassName, className)}\n        >\n          {children}\n        </div>\n      </div>\n    </div>\n  )\n}\n\n/**\n * ui-sdk 0.1.0-beta.18's drawer scrolls a field that takes focus into view\n * in the area that scrolls around it, and takes a scroller that has focus\n * itself, such as the body or a Scroll area, for both, so every click or Tab\n * into one scrolled it 16px. While an element in the drawer has focus, a\n * script's scroll by on that element leaves it where it is; the keys and the\n * wheel still scroll it.\n */\nfunction holdFocusedStill(content: HTMLElement | null) {\n  if (!content) return\n  const held = new WeakSet<Element>()\n  const hold = (event: FocusEvent) => {\n    const target = event.target\n    // jsdom has no scrollBy.\n    if (!(target instanceof HTMLElement) || held.has(target) || !target.scrollBy) return\n    held.add(target)\n    const scrollBy = target.scrollBy.bind(target)\n    target.scrollBy = ((...args: Parameters<typeof scrollBy>) => {\n      if (target.ownerDocument.activeElement !== target) scrollBy(...args)\n    }) as HTMLElement['scrollBy']\n  }\n  // Before ui-sdk's own listener on the drawer.\n  content.addEventListener('focusin', hold, true)\n  return () => content.removeEventListener('focusin', hold, true)\n}\n\n/**\n * Writes the panel's height as `--drawer-height`, and on the panel below it\n * as `--drawer-front-height`, so a `recede` panel below lifts to its top.\n */\nconst MOUSE = '(hover: hover) and (pointer: fine)'\n\n/** Whether the device's main pointer is a mouse or a trackpad. */\nfunction pointsWithMouse() {\n  return window.matchMedia(MOUSE).matches\n}\n\nfunction watchMouse(onChange: () => void) {\n  const query = window.matchMedia(MOUSE)\n  query.addEventListener('change', onChange)\n  return () => query.removeEventListener('change', onChange)\n}\n\n/** Tells the drawer while a finger, mouse or pen drags it, in time for the release. */\nfunction followDrag(onDrag?: (dragging: boolean) => void) {\n  return (panel: HTMLElement | null) => {\n    if (!panel || !onDrag) return\n    const observer = new MutationObserver(() => {\n      const dragging = panel.hasAttribute('data-dragging')\n      flushSync(() => onDrag(dragging))\n    })\n    observer.observe(panel, { attributes: true, attributeFilter: ['data-dragging'] })\n    return () => observer.disconnect()\n  }\n}\n\nfunction stackHeights(below: RefObject<HTMLElement | null> | null) {\n  return (panel: HTMLElement | null) => {\n    if (!panel || typeof ResizeObserver === 'undefined') return\n    const observer = new ResizeObserver(() => {\n      const height = `${panel.offsetHeight}px`\n      panel.style.setProperty('--drawer-height', height)\n      below?.current?.style.setProperty('--drawer-front-height', height)\n    })\n    observer.observe(panel)\n    return () => {\n      observer.disconnect()\n      below?.current?.style.removeProperty('--drawer-front-height')\n    }\n  }\n}\n\nfunction DrawerFooter({\n  className,\n  render,\n  ...props\n}: Omit<PartProps<'div'>, 'className'> & { className?: string }) {\n  return renderElement(\n    'div',\n    {\n      'data-slot': 'drawer-footer',\n      'data-panel': 'footer',\n      className: cn(panelFooterClassName, 'mt-auto', className),\n      ...props,\n    },\n    render,\n  )\n}\n\n/**\n * The page steps back while the drawer opens: it shrinks by\n * `--drawer-recede` (0.94), drops `--drawer-recede-offset` (0.75rem) and\n * rounds its corners over black, and comes back with the finger as the\n * drawer is dragged away. ui-sdk plays it on the compositor. Inside\n * `Drawer`, or outside it with the drawer's `controller`.\n */\nfunction DrawerOutlet({\n  className,\n  keyframes = RECEDE,\n  ...props\n}: Omit<ComponentProps<typeof DrawerOutletPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <DrawerOutletPrimitive\n      keyframes={keyframes}\n      className={cn(\n        // Under reduced motion the page stays where it is, and only the dim shows the drawer.\n        'bg-background origin-top [--drawer-outlet-edge:transparent] dark:[--drawer-outlet-edge:--alpha(var(--color-white)/15%)] motion-reduce:scale-100! motion-reduce:translate-none! motion-reduce:rounded-none! motion-reduce:shadow-none!',\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/* A spread shadow paints the black around the page as it shrinks; in dark mode a thin edge keeps the two apart. */\nconst RECEDE: DrawerKeyframes = {\n  scale: ['1', 'var(--drawer-recede, 0.94)'],\n  translate: ['0 0', '0 var(--drawer-recede-offset, 0.75rem)'],\n  borderRadius: ['0px', 'var(--surface-radius)'],\n  boxShadow: [\n    '0 0 0 1px transparent, 0 0 0 100vmax transparent',\n    '0 0 0 1px var(--drawer-outlet-edge), 0 0 0 100vmax black',\n  ],\n}\n\nexport {\n  Drawer,\n  DrawerBackdrop,\n  DrawerBody,\n  DrawerClose,\n  DrawerContent,\n  DrawerDescription,\n  DrawerFooter,\n  DrawerHandle,\n  DrawerHeader,\n  DrawerOutlet,\n  DrawerTitle,\n  DrawerTrigger,\n  type DrawerVariant,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/drawer.tsx"
    }
  ],
  "type": "registry:component"
}