{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"helpful-prompt","type":"registry:component","title":"Helpful prompt","description":"Asks if the page helped, and on a no opens into a field right where the question was.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/helpful-prompt.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\ntype Step = \"ask\" | \"why\" | \"done\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// The pill reshapes around each step; a touch of bounce so it settles\n// rather than stops.\nconst RESHAPE = { type: \"spring\", duration: 0.45, bounce: 0.12 } as const;\nconst SWAP = { duration: 0.22, ease: EASE_OUT } as const;\n\nexport function HelpfulPrompt({\n  question = \"Was this helpful?\",\n  onAnswer,\n  demo,\n  className,\n}: {\n  question?: string;\n  // Fires with the answer and, for a \"no\", what was missing (may be empty).\n  onAnswer?: (helpful: boolean, note?: string) => void;\n  // Drives the steps from outside (the card preview) without touching focus.\n  demo?: { step: Step; note: string; helpful: boolean } | null;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [step, setStep] = useState<Step>(\"ask\");\n  const [helpful, setHelpful] = useState(true);\n  const [note, setNote] = useState(\"\");\n  const input = useRef<HTMLInputElement>(null);\n  const undo = useRef<HTMLButtonElement>(null);\n  const yes = useRef<HTMLButtonElement>(null);\n  // Focus follows the step, but only after a person acted, never on load.\n  const moveFocus = useRef<Step | null>(null);\n  const usingKeys = useRef(false);\n\n  const shown = demo ?? { step, note, helpful };\n\n  useEffect(() => {\n    const target = moveFocus.current;\n    moveFocus.current = null;\n    if (target === \"why\") input.current?.focus();\n    else if (target === \"done\") undo.current?.focus();\n    else if (target === \"ask\") yes.current?.focus();\n  }, [step]);\n\n  const go = (next: Step) => {\n    // Saying no always drops you into the field, ready to type. Other steps\n    // take focus only for keyboard users (typing counts), so a mouse click\n    // never leaves a ring behind.\n    if (next === \"why\" || usingKeys.current) {\n      moveFocus.current = next;\n    }\n    setStep(next);\n  };\n\n  const answerYes = () => {\n    setHelpful(true);\n    go(\"done\");\n    onAnswer?.(true);\n  };\n\n  const send = (e?: React.FormEvent) => {\n    e?.preventDefault();\n    if (!note.trim()) return;\n    setHelpful(false);\n    go(\"done\");\n    onAnswer?.(false, note.trim());\n  };\n\n  const t = reduceMotion ? { duration: 0 } : RESHAPE;\n  const swap = reduceMotion ? { duration: 0 } : SWAP;\n  const enter = {\n    initial: { opacity: 0, filter: \"blur(4px)\", scale: 0.98 },\n    animate: { opacity: 1, filter: \"blur(0px)\", scale: 1 },\n    exit: {\n      opacity: 0,\n      filter: \"blur(4px)\",\n      scale: 0.98,\n      transition: { duration: 0.12 },\n    },\n    transition: swap,\n  };\n\n  return (\n    <motion.div\n      layout\n      transition={t}\n      role=\"group\"\n      aria-label=\"Page feedback\"\n      onPointerDownCapture={() => (usingKeys.current = false)}\n      onKeyDownCapture={() => (usingKeys.current = true)}\n      // Radius set here so the reshaping keeps a true pill, never an oval.\n      style={{ borderRadius: 999 }}\n      className={cn(\n        \"relative flex h-12 items-center overflow-hidden bg-background shadow-raised\",\n        className,\n      )}\n    >\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        {shown.step === \"ask\" && (\n          <motion.div\n            key=\"ask\"\n            {...enter}\n            className=\"flex items-center gap-1 pr-1.5 pl-5\"\n          >\n            <span className=\"mr-2 text-[14px] whitespace-nowrap text-foreground\">\n              {question}\n            </span>\n            <Choice ref={yes} onClick={answerYes}>\n              Yes\n            </Choice>\n            <Choice onClick={() => go(\"why\")}>No</Choice>\n          </motion.div>\n        )}\n\n        {shown.step === \"why\" && (\n          <motion.form\n            key=\"why\"\n            {...enter}\n            onSubmit={send}\n            className=\"flex items-center gap-1 pr-1.5 pl-5\"\n          >\n            <label htmlFor=\"helpful-note\" className=\"sr-only\">\n              What was missing?\n            </label>\n            <input\n              ref={input}\n              id=\"helpful-note\"\n              value={shown.note}\n              onChange={(e) => setNote(e.target.value)}\n              onKeyDown={(e) => {\n                if (e.key === \"Escape\") go(\"ask\");\n              }}\n              placeholder=\"What was missing?\"\n              autoComplete=\"off\"\n              maxLength={200}\n              // 16px on phones: iOS zooms into any smaller input it focuses.\n              className=\"h-9 w-[min(14rem,48vw)] bg-transparent text-base text-foreground outline-hidden placeholder:text-muted-foreground sm:text-[14px]\"\n            />\n            <button\n              type=\"button\"\n              aria-label=\"Cancel\"\n              onClick={() => go(\"ask\")}\n              className=\"grid size-9 shrink-0 place-items-center rounded-full text-muted-foreground outline-hidden transition-[color,background-color,scale] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n            >\n              <svg\n                viewBox=\"0 0 16 16\"\n                className=\"size-3.5\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={1.7}\n                strokeLinecap=\"round\"\n                aria-hidden\n              >\n                <path d=\"M4.5 4.5l7 7M11.5 4.5l-7 7\" />\n              </svg>\n            </button>\n            <button\n              type=\"submit\"\n              aria-label=\"Send feedback\"\n              disabled={!shown.note.trim()}\n              className=\"grid size-9 shrink-0 place-items-center rounded-full bg-foreground text-background outline-hidden transition-[scale,opacity] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] disabled:opacity-25\"\n            >\n              <svg\n                viewBox=\"0 0 16 16\"\n                className=\"size-4\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={1.7}\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                aria-hidden\n              >\n                <path d=\"M8 12.5v-9M4 7l4-4 4 4\" />\n              </svg>\n            </button>\n          </motion.form>\n        )}\n\n        {shown.step === \"done\" && (\n          <motion.div\n            key=\"done\"\n            {...enter}\n            className=\"flex items-center gap-2 pr-1.5 pl-4\"\n          >\n            <svg\n              viewBox=\"0 0 16 16\"\n              className=\"size-4 shrink-0 text-foreground\"\n              fill=\"none\"\n              aria-hidden\n            >\n              <motion.path\n                d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n                stroke=\"currentColor\"\n                strokeWidth={1.8}\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                initial={{ pathLength: reduceMotion ? 1 : 0 }}\n                animate={{ pathLength: 1 }}\n                transition={{ duration: 0.35, delay: 0.1, ease: EASE_OUT }}\n              />\n            </svg>\n            <span className=\"text-[14px] whitespace-nowrap text-foreground\">\n              {shown.helpful ? \"Thanks, glad it helped\" : \"Thanks, noted\"}\n            </span>\n            <button\n              ref={undo}\n              type=\"button\"\n              onClick={() => {\n                setNote(\"\");\n                go(\"ask\");\n              }}\n              className=\"ml-1 h-9 rounded-full px-3 text-[13px] text-muted-foreground outline-hidden transition-[color,background-color,scale] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n            >\n              Undo\n            </button>\n          </motion.div>\n        )}\n      </AnimatePresence>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {shown.step === \"done\" ? \"Thanks for your feedback\" : \"\"}\n      </span>\n    </motion.div>\n  );\n}\n\nfunction Choice({\n  ref,\n  onClick,\n  children,\n}: {\n  ref?: React.Ref<HTMLButtonElement>;\n  onClick: () => void;\n  children: React.ReactNode;\n}) {\n  return (\n    <button\n      ref={ref}\n      type=\"button\"\n      onClick={onClick}\n      className=\"h-9 rounded-full bg-muted px-4 text-[14px] font-medium text-foreground outline-hidden transition-[background-color,scale] duration-150 ease-out hover:bg-foreground/10 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n    >\n      {children}\n    </button>\n  );\n}\n\n// The card's hover show: a reader says no, types what was missing, sends,\n// then another says yes.\nconst NOTE = \"An example with forms\";\n\nexport default function HelpfulPromptDemo() {\n  const play = usePreviewPlay();\n  const [demo, setDemo] = useState<{\n    step: Step;\n    note: string;\n    helpful: boolean;\n  } | null>(null);\n\n  useEffect(() => {\n    if (play !== true) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const at = (ms: number, fn: () => void) => timers.push(setTimeout(fn, ms));\n    const run = () => {\n      at(500, () => setDemo({ step: \"why\", note: \"\", helpful: false }));\n      for (let i = 1; i <= NOTE.length; i++) {\n        at(1000 + i * 45, () =>\n          setDemo({ step: \"why\", note: NOTE.slice(0, i), helpful: false }),\n        );\n      }\n      const sent = 1000 + NOTE.length * 45 + 450;\n      at(sent, () => setDemo({ step: \"done\", note: NOTE, helpful: false }));\n      at(sent + 1700, () => setDemo({ step: \"ask\", note: \"\", helpful: true }));\n      at(sent + 2500, () => setDemo({ step: \"done\", note: \"\", helpful: true }));\n      at(sent + 4300, () => {\n        setDemo({ step: \"ask\", note: \"\", helpful: true });\n        run();\n      });\n    };\n    run();\n    return () => {\n      timers.forEach(clearTimeout);\n      setDemo(null);\n    };\n  }, [play]);\n\n  return <HelpfulPrompt demo={play === true ? demo : null} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/helpful-prompt"}