{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "commitment",
  "type": "registry:ui",
  "title": "Commitment",
  "description": "The end of a session, and a week later. `CommitmentPicker` asks each person to pick one thing to do this week, from a short list or in their own words, and says when they will be asked about it. `CommitmentCheckIn` is that question, on the follow-up link…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "pattern"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/input.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/commitment.tsx",
      "target": "components/ui/patterns/commitment.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/commitment v1.1.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/commitment\n// What changed since: https://ds.interlace.tools/c/commitment#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — CommitmentPicker, CommitmentCheckIn\n *\n * The end of a session, and a week later. `CommitmentPicker` asks each\n * person to pick one thing to do this week, from a short list or in their\n * own words, and says when they will be asked about it. `CommitmentCheckIn`\n * is that question, on the follow-up link: did you? Yes, partly, or not yet.\n * Together they turn \"that was interesting\" into something a person did,\n * and give whoever ran the session a number for it (`commitmentImpact`).\n *\n * ## Anatomy\n *\n *   CommitmentPicker               (div — data-slot=\"commitment\", data-state=open|own|committed)\n *     ├─ p                         (data-slot=\"commitment-prompt\", the options' group label)\n *     ├─ div role=\"group\"          (data-slot=\"commitment-options\": one Button per option, then \"Something else\")\n *     ├─ form                      (data-slot=\"commitment-own\": label, input, submit; after \"Something else\")\n *     └─ div tabIndex=-1           (data-slot=\"commitment-summary\": once committed)\n *         ├─ svg                   (data-slot=\"commitment-icon\")\n *         ├─ p                     (data-slot=\"commitment-choice\": \"Your pick: …\")\n *         ├─ p                     (data-slot=\"commitment-follow-up\": when they will be asked)\n *         └─ Button?               (data-slot=\"commitment-change\")\n *\n *   CommitmentCheckIn              (div — data-slot=\"commitment-check-in\", data-state=open|answered, data-answer)\n *     ├─ p                         (data-slot=\"commitment-check-in-commitment\": what they picked)\n *     ├─ p                         (data-slot=\"commitment-check-in-question\", the group label)\n *     ├─ div role=\"group\"          (data-slot=\"commitment-check-in-options\": Yes / Partly / Not yet)\n *     ├─ p tabIndex=-1 aria-live   (data-slot=\"commitment-check-in-thanks\")\n *     ├─ Button?                   (data-slot=\"commitment-check-in-change\": with allowChange, once answered)\n *     └─ div                       (data-slot=\"commitment-check-in-footer\": optional, e.g. the next step)\n *\n * ## Data\n *\n * A commitment is `{ id, text }`: the option's id and its words, or\n * `id: null` for the person's own words. `value` / `defaultValue` /\n * `onValueChange` hold it (null after \"Change\"). Store `madeAt` with it;\n * `patterns/commitment-model` says when the follow-up is due\n * (`followUpAt`, `followUpState`) and what a room's answers add up to.\n *\n * ## Motion\n *\n * The check lands with a short scale (200ms) when the person commits here.\n * Transform only, off under reduced motion; a restored commitment shows\n * still.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                        |\n * | R6   | data-slot per part        | commitment-* / commitment-check-in-*                 |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onValueChange`; `answer` / `defaultAnswer` / `onAnswer` |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | labelled groups of buttons; focus moves to what replaced them |\n */\n\nimport { Check } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { CHECK_IN_ANSWERS, followUpAt, type CheckInAnswer } from '@/components/ui/patterns/commitment-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nconst OWN_MAX = 120;\n\n/** Moves focus to `ref` after a render that replaced the control the reader was on. */\nfunction useFocusAfter<T extends HTMLElement>(when: boolean) {\n  const ref = React.useRef<T>(null);\n  const pending = React.useRef(false);\n  React.useEffect(() => {\n    if (!when || !pending.current) return;\n    pending.current = false;\n    ref.current?.focus();\n  }, [when]);\n  return [ref, pending] as const;\n}\n\nfunction usePop(when: boolean, reduced: boolean) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  const armed = React.useRef(false);\n  React.useEffect(() => {\n    if (!when || !armed.current) return;\n    armed.current = false;\n    const el = ref.current;\n    if (reduced || !el || typeof el.animate !== 'function') return;\n    el.animate([{ transform: 'scale(0.5)' }, { transform: 'scale(1)' }], { duration: 200, easing: motionEase(el, 'enter') });\n  }, [when, reduced]);\n  return [ref, armed] as const;\n}\n\ninterface CommitmentOption {\n  id: string;\n  label: React.ReactNode;\n  /** Plain text for the summary, when `label` is not a string. */\n  text?: string;\n}\n\ninterface CommitmentValue {\n  /** The option's id, or null for the person's own words. */\n  id: string | null;\n  text: string;\n}\n\ninterface CommitmentPickerLabels {\n  /** The button that opens the own-words field. @default 'Something else' */\n  own?: string;\n  /** The own-words field's label. @default 'What will you do?' */\n  ownField?: string;\n  /** Submits the own words. @default 'Commit to it' */\n  ownSubmit?: string;\n  /** Before the choice in the summary. @default 'Your pick' */\n  committed?: string;\n  /** When they will be asked. `date` is null when the commitment time is unknown. */\n  followUp?: (date: string | null) => string;\n  /** @default 'Change' */\n  change?: string;\n}\n\ntype CommitmentPickerProps = Omit<React.ComponentProps<'div'>, 'children' | 'onChange' | 'defaultValue'> & {\n  /** The ask, e.g. \"Pick one thing to try this week\". */\n  prompt: React.ReactNode;\n  options: readonly CommitmentOption[];\n  /** Offer \"Something else\" with a short field. @default false */\n  allowOwn?: boolean;\n  value?: CommitmentValue | null;\n  defaultValue?: CommitmentValue | null;\n  /** Called with the commitment, and with null after \"Change\". */\n  onValueChange?: (value: CommitmentValue | null) => void;\n  /** When the shown commitment was made, in ms. Set for a restored one; the picker stamps its own. */\n  madeAt?: number;\n  /** Days until \"did you?\". @default 7 */\n  followUpDays?: number;\n  /** Show \"Change\" after committing. @default true */\n  allowChange?: boolean;\n  locale?: string;\n  labels?: CommitmentPickerLabels;\n};\n\nconst FOLLOW_UP: NonNullable<CommitmentPickerLabels['followUp']> = (date) =>\n  date ? `We will ask how it went on ${date}.` : 'We will ask how it went in a week.';\n\nconst textOf = (o: CommitmentOption) =>\n  o.text ?? (typeof o.label === 'string' || typeof o.label === 'number' ? String(o.label) : o.id);\n\nfunction CommitmentPicker({\n  prompt,\n  options,\n  allowOwn = false,\n  value: valueProp,\n  defaultValue = null,\n  onValueChange,\n  madeAt: madeAtProp,\n  followUpDays = 7,\n  allowChange = true,\n  locale,\n  labels,\n  className,\n  ...props\n}: CommitmentPickerProps) {\n  const [uncontrolled, setUncontrolled] = React.useState<CommitmentValue | null>(defaultValue);\n  const value = valueProp === undefined ? uncontrolled : valueProp;\n  const committed = !!value && value.text.trim() !== '';\n  const [writing, setWriting] = React.useState(false);\n  const [own, setOwn] = React.useState('');\n  const [stamped, setStamped] = React.useState<number | null>(null);\n  const reduced = useReducedMotion();\n  const promptId = React.useId();\n  const fieldId = React.useId();\n  const [summaryRef, focusSummary] = useFocusAfter<HTMLDivElement>(committed);\n  const [iconRef, pop] = usePop(committed, reduced);\n  const groupRef = React.useRef<HTMLDivElement>(null);\n  const fieldRef = React.useRef<HTMLInputElement>(null);\n\n  React.useEffect(() => {\n    if (writing) fieldRef.current?.focus();\n  }, [writing]);\n\n  const set = (next: CommitmentValue | null) => {\n    if (valueProp === undefined) setUncontrolled(next);\n    onValueChange?.(next);\n  };\n\n  const commit = (next: CommitmentValue) => {\n    focusSummary.current = true;\n    pop.current = true;\n    setStamped(Date.now());\n    setWriting(false);\n    set(next);\n  };\n\n  const change = () => {\n    setStamped(null);\n    setOwn('');\n    set(null);\n    // The summary goes away; the options come back with focus on the first.\n    requestFocus(groupRef);\n  };\n\n  const madeAt = madeAtProp ?? stamped;\n  const date =\n    madeAt === null || madeAt === undefined\n      ? null\n      : new Intl.DateTimeFormat(locale, { weekday: 'long', month: 'long', day: 'numeric' }).format(\n          new Date(followUpAt(madeAt, { days: followUpDays })),\n        );\n\n  return (\n    <div\n      data-slot=\"commitment\"\n      data-state={committed ? 'committed' : writing ? 'own' : 'open'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      {committed && value ? (\n        <div\n          ref={summaryRef}\n          tabIndex={-1}\n          data-slot=\"commitment-summary\"\n          className=\"bg-card text-card-foreground focus-visible:outline-ring grid grid-cols-[auto_1fr] items-start gap-x-3 gap-y-1 rounded-xl border p-4 outline-offset-4 focus-visible:outline-2\"\n        >\n          <span\n            ref={iconRef}\n            data-slot=\"commitment-icon\"\n            aria-hidden=\"true\"\n            className=\"bg-primary text-primary-foreground row-span-2 inline-flex size-8 items-center justify-center rounded-full\"\n          >\n            <Check className=\"size-4\" />\n          </span>\n          <p data-slot=\"commitment-choice\" className=\"font-medium text-pretty\">\n            <span className=\"text-muted-foreground font-normal\">{labels?.committed ?? 'Your pick'}: </span>\n            {value.text}\n          </p>\n          <p data-slot=\"commitment-follow-up\" className=\"text-muted-foreground text-sm\">\n            {(labels?.followUp ?? FOLLOW_UP)(date)}\n          </p>\n          {allowChange ? (\n            <div className=\"col-start-2 pt-2\">\n              <Button type=\"button\" variant=\"outline\" size=\"sm\" data-slot=\"commitment-change\" onClick={change}>\n                {labels?.change ?? 'Change'}\n              </Button>\n            </div>\n          ) : null}\n        </div>\n      ) : (\n        <>\n          <p id={promptId} data-slot=\"commitment-prompt\" className=\"font-heading text-lg font-semibold text-balance\">\n            {prompt}\n          </p>\n          <div ref={groupRef} role=\"group\" aria-labelledby={promptId} data-slot=\"commitment-options\" className=\"grid gap-2\">\n            {options.map((o) => (\n              <Button\n                key={o.id}\n                type=\"button\"\n                variant=\"outline\"\n                size=\"lg\"\n                className=\"h-auto min-h-11 justify-start py-2.5 text-start whitespace-normal\"\n                onClick={() => commit({ id: o.id, text: textOf(o) })}\n              >\n                {o.label}\n              </Button>\n            ))}\n            {allowOwn && !writing ? (\n              <Button\n                type=\"button\"\n                variant=\"ghost\"\n                size=\"lg\"\n                className=\"h-auto min-h-11 justify-start py-2.5 text-start whitespace-normal\"\n                onClick={() => setWriting(true)}\n              >\n                {labels?.own ?? 'Something else'}\n              </Button>\n            ) : null}\n          </div>\n          {allowOwn && writing ? (\n            <form\n              data-slot=\"commitment-own\"\n              className=\"grid gap-2\"\n              onSubmit={(e) => {\n                e.preventDefault();\n                const text = own.trim();\n                if (text) commit({ id: null, text });\n              }}\n            >\n              <label htmlFor={fieldId} className=\"text-sm font-medium\">\n                {labels?.ownField ?? 'What will you do?'}\n              </label>\n              <div className=\"flex flex-wrap gap-2\">\n                <Input\n                  ref={fieldRef}\n                  id={fieldId}\n                  value={own}\n                  maxLength={OWN_MAX}\n                  autoComplete=\"off\"\n                  onChange={(e) => setOwn(e.target.value)}\n                  className=\"min-w-0 flex-1 basis-48\"\n                />\n                <Button type=\"submit\" disabled={!own.trim()}>\n                  {labels?.ownSubmit ?? 'Commit to it'}\n                </Button>\n              </div>\n            </form>\n          ) : null}\n        </>\n      )}\n    </div>\n  );\n}\nCommitmentPicker.displayName = 'CommitmentPicker';\n\n/** Focus the first button in a group once it is back in the document. */\nfunction requestFocus(ref: React.RefObject<HTMLElement | null>) {\n  setTimeout(() => ref.current?.querySelector<HTMLElement>('button')?.focus(), 0);\n}\n\ninterface CommitmentCheckInLabels {\n  /** @default 'Did you do it?' */\n  question?: string;\n  /** @default 'Yes' */\n  done?: string;\n  /** @default 'Partly' */\n  partly?: string;\n  /** @default 'Not yet' */\n  notYet?: string;\n  /** After answering. */\n  thanks?: (answer: CheckInAnswer) => string;\n  /** Before the commitment. @default 'Last time you picked' */\n  picked?: string;\n  /** @default 'Change my answer' */\n  change?: string;\n}\n\ntype CommitmentCheckInProps = Omit<React.ComponentProps<'div'>, 'children' | 'onChange'> & {\n  /** What they picked, from the stored commitment. */\n  commitment: React.ReactNode;\n  answer?: CheckInAnswer | null;\n  defaultAnswer?: CheckInAnswer | null;\n  /** Called with each answer. */\n  onAnswer?: (answer: CheckInAnswer | null) => void;\n  /** Show \"Change my answer\" after answering. @default true */\n  allowChange?: boolean;\n  /** Under the answer: what to do next. */\n  footer?: React.ReactNode;\n  labels?: CommitmentCheckInLabels;\n};\n\nconst THANKS: Record<CheckInAnswer, string> = {\n  done: 'Well done, and thank you for telling us.',\n  partly: 'A start counts. Thank you for telling us.',\n  'not-yet': 'Thank you for saying so. It is still worth a try.',\n};\n\nfunction CommitmentCheckIn({\n  commitment,\n  answer: answerProp,\n  defaultAnswer = null,\n  onAnswer,\n  allowChange = true,\n  footer,\n  labels,\n  className,\n  ...props\n}: CommitmentCheckInProps) {\n  const [uncontrolled, setUncontrolled] = React.useState<CheckInAnswer | null>(defaultAnswer);\n  const raw = answerProp === undefined ? uncontrolled : answerProp;\n  const answer = raw && CHECK_IN_ANSWERS.includes(raw) ? raw : null;\n  const questionId = React.useId();\n  const groupRef = React.useRef<HTMLDivElement>(null);\n  const [thanksRef, focusThanks] = useFocusAfter<HTMLParagraphElement>(answer !== null);\n\n  const set = (next: CheckInAnswer | null) => {\n    if (answerProp === undefined) setUncontrolled(next);\n    onAnswer?.(next);\n  };\n\n  const words: Record<CheckInAnswer, string> = {\n    done: labels?.done ?? 'Yes',\n    partly: labels?.partly ?? 'Partly',\n    'not-yet': labels?.notYet ?? 'Not yet',\n  };\n\n  return (\n    <div\n      data-slot=\"commitment-check-in\"\n      data-state={answer ? 'answered' : 'open'}\n      data-answer={answer ?? undefined}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      <p data-slot=\"commitment-check-in-commitment\" className=\"text-pretty\">\n        <span className=\"text-muted-foreground\">{labels?.picked ?? 'Last time you picked'}: </span>\n        <span className=\"font-medium\">{commitment}</span>\n      </p>\n      <p id={questionId} data-slot=\"commitment-check-in-question\" className=\"font-heading text-lg font-semibold text-balance\">\n        {labels?.question ?? 'Did you do it?'}\n      </p>\n      {answer ? null : (\n        <div\n          ref={groupRef}\n          role=\"group\"\n          aria-labelledby={questionId}\n          data-slot=\"commitment-check-in-options\"\n          className=\"flex flex-wrap gap-2\"\n        >\n          {CHECK_IN_ANSWERS.map((a) => (\n            <Button\n              key={a}\n              type=\"button\"\n              variant=\"outline\"\n              size=\"lg\"\n              data-answer={a}\n              className=\"min-w-24 flex-1\"\n              onClick={() => {\n                focusThanks.current = !!groupRef.current?.contains(document.activeElement);\n                set(a);\n              }}\n            >\n              {words[a]}\n            </Button>\n          ))}\n        </div>\n      )}\n      <p\n        ref={thanksRef}\n        tabIndex={-1}\n        data-slot=\"commitment-check-in-thanks\"\n        aria-live=\"polite\"\n        className=\"focus-visible:outline-ring rounded-sm outline-offset-4 empty:hidden focus-visible:outline-2\"\n      >\n        {answer ? (labels?.thanks?.(answer) ?? THANKS[answer]) : ''}\n      </p>\n      {answer && allowChange ? (\n        <div>\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"sm\"\n            data-slot=\"commitment-check-in-change\"\n            onClick={() => {\n              set(null);\n              requestFocus(groupRef);\n            }}\n          >\n            {labels?.change ?? 'Change my answer'}\n          </Button>\n        </div>\n      ) : null}\n      {footer ? (\n        <div data-slot=\"commitment-check-in-footer\" className=\"text-muted-foreground text-sm\">\n          {footer}\n        </div>\n      ) : null}\n    </div>\n  );\n}\nCommitmentCheckIn.displayName = 'CommitmentCheckIn';\n\nexport { CommitmentPicker, CommitmentCheckIn };\nexport type {\n  CommitmentPickerProps,\n  CommitmentPickerLabels,\n  CommitmentOption,\n  CommitmentValue,\n  CommitmentCheckInProps,\n  CommitmentCheckInLabels,\n};\n"
    },
    {
      "path": "registry/interlace-ui/patterns/commitment-model.ts",
      "target": "components/ui/patterns/commitment-model.ts",
      "type": "registry:ui",
      "content": "export const DAY_MS = 86_400_000;\n\nexport type CheckInAnswer = 'done' | 'partly' | 'not-yet';\nexport const CHECK_IN_ANSWERS: readonly CheckInAnswer[] = ['done', 'partly', 'not-yet'];\n\nexport interface CommitmentRecord {\n  /** The option or the person's own words. */\n  choice: string;\n  /** When it was made, in ms. */\n  madeAt: number;\n  /** The answer to \"did you?\", once given. */\n  checkIn?: { answer: CheckInAnswer; at: number } | null;\n}\n\nexport interface FollowUpOptions {\n  /** Days from the commitment to the question. @default 7 */\n  days?: number;\n  /** Days the question stays open once due. @default 14 */\n  openDays?: number;\n}\n\nexport type FollowUpState = 'waiting' | 'due' | 'answered' | 'lapsed';\n\nconst days = (n: number | undefined, fallback: number) =>\n  typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : fallback;\n\n/** When to ask \"did you?\". */\nexport function followUpAt(madeAt: number, { days: d }: FollowUpOptions = {}): number {\n  return madeAt + days(d, 7) * DAY_MS;\n}\n\n/** Where a commitment stands at `now`. */\nexport function followUpState(c: CommitmentRecord, now: number, options: FollowUpOptions = {}): FollowUpState {\n  if (c.checkIn && CHECK_IN_ANSWERS.includes(c.checkIn.answer)) return 'answered';\n  const due = followUpAt(c.madeAt, options);\n  if (now < due) return 'waiting';\n  return now < due + days(options.openDays, 14) * DAY_MS ? 'due' : 'lapsed';\n}\n\nexport interface CommitmentImpact {\n  /** Commitments made. */\n  made: number;\n  /** Of those, how many answered \"did you?\". */\n  answered: number;\n  done: number;\n  partly: number;\n  notYet: number;\n  /** answered ÷ made, or null with nothing made. */\n  responseRate: number | null;\n  /** (done + partly) ÷ answered, or null with no answers. */\n  followThrough: number | null;\n  /** Commitments per choice, most-chosen first. */\n  choices: { choice: string; count: number }[];\n}\n\n/** What a room's commitments add up to: how many answered, how many did it. */\nexport function commitmentImpact(records: readonly CommitmentRecord[]): CommitmentImpact {\n  let done = 0;\n  let partly = 0;\n  let notYet = 0;\n  const byChoice = new Map<string, number>();\n  for (const r of records) {\n    byChoice.set(r.choice, (byChoice.get(r.choice) ?? 0) + 1);\n    const a = r.checkIn?.answer;\n    if (a === 'done') done++;\n    else if (a === 'partly') partly++;\n    else if (a === 'not-yet') notYet++;\n  }\n  const made = records.length;\n  const answered = done + partly + notYet;\n  return {\n    made,\n    answered,\n    done,\n    partly,\n    notYet,\n    responseRate: made ? answered / made : null,\n    followThrough: answered ? (done + partly) / answered : null,\n    choices: [...byChoice.entries()]\n      .map(([choice, count]) => ({ choice, count }))\n      .sort((a, b) => b.count - a.count),\n  };\n}\n\n/**\n * @interlace/ui — commitment-model\n *\n * One thing to do this week, and a question a week later: \"did you?\".\n * The rules for when the follow-up is due and what the answers add up to\n * live here, pure, so the page that asks, the reminder that sends the link\n * and the report that counts the answers agree.\n *\n * Time is milliseconds since the epoch. The follow-up opens `days` after\n * the commitment was made and stays open for `openDays`; after that the\n * question has lapsed, because \"did you, a month ago?\" gets guesses, not\n * answers.\n */\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/commitment\n\nInstalled to `components/ui/patterns/commitment.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/commitment';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/commitment\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
