{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-page",
  "title": "Settings page",
  "description": "An app's settings: the sections in a list beside the page, every one in one form, so a change anywhere raises the Save bar and Save sends them all, and moving between sections keeps what was typed. A profile photo cropped in a dialog, notifications by channel whose rows fold away when it's off, and a danger zone of Confirm buttons.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/avatar.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/card.json",
    "https://kinoui.com/r/collapsible.json",
    "https://kinoui.com/r/confirm-button.json",
    "https://kinoui.com/r/dialog.json",
    "https://kinoui.com/r/field.json",
    "https://kinoui.com/r/file-input.json",
    "https://kinoui.com/r/image-cropper.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/item.json",
    "https://kinoui.com/r/label.json",
    "https://kinoui.com/r/preferences.json",
    "https://kinoui.com/r/save-bar.json",
    "https://kinoui.com/r/segmented-control.json",
    "https://kinoui.com/r/select.json",
    "https://kinoui.com/r/switch.json",
    "https://kinoui.com/r/tabs.json",
    "https://kinoui.com/r/theme-switcher.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/settings-page/settings-page.tsx",
      "content": "'use client'\n\nimport {\n  Card,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from '@/registry/components/kino/card'\nimport {\n  Field,\n  FieldDescription,\n  FieldError,\n  FieldLabel,\n  Form,\n  useFormSubmission,\n} from '@/registry/components/kino/field'\nimport {\n  Item,\n  ItemActions,\n  ItemContent,\n  ItemDescription,\n  ItemTitle,\n} from '@/registry/components/kino/item'\nimport { labelClassName } from '@/registry/components/kino/label'\nimport { SaveBar } from '@/registry/components/kino/save-bar'\nimport { SettingsChannel } from '@/registry/components/kino/settings-page/settings-channel'\nimport {\n  SettingsPhoto,\n  type SettingsPhotoValue,\n} from '@/registry/components/kino/settings-page/settings-photo'\nimport { Tabs, TabsPanel, TabsList, TabsTab } from '@/registry/components/kino/tabs'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { revealBehavior, scrollerOf } from '@/registry/lib/scroll'\nimport {\n  Children,\n  cloneElement,\n  type ComponentProps,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  use,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * An app's settings: the sections in a list beside the page, and the page\n * of the one picked; across the top of the page in a column too narrow for\n * both. The whole page is one Kino Form, so a change in any section raises\n * the Save bar, Save sends every section at once, and moving to another\n * section keeps what was typed. A field turned down in a section out of\n * sight, by the form's checks or by the save, brings its section back.\n *\n *   <SettingsPage onSave={save}>\n *     <SettingsNav>\n *       <SettingsNavItem value='profile' icon={<UserIcon />}>Profile</SettingsNavItem>\n *     </SettingsNav>\n *     <SettingsSection value='profile' title='Profile'>\n *       <SettingsGroup title='Your details'>\n *         <SettingsRow name='name' label='Name'><Input defaultValue={me.name} /></SettingsRow>\n *       </SettingsGroup>\n *     </SettingsSection>\n *   </SettingsPage>\n */\n\ninterface SettingsPageContextValue {\n  /** Whether the list sits beside the page, rather than across its top. */\n  beside: boolean\n  /** Whether `beside` has been read from the page's width, which the server can't do. */\n  measured: boolean\n  /** The page title's level: sections take the next, groups the one after. */\n  level: 1 | 2\n}\n\nconst SettingsPageContext = createContext<SettingsPageContextValue | null>(null)\n\nfunction useSettingsPage(part: string) {\n  const context = use(SettingsPageContext)\n  if (!context) throw new Error(`${part} goes inside a SettingsPage.`)\n  return context\n}\n\n/** How wide the page's column must be for the list to sit beside the sections, in px: 48rem, Tailwind's `@3xl`. */\nconst BESIDE_WIDTH = 768\n\n/** Whether a page `width` px wide has room for the list beside the sections. */\nfunction fitsBeside(width: number) {\n  return width >= BESIDE_WIDTH\n}\n\n/**\n * The page's own width, read before it paints: the list sits beside the\n * sections only when both fit. The server can't know it, so until it's\n * `measured` a narrow page shows no list rather than one that doesn't fit.\n */\nfunction useBeside(root: { current: HTMLElement | null }) {\n  const [beside, setBeside] = useState<boolean | null>(null)\n  useLayoutEffect(() => {\n    const element = root.current\n    if (!element) return undefined\n    const measure = () => setBeside(fitsBeside(element.offsetWidth))\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [root])\n  return { beside: beside ?? true, measured: beside !== null }\n}\n\n/** The top of `scroller`'s view, inside its border, in the viewport's pixels: the window's is 0. */\nfunction viewTop(scroller: HTMLElement | null) {\n  return scroller ? scroller.getBoundingClientRect().top + scroller.clientTop : 0\n}\n\n/**\n * How far to scroll so an element whose top is at `top` sits `margin` below\n * the view's top at `view`, both in the viewport's pixels: nothing while its\n * top is still in view, and a negative distance, up, once the page has\n * scrolled past it. `room` is how far the page could still be scrolled down\n * after the change, which may be less than now, as when a shorter section\n * shows: it never scrolls to where the page can't rest.\n */\nfunction scrollToTopBy(top: number, view: number, margin: number, room = 0) {\n  return top >= view ? 0 : Math.min(top - margin - view, room)\n}\n\n/**\n * Holds `element` at its height while the section in it changes, so the\n * page doesn't shorten under a scroll. Returns the function that lets go.\n */\nfunction holdHeight(element: HTMLElement) {\n  element.style.minHeight = `${element.offsetHeight}px`\n  return () => {\n    element.style.minHeight = ''\n  }\n}\n\n/**\n * Scrolls `element`'s top, less its scroll margin, up to the top of the box\n * that scrolls it when the page has scrolled past it, so a section picked\n * from far down its neighbour opens at its heading. `release` lets go of\n * the height held through the switch, once the scroll ends. Only that box\n * scrolls, never the ones around it, as `scrollIntoView` would.\n */\nfunction bringIntoView(element: HTMLElement, release: () => void) {\n  const box = scrollerOf(element)\n  const page = box ?? document.scrollingElement ?? document.documentElement\n  // How far the page will scroll once the held height goes: what it can\n  // now, less what the held height adds under the new section.\n  const { top, bottom } = element.getBoundingClientRect()\n  const content = Math.max(\n    top,\n    ...[...element.children].map((child) => child.getBoundingClientRect().bottom),\n  )\n  const room = page.scrollHeight - page.clientHeight - page.scrollTop - (bottom - content)\n  const margin = Number.parseFloat(getComputedStyle(element).scrollMarginTop) || 0\n  const by = scrollToTopBy(top, viewTop(box), margin, room)\n  if (by === 0) {\n    release()\n    return\n  }\n  // Held until the glide ends, so the browser never cuts it short.\n  const target = box ?? window\n  const done = () => {\n    clearTimeout(timer)\n    target.removeEventListener('scrollend', done)\n    release()\n  }\n  // A scroll the browser can't make never ends.\n  const timer = setTimeout(done, 1000)\n  target.addEventListener('scrollend', done)\n  target.scrollBy({ top: by, behavior: revealBehavior(element) })\n}\n\n/** The first field the last submit turned down, and the section it sits in. */\nfunction firstInvalid(form: HTMLFormElement) {\n  // A Field's root comes before its control, so the first match is the field.\n  const field = form.querySelector<HTMLElement>('[data-invalid]')\n  const section = field?.closest<HTMLElement>('[data-settings-section]')\n  return field && section?.dataset.value\n    ? { field, section: section.dataset.value }\n    : null\n}\n\n/** The control in `field` a person types in or presses, for focus. */\nfunction controlIn(field: HTMLElement) {\n  return field.querySelector<HTMLElement>(\n    'input:not([type=hidden]):not([aria-hidden=true]), textarea, button, [role=combobox], [tabindex=\"0\"]',\n  )\n}\n\n/**\n * The settings screen: its title, the list of sections and the section\n * picked, in one form with a Save bar. It fills the height its parent gives\n * it, and the list stays in view as the page scrolls.\n */\nfunction SettingsPage({\n  title = 'Settings',\n  description,\n  heading = 'h1',\n  section,\n  defaultSection,\n  onSectionChange,\n  onSave,\n  onDiscard,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<'div'>, 'title' | 'children'> & {\n  title?: ReactNode\n  description?: ReactNode\n  /** The title's level: the page's `h1` on a page of its own, lower inside a dialog. Sections and groups take the levels under it. */\n  heading?: 'h1' | 'h2'\n  /** The section shown, when you hold it, such as from the address. */\n  section?: string\n  /** The section it opens on: the first when left out. */\n  defaultSection?: string\n  onSectionChange?: (section: string) => void\n  /** Saves the form's values, by field name. A promise keeps the Save bar saving until it settles; a throw or a rejection says it failed; errors by field, such as `{ email: '…' }`, show on those fields. */\n  onSave?: (values: Record<string, unknown>) => unknown\n  /** Runs after Discard has put every field back, for state the form doesn't hold. */\n  onDiscard?: () => void\n  /** A SettingsNav, then the SettingsSections. */\n  children: ReactNode\n}) {\n  const parts = Children.toArray(children)\n  const nav = parts.filter((part) => isValidElement(part) && part.type === SettingsNav)\n  const sections = parts.filter((part) => !nav.includes(part))\n  const first = sections.find(\n    (part): part is ReactElement<{ value: string }> =>\n      isValidElement<{ value?: unknown }>(part) && typeof part.props.value === 'string',\n  )?.props.value\n  const [current, setCurrent] = useControllable(\n    section,\n    defaultSection ?? first ?? '',\n    onSectionChange,\n  )\n  const root = useRef<HTMLDivElement>(null)\n  const formRef = useRef<HTMLFormElement>(null)\n  const tabsRef = useRef<HTMLDivElement>(null)\n  const { beside, measured } = useBeside(root)\n  // Lets go of the height held through a section switch, once the new section is in.\n  const switching = useRef<(() => void) | null>(null)\n  useLayoutEffect(() => {\n    const release = switching.current\n    const tabs = tabsRef.current\n    switching.current = null\n    if (release && tabs) bringIntoView(tabs, release)\n  }, [current])\n\n  // A field turned down in a section out of sight brings its section into\n  // view, and takes focus there: the form couldn't focus it while it hid.\n  const pending = useRef<HTMLElement | null>(null)\n  const setCurrentRef = useRef(setCurrent)\n  useEffect(() => {\n    setCurrentRef.current = setCurrent\n  })\n  const revealInvalid = () => {\n    const form = formRef.current\n    const invalid = form ? firstInvalid(form) : null\n    if (!invalid) return\n    const panel = invalid.field.closest<HTMLElement>('[data-settings-section]')\n    if (!panel?.hidden) return\n    pending.current = invalid.field\n    setCurrentRef.current(invalid.section)\n  }\n  useEffect(() => {\n    const field = pending.current\n    if (!field) return\n    pending.current = null\n    controlIn(field)?.focus()\n  }, [current])\n\n  const Heading = heading\n  return (\n    <SettingsPageContext value={{ beside, measured, level: heading === 'h1' ? 1 : 2 }}>\n      <div\n        ref={root}\n        data-slot='settings-page'\n        className={cn('@container min-h-full min-w-0', className)}\n        {...props}\n      >\n        <Form\n          ref={formRef}\n          aria-label={typeof title === 'string' ? title : 'Settings'}\n          onFormSubmit={onSave}\n          className='flex min-w-0 flex-col gap-(--surface-padding-lg)'\n        >\n          <div className='flex min-w-0 flex-col gap-1'>\n            <Heading className='text-2xl font-medium tracking-tight'>{title}</Heading>\n            {description ? (\n              <p className='text-muted-foreground text-sm'>{description}</p>\n            ) : null}\n          </div>\n          <Tabs\n            ref={tabsRef}\n            value={current}\n            onValueChange={(value) => {\n              // The page keeps its height until the new section is in, then scrolls to its heading.\n              const tabs = tabsRef.current\n              if (tabs) switching.current = holdHeight(tabs)\n              setCurrent(String(value))\n            }}\n            orientation={beside ? 'vertical' : 'horizontal'}\n            className={cn(\n              'scroll-mt-(--settings-page-top,1.5rem)',\n              beside ? 'items-start gap-10' : 'gap-(--surface-padding-lg)',\n            )}\n          >\n            {nav}\n            {sections}\n          </Tabs>\n          <RevealInvalid onInvalid={revealInvalid} />\n          <SaveBar onDiscard={onDiscard} />\n        </Form>\n      </div>\n    </SettingsPageContext>\n  )\n}\n\n/**\n * Calls `onInvalid` a frame after the form is sent, once its checks have\n * run, and again when a save comes back with errors by field, which land\n * on fields that may be out of sight.\n */\nfunction RevealInvalid({ onInvalid }: { onInvalid: () => void }) {\n  const latest = useRef(onInvalid)\n  useEffect(() => {\n    latest.current = onInvalid\n  })\n  const marker = useRef<HTMLSpanElement>(null)\n  useEffect(() => {\n    const form = marker.current?.closest('form')\n    if (!form) return undefined\n    let frame = 0\n    const onSubmit = () => {\n      cancelAnimationFrame(frame)\n      frame = requestAnimationFrame(() => latest.current())\n    }\n    form.addEventListener('submit', onSubmit, true)\n    return () => {\n      cancelAnimationFrame(frame)\n      form.removeEventListener('submit', onSubmit, true)\n    }\n  }, [])\n  const status = useFormSubmission()?.status\n  const last = useRef(status)\n  useEffect(() => {\n    const was = last.current\n    last.current = status\n    if (was !== 'saving' || status === 'saving') return undefined\n    const frame = requestAnimationFrame(() => latest.current())\n    return () => cancelAnimationFrame(frame)\n  }, [status])\n  return <span ref={marker} hidden />\n}\n\n/** The list of sections: beside the page, or across its top in a narrow column. */\nfunction SettingsNav({\n  className,\n  children,\n  'aria-label': label = 'Sections',\n  ...props\n}: Omit<ComponentProps<typeof TabsList>, 'children' | 'variant'> & {\n  /** SettingsNavItems, one for each section, in the same order. */\n  children: ReactNode\n}) {\n  const { beside, measured } = useSettingsPage('SettingsNav')\n  return (\n    <TabsList\n      data-settings-nav=''\n      aria-label={label}\n      {...props}\n      className={cn(\n        beside && 'sticky top-(--settings-page-top,1.5rem) w-52 shrink-0',\n        // Until the page's width is read, a narrow page shows no list rather than one beside it that doesn't fit.\n        !measured && '@max-3xl:hidden',\n        className,\n      )}\n    >\n      {children}\n    </TabsList>\n  )\n}\n\n/** A section's tab. */\nfunction SettingsNavItem({\n  value,\n  icon,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof TabsTab>, 'value'> & {\n  /** The section's `value`. */\n  value: string\n  /** Before the label, sized by the item. */\n  icon?: ReactNode\n}) {\n  return (\n    <TabsTab value={value} {...props}>\n      {icon}\n      {children}\n    </TabsTab>\n  )\n}\n\n/** One section: its heading, and the groups under it, shown while it's picked. */\nfunction SettingsSection({\n  value,\n  title,\n  description,\n  className,\n  children,\n  ...props\n}: Omit<\n  ComponentProps<typeof TabsPanel>,\n  'value' | 'title' | 'keepMounted' | 'children'\n> & {\n  children?: ReactNode\n  /** Names the section for its SettingsNavItem, `section` and `onSectionChange`. */\n  value: string\n  title: string\n  description?: ReactNode\n}) {\n  const { level } = useSettingsPage('SettingsSection')\n  const Heading = level === 1 ? 'h2' : 'h3'\n  return (\n    <TabsPanel\n      value={value}\n      // Every section stays in the form while another shows, so its changes wait for Save.\n      keepMounted\n      data-settings-section=''\n      data-value={value}\n      {...props}\n      className={cn(\n        'flex w-full max-w-2xl min-w-0 flex-col gap-(--surface-padding-lg) rounded-(--surface-radius)',\n        className,\n      )}\n    >\n      <div className='flex min-w-0 flex-col gap-1'>\n        <Heading className='text-lg font-medium tracking-tight'>{title}</Heading>\n        {description ? (\n          <p className='text-muted-foreground text-sm'>{description}</p>\n        ) : null}\n      </div>\n      {children}\n    </TabsPanel>\n  )\n}\n\n/** A card of related settings, in rows. `destructive` is the danger zone's: actions that can't be taken back. */\nfunction SettingsGroup({\n  title,\n  description,\n  variant = 'default',\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<'div'>, 'title'> & {\n  title: ReactNode\n  description?: ReactNode\n  variant?: 'default' | 'destructive'\n  /** SettingsRows, SettingsActions and SettingsPhotos. */\n  children: ReactNode\n}) {\n  const id = useId()\n  // A level under its section's heading, which is a level under the page's.\n  const level = use(SettingsPageContext)?.level ?? 1\n  return (\n    <Card\n      // A group of settings, named by its title: a landmark of its own would crowd the page's.\n      role='group'\n      aria-labelledby={id}\n      data-slot='settings-group'\n      {...props}\n      className={cn(\n        '@container gap-0 py-0',\n        variant === 'destructive' && 'border-destructive/40 dark:border-destructive/50',\n        className,\n      )}\n    >\n      <CardHeader className='border-b py-(--surface-padding)'>\n        <CardTitle\n          id={id}\n          render={\n            level === 2\n              ? // oxlint-disable-next-line jsx-a11y/heading-has-content -- the title's text goes in through the part's children.\n                (props) => <h4 {...props} />\n              : undefined\n          }\n          className={cn(variant === 'destructive' && 'text-destructive')}\n        >\n          {title}\n        </CardTitle>\n        {description ? <CardDescription>{description}</CardDescription> : null}\n      </CardHeader>\n      <div className='flex min-w-0 flex-col divide-y'>{children}</div>\n    </Card>\n  )\n}\n\n/** Where a row's control sits: beside its label when there's room (`auto`), always beside it (`row`), or under it (`column`). */\ntype SettingsRowLayout = 'auto' | 'row' | 'column'\n\nconst rowLayouts: Record<SettingsRowLayout, string> = {\n  // Under the label in a narrow card, the description beneath it; beside it from 28rem.\n  auto: \"[grid-template-areas:'label'_'message'_'control'] @md:grid-cols-[minmax(0,1fr)_auto] @md:gap-x-6 @md:[grid-template-areas:'label_control'_'message_control'] [&>[data-slot=settings-row-control]]:pt-2 @md:[&>[data-slot=settings-row-control]]:pt-0\",\n  row: \"grid-cols-[minmax(0,1fr)_auto] gap-x-4 [grid-template-areas:'label_control'_'message_control']\",\n  column: '',\n}\n\n/**\n * One setting: its label and description at the start, its control at the\n * end. It is a Field, so the label names the control, the description\n * describes it, and `name` is what Save sends. A control made of options,\n * such as a Segmented control, takes `group`: the label then names that\n * control, and each option keeps its own name.\n */\n/** What names and describes a group of options, which a row with `group` hands its control. */\ntype GroupNameProps = { 'aria-labelledby'?: string; 'aria-describedby'?: string }\n\nfunction SettingsRow({\n  name,\n  label,\n  description,\n  layout = 'auto',\n  group = false,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof Field>, 'children'> & {\n  label: ReactNode\n  description?: ReactNode\n  layout?: SettingsRowLayout\n  /** Whether the control is a group of options, such as a Segmented control or a Radio group. */\n  group?: boolean\n  /** The control: an Input, a Select, a Switch, a Segmented control. */\n  children: ReactNode\n}) {\n  const labelId = useId()\n  const descriptionId = useId()\n  const labelClass = cn(layout !== 'column' && 'pb-0.5 self-end')\n  return (\n    <Field\n      name={name}\n      data-settings-row=''\n      className={cn('p-(--surface-padding)', rowLayouts[layout], className)}\n      {...props}\n    >\n      {group ? (\n        // Not the Field's label, which would name every option after the row.\n        <span\n          id={labelId}\n          className={cn(labelClassName, 'w-fit pb-2 [grid-area:label]', labelClass)}\n        >\n          {label}\n        </span>\n      ) : (\n        <FieldLabel className={labelClass}>{label}</FieldLabel>\n      )}\n      <div\n        data-slot='settings-row-control'\n        className={cn(\n          'flex min-w-0 [grid-area:control]',\n          // A text field takes the row's width, up to what a long email needs.\n          layout === 'column'\n            ? 'flex-col *:max-w-md'\n            : // A control wider than a narrow card, such as a row of options, keeps inside it and scrolls.\n              'items-center self-center *:max-w-full *:min-w-0 @md:justify-end',\n        )}\n      >\n        {group && isValidElement<GroupNameProps>(children)\n          ? // The row's label names the group itself, so a screen reader and an agent find it by it.\n            cloneElement(children, {\n              'aria-labelledby': labelId,\n              'aria-describedby': description ? descriptionId : undefined,\n            })\n          : children}\n      </div>\n      {description ? (\n        <FieldDescription\n          id={descriptionId}\n          className={cn(layout !== 'column' && 'pt-0.5')}\n        >\n          {description}\n        </FieldDescription>\n      ) : null}\n      <FieldError />\n    </Field>\n  )\n}\n\n/** A row for an action rather than a value, such as the danger zone's: an Item, with the action at its end. */\nfunction SettingsAction({\n  title,\n  description,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof Item>, 'title' | 'render'> & {\n  title: ReactNode\n  description?: ReactNode\n  /** The action: a Button or a Confirm button. */\n  children: ReactNode\n}) {\n  return (\n    <Item\n      data-slot='settings-action'\n      {...props}\n      className={cn(\n        // A row of its group: its line under it where the group's other rows have theirs, and their padding.\n        'rounded-none border-0 p-(--surface-padding) not-last:border-b not-last:border-border',\n        className,\n      )}\n    >\n      <ItemContent className='gap-0.5'>\n        <ItemTitle>{title}</ItemTitle>\n        {description ? (\n          // As small as a setting's description, so the rows of a page read alike.\n          <ItemDescription className='text-xs'>{description}</ItemDescription>\n        ) : null}\n      </ItemContent>\n      <ItemActions>{children}</ItemActions>\n    </Item>\n  )\n}\n\nexport {\n  SettingsAction,\n  SettingsChannel,\n  SettingsGroup,\n  SettingsNav,\n  SettingsNavItem,\n  SettingsPage,\n  SettingsPhoto,\n  SettingsRow,\n  SettingsSection,\n}\n\nexport { fitsBeside, scrollToTopBy }\n\nexport type { SettingsPhotoValue, SettingsRowLayout }\n",
      "type": "registry:component",
      "target": "@components/kino/settings-page/settings-page.tsx"
    },
    {
      "path": "registry/components/kino/settings-page/settings-channel.tsx",
      "content": "'use client'\n\nimport { Card } from '@/registry/components/kino/card'\nimport { Collapsible, CollapsiblePanel } from '@/registry/components/kino/collapsible'\nimport {\n  Field,\n  FieldDescription,\n  FieldLabel,\n  useFormSubmission,\n} from '@/registry/components/kino/field'\nimport { ItemMedia } from '@/registry/components/kino/item'\nimport { Switch } from '@/registry/components/kino/switch'\nimport { type ComponentProps, type ReactNode, useId, useState } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * One way notifications reach the person, such as email or Slack: a switch\n * for the whole channel, and under it a row for each kind of notification\n * it sends. Turned off, the rows fold away under the switch, keeping what\n * they were set to for when it's turned back on; they still go with Save.\n */\n\nfunction SettingsChannel({\n  name,\n  label,\n  description,\n  icon,\n  defaultChecked = true,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  /** What Save sends the channel's switch under. */\n  name: string\n  label: ReactNode\n  description?: ReactNode\n  /** In a tile before the label. */\n  icon?: ReactNode\n  /** Whether the channel is on, as it was saved. */\n  defaultChecked?: boolean\n  /** A SettingsRow for each kind of notification, each with a Switch. */\n  children: ReactNode\n}) {\n  const [on, setOn] = useState(defaultChecked)\n  // Discard puts every field back, the switch with them: the rows fold or\n  // unfold to follow it, rather than the card starting again.\n  const revision = useFormSubmission()?.revision ?? 0\n  const [shownRevision, setShownRevision] = useState(revision)\n  if (revision !== shownRevision) {\n    setShownRevision(revision)\n    setOn(defaultChecked)\n  }\n  const labelId = useId()\n  return (\n    <Card\n      role='group'\n      aria-labelledby={labelId}\n      data-slot='settings-channel'\n      {...props}\n      className={cn('@container gap-0 py-0', className)}\n    >\n      <Field\n        name={name}\n        className=\"grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-(--surface-padding) py-(--surface-padding) [grid-template-areas:'icon_label_control'_'icon_message_control']\"\n      >\n        {icon ? (\n          <ItemMedia variant='icon' className='[grid-area:icon]'>\n            {icon}\n          </ItemMedia>\n        ) : null}\n        <FieldLabel id={labelId} className='self-end pb-0.5 text-sm font-medium'>\n          {label}\n        </FieldLabel>\n        {description ? (\n          <FieldDescription className='self-start pt-0.5'>{description}</FieldDescription>\n        ) : null}\n        <Switch checked={on} onCheckedChange={setOn} className='[grid-area:control]' />\n      </Field>\n      {/* The switch opens it, so an agent turns that on, as a person does. */}\n      <Collapsible open={on} disabled role='group' aria-labelledby={labelId}>\n        <CollapsiblePanel keepMounted className='p-0'>\n          <div className='flex min-w-0 flex-col divide-y border-t'>{children}</div>\n        </CollapsiblePanel>\n      </Collapsible>\n    </Card>\n  )\n}\n\nexport { SettingsChannel }\n",
      "type": "registry:component",
      "target": "@components/kino/settings-page/settings-channel.tsx"
    },
    {
      "path": "registry/components/kino/settings-page/settings-photo.tsx",
      "content": "'use client'\n\nimport { Avatar, AvatarFallback, AvatarImage } from '@/registry/components/kino/avatar'\nimport { Button } from '@/registry/components/kino/button'\nimport {\n  Dialog,\n  DialogBody,\n  DialogClose,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from '@/registry/components/kino/dialog'\nimport { Field, FieldDescription, FieldLabel } from '@/registry/components/kino/field'\nimport { FileInput, FileInputTrigger } from '@/registry/components/kino/file-input'\nimport {\n  ImageCropper,\n  ImageCropperArea,\n  ImageCropperPreview,\n  ImageCropperRotate,\n  ImageCropperZoom,\n} from '@/registry/components/kino/image-cropper'\nimport { FieldCheck } from '@/registry/lib/field-control'\nimport { cropImage, type ImageCrop } from '@ui-sdk/core/image'\nimport {\n  type ReactNode,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A profile photo as a setting: the photo, or the initials without one, and\n * Upload and Remove beside it. An upload opens the Image cropper in a\n * dialog, round, and the crop it keeps shows at once and waits for Save as\n * any other change does; Discard brings the old photo back. What Save sends\n * under `name` is the cropped image as a File, an empty value once removed, or the\n * photo's address when it hasn't changed.\n */\n\n/** What the photo setting holds: the saved photo's address, a new image, or none. */\ntype SettingsPhotoValue = string | File | null\n\n/** A new image's address while it shows, released once another takes its place. */\nfunction usePreview(value: SettingsPhotoValue) {\n  const url = useMemo(\n    () => (value instanceof Blob ? URL.createObjectURL(value) : null),\n    [value],\n  )\n  useEffect(() => () => (url ? URL.revokeObjectURL(url) : undefined), [url])\n  return typeof value === 'string' ? value : url\n}\n\nfunction SettingsPhoto({\n  name = 'photo',\n  label = 'Photo',\n  description,\n  defaultValue = null,\n  fallback,\n  alt = '',\n  className,\n}: {\n  name?: string\n  label?: ReactNode\n  description?: ReactNode\n  /** The saved photo's address, or `null` for none. */\n  defaultValue?: string | null\n  /** Shown without a photo: the person's initials. */\n  fallback: ReactNode\n  /** The person's name, for the cropper's picture. */\n  alt?: string\n  className?: string\n}) {\n  return (\n    <Field\n      name={name}\n      data-settings-photo=''\n      className={cn(\n        \"grid-cols-[auto_minmax(0,1fr)] items-center gap-x-4 p-(--surface-padding) [grid-template-areas:'picture_label'_'picture_message'_'control_control'] @md:grid-cols-[auto_minmax(0,1fr)_auto] @md:[grid-template-areas:'picture_label_control'_'picture_message_control']\",\n        className,\n      )}\n    >\n      <PhotoControl\n        name={name}\n        defaultValue={defaultValue}\n        fallback={fallback}\n        alt={alt}\n        label={label}\n        description={description}\n      />\n    </Field>\n  )\n}\n\nfunction PhotoControl({\n  name,\n  defaultValue,\n  fallback,\n  alt,\n  label,\n  description,\n}: {\n  name: string\n  defaultValue: string | null\n  fallback: ReactNode\n  alt: string\n  label: ReactNode\n  description: ReactNode\n}) {\n  // Remounted by Discard, as every Field is, so it starts again from what was saved.\n  const [value, setValue] = useState<SettingsPhotoValue>(defaultValue)\n  const shown = usePreview(value)\n  // The upload: the Field's control, which its label names, and where a failed check sends focus.\n  const [upload, setUpload] = useState<HTMLButtonElement | null>(null)\n\n  // The image picked and waiting to be cropped, with its address.\n  const [picked, setPicked] = useState<{ file: File; url: string } | null>(null)\n  useEffect(() => (picked ? () => URL.revokeObjectURL(picked.url) : undefined), [picked])\n  const [open, setOpen] = useState(false)\n  const [crop, setCrop] = useState<ImageCrop | null>(null)\n  const [cropping, setCropping] = useState(false)\n  const [failed, setFailed] = useState(false)\n  // The new image, in a file input, so the form sends it as a File.\n  const fileRef = useRef<HTMLInputElement>(null)\n  useLayoutEffect(() => {\n    const input = fileRef.current\n    if (!input || !(value instanceof File) || typeof DataTransfer === 'undefined') return\n    const transfer = new DataTransfer()\n    transfer.items.add(value)\n    input.files = transfer.files\n  }, [value])\n\n  const change = (next: SettingsPhotoValue) => setValue(next)\n\n  const keep = async () => {\n    if (!picked || !crop) return\n    setCropping(true)\n    setFailed(false)\n    try {\n      // Never larger than the crop itself.\n      const file = await cropImage(picked.url, crop, {\n        shape: 'circle',\n        width: Math.min(512, crop.width),\n        name: 'photo.png',\n      })\n      change(file)\n      setOpen(false)\n    } catch {\n      setFailed(true)\n    } finally {\n      setCropping(false)\n    }\n  }\n\n  return (\n    <>\n      <Avatar\n        size='lg'\n        className='size-14 text-base [grid-area:picture] [--avatar-size:3.5rem]'\n      >\n        {shown ? <AvatarImage src={shown} alt='' draggable={false} /> : null}\n        <AvatarFallback>{fallback}</AvatarFallback>\n      </Avatar>\n      <FieldLabel className='self-end pb-0.5'>{label}</FieldLabel>\n      {description ? (\n        <FieldDescription className='self-start pt-0.5'>{description}</FieldDescription>\n      ) : null}\n      {/* What the Field checks: focus that reaches it goes on to the upload. */}\n      <FieldCheck\n        value={typeof value === 'string' ? value : value ? value.name : ''}\n        onFocus={() => upload?.focus()}\n      />\n      {value instanceof File ? (\n        <input ref={fileRef} type='file' name={name} hidden tabIndex={-1} aria-hidden />\n      ) : (\n        <input type='hidden' name={name} value={value ?? ''} />\n      )}\n      <div className='flex flex-wrap items-center gap-2 pt-3 [grid-area:control] @md:justify-end @md:pt-0'>\n        <FileInput\n          accept='image/*'\n          value={[]}\n          // The photo goes with the form from the input above, so the upload sends nothing.\n          name=''\n          onValueChange={(files) => {\n            const file = files[0]\n            if (!file) return\n            setPicked({ file, url: URL.createObjectURL(file) })\n            setCrop(null)\n            setFailed(false)\n            setOpen(true)\n          }}\n        >\n          <FileInputTrigger ref={setUpload} size='sm'>\n            {value === null ? 'Upload photo' : 'Change photo'}\n          </FileInputTrigger>\n        </FileInput>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          disabled={value === null}\n          focusableWhenDisabled\n          onClick={() => change(null)}\n        >\n          Remove photo\n        </Button>\n      </div>\n      <Dialog open={open} onOpenChange={setOpen}>\n        <DialogContent>\n          <DialogHeader>\n            <DialogTitle>Crop your photo</DialogTitle>\n            <DialogDescription>\n              Move and zoom until your face fills the circle.\n            </DialogDescription>\n          </DialogHeader>\n          <DialogBody>\n            {picked ? (\n              <ImageCropper\n                key={picked.url}\n                aria-label='Photo'\n                src={picked.url}\n                mode='frame'\n                shape='circle'\n                onCropCommit={setCrop}\n              >\n                <div className='flex min-w-0 gap-4'>\n                  <ImageCropperArea alt={alt} className='h-72 flex-1' />\n                  <div className='hidden flex-col items-center gap-3 pt-1 @sm:flex'>\n                    <ImageCropperPreview className='size-16' />\n                    <ImageCropperPreview className='size-10' />\n                    <ImageCropperPreview className='size-6' />\n                  </div>\n                </div>\n                <div className='flex min-w-0 items-center gap-4'>\n                  <ImageCropperZoom className='flex-1' />\n                  <ImageCropperRotate />\n                </div>\n              </ImageCropper>\n            ) : null}\n          </DialogBody>\n          <DialogFooter>\n            {failed ? (\n              <p role='alert' className='text-destructive w-full text-sm'>\n                The photo couldn’t be cropped. Try another.\n              </p>\n            ) : null}\n            <DialogClose render={<Button variant='outline' size='sm' />}>\n              Cancel\n            </DialogClose>\n            <Button size='sm' loading={cropping} disabled={!crop} onClick={keep}>\n              Use photo\n            </Button>\n          </DialogFooter>\n        </DialogContent>\n      </Dialog>\n    </>\n  )\n}\n\nexport { SettingsPhoto }\n\nexport type { SettingsPhotoValue }\n",
      "type": "registry:component",
      "target": "@components/kino/settings-page/settings-photo.tsx"
    }
  ],
  "type": "registry:block"
}