{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "carousel",
  "title": "Carousel",
  "description": "Slides on Embla, as the reference: a frame of slides on travelling 1px seams with a control row of cells (previous, n / N with position ticks, next). APG carousel without rotation: named region, slides labelled n of N, out-of-view slides inert, arrow keys mirrored in RTL, moves announced politely, instant steps under reduced motion.",
  "dependencies": [
    "@base-ui/react@1.9.0",
    "embla-carousel-react@8.6.0"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/button",
    "@keyline-ui/keyline-scope",
    "@keyline-ui/keyline-motion",
    "@keyline-ui/keyline-render"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/carousel.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport useEmblaCarousel, { type UseEmblaCarouselType } from \"embla-carousel-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { Button } from \"./button\";\nimport { domDir } from \"../lib/keyline-scope\";\nimport { useStretch } from \"../lib/keyline-motion\";\nimport { resolveClassName, resolveStyle, type PartProps } from \"../lib/keyline-render\";\n\n/* Behaviour is Embla (as in shadcn and neobrutalism.dev): dragging, snapping, loop, alignment, slides per\n   view, plugins. Keyline adds the APG carousel pattern without rotation (there is no autoplay, so no\n   rotation control): a named region, slides as groups labelled \"n of N\", polite announcements of the\n   slide that comes into view, arrow keys on the region (mirrored in RTL), slides out of view made inert\n   so Tab never lands on a hidden link, and instant steps under reduced motion. */\n\ntype CarouselApi = UseEmblaCarouselType[1];\ntype Opts = Parameters<typeof useEmblaCarousel>[0];\ntype Plugins = Parameters<typeof useEmblaCarousel>[1];\n\ntype Ctx = {\n  carouselRef: UseEmblaCarouselType[0];\n  api: CarouselApi;\n  orientation: \"horizontal\" | \"vertical\";\n  scrollPrev: () => void;\n  scrollNext: () => void;\n  canScrollPrev: boolean;\n  canScrollNext: boolean;\n  index: number;\n  count: number;\n  inView: number[];\n};\nconst CarouselContext = React.createContext<Ctx | null>(null);\n\nfunction useCarousel() {\n  const ctx = React.useContext(CarouselContext);\n  if (!ctx) throw new Error(\"useCarousel must be used within a <Carousel />\");\n  return ctx;\n}\n\nconst still = (el: Element | null) =>\n  window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches || !!el?.closest('[data-kl-motion=\"reduce\"]');\n\n/* ------------------------------------------------------------------ *\n * CLASSES\n * The position ticks are a stretch row: the engine clones it for a move and drops the clone's data-slot, so the\n * ticks and the band carry their own classes. What the orientation decides is chosen here from context; the root\n * mirrors it as data-orientation.\n * ------------------------------------------------------------------ */\n\n/** the frame: a viewport of slides on 1px seams, the control row as its foot */\nconst root = \"kl-frame flex min-w-0 flex-col bg-kl-cell\";\nconst viewport = \"min-w-0 overflow-hidden active:cursor-grabbing\";\n/* seams travel with the slides: each slide after the first draws the one it shares with its neighbour */\nconst track = cn(\n  \"flex touch-pan-y touch-pinch-zoom\",\n  \"[&>[data-slot=carousel-item]+[data-slot=carousel-item]]:border-s-(length:--kl-k1)\",\n  \"[&>[data-slot=carousel-item]+[data-slot=carousel-item]]:border-s-kl-seam\",\n);\nconst trackVertical = cn(\n  \"flex h-[var(--kl-carousel-h,320px)] touch-pan-x touch-pinch-zoom flex-col\",\n  \"[&>[data-slot=carousel-item]+[data-slot=carousel-item]]:border-t-(length:--kl-k1)\",\n  \"[&>[data-slot=carousel-item]+[data-slot=carousel-item]]:border-t-kl-seam\",\n);\nconst slide = \"min-h-0 min-w-0 flex-[0_0_100%]\";\n\nconst bar = cn(\n  \"kl-cells min-h-(--kl-ctl) border-t-(length:--kl-k1) border-t-kl-line\",\n  \"[&>[data-slot=carousel-position]]:min-h-0 [&>[data-slot=carousel-position]]:flex-auto\",\n  \"[&>[data-slot=carousel-position]]:justify-center [&>[data-slot=carousel-position]]:gap-3\",\n);\n\n/* position ticks: a 24px target, an 8px square mark; the current one is the band (Stretch), not the tick */\nconst tick = cn(\n  \"box-border grid size-6 cursor-pointer appearance-none place-items-center bg-transparent p-0\",\n  \"before:size-2 before:border-(length:--kl-k1) before:border-kl-line before:bg-transparent before:content-['']\",\n  \"hover:[&:not([aria-current])]:before:bg-kl-tint\",\n  \"active:[&:not([aria-current])]:before:border-kl-ink active:[&:not([aria-current])]:before:bg-kl-press\",\n  // the tick under the band gives up its outline, so the band reads as one solid mark at rest\n  \"[&[aria-current]]:before:border-transparent\",\n  \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-offset-(--kl-ring-in) focus-visible:outline-kl-focus focus-visible:outline-solid\",\n  \"forced-colors:[&:not([aria-current])]:before:border-[CanvasText]\",\n);\n/* one ink mark 16x8, centred on its 24px tick (the band is inset 4px from the tick's box, so the mark is the band's\n   full length) */\nconst band = cn(\n  \"pointer-events-none absolute -z-1\",\n  \"before:absolute before:inset-x-0 before:top-1/2 before:h-2 before:-translate-y-1/2 before:bg-kl-ink before:content-['']\",\n  \"forced-colors:before:bg-[Highlight] forced-colors:before:[forced-color-adjust:none]\",\n);\n\ntype CarouselState = { orientation: \"horizontal\" | \"vertical\" };\ntype CarouselPartState = Record<string, never>;\nconst PART_STATE: CarouselPartState = {};\n\ntype CarouselProps = Omit<PartProps<\"section\", CarouselState>, \"dir\"> & {\n  /** Names the region (\"Dock photos\"). Required: a carousel is a landmark-like region. */\n  \"aria-label\": string;\n  opts?: Opts;\n  plugins?: Plugins;\n  orientation?: \"horizontal\" | \"vertical\";\n  setApi?: (api: CarouselApi) => void;\n};\n\n/**\n * The frame. Slides sit side by side on 1px seams inside it; the control row (CarouselBar) is its foot.\n * Direction follows the page: in RTL the first slide is at the inline start and the arrows mirror.\n */\nfunction Carousel({\n  orientation = \"horizontal\",\n  opts,\n  plugins,\n  setApi,\n  render,\n  className,\n  style,\n  children,\n  ...props\n}: CarouselProps): React.ReactElement {\n  const ref = React.useRef<HTMLElement>(null);\n  // first guess from the page, so an RTL page does not initialise embla twice\n  const [rtl, setRtl] = React.useState(() => typeof document !== \"undefined\" && document.documentElement.dir === \"rtl\");\n  React.useLayoutEffect(() => {\n    if (ref.current) setRtl(domDir(ref.current) === \"rtl\");\n  }, []);\n  const [carouselRef, api] = useEmblaCarousel(\n    { inViewThreshold: 0.5, ...opts, axis: orientation === \"horizontal\" ? \"x\" : \"y\", direction: rtl ? \"rtl\" : \"ltr\" },\n    plugins,\n  );\n  const [s, setS] = React.useState({\n    canScrollPrev: false,\n    canScrollNext: false,\n    index: 0,\n    count: 0,\n    inView: [] as number[],\n  });\n  const [said, say] = React.useState(\"\");\n  const sync = React.useCallback((a: CarouselApi) => {\n    if (!a) return;\n    setS({\n      canScrollPrev: a.canScrollPrev(),\n      canScrollNext: a.canScrollNext(),\n      index: a.selectedScrollSnap(),\n      count: a.scrollSnapList().length,\n      inView: a.slidesInView(),\n    });\n  }, []);\n  React.useEffect(() => {\n    if (!api) return;\n    setApi?.(api);\n    sync(api);\n    // a move is announced once it settles (never on load: nothing moved): the first slide now in view\n    const onSettle = (a: CarouselApi) => {\n      if (!a) return;\n      const node = a.slideNodes()[Math.min(...a.slidesInView())];\n      say(node?.getAttribute(\"aria-label\") ?? \"\");\n    };\n    api.on(\"reInit\", sync).on(\"select\", sync).on(\"slidesInView\", sync).on(\"settle\", onSettle);\n    return () => {\n      api.off(\"reInit\", sync).off(\"select\", sync).off(\"slidesInView\", sync).off(\"settle\", onSettle);\n    };\n  }, [api, setApi, sync]);\n  const scrollPrev = React.useCallback(() => api?.scrollPrev(still(ref.current)), [api]);\n  const scrollNext = React.useCallback(() => api?.scrollNext(still(ref.current)), [api]);\n  // Arrow keys step only from the region itself, a slide, or the control row, in the bubble phase: anything inside a\n  // slide that owns its arrows (a radio group, a link list, a field) acts first, and focus is never on content that\n  // the step makes inert. (capturing on the whole region stole arrows from slide content and dropped focus\n  // to the page when the focused slide went inert.)\n  const onKeyDown = (e: React.KeyboardEvent<HTMLElement>) => {\n    const t = e.target as HTMLElement;\n    const own =\n      t === e.currentTarget || t.matches('[data-slot=\"carousel-item\"]') || !!t.closest('[data-slot=\"carousel-bar\"]');\n    if (\n      e.defaultPrevented ||\n      !own ||\n      t.closest(\"input, textarea, select, [contenteditable], [role=slider], [role=spinbutton]\")\n    )\n      return;\n    const [back, fwd] =\n      orientation === \"vertical\"\n        ? [\"ArrowUp\", \"ArrowDown\"]\n        : rtl\n          ? [\"ArrowRight\", \"ArrowLeft\"]\n          : [\"ArrowLeft\", \"ArrowRight\"];\n    if (e.key === back) {\n      e.preventDefault();\n      scrollPrev();\n    } else if (e.key === fwd) {\n      e.preventDefault();\n      scrollNext();\n    }\n  };\n  const state: CarouselState = { orientation };\n  const own = {\n    \"aria-roledescription\": \"carousel\",\n    \"data-slot\": \"carousel\",\n    \"data-orientation\": orientation,\n    className: resolveClassName(root, className)(state),\n    style: resolveStyle(undefined, style)(state),\n    children: (\n      <>\n        {children}\n        <span className=\"kl-sr\" aria-live=\"polite\" aria-atomic=\"true\">\n          {said ? `Slide ${said}` : \"\"}\n        </span>\n      </>\n    ),\n  };\n  const el = useRender({\n    defaultTagName: \"section\",\n    render,\n    ref,\n    state,\n    // mergeProps calls handlers right to left: the consumer's onKeyDown runs first, so it can preventDefault a step\n    props: mergeProps<\"section\">({ onKeyDown }, props, own),\n  });\n  return (\n    <CarouselContext.Provider value={{ carouselRef, api, orientation, scrollPrev, scrollNext, ...s }}>\n      {el}\n    </CarouselContext.Provider>\n  );\n}\n\n/**\n * The viewport, which clips the slides; the track inside it moves. `className`, `style` and `render` are the\n * viewport's; `trackClassName` styles the track.\n */\nfunction CarouselContent({\n  render,\n  className,\n  style,\n  trackClassName,\n  children,\n  ...props\n}: PartProps<\"div\", CarouselPartState> & { trackClassName?: string }): React.ReactElement {\n  const { carouselRef, orientation } = useCarousel();\n  const own = {\n    \"data-slot\": \"carousel-content\",\n    className: resolveClassName(viewport, className)(PART_STATE),\n    style: resolveStyle(undefined, style)(PART_STATE),\n    children: (\n      <div\n        data-slot=\"carousel-track\"\n        data-orientation={orientation}\n        className={cn(orientation === \"vertical\" ? trackVertical : track, trackClassName)}\n      >\n        {children}\n      </div>\n    ),\n  };\n  return useRender({\n    defaultTagName: \"div\",\n    render,\n    ref: carouselRef,\n    state: PART_STATE,\n    props: mergeProps<\"div\">(props, own),\n  });\n}\n\n/**\n * One slide: a group named \"n of N\". `basis` is the share of the viewport it takes (\"50%\" shows two).\n * Slides out of view are inert.\n */\nfunction CarouselItem({\n  render,\n  className,\n  style,\n  basis,\n  ...props\n}: PartProps<\"div\", CarouselPartState> & { basis?: string }): React.ReactElement {\n  const { inView, api } = useCarousel();\n  const ref = React.useRef<HTMLDivElement>(null);\n  const nodes = api?.slideNodes() ?? [];\n  const index = ref.current ? nodes.indexOf(ref.current) : -1;\n  const total = nodes.length;\n  const hidden = index >= 0 && !inView.includes(index);\n  const own = {\n    role: \"group\",\n    \"aria-roledescription\": \"slide\",\n    \"aria-label\": index >= 0 ? `${index + 1} of ${total}` : undefined,\n    \"data-slot\": \"carousel-item\",\n    \"data-in-view\": hidden ? undefined : \"\",\n    inert: hidden || undefined,\n    className: resolveClassName(slide, className)(PART_STATE),\n    style: resolveStyle(basis ? { flexBasis: basis } : undefined, style)(PART_STATE),\n  };\n  return useRender({ defaultTagName: \"div\", render, ref, state: PART_STATE, props: mergeProps<\"div\">(props, own) });\n}\n\n/* in RTL the arrows mirror; vertical, they turn a quarter (and no longer mirror) */\nfunction Chevron({ back }: { back?: boolean }) {\n  const { orientation } = useCarousel();\n  const turn =\n    orientation === \"vertical\"\n      ? back\n        ? \"[transform:rotate(-90deg)]\"\n        : \"[transform:rotate(90deg)]\"\n      : back\n        ? \"[transform:scaleX(-1)] kl-rtl:[transform:none]\"\n        : \"kl-rtl:[transform:scaleX(-1)]\";\n  return (\n    <svg\n      data-slot=\"carousel-chevron\"\n      className={cn(\"block\", turn)}\n      viewBox=\"0 0 16 16\"\n      width=\"16\"\n      height=\"16\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.75\"\n      strokeLinecap=\"square\"\n      aria-hidden\n    >\n      <path d=\"M6 3l5 5-5 5\" />\n    </svg>\n  );\n}\n\n/** Previous / next: cells of the control row, rendered by Button. At an end they stay focusable and say why they do\n *  nothing. */\nfunction CarouselPrevious({ className, children, ...props }: React.ComponentProps<typeof Button>) {\n  const { scrollPrev, canScrollPrev, orientation } = useCarousel();\n  return (\n    <Button\n      layout=\"cell\"\n      size=\"icon\"\n      aria-label=\"Previous slide\"\n      disabled={!canScrollPrev}\n      focusableWhenDisabled\n      data-orientation={orientation}\n      className={resolveClassName(\"flex-none\", className)}\n      onClick={scrollPrev}\n      {...props}\n    >\n      {children ?? <Chevron back />}\n    </Button>\n  );\n}\n\nfunction CarouselNext({ className, children, ...props }: React.ComponentProps<typeof Button>) {\n  const { scrollNext, canScrollNext, orientation } = useCarousel();\n  return (\n    <Button\n      layout=\"cell\"\n      size=\"icon\"\n      aria-label=\"Next slide\"\n      disabled={!canScrollNext}\n      focusableWhenDisabled\n      data-orientation={orientation}\n      className={resolveClassName(\"flex-none\", className)}\n      onClick={scrollNext}\n      {...props}\n    >\n      {children ?? <Chevron />}\n    </Button>\n  );\n}\n\n/**\n * Where you are: \"2 / 5\" in the Code voice and a row of position ticks you can press. The current position is one\n * ink band that STRETCHES between ticks: its leading edge reaches the new tick first and the trailing edge\n * follows, so a step or a jump shows its direction and distance, the way the slides travel. Zero bounce; reduced\n * motion places it at once. With many slides (12 or more) the ticks give way to the count alone.\n */\nfunction CarouselPosition({\n  render,\n  className,\n  style,\n  ...props\n}: PartProps<\"div\", CarouselPartState>): React.ReactElement {\n  const { index, count, api } = useCarousel();\n  const ticks = React.useRef<HTMLSpanElement>(null);\n  // inset 4: the band is the 16x8 mark itself (its ::before spans it), so a move clips it exactly at both ends\n  useStretch(ticks, count ? index : -1, { press: false, inset: 4 });\n  const own = {\n    \"data-slot\": \"carousel-position\",\n    className: resolveClassName(\"kl-cell\", className)(PART_STATE),\n    style: resolveStyle(undefined, style)(PART_STATE),\n    children: (\n      <>\n        <span\n          data-slot=\"carousel-count\"\n          className=\"kl-code min-w-[4.5ch] text-center text-kl-ink-2\"\n          dir=\"ltr\"\n          aria-hidden\n        >\n          {count ? index + 1 : 0} / {count}\n        </span>\n        <span\n          ref={ticks}\n          data-kl-stretch=\"\"\n          data-slot=\"carousel-ticks\"\n          className={cn(\"relative isolate flex items-center\", count >= 12 && \"hidden\")}\n        >\n          <span data-kl-band=\"\" className={band} aria-hidden hidden />\n          {Array.from({ length: count }, (_, i) => (\n            <button\n              key={i}\n              data-kl-item=\"\"\n              data-slot=\"carousel-tick\"\n              type=\"button\"\n              className={tick}\n              aria-label={`Go to ${i + 1} of ${count}`}\n              aria-current={i === index ? \"true\" : undefined}\n              onClick={(e) => api?.scrollTo(i, still(e.currentTarget))}\n            />\n          ))}\n        </span>\n      </>\n    ),\n  };\n  return useRender({ defaultTagName: \"div\", render, state: PART_STATE, props: mergeProps<\"div\">(props, own) });\n}\n\n/** The control row: previous, position, next. Compose your own from the same parts if needed. */\nfunction CarouselBar({\n  render,\n  className,\n  style,\n  children,\n  ...props\n}: PartProps<\"div\", CarouselPartState>): React.ReactElement {\n  const own = {\n    \"data-slot\": \"carousel-bar\",\n    className: resolveClassName(bar, className)(PART_STATE),\n    style: resolveStyle(undefined, style)(PART_STATE),\n    children: children ?? (\n      <>\n        <CarouselPrevious />\n        <CarouselPosition />\n        <CarouselNext />\n      </>\n    ),\n  };\n  return useRender({ defaultTagName: \"div\", render, state: PART_STATE, props: mergeProps<\"div\">(props, own) });\n}\n\nexport {\n  Carousel,\n  CarouselContent,\n  CarouselItem,\n  CarouselPrevious,\n  CarouselNext,\n  CarouselPosition,\n  CarouselBar,\n  useCarousel,\n  type CarouselApi,\n};\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/carousel.tsx"
    }
  ],
  "type": "registry:ui"
}