{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-07",
  "title": "Prompt templates",
  "description": "Saved prompts with blanks typed straight into the sentence, a filled count that rolls, a live preview with a token estimate, Copy and Use prompt.",
  "dependencies": [
    "),\n      blank(",
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/copy-button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-07.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useImperativeHandle, useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  hold,\n  keyDelayOf,\n  prefixesOf,\n  PRESS_LEAD_MS,\n  pressedSolidOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { FileTextIcon, SearchIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { CopyButton } from '@/registry/ndeko/ui/copy-button';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\n\nimport { includesQuery, Marked } from './_parts/marked';\n\nexport type TemplateField =\n  | { kind: 'text'; id: string; label: string }\n  | { kind: 'choice'; id: string; label: string; options: string[] }\n  | {\n      kind: 'optional';\n      id: string;\n      label: string;\n      /** Words around the field that leave the prompt with it while it is empty. */\n      before: string;\n      after: string;\n    };\n\nexport type TemplatePart =\n  { kind: 'text'; text: string } | { kind: 'field'; field: TemplateField };\n\nexport type PromptTemplate = {\n  id: string;\n  title: string;\n  parts: TemplatePart[];\n};\n\nexport type TemplateValues = Record<string, string>;\n\nfunction text(value: string): TemplatePart {\n  return { kind: 'text', text: value };\n}\n\nfunction blank(id: string, label: string): TemplatePart {\n  return { kind: 'field', field: { kind: 'text', id, label } };\n}\n\nfunction oneOf(id: string, label: string, options: string[]): TemplatePart {\n  return { kind: 'field', field: { kind: 'choice', id, label, options } };\n}\n\nfunction maybe(\n  id: string,\n  label: string,\n  before: string,\n  after: string\n): TemplatePart {\n  return {\n    kind: 'field',\n    field: { kind: 'optional', id, label, before, after },\n  };\n}\n\nfunction fieldsOf(template: PromptTemplate) {\n  const fields: TemplateField[] = [];\n  for (const part of template.parts) {\n    if (part.kind === 'field') {\n      fields.push(part.field);\n    }\n  }\n  return fields;\n}\n\nfunction valueOf(values: TemplateValues, field: TemplateField) {\n  const value = values[field.id] ?? '';\n  return value.trim();\n}\n\nfunction isFilled(values: TemplateValues, field: TemplateField) {\n  return valueOf(values, field) !== '';\n}\n\nfunction isRequired(field: TemplateField) {\n  return field.kind !== 'optional';\n}\n\nexport function missingFieldOf(\n  template: PromptTemplate,\n  values: TemplateValues\n) {\n  const fields = fieldsOf(template);\n  return fields.find((field) => {\n    const required = isRequired(field);\n    const empty = !isFilled(values, field);\n    return required && empty;\n  });\n}\n\nfunction filledCountOf(template: PromptTemplate, values: TemplateValues) {\n  const fields = fieldsOf(template);\n  const filled = fields.filter((field) => isFilled(values, field));\n  return filled.length;\n}\n\n/** The prompt as it will be sent: values in place, an empty optional field leaves with its words. */\nexport function finalPromptOf(\n  template: PromptTemplate,\n  values: TemplateValues\n) {\n  const pieces: string[] = [];\n  for (const part of template.parts) {\n    if (part.kind === 'text') {\n      pieces.push(part.text);\n      continue;\n    }\n    const field = part.field;\n    const value = valueOf(values, field);\n    const isEmpty = value === '';\n    if (field.kind === 'optional') {\n      if (!isEmpty) {\n        pieces.push(`${field.before}${value}${field.after}`);\n      }\n      continue;\n    }\n    if (isEmpty) {\n      pieces.push(`[${field.label}]`);\n      continue;\n    }\n    pieces.push(value);\n  }\n  return pieces.join('');\n}\n\n/** About four characters a token: an estimate, shown as one. */\nfunction tokenEstimateOf(prompt: string) {\n  return Math.ceil(prompt.length / 4);\n}\n\nfunction searchTextOf(template: PromptTemplate) {\n  const words: string[] = [template.title];\n  for (const part of template.parts) {\n    if (part.kind === 'text') {\n      words.push(part.text);\n      continue;\n    }\n    words.push(part.field.label);\n  }\n  return words.join(' ');\n}\n\nfunction actionLabelOf(missing: TemplateField | undefined) {\n  if (!missing) {\n    return 'Use prompt';\n  }\n  if (missing.kind === 'choice') {\n    return `Pick a ${missing.label}`;\n  }\n  return `Add ${missing.label}`;\n}\n\nfunction fieldToneOf(field: TemplateField, isEmpty: boolean) {\n  const isOptional = field.kind === 'optional';\n  const isOpenSlot = isOptional && isEmpty;\n  if (isOpenSlot) {\n    return 'hairline-border border-dashed border-foreground/30 bg-transparent';\n  }\n  if (isEmpty) {\n    return 'bg-card hairline-ring ring-foreground/15 dark:bg-foreground/[0.04]';\n  }\n  return 'bg-primary/[0.08] hairline-ring ring-primary/25';\n}\n\nconst INLINE_FOCUS =\n  'outline-none focus-visible:ring-[3px] focus-visible:ring-ring/25';\n\ntype InlineTextProps = {\n  field: TemplateField;\n  value: string;\n  onChange: (value: string) => void;\n};\n\nfunction InlineText({ field, value, onChange }: InlineTextProps) {\n  const isEmpty = value.trim() === '';\n  const sizer = sizerTextOf(value, field.label);\n\n  return (\n    <span className='inline-grid max-w-full align-baseline'>\n      <span\n        aria-hidden='true'\n        className='invisible col-start-1 row-start-1 truncate px-1.5 text-[13px] whitespace-pre'\n      >\n        {sizer}\n      </span>\n      <input\n        value={value}\n        onChange={(event) => onChange(event.target.value)}\n        placeholder={field.label}\n        aria-label={labelOf(field)}\n        className={cn(\n          'placeholder:text-muted-foreground/80 col-start-1 row-start-1 h-6 w-full min-w-0 rounded-md px-1.5 text-[13px] transition-[background-color,box-shadow] duration-150',\n          INLINE_FOCUS,\n          fieldToneOf(field, isEmpty)\n        )}\n      />\n    </span>\n  );\n}\n\nfunction sizerTextOf(value: string, label: string) {\n  if (value === '') {\n    return label;\n  }\n  return value;\n}\n\nfunction labelOf(field: TemplateField) {\n  if (field.kind === 'optional') {\n    return `${field.label}, optional`;\n  }\n  return field.label;\n}\n\ntype InlineChoiceProps = {\n  field: Extract<TemplateField, { kind: 'choice' }>;\n  value: string;\n  onChange: (value: string) => void;\n};\n\nfunction InlineChoice({ field, value, onChange }: InlineChoiceProps) {\n  const isEmpty = value === '';\n  const items = field.options.map((option) => ({\n    value: option,\n    label: option,\n  }));\n\n  function change(next: unknown) {\n    if (typeof next === 'string') {\n      onChange(next);\n    }\n  }\n\n  return (\n    <Select items={items} value={selectValueOf(value)} onValueChange={change}>\n      <SelectTrigger\n        size='sm'\n        aria-label={field.label}\n        className={cn(\n          'inline-flex h-6 w-auto gap-1 px-1.5 align-baseline text-[13px] shadow-none md:text-[13px]',\n          fieldToneOf(field, isEmpty)\n        )}\n      >\n        <SelectValue placeholder={field.label} />\n      </SelectTrigger>\n      <SelectContent>\n        {field.options.map((option) => (\n          <SelectItem key={option} value={option}>\n            {option}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\nfunction selectValueOf(value: string) {\n  if (value === '') {\n    return null;\n  }\n  return value;\n}\n\ntype TemplateSentenceProps = {\n  template: PromptTemplate;\n  values: TemplateValues;\n  onValueChange: (fieldId: string, value: string) => void;\n};\n\nexport function TemplateSentence({\n  template,\n  values,\n  onValueChange,\n}: TemplateSentenceProps) {\n  return (\n    <div className='text-[15px] leading-9 text-pretty'>\n      {template.parts.map((part, index) => {\n        if (part.kind === 'text') {\n          return <span key={index}>{part.text}</span>;\n        }\n        const field = part.field;\n        const value = values[field.id] ?? '';\n        const change = (next: string) => onValueChange(field.id, next);\n        if (field.kind === 'choice') {\n          return (\n            <InlineChoice\n              key={field.id}\n              field={field}\n              value={value}\n              onChange={change}\n            />\n          );\n        }\n        if (field.kind === 'optional') {\n          return (\n            <span key={field.id}>\n              <span className='text-muted-foreground'>{field.before}</span>\n              <InlineText field={field} value={value} onChange={change} />\n              <span className='text-muted-foreground'>{field.after}</span>\n            </span>\n          );\n        }\n        return (\n          <InlineText\n            key={field.id}\n            field={field}\n            value={value}\n            onChange={change}\n          />\n        );\n      })}\n    </div>\n  );\n}\n\nfunction PreviewText({\n  template,\n  values,\n}: {\n  template: PromptTemplate;\n  values: TemplateValues;\n}) {\n  return (\n    <p className='text-[13px] leading-6 text-pretty whitespace-pre-wrap'>\n      {template.parts.map((part, index) => {\n        if (part.kind === 'text') {\n          return <span key={index}>{part.text}</span>;\n        }\n        const field = part.field;\n        const value = valueOf(values, field);\n        const isEmpty = value === '';\n        if (field.kind === 'optional') {\n          if (isEmpty) {\n            return null;\n          }\n          return (\n            <span key={field.id}>\n              {field.before}\n              <span className='text-primary-ink'>{value}</span>\n              {field.after}\n            </span>\n          );\n        }\n        if (isEmpty) {\n          return (\n            <span\n              key={field.id}\n              className='bg-warning/15 text-warning-foreground rounded-[3px] px-0.5'\n            >\n              [{field.label}]\n            </span>\n          );\n        }\n        return (\n          <span key={field.id} className='text-primary-ink'>\n            {value}\n          </span>\n        );\n      })}\n    </p>\n  );\n}\n\nconst MORPH_HOLD_MS = 650;\n\nconst DONE_HOLD_MS = 1500;\n\nexport type TemplateEditorHandle = {\n  /** Shows Use prompt held down. */\n  press: () => void;\n  /** Sends the prompt, as Use prompt does. */\n  use: () => void;\n};\n\ntype TemplateEditorProps = {\n  template: PromptTemplate;\n  values: TemplateValues;\n  onValueChange: (fieldId: string, value: string) => void;\n  onUse: (prompt: string) => void;\n  handleRef?: React.Ref<TemplateEditorHandle>;\n};\n\nexport function TemplateEditor({\n  template,\n  values,\n  onValueChange,\n  onUse,\n  handleRef,\n}: TemplateEditorProps) {\n  const [sendState, setSendState] = useState<MorphState>('idle');\n  const { schedule } = useTimeouts();\n  const { pressed, press } = usePress<'use'>();\n  const fields = fieldsOf(template);\n  const filledCount = filledCountOf(template, values);\n  const missing = missingFieldOf(template, values);\n  const isReady = missing === undefined;\n  const prompt = finalPromptOf(template, values);\n  const tokens = tokenEstimateOf(prompt);\n  const actionLabel = actionLabelOf(missing);\n  const filledWords = [\n    {\n      key: 'filled',\n      text: String(filledCount),\n      node: <MotionNumber value={filledCount} />,\n    },\n    'of',\n    String(fields.length),\n    'filled',\n  ];\n\n  function use() {\n    if (!isReady) {\n      return;\n    }\n    setSendState('busy');\n    schedule(() => {\n      setSendState('done');\n      onUse(prompt);\n    }, MORPH_HOLD_MS);\n    schedule(() => setSendState('idle'), MORPH_HOLD_MS + DONE_HOLD_MS);\n  }\n\n  useImperativeHandle(handleRef, () => ({\n    press: () => press('use'),\n    use,\n  }));\n\n  return (\n    <div className='flex min-w-0 flex-col gap-4'>\n      <div className='flex flex-col gap-1'>\n        <div className='flex items-baseline justify-between gap-3'>\n          <h3 className='text-sm font-medium'>{template.title}</h3>\n          <p className='text-muted-foreground shrink-0 text-xs'>\n            <WordRoll words={filledWords} value={filledCount} />\n          </p>\n        </div>\n        <TemplateSentence\n          template={template}\n          values={values}\n          onValueChange={onValueChange}\n        />\n      </div>\n      <div className='bg-foreground/[0.03] dark:bg-foreground/[0.05] flex flex-col gap-3 rounded-lg p-3'>\n        <div className='flex items-center justify-between gap-2'>\n          <p className='text-muted-foreground text-xs'>Preview</p>\n          <p className='text-muted-foreground text-xs'>\n            about <MotionNumber value={tokens} /> tokens\n          </p>\n        </div>\n        <AnimatedSize>\n          <PreviewText template={template} values={values} />\n        </AnimatedSize>\n        <div className='flex flex-wrap items-center justify-end gap-2'>\n          <CopyButton\n            text={prompt}\n            label='Copy the prompt'\n            className='size-8'\n          />\n          <MorphButton\n            type='button'\n            size='sm'\n            state={sendState}\n            labels={{\n              idle: actionLabel,\n              busy: 'Sending',\n              done: 'In the composer',\n            }}\n            disabled={!isReady}\n            onClick={use}\n            className={pressedSolidOf(pressed === 'use')}\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction listToneOf(isActive: boolean) {\n  if (isActive) {\n    return 'text-foreground';\n  }\n  return 'text-muted-foreground hover:text-foreground';\n}\n\nfunction stepOf(key: string) {\n  if (key === 'ArrowDown') {\n    return 1;\n  }\n  if (key === 'ArrowUp') {\n    return -1;\n  }\n  return 0;\n}\n\ntype TemplateListProps = {\n  templates: PromptTemplate[];\n  activeId: string;\n  onActivate: (templateId: string) => void;\n  query: string;\n  onQueryChange: (query: string) => void;\n};\n\nfunction TemplateList({\n  templates,\n  activeId,\n  onActivate,\n  query,\n  onQueryChange,\n}: TemplateListProps) {\n  const listRef = useRef<HTMLUListElement>(null);\n  const highlightId = useId();\n  const searchId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const spring = springOf(shouldReduceMotion);\n  const matching = templates.filter((template) =>\n    includesQuery(searchTextOf(template), query)\n  );\n  const isEmpty = matching.length === 0;\n  const trimmed = query.trim();\n  const tabStopId = tabStopOf(activeId, matching);\n\n  function moveFromKeys(event: React.KeyboardEvent<HTMLButtonElement>) {\n    const step = stepOf(event.key);\n    if (step === 0) {\n      return;\n    }\n    event.preventDefault();\n    const index = matching.findIndex((template) => template.id === activeId);\n    const moved = index + step;\n    const bounded = Math.min(matching.length - 1, Math.max(0, moved));\n    const next = matching[bounded];\n    onActivate(next.id);\n    requestAnimationFrame(() => {\n      const button = listRef.current?.querySelector<HTMLElement>(\n        `[data-template=\"${next.id}\"]`\n      );\n      button?.focus();\n    });\n  }\n\n  return (\n    <div className='flex min-w-0 flex-col gap-2'>\n      <div className='relative'>\n        <label htmlFor={searchId} className='sr-only'>\n          Search templates\n        </label>\n        <SearchIcon className='text-muted-foreground pointer-events-none absolute start-2.5 top-1/2 size-4 -translate-y-1/2' />\n        <Input\n          id={searchId}\n          type='search'\n          value={query}\n          onChange={(event) => onQueryChange(event.target.value)}\n          placeholder='Search templates'\n          className='ps-8'\n        />\n      </div>\n      <ul ref={listRef} aria-label='Templates' className='flex flex-col'>\n        {matching.map((template) => {\n          const isActive = template.id === activeId;\n          const fieldCount = fieldsOf(template).length;\n          return (\n            <li key={template.id}>\n              <button\n                type='button'\n                data-template={template.id}\n                aria-current={currentOf(isActive)}\n                tabIndex={tabIndexOf(template.id, tabStopId)}\n                onClick={() => onActivate(template.id)}\n                onKeyDown={moveFromKeys}\n                className={cn(\n                  'focus-visible:ring-ring/25 relative flex w-full cursor-pointer items-center gap-2.5 rounded-md px-2 py-2 text-start outline-none focus-visible:ring-[3px]',\n                  listToneOf(isActive)\n                )}\n              >\n                {isActive && (\n                  <motion.span\n                    layoutId={highlightId}\n                    layoutDependency={activeId}\n                    transition={spring}\n                    aria-hidden='true'\n                    className='bg-foreground/[0.05] dark:bg-foreground/[0.07] absolute inset-0 rounded-md'\n                  />\n                )}\n                <FileTextIcon className='relative size-4 shrink-0' />\n                <span className='relative min-w-0 flex-1'>\n                  <span className='block truncate text-[13px] font-medium'>\n                    <Marked text={template.title} query={query} />\n                  </span>\n                  <span className='text-muted-foreground block text-xs'>\n                    {countOf(fieldCount, 'field')}\n                  </span>\n                </span>\n              </button>\n            </li>\n          );\n        })}\n      </ul>\n      {isEmpty && (\n        <div className='bg-foreground/[0.03] dark:bg-foreground/[0.05] flex flex-col items-center gap-2 rounded-lg px-3 py-5 text-center'>\n          <p className='text-muted-foreground text-[13px]'>\n            No template matches “{trimmed}”\n          </p>\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            onClick={() => onQueryChange('')}\n          >\n            <XIcon />\n            Clear the search\n          </Button>\n        </div>\n      )}\n    </div>\n  );\n}\n\nfunction currentOf(isActive: boolean) {\n  if (isActive) {\n    return 'true';\n  }\n  return undefined;\n}\n\n/** One tab stop for the list: the active template, or the first one when the active one is filtered out. */\nfunction tabStopOf(activeId: string, matching: PromptTemplate[]) {\n  const isActiveShown = matching.some((template) => template.id === activeId);\n  if (isActiveShown) {\n    return activeId;\n  }\n  return matching[0]?.id;\n}\n\nfunction tabIndexOf(templateId: string, tabStopId: string | undefined) {\n  if (templateId === tabStopId) {\n    return 0;\n  }\n  return -1;\n}\n\nexport type PromptTemplatesHandle = {\n  /** Opens a template, as a click on its row does. */\n  activate: (templateId: string) => void;\n  /** Writes into a blank of the open template, as typing or picking does. */\n  fill: (fieldId: string, value: string) => void;\n  /** Shows Use prompt held down. */\n  press: () => void;\n  use: () => void;\n  /** Back to the first template, the first values and an empty search. */\n  reset: () => void;\n};\n\nexport type PromptTemplatesProps = {\n  templates: PromptTemplate[];\n  initialValues?: Record<string, TemplateValues>;\n  onUse: (prompt: string) => void;\n  /** Runs what the list and the editor do, for a demonstration or a control beside them. */\n  handleRef?: React.Ref<PromptTemplatesHandle>;\n  className?: string;\n};\n\nconst EDITOR_ARRIVAL = { duration: 0.2 };\n\nexport function PromptTemplates({\n  templates,\n  initialValues = {},\n  onUse,\n  handleRef,\n  className,\n}: PromptTemplatesProps) {\n  const firstId = templates[0]?.id ?? '';\n  const [activeId, setActiveId] = useState(firstId);\n  const [query, setQuery] = useState('');\n  const [values, setValues] =\n    useState<Record<string, TemplateValues>>(initialValues);\n  const editor = useRef<TemplateEditorHandle>(null);\n  const active = templates.find((template) => template.id === activeId);\n\n  function changeValue(fieldId: string, value: string) {\n    setValues((current) => {\n      const forTemplate = current[activeId] ?? {};\n      const nextForTemplate = { ...forTemplate, [fieldId]: value };\n      return { ...current, [activeId]: nextForTemplate };\n    });\n  }\n\n  function reset() {\n    setActiveId(firstId);\n    setQuery('');\n    setValues(initialValues);\n  }\n\n  useImperativeHandle(handleRef, () => ({\n    activate: setActiveId,\n    fill: changeValue,\n    press: () => editor.current?.press(),\n    use: () => editor.current?.use(),\n    reset,\n  }));\n\n  return (\n    <div className={cn('@container', className)}>\n      <div className='grid gap-4 @xl:grid-cols-[13rem_minmax(0,1fr)] @xl:gap-5'>\n        <TemplateList\n          templates={templates}\n          activeId={activeId}\n          onActivate={setActiveId}\n          query={query}\n          onQueryChange={setQuery}\n        />\n        <AnimatePresence initial={false}>\n          {active && (\n            <motion.div\n              key={active.id}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              transition={EDITOR_ARRIVAL}\n              className='min-w-0'\n            >\n              <TemplateEditor\n                template={active}\n                values={values[active.id] ?? {}}\n                onValueChange={changeValue}\n                onUse={onUse}\n                handleRef={editor}\n              />\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n\nconst TEMPLATES: PromptTemplate[] = [\n  {\n    id: 'follow-up',\n    title: 'Follow-up email',\n    parts: [\n      text('Write a '),\n      oneOf('tone', 'tone', ['friendly', 'formal', 'short']),\n      text(' follow-up to '),\n      blank('customer', 'the customer'),\n      text(' about '),\n      blank('topic', 'the topic'),\n      text('.'),\n      maybe('detail', 'a detail', ' Mention ', '.'),\n    ],\n  },\n  {\n    id: 'summary',\n    title: 'Summarize a document',\n    parts: [\n      text('Summarize '),\n      blank('document', 'the document'),\n      text(' for '),\n      oneOf('audience', 'reader', ['the team', 'a customer', 'an executive']),\n      text(' in '),\n      oneOf('length', 'length', ['3', '5', '10']),\n      text(' bullet points.'),\n      maybe('focus', 'a topic', ' Focus on ', '.'),\n    ],\n  },\n  {\n    id: 'triage',\n    title: 'Triage a bug report',\n    parts: [\n      text('Read the bug report from '),\n      blank('reporter', 'the reporter'),\n      text(' and rate it '),\n      oneOf('severity', 'severity', ['low', 'medium', 'high', 'critical']),\n      text('.'),\n      maybe('next', 'a next step', ' Suggest ', '.'),\n    ],\n  },\n  {\n    id: 'agenda',\n    title: 'Meeting agenda',\n    parts: [\n      text('Draft a '),\n      oneOf('duration', 'length', ['15 minute', '30 minute', 'one hour']),\n      text(' agenda for '),\n      blank('meeting', 'the meeting'),\n      text(' with '),\n      blank('people', 'the attendees'),\n      text('.'),\n      maybe('time', 'a topic', ' Leave time for ', '.'),\n    ],\n  },\n  {\n    id: 'release',\n    title: 'Release notes',\n    parts: [\n      text('Turn the changes in '),\n      blank('version', 'the version'),\n      text(' into release notes for '),\n      oneOf('readers', 'reader', [\n        'customers',\n        'the support team',\n        'developers',\n      ]),\n      text('.'),\n    ],\n  },\n];\n\nconst SEED_VALUES: Record<string, TemplateValues> = {\n  'follow-up': { tone: 'friendly', customer: 'Dana Ruiz' },\n  summary: { document: 'the Q3 vendor review', audience: 'an executive' },\n};\n\ntype DemoBlank = {\n  fieldId: string;\n  value: string;\n  /** A text is typed key by key, a choice is picked at once. */\n  isTyped: boolean;\n};\n\ntype DemoFill = {\n  templateId: string;\n  blanks: DemoBlank[];\n};\n\n/** A round opens one of these templates and fills its blanks, a different one each time. */\nconst DEMO_FILLS: DemoFill[] = [\n  {\n    templateId: 'triage',\n    blanks: [\n      { fieldId: 'reporter', value: 'Mina Okafor', isTyped: true },\n      { fieldId: 'severity', value: 'high', isTyped: false },\n      { fieldId: 'next', value: 'a rollback plan', isTyped: true },\n    ],\n  },\n  {\n    templateId: 'agenda',\n    blanks: [\n      { fieldId: 'duration', value: '30 minute', isTyped: false },\n      { fieldId: 'meeting', value: 'the launch review', isTyped: true },\n      { fieldId: 'people', value: 'Priya and Jonas', isTyped: true },\n    ],\n  },\n];\n\nexport default function Prompt07() {\n  const [message, setMessage] = useState('');\n  const [round, setRound] = useState(0);\n  const templates = useRef<PromptTemplatesHandle>(null);\n  const fill = DEMO_FILLS[round % DEMO_FILLS.length];\n\n  function use(prompt: string) {\n    setMessage(`Prompt placed in the composer: ${prompt}`);\n  }\n\n  function resetDemo() {\n    templates.current?.reset();\n    setMessage('');\n    setRound((current) => current + 1);\n  }\n\n  function stepsOfBlank(blank: DemoBlank): AutoplayStep[] {\n    if (!blank.isTyped) {\n      return [\n        {\n          after: 800,\n          run: () => templates.current?.fill(blank.fieldId, blank.value),\n        },\n      ];\n    }\n    return prefixesOf(blank.value).map((typed, index) => ({\n      after: keyDelayOf(index, 800, 55),\n      run: () => templates.current?.fill(blank.fieldId, typed),\n    }));\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 1600, run: () => templates.current?.activate(fill.templateId) },\n    ...fill.blanks.flatMap(stepsOfBlank),\n    { after: 900, run: () => templates.current?.press() },\n    { after: PRESS_LEAD_MS, run: () => templates.current?.use() },\n    { after: MORPH_HOLD_MS + DONE_HOLD_MS + 300, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2400,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='flex w-full max-w-[44rem] flex-col gap-3'>\n      <PromptTemplates\n        templates={TEMPLATES}\n        initialValues={SEED_VALUES}\n        onUse={use}\n        handleRef={templates}\n        className='bg-card hairline-ring ring-border rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n      />\n      <LiveRegion message={spokenUnless(isAutoplaying, message)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-07.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/marked.tsx",
      "content": "type TextPiece = { text: string; isMatch: boolean };\n\nexport function piecesOf(text: string, query: string): TextPiece[] {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return [{ text, isMatch: false }];\n  }\n  const haystack = text.toLowerCase();\n  const pieces: TextPiece[] = [];\n  let cursor = 0;\n  let found = haystack.indexOf(needle, cursor);\n  while (found >= 0) {\n    const before = text.slice(cursor, found);\n    const matchEnd = found + needle.length;\n    const match = text.slice(found, matchEnd);\n    if (before !== '') {\n      pieces.push({ text: before, isMatch: false });\n    }\n    pieces.push({ text: match, isMatch: true });\n    cursor = matchEnd;\n    found = haystack.indexOf(needle, cursor);\n  }\n  const rest = text.slice(cursor);\n  if (rest !== '') {\n    pieces.push({ text: rest, isMatch: false });\n  }\n  return pieces;\n}\n\nexport function includesQuery(text: string, query: string) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return true;\n  }\n  const haystack = text.toLowerCase();\n  return haystack.includes(needle);\n}\n\ntype MarkedProps = {\n  text: string;\n  query: string;\n};\n\nexport function Marked({ text, query }: MarkedProps) {\n  const pieces = piecesOf(text, query);\n\n  return (\n    <>\n      {pieces.map((piece, index) => {\n        if (piece.isMatch) {\n          return (\n            <mark\n              key={index}\n              className='bg-warning/25 text-foreground rounded-[3px] px-px'\n            >\n              {piece.text}\n            </mark>\n          );\n        }\n        return <span key={index}>{piece.text}</span>;\n      })}\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/_parts/marked.tsx"
    }
  ],
  "categories": [
    "components",
    "prompt"
  ],
  "type": "registry:component"
}