{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "segmented-input",
  "title": "Segmented input",
  "description": "How ui-sdk's date and time segments are drawn: one highlight glides between the segments and each number rolls to its new value. Date input and Time input draw it.",
  "dependencies": [
    "@ui-sdk/react"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/dates.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/roll.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/segmented-input.tsx",
      "content": "'use client'\n\nimport { InputInvalidIcon, inputBoxClassName } from '@/registry/components/kino/input'\nimport { dayPeriodNames } from '@/registry/lib/dates'\nimport { followFocus, highlightClassName } from '@/registry/lib/highlight'\nimport { Roll } from '@/registry/lib/roll'\nimport { revealInRow } from '@/registry/lib/scroll'\nimport type { DateInputSegment, DateInputSegmentData } from '@ui-sdk/react/date-input'\nimport { type ComponentProps, type ReactNode, useEffect, useRef, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * How the Date input and the Time input draw ui-sdk's segments: one\n * highlight marks the segment you are in and glides to the next, and each\n * number rolls up or down to its new value, however it changed. ui-sdk\n * holds the segments, the keys and the value; this is only their look.\n */\n\n/** ui-sdk's segment part: the Date input's or the Time input's. */\ntype SegmentPart = (props: ComponentProps<typeof DateInputSegment>) => ReactNode\n\nconst segmentClassName =\n  'relative inline-grid h-(--control-height-xs) min-w-6 place-items-center px-(--segment-padding,0.375rem) tabular-nums'\n\n/** What a segment can show at its widest, so typing never moves what follows. */\nfunction segmentSizes(segment: DateInputSegmentData, locale: string): string[] {\n  if (segment.type === 'dayPeriod') return dayPeriodNames(locale)\n  return ['0'.repeat(String(segment.max).length)]\n}\n\ntype Trend = 1 | -1\n\n/**\n * Which way each segment's number rolls after a change; a segment that\n * didn't change keeps its last way. Several that change together roll the\n * way the whole value went (`whole`), as an odometer's wheels do: 11:45 to\n * 12:00 rolls the minutes up too. One stepped by a key rolls the key's way\n * (`step`), past its end too: 23 up to 00 rolls up. Otherwise a number rolls\n * up as it rises and down as it falls, with an empty segment counted as 0.\n */\nfunction segmentTrends(\n  from: Record<string, number | null>,\n  to: Record<string, number | null>,\n  last: Record<string, Trend>,\n  { whole, step }: { whole: Trend | null; step: Trend | null },\n): Record<string, Trend> {\n  const changed = Object.keys(to).filter((key) => (from[key] ?? null) !== to[key])\n  const trends = { ...last }\n  for (const key of changed) {\n    const own: Trend = (to[key] ?? 0) >= (from[key] ?? 0) ? 1 : -1\n    trends[key] =\n      changed.length > 1 ? (whole ?? own) : changed.length === 1 ? (step ?? own) : own\n  }\n  return trends\n}\n\n/** Which way a whole value went: later is 1. ISO dates and times sort as text in the order of time. */\nfunction valueTrend(from: string | null, to: string | null): Trend | null {\n  if (from === null || to === null || from === to) return null\n  return to > from ? 1 : -1\n}\n\nconst LATIN_LETTER: Record<string, string> = { day: 'd', month: 'm', year: 'y' }\n\n/**\n * What an empty segment shows: a date's segment repeats the first letter of\n * its name in the locale, lower case (tt.mm.jjjj in German), or the Latin\n * letter in a script without capitals; a time's segment shows dashes.\n */\nfunction segmentPlaceholder(type: string, locale: string): string {\n  const latin = LATIN_LETTER[type]\n  if (!latin) return '––'\n  let letter = latin\n  try {\n    const name = new Intl.DisplayNames(locale, { type: 'dateTimeField' }).of(type)\n    const code = name?.codePointAt(0)\n    const first = code === undefined ? undefined : String.fromCodePoint(code)\n    if (first && first.toLocaleUpperCase(locale) !== first.toLocaleLowerCase(locale)) {\n      letter = first.toLocaleLowerCase(locale)\n    }\n  } catch {\n    // An engine without dateTimeField names keeps the Latin letters.\n  }\n  return letter.repeat(type === 'year' ? 4 : 2)\n}\n\n/** A segment's face: its placeholder until it holds a number, which rolls in. */\nfunction SegmentFace({\n  segment,\n  locale,\n  trend,\n  placeholderClassName,\n}: {\n  segment: DateInputSegmentData\n  locale: string\n  trend: Trend\n  placeholderClassName: string\n}) {\n  const placeholder = segmentPlaceholder(segment.type, locale)\n  return (\n    <>\n      {/* Its characters stand apart, split as the roll splits them into columns, so a name's width matches theirs without kerning. */}\n      {[...segmentSizes(segment, locale), placeholder].map((size) => (\n        <span key={size} aria-hidden className='invisible col-start-1 row-start-1 flex'>\n          {size.split('').map((char, index) => (\n            // oxlint-disable-next-line react/no-array-index-key -- a name's characters keep their places.\n            <span key={index}>{char}</span>\n          ))}\n        </span>\n      ))}\n      <span\n        aria-hidden\n        className={cn(\n          'absolute inset-0 flex items-center justify-center whitespace-nowrap',\n          placeholderClassName,\n          // Gone before the first digit has rolled in; back once the number has mostly rolled away.\n          segment.text\n            ? 'opacity-0 transition-opacity duration-[calc(var(--motion-exit-duration)*0.4)] ease-(--motion-exit-easing)'\n            : 'transition-opacity delay-[calc(var(--motion-exit-duration)*0.8)] duration-(--motion-enter-duration) ease-(--motion-enter-easing)',\n        )}\n      >\n        {placeholder}\n      </span>\n      <Roll\n        value={segment.text}\n        trend={trend}\n        typed\n        className='col-start-1 row-start-1'\n      />\n    </>\n  )\n}\n\n/** Which way `locale`'s text runs: `rtl` for Hebrew and Arabic. */\nfunction localeDirection(locale: string): 'ltr' | 'rtl' {\n  try {\n    const info = new Intl.Locale(locale) as Intl.Locale & {\n      getTextInfo?: () => { direction?: string }\n      textInfo?: { direction?: string }\n    }\n    return (info.getTextInfo?.() ?? info.textInfo)?.direction === 'rtl' ? 'rtl' : 'ltr'\n  } catch {\n    return 'ltr'\n  }\n}\n\n/**\n * The segments in the order the row shows them, left to right. A\n * right-to-left language writes AM or PM after the time, which shows on its\n * left (م ٢:٣٠ in Arabic), so it and the space before it come first: the\n * arrow keys and Tab then move the way the row reads on screen.\n */\nfunction segmentsOnScreen<Segment extends { type: string }>(\n  segments: readonly Segment[],\n  rtl: boolean,\n): Segment[] {\n  const last = segments.at(-1)\n  if (!rtl || last?.type !== 'dayPeriod') return [...segments]\n  const gap = segments.at(-2)?.type === 'literal' ? 1 : 0\n  const time = segments.slice(0, segments.length - 1 - gap)\n  return [last, ...segments.slice(time.length, segments.length - 1), ...time]\n}\n\nconst STEP_KEYS: Record<string, Trend> = {\n  ArrowUp: 1,\n  PageUp: 1,\n  ArrowDown: -1,\n  PageDown: -1,\n}\n\n/**\n * A field's segments in a row with one highlight, which glides from segment\n * to segment. `compact` segments are tighter, and a row too long for its box\n * scrolls, with its edges fading, and focus brings each segment into view,\n * as text does in a text field.\n */\nfunction SegmentRow({\n  segments,\n  Segment,\n  value,\n  locale,\n  compact,\n}: {\n  segments: DateInputSegmentData[]\n  Segment: SegmentPart\n  /** The whole value, as ui-sdk's state holds it. */\n  value: string | null\n  locale: string\n  compact?: boolean\n}) {\n  const numbers = Object.fromEntries(\n    segments.map((segment) => [segment.key, segment.value]),\n  )\n  // The last step key pressed, which a change in the same press reads; any other key clears it.\n  const [step, setStep] = useState<Trend | null>(null)\n  const [seen, setSeen] = useState({\n    numbers,\n    value,\n    trends: {} as Record<string, Trend>,\n  })\n  let trends = seen.trends\n  if (segments.some((segment) => seen.numbers[segment.key] !== segment.value)) {\n    trends = segmentTrends(seen.numbers, numbers, seen.trends, {\n      whole: valueTrend(seen.value, value),\n      step,\n    })\n    setSeen({ numbers, value, trends })\n    if (step !== null) setStep(null)\n  } else if (seen.value !== value) setSeen({ ...seen, value })\n  const trendOf = (segment: DateInputSegmentData) => trends[segment.key] ?? 1\n  const shown = segmentsOnScreen(segments, localeDirection(locale) === 'rtl')\n  const onKeyDownCapture = (event: { key: string }) =>\n    setStep(STEP_KEYS[event.key] ?? null)\n\n  const scrollerRef = useRef<HTMLDivElement>(null)\n  const rowRef = useRef<HTMLDivElement>(null)\n  const layerRef = useRef<HTMLSpanElement>(null)\n\n  useEffect(() => {\n    const scroller = scrollerRef.current\n    if (!scroller || !compact) return\n    return revealInRow(scroller, { item: '[data-segment]', fade: '--segment-row-fade' })\n  }, [compact])\n\n  useEffect(() => {\n    const row = rowRef.current\n    if (!row || !layerRef.current) return\n    return followFocus(row, layerRef.current, (node) => {\n      const segment =\n        node instanceof Element ? node.closest<HTMLElement>('[data-segment]') : null\n      return segment && row.contains(segment) ? segment : null\n    })\n  }, [])\n\n  const content = (\n    <>\n      {shown.map((segment) =>\n        segment.editable ? (\n          <span\n            key={segment.key}\n            data-segment={segment.type}\n            className={cn(\n              segmentClassName,\n              'rounded-(--control-radius-xs) has-[input:read-only]:text-muted-foreground',\n            )}\n          >\n            <SegmentFace\n              segment={segment}\n              locale={locale}\n              trend={trendOf(segment)}\n              placeholderClassName='text-muted-foreground'\n            />\n            <Segment\n              segment={segment}\n              className='absolute inset-0 size-full cursor-text rounded-[inherit] bg-transparent text-center text-transparent forced-color-adjust-none caret-transparent selection:bg-transparent placeholder:text-transparent focus-visible:outline-hidden'\n            />\n          </span>\n        ) : (\n          // Pre, so a separator's space (the one after the comma in 27/11/2026, 14:30) keeps its width.\n          <Segment\n            key={segment.key}\n            segment={segment}\n            className='whitespace-pre text-muted-foreground'\n          />\n        ),\n      )}\n      {/* The highlight carries a copy of the row in its own colours, so what it covers reads at full contrast as it glides. */}\n      <span\n        ref={layerRef}\n        aria-hidden\n        data-segment-highlight=''\n        className={cn(\n          highlightClassName,\n          'flex items-center bg-primary text-primary-foreground forced-color-adjust-none forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]',\n        )}\n      >\n        {shown.map((segment) =>\n          segment.editable ? (\n            <span key={segment.key} className={segmentClassName}>\n              <SegmentFace\n                segment={segment}\n                locale={locale}\n                trend={trendOf(segment)}\n                placeholderClassName='text-primary-foreground forced-colors:text-[HighlightText]'\n              />\n            </span>\n          ) : (\n            <span\n              key={segment.key}\n              className={cn(\n                'whitespace-pre text-primary-foreground forced-colors:text-[HighlightText]',\n              )}\n            >\n              {segment.text}\n            </span>\n          ),\n        )}\n      </span>\n    </>\n  )\n\n  // Digits and their separators read left to right in every language.\n  return compact ? (\n    // The row inside the scroller is as wide as its segments, so the highlight's copy spans all of them, not just what shows.\n    <div\n      ref={scrollerRef}\n      dir='ltr'\n      className='scrollbar-none flex min-w-0 overflow-x-auto [--segment-padding:0.25rem] [mask-image:linear-gradient(to_right,transparent,black_var(--segment-row-fade-left,0px),black_calc(100%-var(--segment-row-fade-right,0px)),transparent)]'\n    >\n      <div\n        ref={rowRef}\n        onKeyDownCapture={onKeyDownCapture}\n        className='relative flex w-max shrink-0 items-center'\n      >\n        {content}\n      </div>\n    </div>\n  ) : (\n    <div\n      ref={rowRef}\n      dir='ltr'\n      onKeyDownCapture={onKeyDownCapture}\n      className='relative flex min-w-0 items-center'\n    >\n      {content}\n    </div>\n  )\n}\n\n/** The segments' own padding makes up the rest of the control's, so their digits line up with other fields' text. */\nconst segmentRowPadding = 'ps-[calc(var(--control-padding)-0.375rem)]'\n\n/**\n * The box ui-sdk's segmented root is drawn as: what its `className` takes,\n * with its row inside and the invalid mark at its end. ui-sdk puts focus in\n * the nearest segment on a press outside them.\n */\nconst segmentedBoxClassName = cn(\n  inputBoxClassName,\n  'h-(--control-height) cursor-text text-base md:text-sm',\n  // The box is the control a Field marks invalid, so it reads its own state as well as its segments'.\n  'aria-invalid:border-destructive aria-invalid:has-focus-visible:border-destructive aria-invalid:has-focus-visible:ring-destructive/20 forced-colors:aria-invalid:outline-2 forced-colors:aria-invalid:outline-offset-1 forced-colors:aria-invalid:outline-dashed dark:aria-invalid:border-destructive/70 dark:aria-invalid:has-focus-visible:ring-destructive/40',\n  segmentRowPadding,\n)\n\n/** What goes inside the root: the row, then the invalid mark. */\nfunction SegmentedBody(props: ComponentProps<typeof SegmentRow>) {\n  return (\n    <>\n      <SegmentRow {...props} />\n      <InputInvalidIcon className='ms-auto' />\n    </>\n  )\n}\n\nexport {\n  segmentedBoxClassName,\n  SegmentedBody,\n  segmentsOnScreen,\n  segmentPlaceholder,\n  segmentTrends,\n  valueTrend,\n}\n",
      "type": "registry:lib",
      "target": "@lib/segmented-input.tsx"
    }
  ],
  "type": "registry:lib"
}