{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "notes",
  "type": "registry:block",
  "title": "Notes",
  "description": "A notes app with folders, pinned notes that glide to the top, search that highlights matches as you type, and an editor where typing “[] ”, “- ” or “# ” turns a line into a checklist, bullet or heading.",
  "categories": [
    "screen",
    "Personal"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/input-group.json",
    "https://coss.com/ui/r/menu.json"
  ],
  "files": [
    {
      "path": "registry/devl/notes.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport {\n  ChevronDownIcon,\n  ChevronLeftIcon,\n  FolderIcon,\n  Heading1Icon,\n  Heading2Icon,\n  ListChecksIcon,\n  ListIcon,\n  NotebookPenIcon,\n  PilcrowIcon,\n  PinIcon,\n  RotateCcwIcon,\n  SearchIcon,\n  SquarePenIcon,\n  Trash2Icon,\n  Undo2Icon,\n  XIcon,\n} from \"lucide-react\";\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type ReactNode,\n  type TextareaHTMLAttributes,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { Button } from \"@/components/ui/button\";\nimport { InputGroup, InputGroupAddon, InputGroupInput } from \"@/components/ui/input-group\";\nimport {\n  Menu,\n  MenuGroup,\n  MenuGroupLabel,\n  MenuItem,\n  MenuPopup,\n  MenuRadioGroup,\n  MenuRadioItem,\n  MenuTrigger,\n} from \"@/components/ui/menu\";\n\nfunction useReducedMotionSafe() {\n  const prefers = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && Boolean(prefers);\n}\n\nexport type NoteBlockType = \"h1\" | \"h2\" | \"p\" | \"todo\" | \"bullet\";\n\nexport interface NoteBlock {\n  id: string;\n  type: NoteBlockType;\n  text: string;\n  done?: boolean;\n}\n\nexport type NoteFolderTone = \"amber\" | \"sky\" | \"rose\" | \"emerald\" | \"violet\";\n\nexport interface NoteFolder {\n  id: string;\n  name: string;\n  tone: NoteFolderTone;\n}\n\nexport interface Note {\n  id: string;\n  title: string;\n  folderId: string;\n  updatedAt: string;\n  pinned?: boolean;\n  deleted?: boolean;\n  blocks: NoteBlock[];\n}\n\nexport interface NotesProps {\n  className?: string;\n  folders?: NoteFolder[];\n  notes?: Note[];\n  now?: string;\n  initialNoteId?: string;\n}\n\nconst easeOut = [0.23, 1, 0.32, 1] as const;\nconst spring = { type: \"spring\", stiffness: 520, damping: 46, mass: 1 } as const;\nconst press = \"transition-[color,background-color,box-shadow,scale] duration-150 ease-out active:scale-[0.97]\";\nconst ring = \"outline-none focus-visible:ring-2 focus-visible:ring-ring\";\nconst menuPop =\n  \"transition-[opacity,scale] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] data-starting-style:scale-95 data-starting-style:opacity-0 data-ending-style:scale-95 data-ending-style:opacity-0 data-ending-style:duration-100\";\n\nconst tones: Record<NoteFolderTone, string> = {\n  amber: \"bg-amber-500 dark:bg-amber-400\",\n  sky: \"bg-sky-500 dark:bg-sky-400\",\n  rose: \"bg-rose-500 dark:bg-rose-400\",\n  emerald: \"bg-emerald-500 dark:bg-emerald-400\",\n  violet: \"bg-violet-500 dark:bg-violet-400\",\n};\n\nconst defaultFolders: NoteFolder[] = [\n  { id: \"personal\", name: \"Personal\", tone: \"amber\" },\n  { id: \"work\", name: \"Work\", tone: \"sky\" },\n  { id: \"recipes\", name: \"Recipes\", tone: \"rose\" },\n  { id: \"travel\", name: \"Travel\", tone: \"emerald\" },\n];\n\nlet seed = 0;\nconst b = (type: NoteBlockType, text: string, done?: boolean): NoteBlock => ({ id: `b${++seed}`, type, text, done });\n\nconst defaultNotes: Note[] = [\n  {\n    id: \"n1\",\n    title: \"Lisbon in May\",\n    folderId: \"travel\",\n    updatedAt: \"2026-10-24T09:41:00\",\n    pinned: true,\n    blocks: [\n      b(\"p\", \"Five nights, flying in on the 14th. Staying in Príncipe Real, ten minutes up the hill from Bairro Alto.\"),\n      b(\"h2\", \"Before we go\"),\n      b(\"todo\", \"Renew passport\", true),\n      b(\"todo\", \"Book the 28 tram early, before the queues\", true),\n      b(\"todo\", \"Pack a travel adapter (type F)\"),\n      b(\"todo\", \"Download offline maps for Sintra\"),\n      b(\"h2\", \"Eat\"),\n      b(\"bullet\", \"Custard tarts warm from the oven, first morning\"),\n      b(\"bullet\", \"Grilled sardines somewhere in Alfama\"),\n      b(\"bullet\", \"Ask Rui for the tasca with no sign on the door\"),\n      b(\"h2\", \"Maybe\"),\n      b(\"p\", \"Day trip to Cascais if the weather holds. Train from Cais do Sodré, 40 minutes.\"),\n    ],\n  },\n  {\n    id: \"n2\",\n    title: \"Q4 planning\",\n    folderId: \"work\",\n    updatedAt: \"2026-10-23T16:20:00\",\n    pinned: true,\n    blocks: [\n      b(\"p\", \"Three bets for the quarter. Everything else waits for January.\"),\n      b(\"h2\", \"Bets\"),\n      b(\"bullet\", \"Self-serve onboarding: cut time to first project under 5 minutes\"),\n      b(\"bullet\", \"Usage-based billing for teams over 50 seats\"),\n      b(\"bullet\", \"Kill the legacy export pipeline\"),\n      b(\"h2\", \"Owners\"),\n      b(\"todo\", \"Confirm onboarding owner with Mara\", true),\n      b(\"todo\", \"Draft billing RFC by Nov 3\"),\n      b(\"todo\", \"Get export deprecation date into the changelog\"),\n    ],\n  },\n  {\n    id: \"n3\",\n    title: \"Weekend sourdough\",\n    folderId: \"recipes\",\n    updatedAt: \"2026-10-22T08:05:00\",\n    blocks: [\n      b(\"p\", \"500g flour (80% bread, 20% whole wheat), 375g water, 100g starter, 10g salt.\"),\n      b(\"h2\", \"Schedule\"),\n      b(\"todo\", \"Fri 9pm: feed starter\", true),\n      b(\"todo\", \"Sat 9am: mix, rest 1 hour\", true),\n      b(\"todo\", \"Sat 10am to 2pm: four sets of folds\", true),\n      b(\"todo\", \"Shape, then cold proof overnight\"),\n      b(\"todo\", \"Sun 8am: bake 250°C, 20 min lid on, 25 off\"),\n    ],\n  },\n  {\n    id: \"n4\",\n    title: \"1:1 with Mara\",\n    folderId: \"work\",\n    updatedAt: \"2026-10-21T11:30:00\",\n    blocks: [\n      b(\"h2\", \"Her topics\"),\n      b(\"bullet\", \"Wants more ownership of the design system\"),\n      b(\"bullet\", \"Feeling stretched across two squads\"),\n      b(\"h2\", \"Mine\"),\n      b(\"bullet\", \"Promo packet timeline: draft due before the end of the month\"),\n      b(\"todo\", \"Move her off the billing squad after the RFC lands\"),\n    ],\n  },\n  {\n    id: \"n5\",\n    title: \"Gift ideas\",\n    folderId: \"personal\",\n    updatedAt: \"2026-10-18T19:12:00\",\n    blocks: [\n      b(\"todo\", \"Dad: the hiking poles he keeps borrowing\"),\n      b(\"todo\", \"Ines: pottery class voucher\", true),\n      b(\"todo\", \"Sam: that out-of-print photo book (check secondhand)\"),\n      b(\"p\", \"Budget around €60 each. Order before Dec 10 for shipping.\"),\n    ],\n  },\n  {\n    id: \"n6\",\n    title: \"Reading list\",\n    folderId: \"personal\",\n    updatedAt: \"2026-10-12T22:40:00\",\n    blocks: [\n      b(\"p\", \"Slowly working through the pile on the nightstand.\"),\n      b(\"bullet\", \"The one about lighthouse keepers Jo recommended\"),\n      b(\"bullet\", \"Something short and funny for the flight\"),\n      b(\"bullet\", \"Finish the essay collection (stuck on chapter 6)\"),\n    ],\n  },\n  {\n    id: \"n7\",\n    title: \"Apartment move\",\n    folderId: \"personal\",\n    updatedAt: \"2026-09-30T10:00:00\",\n    blocks: [\n      b(\"todo\", \"Give notice to landlord\", true),\n      b(\"todo\", \"Book van for the 2nd\", true),\n      b(\"todo\", \"Forward mail\"),\n      b(\"todo\", \"Measure the alcove for the bookshelf\"),\n    ],\n  },\n];\n\nfunction relDate(iso: string, nowIso: string) {\n  const d = new Date(iso);\n  const now = new Date(nowIso);\n  const day = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();\n  const diff = Math.round((day(now) - day(d)) / 86400000);\n  const hm = `${d.getHours() % 12 || 12}:${String(d.getMinutes()).padStart(2, \"0\")} ${d.getHours() < 12 ? \"AM\" : \"PM\"}`;\n  if (diff <= 0) return { short: hm, long: `today at ${hm}` };\n  if (diff === 1) return { short: \"Yesterday\", long: `yesterday at ${hm}` };\n  if (diff < 7) {\n    const wd = d.toLocaleDateString(\"en-US\", { weekday: \"long\" });\n    return { short: wd, long: `${wd} at ${hm}` };\n  }\n  const md = d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" });\n  return { short: md, long: md };\n}\n\nfunction preview(n: Note) {\n  return n.blocks\n    .filter((x) => x.text.trim())\n    .map((x) => x.text)\n    .join(\" · \");\n}\n\nfunction todoStats(n: Note) {\n  const todos = n.blocks.filter((x) => x.type === \"todo\");\n  return { done: todos.filter((x) => x.done).length, total: todos.length };\n}\n\nfunction Highlight({ text, query }: { text: string; query: string }) {\n  const q = query.trim();\n  if (!q) return <>{text}</>;\n  const i = text.toLowerCase().indexOf(q.toLowerCase());\n  if (i < 0) return <>{text}</>;\n  return (\n    <>\n      {text.slice(0, i)}\n      <mark className=\"rounded-[calc(var(--radius)*0.3)] bg-warning/30 text-foreground\">{text.slice(i, i + q.length)}</mark>\n      {text.slice(i + q.length)}\n    </>\n  );\n}\n\nfunction excerpt(text: string, query: string) {\n  const q = query.trim().toLowerCase();\n  if (!q) return text;\n  const i = text.toLowerCase().indexOf(q);\n  if (i < 30) return text;\n  const from = text.lastIndexOf(\" \", i - 16);\n  return `…${text.slice(from > 0 ? from + 1 : i - 16)}`;\n}\n\nfunction ProgressRing({ done, total }: { done: number; total: number }) {\n  const r = 5.5;\n  const c = 2 * Math.PI * r;\n  const reduce = useReducedMotionSafe();\n  return (\n    <svg aria-hidden className=\"size-3.5 -rotate-90\" viewBox=\"0 0 14 14\">\n      <circle className=\"fill-none stroke-border\" cx=\"7\" cy=\"7\" r={r} strokeWidth=\"2\" />\n      <motion.circle\n        animate={{ strokeDashoffset: c * (1 - done / Math.max(1, total)) }}\n        className={cn(\"fill-none\", done === total ? \"stroke-success\" : \"stroke-foreground/70\")}\n        cx=\"7\"\n        cy=\"7\"\n        initial={false}\n        r={r}\n        strokeDasharray={c}\n        strokeLinecap=\"round\"\n        strokeWidth=\"2\"\n        transition={reduce ? { duration: 0 } : { duration: 0.35, ease: easeOut }}\n      />\n    </svg>\n  );\n}\n\nfunction AutoText({\n  value,\n  className,\n  inputRef,\n  ...props\n}: TextareaHTMLAttributes<HTMLTextAreaElement> & { value: string; inputRef?: (el: HTMLTextAreaElement | null) => void }) {\n  const local = useRef<HTMLTextAreaElement | null>(null);\n  useLayoutEffect(() => {\n    const el = local.current;\n    if (!el || (typeof CSS !== \"undefined\" && CSS.supports(\"field-sizing\", \"content\"))) return;\n    el.style.height = \"auto\";\n    el.style.height = `${el.scrollHeight}px`;\n  }, [value]);\n  return (\n    <textarea\n      className={cn(\n        \"block w-full resize-none overflow-hidden bg-transparent outline-none [field-sizing:content] placeholder:text-muted-foreground/60\",\n        className,\n      )}\n      ref={(el) => {\n        local.current = el;\n        inputRef?.(el);\n      }}\n      rows={1}\n      value={value}\n      {...props}\n    />\n  );\n}\n\nfunction CheckBox({ checked, onToggle, label }: { checked: boolean; onToggle: () => void; label: string }) {\n  const reduce = useReducedMotionSafe();\n  return (\n    <button\n      aria-checked={checked}\n      aria-label={label}\n      className={cn(\n        \"relative mt-[5px] flex size-4.5 shrink-0 cursor-pointer items-center justify-center rounded-[calc(var(--radius)*0.5)] border transition-[background-color,border-color,scale] duration-150 ease-out after:absolute after:-inset-2.5 after:content-[''] active:scale-[0.92]\",\n        ring,\n        \"focus-visible:ring-offset-1 focus-visible:ring-offset-background\",\n        checked ? \"border-primary bg-primary text-primary-foreground\" : \"border-input bg-background hover:border-foreground/40 dark:bg-input/32\",\n      )}\n      onClick={onToggle}\n      role=\"checkbox\"\n      type=\"button\"\n    >\n      <svg aria-hidden className=\"size-3\" fill=\"none\" viewBox=\"0 0 12 12\">\n        <motion.path\n          animate={{ pathLength: checked ? 1 : 0, opacity: checked ? 1 : 0 }}\n          d=\"M2.5 6.2 5 8.6l4.5-5\"\n          initial={false}\n          stroke=\"currentColor\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          strokeWidth=\"1.8\"\n          transition={reduce ? { duration: 0 } : { duration: 0.18, ease: easeOut }}\n        />\n      </svg>\n    </button>\n  );\n}\n\nconst blockStyles: Record<NoteBlockType, string> = {\n  h1: \"font-heading font-semibold text-xl leading-8 tracking-tight\",\n  h2: \"font-heading font-semibold text-base leading-7 tracking-tight\",\n  p: \"text-[15px] leading-7\",\n  todo: \"text-[15px] leading-7\",\n  bullet: \"text-[15px] leading-7\",\n};\n\nconst blockTypes: { value: NoteBlockType; label: string; icon: ReactNode }[] = [\n  { value: \"h1\", label: \"Heading\", icon: <Heading1Icon /> },\n  { value: \"h2\", label: \"Subheading\", icon: <Heading2Icon /> },\n  { value: \"p\", label: \"Text\", icon: <PilcrowIcon /> },\n  { value: \"todo\", label: \"Checklist\", icon: <ListChecksIcon /> },\n  { value: \"bullet\", label: \"Bullets\", icon: <ListIcon /> },\n];\n\ntype Pending = { id: string; at: \"start\" | \"end\" } | null;\n\nexport function Notes({\n  className,\n  folders = defaultFolders,\n  notes: initialNotes = defaultNotes,\n  now = \"2026-10-24T10:00:00\",\n  initialNoteId = \"n1\",\n}: NotesProps) {\n  const reduce = useReducedMotionSafe();\n  const [notes, setNotes] = useState(initialNotes);\n  const [folder, setFolder] = useState<string>(\"all\");\n  const [selectedId, setSelectedId] = useState<string | null>(initialNoteId);\n  const [query, setQuery] = useState(\"\");\n  const [focusedBlock, setFocusedBlock] = useState<string | null>(null);\n  const [view, setView] = useState<\"list\" | \"editor\">(\"list\");\n  const [undo, setUndo] = useState<{ id: string } | null>(null);\n  const [pending, setPending] = useState<Pending>(null);\n  const blockRefs = useRef(new Map<string, HTMLTextAreaElement>());\n  const titleRef = useRef<HTMLTextAreaElement | null>(null);\n  const counter = useRef(0);\n  const mountedAt = useRef(0);\n  useEffect(() => {\n    mountedAt.current = Date.now();\n  }, []);\n  const uid = (p: string) => {\n    counter.current += 1;\n    return `${p}${Date.now().toString(36)}${counter.current}`;\n  };\n\n  useEffect(() => {\n    if (!pending) return;\n    const el = pending.id === \"title\" ? titleRef.current : blockRefs.current.get(pending.id);\n    if (el) {\n      el.focus();\n      const pos = pending.at === \"end\" ? el.value.length : 0;\n      el.setSelectionRange(pos, pos);\n    }\n    setPending(null);\n  }, [pending]);\n\n  useEffect(() => {\n    if (!undo) return;\n    const t = setTimeout(() => setUndo(null), 6000);\n    return () => clearTimeout(t);\n  }, [undo]);\n\n  const live = notes.filter((n) => !n.deleted);\n  const inFolder = (n: Note) => (folder === \"trash\" ? n.deleted : !n.deleted && (folder === \"all\" || n.folderId === folder));\n  const q = query.trim().toLowerCase();\n  const matches = (n: Note) => !q || n.title.toLowerCase().includes(q) || preview(n).toLowerCase().includes(q);\n  const visible = notes\n    .filter((n) => inFolder(n) && matches(n))\n    .sort((a, b2) => b2.updatedAt.localeCompare(a.updatedAt));\n  const pinned = folder === \"trash\" ? [] : visible.filter((n) => n.pinned);\n  const rest = folder === \"trash\" ? visible : visible.filter((n) => !n.pinned);\n  const note = notes.find((n) => n.id === selectedId) ?? null;\n  const folderName = (id: string) =>\n    id === \"all\" ? \"All notes\" : id === \"trash\" ? \"Recently deleted\" : (folders.find((f) => f.id === id)?.name ?? \"Notes\");\n\n  const touch = (id: string, patch: (n: Note) => Partial<Note>) =>\n    setNotes((all) => all.map((n) => (n.id === id ? { ...n, ...patch(n), updatedAt: stamp() } : n)));\n  const stamp = () => {\n    const d = new Date(new Date(now).getTime() + (Date.now() - mountedAt.current));\n    const pad = (x: number) => String(x).padStart(2, \"0\");\n    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:00`;\n  };\n\n  const setBlocks = (fn: (blocks: NoteBlock[]) => NoteBlock[]) => {\n    if (!note) return;\n    touch(note.id, (n) => ({ blocks: fn(n.blocks) }));\n  };\n  const patchBlock = (id: string, patch: Partial<NoteBlock>) =>\n    setBlocks((bs) => bs.map((x) => (x.id === id ? { ...x, ...patch } : x)));\n\n  const open = (id: string) => {\n    setSelectedId(id);\n    setView(\"editor\");\n  };\n\n  const newNote = () => {\n    const id = uid(\"n\");\n    const folderId = folder === \"all\" || folder === \"trash\" ? (folders[0]?.id ?? \"personal\") : folder;\n    setNotes((all) => [{ id, title: \"\", folderId, updatedAt: stamp(), blocks: [{ id: uid(\"b\"), type: \"p\", text: \"\" }] }, ...all]);\n    if (folder === \"trash\") setFolder(\"all\");\n    setQuery(\"\");\n    setSelectedId(id);\n    setView(\"editor\");\n    setPending({ id: \"title\", at: \"end\" });\n  };\n\n  const removeNote = (id: string) => {\n    setNotes((all) => all.map((n) => (n.id === id ? { ...n, deleted: true, pinned: false } : n)));\n    setUndo({ id });\n    const next = visible.filter((n) => n.id !== id)[0];\n    setSelectedId(next?.id ?? null);\n    setView(\"list\");\n  };\n\n  const restore = (id: string) => {\n    setNotes((all) => all.map((n) => (n.id === id ? { ...n, deleted: false } : n)));\n    setUndo(null);\n  };\n\n  const convert = (id: string, type: NoteBlockType) => {\n    patchBlock(id, { type, done: type === \"todo\" ? false : undefined });\n    setPending({ id, at: \"end\" });\n  };\n\n  const onBlockKey = (e: KeyboardEvent<HTMLTextAreaElement>, block: NoteBlock, index: number) => {\n    if (!note) return;\n    const el = e.currentTarget;\n    if (e.key === \"Enter\" && !e.shiftKey) {\n      e.preventDefault();\n      const listy = block.type === \"todo\" || block.type === \"bullet\";\n      if (listy && !block.text.trim()) {\n        convert(block.id, \"p\");\n        return;\n      }\n      const before = block.text.slice(0, el.selectionStart);\n      const after = block.text.slice(el.selectionEnd);\n      const id = uid(\"b\");\n      const type: NoteBlockType = listy ? block.type : \"p\";\n      setBlocks((bs) => {\n        const copy = bs.map((x) => (x.id === block.id ? { ...x, text: before } : x));\n        copy.splice(index + 1, 0, { id, type, text: after, done: type === \"todo\" ? false : undefined });\n        return copy;\n      });\n      setPending({ id, at: \"start\" });\n    } else if (e.key === \"Backspace\" && el.selectionStart === 0 && el.selectionEnd === 0) {\n      if (block.type !== \"p\") {\n        e.preventDefault();\n        convert(block.id, \"p\");\n        return;\n      }\n      if (index === 0) {\n        if (!block.text) {\n          e.preventDefault();\n          setPending({ id: \"title\", at: \"end\" });\n        }\n        return;\n      }\n      e.preventDefault();\n      const prev = note.blocks[index - 1];\n      const caret = prev.text.length;\n      setBlocks((bs) => bs.filter((x) => x.id !== block.id).map((x) => (x.id === prev.id ? { ...x, text: x.text + block.text } : x)));\n      requestAnimationFrame(() => {\n        const p = blockRefs.current.get(prev.id);\n        if (p) {\n          p.focus();\n          p.setSelectionRange(caret, caret);\n        }\n      });\n    } else if (e.key === \"ArrowUp\" && el.selectionStart === 0 && index > 0) {\n      e.preventDefault();\n      setPending({ id: note.blocks[index - 1].id, at: \"end\" });\n    } else if (e.key === \"ArrowDown\" && el.selectionStart === el.value.length && index < note.blocks.length - 1) {\n      e.preventDefault();\n      setPending({ id: note.blocks[index + 1].id, at: \"start\" });\n    }\n  };\n\n  const onBlockChange = (block: NoteBlock, text: string) => {\n    const shortcuts: [string, NoteBlockType][] = [\n      [\"## \", \"h2\"],\n      [\"# \", \"h1\"],\n      [\"- \", \"bullet\"],\n      [\"* \", \"bullet\"],\n      [\"[] \", \"todo\"],\n      [\"[ ] \", \"todo\"],\n    ];\n    if (block.type === \"p\") {\n      const hit = shortcuts.find(([s]) => text.startsWith(s));\n      if (hit) {\n        patchBlock(block.id, { type: hit[1], text: text.slice(hit[0].length), done: hit[1] === \"todo\" ? false : undefined });\n        return;\n      }\n    }\n    patchBlock(block.id, { text });\n  };\n\n  const focusedType = note?.blocks.find((x) => x.id === focusedBlock)?.type;\n  const stats = note ? todoStats(note) : { done: 0, total: 0 };\n  const words = note ? `${note.title} ${preview(note)}`.split(/\\s+/).filter((w) => /\\w/.test(w)).length : 0;\n\n  const folderList = (\n    <nav aria-label=\"Folders\" className=\"flex flex-col gap-0.5\">\n      {[\n        { id: \"all\", name: \"All notes\", icon: <NotebookPenIcon />, count: live.length },\n        ...folders.map((f) => ({\n          id: f.id,\n          name: f.name,\n          icon: <span className={cn(\"size-2 rounded-full\", tones[f.tone])} />,\n          count: live.filter((n) => n.folderId === f.id).length,\n        })),\n        { id: \"trash\", name: \"Recently deleted\", icon: <Trash2Icon />, count: notes.length - live.length },\n      ].map((f) => {\n        const active = folder === f.id;\n        return (\n          <button\n            aria-current={active ? \"page\" : undefined}\n            className={cn(\n              \"relative flex h-8 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-left [&_svg]:size-4 [&_svg]:opacity-80\",\n              ring,\n              press,\n              active ? \"font-medium text-foreground\" : \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n              f.id === \"trash\" && \"mt-3\",\n            )}\n            key={f.id}\n            onClick={() => {\n              setFolder(f.id);\n              setQuery(\"\");\n            }}\n            type=\"button\"\n          >\n            {active && (\n              <motion.span\n                className=\"absolute inset-0 -z-10 rounded-lg bg-accent\"\n                layoutId=\"notes-folder\"\n                transition={reduce ? { duration: 0 } : spring}\n              />\n            )}\n            <span className=\"flex size-4 items-center justify-center\">{f.icon}</span>\n            <span className=\"flex-1 truncate\">{f.name}</span>\n            <span className=\"text-muted-foreground text-xs tabular-nums\">{f.count}</span>\n          </button>\n        );\n      })}\n    </nav>\n  );\n\n  const noteRow = (n: Note) => {\n    const s = todoStats(n);\n    const date = relDate(n.updatedAt, now);\n    const active = n.id === selectedId;\n    const f = folders.find((x) => x.id === n.folderId);\n    return (\n      <motion.li\n        exit={{ opacity: 0, transition: { duration: 0.12 } }}\n        initial={false}\n        key={n.id}\n        layout={reduce ? false : \"position\"}\n        layoutId={`note-${n.id}`}\n        transition={spring}\n      >\n        <button\n          aria-current={active || undefined}\n          className={cn(\n            \"group/note relative flex w-full cursor-pointer flex-col gap-1 rounded-xl px-3 py-2.5 text-left transition-colors\",\n            ring,\n            active ? \"bg-accent\" : \"hover:bg-accent/50\",\n          )}\n          onClick={() => open(n.id)}\n          type=\"button\"\n        >\n          <span className=\"flex items-center gap-2\">\n            <span className={cn(\"min-w-0 flex-1 truncate font-medium\", !n.title && \"text-muted-foreground\")}>\n              <Highlight query={query} text={n.title || \"New note\"} />\n            </span>\n            {s.total > 0 && (\n              <span className=\"flex shrink-0 items-center gap-1 text-muted-foreground text-xs tabular-nums\">\n                <ProgressRing done={s.done} total={s.total} />\n                {s.done}/{s.total}\n              </span>\n            )}\n          </span>\n          <span className=\"line-clamp-2 text-muted-foreground text-xs leading-5\">\n            <span className=\"me-1.5 font-medium text-foreground/80 tabular-nums\">{date.short}</span>\n            <Highlight query={query} text={excerpt(preview(n), query) || \"No additional text\"} />\n          </span>\n          {folder === \"all\" && f && (\n            <span className=\"flex items-center gap-1.5 text-muted-foreground text-xs\">\n              <span className={cn(\"size-1.5 rounded-full\", tones[f.tone])} />\n              {f.name}\n            </span>\n          )}\n        </button>\n      </motion.li>\n    );\n  };\n\n  const emptyList = q ? (\n    <div className=\"flex flex-col items-center gap-3 px-6 py-16 text-center\">\n      <span className=\"flex size-10 items-center justify-center rounded-xl bg-muted text-muted-foreground\">\n        <SearchIcon className=\"size-4.5\" />\n      </span>\n      <div className=\"flex flex-col gap-1\">\n        <span className=\"text-balance font-medium\">No notes match “{query.trim()}”</span>\n        <span className=\"text-muted-foreground text-xs\">Searching {folderName(folder).toLowerCase()}.</span>\n      </div>\n      {folder !== \"all\" && (\n        <Button className={press} onClick={() => setFolder(\"all\")} size=\"sm\" variant=\"outline\">\n          Search all notes\n        </Button>\n      )}\n    </div>\n  ) : (\n    <div className=\"flex flex-col items-center gap-3 px-6 py-16 text-center\">\n      <span className=\"flex size-10 items-center justify-center rounded-xl bg-muted text-muted-foreground\">\n        {folder === \"trash\" ? <Trash2Icon className=\"size-4.5\" /> : <FolderIcon className=\"size-4.5\" />}\n      </span>\n      <div className=\"flex flex-col gap-1\">\n        <span className=\"font-medium\">{folder === \"trash\" ? \"Nothing deleted\" : \"No notes here yet\"}</span>\n        <span className=\"text-pretty text-muted-foreground text-xs\">\n          {folder === \"trash\" ? \"Deleted notes stay here until you restore them.\" : \"Start one and it'll show up here.\"}\n        </span>\n      </div>\n      {folder !== \"trash\" && (\n        <Button className={press} onClick={newNote} size=\"sm\" variant=\"outline\">\n          <SquarePenIcon /> New note\n        </Button>\n      )}\n    </div>\n  );\n\n  return (\n    <div className={cn(\"@container relative isolate flex h-[760px] w-full overflow-hidden bg-background text-foreground text-sm\", className)}>\n      <aside className=\"hidden w-56 shrink-0 flex-col gap-5 border-r bg-muted/40 p-3 @5xl:flex\">\n        <div className=\"flex items-center gap-2.5 px-1.5 pt-1\">\n          <span className=\"flex size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground\">\n            <NotebookPenIcon className=\"size-4\" />\n          </span>\n          <span className=\"font-heading font-semibold\">Notes</span>\n        </div>\n        {folderList}\n      </aside>\n\n      <section\n        aria-label=\"Notes\"\n        className={cn(\"min-w-0 flex-1 flex-col border-r @3xl:flex @3xl:w-80 @3xl:flex-none\", view === \"list\" ? \"flex\" : \"hidden\")}\n      >\n        <div className=\"flex h-14 shrink-0 items-center gap-2 px-3\">\n          <Menu>\n            <MenuTrigger\n              className={cn(\"flex h-8 min-w-0 cursor-pointer items-center gap-1.5 rounded-lg px-2 font-heading font-semibold text-base hover:bg-accent data-popup-open:bg-accent @5xl:pointer-events-none @5xl:px-1\", ring)}\n            >\n              <span className=\"truncate\">{folderName(folder)}</span>\n              <ChevronDownIcon className=\"size-4 shrink-0 text-muted-foreground @5xl:hidden\" />\n            </MenuTrigger>\n            <MenuPopup align=\"start\" className={cn(\"w-56\", menuPop)}>\n              <MenuRadioGroup onValueChange={(v) => setFolder(v as string)} value={folder}>\n                <MenuRadioItem value=\"all\">All notes</MenuRadioItem>\n                {folders.map((f) => (\n                  <MenuRadioItem key={f.id} value={f.id}>\n                    <span className=\"flex items-center gap-2\">\n                      <span className={cn(\"size-2 rounded-full\", tones[f.tone])} />\n                      {f.name}\n                    </span>\n                  </MenuRadioItem>\n                ))}\n                <MenuRadioItem value=\"trash\">Recently deleted</MenuRadioItem>\n              </MenuRadioGroup>\n            </MenuPopup>\n          </Menu>\n          <span className=\"text-muted-foreground text-xs tabular-nums\">{visible.length}</span>\n          <Button aria-label=\"New note\" className={cn(\"ms-auto\", press)} onClick={newNote} size=\"icon-sm\" variant=\"ghost\">\n            <SquarePenIcon />\n          </Button>\n        </div>\n        <div className=\"px-3 pb-2\">\n          <InputGroup>\n            <InputGroupAddon>\n              <SearchIcon />\n            </InputGroupAddon>\n            <InputGroupInput\n              aria-label=\"Search notes\"\n              onChange={(e) => setQuery(e.target.value)}\n              onKeyDown={(e) => {\n                if (e.key === \"Escape\") setQuery(\"\");\n              }}\n              placeholder=\"Search\"\n              value={query}\n            />\n            {query && (\n              <InputGroupAddon align=\"inline-end\">\n                <Button aria-label=\"Clear search\" onClick={() => setQuery(\"\")} size=\"icon-xs\" variant=\"ghost\">\n                  <XIcon />\n                </Button>\n              </InputGroupAddon>\n            )}\n          </InputGroup>\n        </div>\n        <div className=\"min-h-0 flex-1 overflow-y-auto px-2 pb-6\">\n          {visible.length === 0 ? (\n            emptyList\n          ) : (\n            <LayoutGroup id=\"notes-list\">\n              {pinned.length > 0 && (\n                <>\n                  <h3 className=\"flex items-center gap-1.5 px-3 pt-2 pb-1 font-medium text-muted-foreground text-xs\">\n                    <PinIcon className=\"size-3\" /> Pinned\n                  </h3>\n                  <ul className=\"flex flex-col gap-0.5\">\n                    <AnimatePresence initial={false}>{pinned.map(noteRow)}</AnimatePresence>\n                  </ul>\n                </>\n              )}\n              {rest.length > 0 && (\n                <>\n                  {pinned.length > 0 && <h3 className=\"px-3 pt-4 pb-1 font-medium text-muted-foreground text-xs\">Notes</h3>}\n                  <ul className=\"flex flex-col gap-0.5\">\n                    <AnimatePresence initial={false}>{rest.map(noteRow)}</AnimatePresence>\n                  </ul>\n                </>\n              )}\n            </LayoutGroup>\n          )}\n        </div>\n      </section>\n\n      <section aria-label=\"Editor\" className={cn(\"min-w-0 flex-1 flex-col @3xl:flex\", view === \"editor\" ? \"flex\" : \"hidden\")}>\n        {note ? (\n          <>\n            <div className=\"flex h-14 shrink-0 items-center gap-1 px-3\">\n              <Button className=\"-ms-1 @3xl:hidden\" onClick={() => setView(\"list\")} size=\"sm\" variant=\"ghost\">\n                <ChevronLeftIcon /> {folderName(folder)}\n              </Button>\n              <div className=\"hidden min-w-0 items-center gap-1.5 text-muted-foreground text-xs @3xl:flex\">\n                {note.deleted ? (\n                  <span>In Recently deleted</span>\n                ) : (\n                  <Menu>\n                    <MenuTrigger className={cn(\"flex h-7 cursor-pointer items-center gap-1.5 rounded-md px-1.5 hover:bg-accent hover:text-foreground data-popup-open:bg-accent\", ring)}>\n                      <span className={cn(\"size-1.5 rounded-full\", tones[folders.find((f) => f.id === note.folderId)?.tone ?? \"amber\"])} />\n                      {folderName(note.folderId)}\n                      <ChevronDownIcon className=\"size-3.5\" />\n                    </MenuTrigger>\n                    <MenuPopup align=\"start\" className={cn(\"w-48\", menuPop)}>\n                      <MenuGroup>\n                        <MenuGroupLabel>Move to</MenuGroupLabel>\n                        <MenuRadioGroup onValueChange={(v) => touch(note.id, () => ({ folderId: v as string }))} value={note.folderId}>\n                          {folders.map((f) => (\n                            <MenuRadioItem key={f.id} value={f.id}>\n                              <span className=\"flex items-center gap-2\">\n                                <span className={cn(\"size-2 rounded-full\", tones[f.tone])} />\n                                {f.name}\n                              </span>\n                            </MenuRadioItem>\n                          ))}\n                        </MenuRadioGroup>\n                      </MenuGroup>\n                    </MenuPopup>\n                  </Menu>\n                )}\n                <span aria-hidden>·</span>\n                <span className=\"truncate tabular-nums\">Edited {relDate(note.updatedAt, now).long}</span>\n              </div>\n              <div className=\"ms-auto flex items-center gap-0.5\">\n                {note.deleted ? (\n                  <Button className={press} onClick={() => restore(note.id)} size=\"sm\" variant=\"outline\">\n                    <RotateCcwIcon /> Restore\n                  </Button>\n                ) : (\n                  <>\n                    <div aria-label=\"Formatting\" className=\"flex items-center gap-0.5\" role=\"toolbar\">\n                      {blockTypes.map((t) => {\n                        const active = focusedType === t.value;\n                        return (\n                          <button\n                            aria-label={`Turn into ${t.label.toLowerCase()}`}\n                            aria-pressed={active}\n                            className={cn(\n                              \"relative flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg [&_svg]:size-4 sm:size-7\",\n                              ring,\n                              press,\n                              active ? \"text-foreground\" : \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n                              \"disabled:pointer-events-none disabled:opacity-40\",\n                            )}\n                            disabled={!focusedBlock}\n                            key={t.value}\n                            onClick={() => focusedBlock && convert(focusedBlock, t.value)}\n                            onMouseDown={(e) => e.preventDefault()}\n                            title={t.label}\n                            type=\"button\"\n                          >\n                            {active && (\n                              <motion.span\n                                className=\"absolute inset-0 rounded-lg bg-accent\"\n                                layoutId=\"notes-blocktype\"\n                                transition={reduce ? { duration: 0 } : spring}\n                              />\n                            )}\n                            <span className=\"relative flex\">{t.icon}</span>\n                          </button>\n                        );\n                      })}\n                    </div>\n                    <span aria-hidden className=\"mx-1.5 h-4 w-px bg-border\" />\n                    <Button\n                      aria-label={note.pinned ? \"Unpin note\" : \"Pin note\"}\n                      aria-pressed={!!note.pinned}\n                      className={cn(press, note.pinned && \"text-foreground\")}\n                      onClick={() => setNotes((all) => all.map((n) => (n.id === note.id ? { ...n, pinned: !n.pinned } : n)))}\n                      size=\"icon-sm\"\n                      variant=\"ghost\"\n                    >\n                      <motion.span\n                        animate={{ scale: 1 }}\n                        className=\"flex\"\n                        initial={reduce ? false : { scale: 0.8 }}\n                        key={String(note.pinned)}\n                        transition={{ duration: 0.18, ease: easeOut }}\n                      >\n                        <PinIcon className={cn(note.pinned && \"fill-current\")} />\n                      </motion.span>\n                    </Button>\n                    <Button aria-label=\"Delete note\" className={press} onClick={() => removeNote(note.id)} size=\"icon-sm\" variant=\"ghost\">\n                      <Trash2Icon />\n                    </Button>\n                  </>\n                )}\n              </div>\n            </div>\n\n            <div className=\"min-h-0 flex-1 overflow-y-auto\">\n              <motion.article\n                animate={{ opacity: 1 }}\n                className=\"mx-auto flex max-w-2xl flex-col px-5 pt-6 pb-24 @3xl:px-12 @3xl:pt-10\"\n                initial={reduce ? false : { opacity: 0 }}\n                key={note.id}\n                transition={{ duration: 0.12, ease: \"easeOut\" }}\n              >\n                <AutoText\n                  aria-label=\"Title\"\n                  className=\"font-heading font-semibold text-2xl tracking-tight @3xl:text-3xl\"\n                  inputRef={(el) => {\n                    titleRef.current = el;\n                  }}\n                  onChange={(e) => touch(note.id, () => ({ title: e.target.value.replace(/\\n/g, \"\") }))}\n                  onFocus={() => setFocusedBlock(null)}\n                  onKeyDown={(e) => {\n                    if (e.key === \"Enter\" || (e.key === \"ArrowDown\" && e.currentTarget.selectionStart === e.currentTarget.value.length)) {\n                      e.preventDefault();\n                      if (note.blocks[0]) setPending({ id: note.blocks[0].id, at: \"start\" });\n                    }\n                  }}\n                  placeholder=\"Title\"\n                  readOnly={note.deleted}\n                  value={note.title}\n                />\n                <div className=\"mt-2 mb-6 flex flex-wrap items-center gap-x-3 gap-y-1 border-b pb-5 text-muted-foreground text-xs\">\n                  <span className=\"tabular-nums\">{words} words</span>\n                  {stats.total > 0 && (\n                    <span className=\"flex items-center gap-1.5 tabular-nums\">\n                      <ProgressRing done={stats.done} total={stats.total} />\n                      {stats.done} of {stats.total} done\n                    </span>\n                  )}\n                  <span className=\"tabular-nums @3xl:hidden\">Edited {relDate(note.updatedAt, now).long}</span>\n                </div>\n                {note.blocks.map((block, i) => {\n                  const prevType = note.blocks[i - 1]?.type;\n                  const spacing =\n                    block.type === \"h1\"\n                      ? \"mt-5\"\n                      : block.type === \"h2\"\n                        ? i === 0\n                          ? \"\"\n                          : \"mt-5 mb-0.5\"\n                        : (block.type === \"todo\" || block.type === \"bullet\") && prevType === block.type\n                          ? \"mt-0.5\"\n                          : i === 0\n                            ? \"\"\n                            : \"mt-2\";\n                  const input = (\n                    <AutoText\n                      aria-label={block.type === \"todo\" ? \"Checklist item\" : block.type === \"bullet\" ? \"Bullet\" : block.type === \"p\" ? \"Text\" : \"Heading\"}\n                      className={cn(\n                        blockStyles[block.type],\n                        block.type === \"todo\" && block.done && \"text-muted-foreground line-through decoration-muted-foreground/50\",\n                        \"transition-colors duration-200\",\n                      )}\n                      inputRef={(el) => {\n                        if (el) blockRefs.current.set(block.id, el);\n                        else blockRefs.current.delete(block.id);\n                      }}\n                      onBlur={() => setFocusedBlock((f) => (f === block.id ? null : f))}\n                      onChange={(e) => onBlockChange(block, e.target.value)}\n                      onFocus={() => setFocusedBlock(block.id)}\n                      onKeyDown={(e) => onBlockKey(e, block, i)}\n                      placeholder={\n                        note.blocks.length === 1 && block.type === \"p\"\n                          ? \"Start writing. Type “[] ” for a checklist, “# ” for a heading.\"\n                          : block.type === \"todo\"\n                            ? \"To-do\"\n                            : block.type === \"bullet\"\n                              ? \"List item\"\n                              : block.type === \"p\"\n                                ? \"\"\n                                : \"Heading\"\n                      }\n                      readOnly={note.deleted}\n                      value={block.text}\n                    />\n                  );\n                  return (\n                    <div className={cn(\"flex items-start gap-2.5\", spacing)} key={block.id}>\n                      {block.type === \"todo\" ? (\n                        <CheckBox\n                          checked={!!block.done}\n                          label={block.text || \"To-do\"}\n                          onToggle={() => !note.deleted && patchBlock(block.id, { done: !block.done })}\n                        />\n                      ) : block.type === \"bullet\" ? (\n                        <span aria-hidden className=\"flex h-7 w-4.5 shrink-0 items-center justify-center\">\n                          <span className=\"size-1.5 rounded-full bg-foreground/60\" />\n                        </span>\n                      ) : null}\n                      <div className=\"min-w-0 flex-1\">{input}</div>\n                    </div>\n                  );\n                })}\n                {!note.deleted && (\n                  <button\n                    aria-label=\"Add a line at the end\"\n                    className=\"mt-2 h-16 w-full cursor-text\"\n                    onClick={() => {\n                      const last = note.blocks[note.blocks.length - 1];\n                      if (last && !last.text.trim()) {\n                        setPending({ id: last.id, at: \"end\" });\n                        return;\n                      }\n                      const id = uid(\"b\");\n                      setBlocks((bs) => [...bs, { id, type: \"p\", text: \"\" }]);\n                      setPending({ id, at: \"start\" });\n                    }}\n                    tabIndex={-1}\n                    type=\"button\"\n                  />\n                )}\n              </motion.article>\n            </div>\n          </>\n        ) : (\n          <div className=\"flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center\">\n            <span className=\"flex size-10 items-center justify-center rounded-xl bg-muted text-muted-foreground\">\n              <NotebookPenIcon className=\"size-4.5\" />\n            </span>\n            <span className=\"font-medium\">No note selected</span>\n            <Button className={press} onClick={newNote} size=\"sm\" variant=\"outline\">\n              <SquarePenIcon /> New note\n            </Button>\n          </div>\n        )}\n      </section>\n\n      <div className=\"pointer-events-none absolute inset-x-0 bottom-4 z-30 flex justify-center px-3\">\n        <AnimatePresence>\n          {undo && (\n            <motion.div\n              animate={{ y: 0, opacity: 1, scale: 1 }}\n              className=\"pointer-events-auto flex items-center gap-1 rounded-full bg-primary p-1 ps-4 text-primary-foreground shadow-lg/15 dark:border dark:bg-popover dark:text-popover-foreground\"\n              exit={{ y: 8, opacity: 0, scale: 0.97, transition: { duration: 0.12, ease: easeOut } }}\n              initial={reduce ? { opacity: 0 } : { y: 16, opacity: 0, scale: 0.96 }}\n              role=\"status\"\n              transition={reduce ? { duration: 0.15 } : spring}\n            >\n              <span className=\"pe-2\">Moved to Recently deleted</span>\n              <button\n                className={cn(\n                  \"flex h-8 cursor-pointer items-center gap-1.5 rounded-full px-3 hover:bg-primary-foreground/12 focus-visible:ring-2 focus-visible:ring-primary-foreground/40 dark:hover:bg-accent dark:focus-visible:ring-ring\",\n                  \"outline-none\",\n                  press,\n                )}\n                onClick={() => {\n                  restore(undo.id);\n                  setSelectedId(undo.id);\n                }}\n                type=\"button\"\n              >\n                <Undo2Icon className=\"size-3.5 opacity-80\" /> Undo\n              </button>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n"
    }
  ]
}