{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sticky-board",
  "title": "Sticky board",
  "author": "Stickies <https://stickies.live>",
  "description": "A full canvas of sticky notes: drag, resize, pan, double-click to add, select, copy and paste, saved to the browser.",
  "registryDependencies": [
    "https://stickies.live/r/sticky-note.json",
    "https://stickies.live/r/use-sticky-notes.json",
    "https://stickies.live/r/use-canvas-pan.json",
    "https://stickies.live/r/use-stickies-clipboard.json"
  ],
  "files": [
    {
      "path": "registry/stickies/blocks/sticky-board/sticky-board.tsx",
      "content": "\"use client\"\n\nimport { createContext, type ReactNode, useContext, useEffect, useLayoutEffect, useRef, useState } from \"react\"\nimport { createPortal } from \"react-dom\"\nimport { type Pan, useCanvasPan } from \"@/registry/stickies/hooks/use-canvas-pan\"\nimport { useStickiesClipboard } from \"@/registry/stickies/hooks/use-stickies-clipboard\"\nimport { type StickyNotesApi, useStickyNotes } from \"@/registry/stickies/hooks/use-sticky-notes\"\nimport { placeNotes, type StickiesSource, STICKY_DEFAULT_SIZE, type StickyNoteData } from \"@/registry/stickies/lib/stickies-format\"\nimport {\n  StickyNote,\n  StickyNoteAuthor,\n  StickyNoteClose,\n  StickyNoteColors,\n  StickyNoteDate,\n  StickyNoteFooter,\n  StickyNoteHeader,\n  StickyNoteResize,\n  StickyNoteState,\n  StickyNoteText,\n} from \"@/registry/stickies/ui/sticky-note\"\nimport { cn } from \"@/lib/utils\"\n\ntype StickyBoardContextValue = StickyNotesApi & {\n  pan: { x: number; y: number }\n  setPan: (pan: { x: number; y: number }) => void\n  /** Copies notes from a button or menu (HTML and plain text, carrying the document). */\n  copy: (notes: StickyNoteData[]) => Promise<void>\n}\n\nconst StickyBoardContext = createContext<StickyBoardContextValue | null>(null)\n\n/** The board's notes and actions, for anything rendered inside `<StickyBoard>`, like a toolbar. */\nexport function useStickyBoard() {\n  const context = useContext(StickyBoardContext)\n  if (!context) throw new Error(\"useStickyBoard must be used inside <StickyBoard>.\")\n  return context\n}\n\nexport interface StickyBoardProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\n  /** The notes to start with, and to go back to on reset. */\n  defaultNotes?: StickyNoteData[]\n  /** Controlled notes, with `onNotesChange`. Nothing is saved to the browser. */\n  notes?: StickyNoteData[]\n  onNotesChange?: (notes: StickyNoteData[]) => void\n  /** Keep the board in `localStorage`. On by default. */\n  persist?: boolean\n  storageKey?: string\n  /** Colour comes from each note's state. */\n  semantic?: boolean\n  /** Show when each note last changed. */\n  showDate?: boolean\n  /** Recorded in copied notes, so other apps know where they came from. */\n  source?: StickiesSource\n  /** Your own composition of a note's parts, inside `<StickyNote>`. */\n  renderNote?: (note: StickyNoteData, options: { autoFocus: boolean }) => ReactNode\n  /** Drawn over the board, such as a toolbar. Use `useStickyBoard()` inside. */\n  children?: ReactNode\n}\n\nfunction DefaultNote({ autoFocus, showDate }: { autoFocus: boolean; showDate: boolean }) {\n  return (\n    <>\n      <StickyNoteHeader>\n        <StickyNoteColors />\n        <span className=\"flex-1\" />\n        <StickyNoteState />\n        <StickyNoteClose />\n      </StickyNoteHeader>\n      <StickyNoteText autoFocus={autoFocus} />\n      <StickyNoteFooter>\n        <StickyNoteAuthor />\n        {showDate && <StickyNoteDate />}\n      </StickyNoteFooter>\n      <StickyNoteResize />\n    </>\n  )\n}\n\nconst editable = (el: EventTarget | null) =>\n  el instanceof HTMLElement && (el.isContentEditable || el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement)\n\n/**\n * The board's right-click menu, at the pointer and kept on screen. It closes on a press\n * outside it, Escape, scrolling, or the window losing focus. Its own events stop here, so a\n * key pressed in it (Delete, say) never reaches the board behind.\n */\nfunction BoardMenu({ x, y, onClose, children }: { x: number; y: number; onClose: () => void; children: ReactNode }) {\n  const menu = useRef<HTMLDivElement>(null)\n  const [place, setPlace] = useState({ x, y })\n\n  useLayoutEffect(() => {\n    const el = menu.current\n    if (!el) return\n    const { width, height } = el.getBoundingClientRect()\n    setPlace({\n      x: Math.max(4, Math.min(x, window.innerWidth - width - 4)),\n      y: Math.max(4, Math.min(y, window.innerHeight - height - 4)),\n    })\n    el.querySelector<HTMLElement>('[role=\"menuitem\"]')?.focus()\n  }, [x, y])\n\n  useEffect(() => {\n    const outside = (e: PointerEvent) => {\n      if (!menu.current?.contains(e.target as Node)) onClose()\n    }\n    const escape = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") onClose()\n    }\n    document.addEventListener(\"pointerdown\", outside, true)\n    document.addEventListener(\"keydown\", escape)\n    window.addEventListener(\"wheel\", onClose, { passive: true })\n    window.addEventListener(\"resize\", onClose)\n    window.addEventListener(\"blur\", onClose)\n    return () => {\n      document.removeEventListener(\"pointerdown\", outside, true)\n      document.removeEventListener(\"keydown\", escape)\n      window.removeEventListener(\"wheel\", onClose)\n      window.removeEventListener(\"resize\", onClose)\n      window.removeEventListener(\"blur\", onClose)\n    }\n  }, [onClose])\n\n  return createPortal(\n    <div\n      ref={menu}\n      role=\"menu\"\n      data-slot=\"sticky-board-menu\"\n      className=\"fixed z-50 min-w-36 origin-top-left rounded-md bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none transition-[opacity,scale] duration-150 ease-out starting:scale-95 starting:opacity-0\"\n      style={{ left: place.x, top: place.y }}\n      onPointerDown={(e) => e.stopPropagation()}\n      onDoubleClick={(e) => e.stopPropagation()}\n      onContextMenu={(e) => {\n        e.preventDefault()\n        e.stopPropagation()\n      }}\n      onKeyDown={(e) => {\n        e.stopPropagation()\n        if (e.key === \"Escape\" || e.key === \"Tab\") {\n          e.preventDefault()\n          return onClose()\n        }\n        if (e.key !== \"ArrowDown\" && e.key !== \"ArrowUp\") return\n        e.preventDefault()\n        const items = [...(menu.current?.querySelectorAll<HTMLElement>('[role=\"menuitem\"]') ?? [])]\n        const at = items.indexOf(document.activeElement as HTMLElement)\n        items[(at + (e.key === \"ArrowDown\" ? 1 : -1) + items.length) % items.length]?.focus()\n      }}\n    >\n      {children}\n    </div>,\n    document.body,\n  )\n}\n\nfunction BoardMenuItem({ onSelect, children }: { onSelect: () => void; children: ReactNode }) {\n  return (\n    <button\n      type=\"button\"\n      role=\"menuitem\"\n      onClick={onSelect}\n      // The highlight follows the pointer, as in a native menu.\n      onPointerMove={(e) => e.currentTarget.focus()}\n      className=\"flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none select-none focus:bg-accent focus:text-accent-foreground\"\n    >\n      {children}\n    </button>\n  )\n}\n\n/**\n * A canvas of sticky notes. Drag a note by its top, resize from its corner, drag the\n * background to look around, and double-click or right-click to add a note. Click to\n * select, ⇧-click for more; ⌘C, ⌘X and ⌘V copy, cut and paste in the Stickies format;\n * Delete removes.\n */\nexport function StickyBoard({\n  defaultNotes,\n  notes: controlled,\n  onNotesChange,\n  persist = true,\n  storageKey,\n  semantic = false,\n  showDate = false,\n  source,\n  renderNote,\n  className,\n  children,\n  ...props\n}: StickyBoardProps) {\n  const board = useStickyNotes({ defaultNotes, notes: controlled, onNotesChange, persist, storageKey })\n  const surface = useRef<HTMLDivElement>(null)\n  const { pan, setPan, panning, handlers, toCanvas } = useCanvasPan()\n  const pointer = useRef<{ x: number; y: number } | null>(null)\n  const [fresh, setFresh] = useState<string | null>(null)\n  /** The right-click menu: where it opened on screen, and that point on the board. */\n  const [menu, setMenu] = useState<{ x: number; y: number; at: Pan } | null>(null)\n  const closeMenu = useRef(() => setMenu(null)).current\n  const centred = useRef(false)\n  /**\n   * Notes keep the place in the page they first had: raising one only changes its z-index.\n   * Moving the element itself would take focus away from it, and keyboard use with it.\n   */\n  const places = useRef(new Map<string, number>())\n  for (const note of board.notes) if (!places.current.has(note.id)) places.current.set(note.id, places.current.size)\n  const layers = new Map(board.notes.map((note, i) => [note.id, i + 1]))\n  const inPlace = [...board.notes].sort((a, b) => (places.current.get(a.id) ?? 0) - (places.current.get(b.id) ?? 0))\n\n  // Once the notes are known, put them in the middle of the board, or from its left edge\n  // when they're wider than it.\n  useEffect(() => {\n    const el = surface.current\n    if (!board.ready || centred.current || !el) return\n    centred.current = true\n    if (board.notes.length === 0) return\n    const left = Math.min(...board.notes.map((n) => n.x))\n    const top = Math.min(...board.notes.map((n) => n.y))\n    const width = Math.max(...board.notes.map((n) => n.x + n.width)) - left\n    const height = Math.max(...board.notes.map((n) => n.y + n.height)) - top\n    const { clientWidth, clientHeight } = el\n    setPan({\n      x: Math.round(width > clientWidth - 40 ? 20 - left : (clientWidth - width) / 2 - left),\n      y: Math.round(height > clientHeight - 40 ? 20 - top : (clientHeight - height) / 2 - top),\n    })\n  }, [board.ready, board.notes, setPan])\n\n  const { copy } = useStickiesClipboard({\n    getNotes: () => board.selectedNotes,\n    onCut: (notes) => board.remove(notes.map((n) => n.id)),\n    onPaste: ({ notes }) => {\n      const el = surface.current\n      const view = el ? { x: el.clientWidth / 2 - pan.x - STICKY_DEFAULT_SIZE.width / 2, y: el.clientHeight / 2 - pan.y - STICKY_DEFAULT_SIZE.height / 2 } : { x: 0, y: 0 }\n      board.insert(placeNotes(notes, pointer.current ?? view))\n    },\n    source,\n    scope: surface,\n  })\n\n  const onBackground = (target: EventTarget, current: EventTarget) =>\n    target === current || (target instanceof HTMLElement && target.hasAttribute(\"data-pan-surface\"))\n\n  /** A new, selected note with its corner here, ready to type in. */\n  function addAt(x: number, y: number) {\n    const note = board.add({ x: Math.round(x), y: Math.round(y) })\n    board.setSelected([note.id])\n    setFresh(note.id)\n  }\n\n  return (\n    <StickyBoardContext.Provider value={{ ...board, pan, setPan, copy }}>\n      <div\n        ref={surface}\n        data-slot=\"sticky-board\"\n        // Focusable, so ⌘C, ⌘V and Delete go to the board pressed last when a page has several.\n        tabIndex={-1}\n        className={cn(\n          \"relative isolate h-full w-full touch-none overflow-hidden outline-none select-none\",\n          panning ? \"cursor-grabbing\" : \"cursor-grab\",\n          className,\n        )}\n        onPointerDown={(e) => {\n          handlers.onPointerDown(e)\n          if (!onBackground(e.target, e.currentTarget)) return\n          board.clearSelection()\n          surface.current?.focus({ preventScroll: true })\n        }}\n        onPointerMove={(e) => {\n          handlers.onPointerMove(e)\n          pointer.current = toCanvas(e, surface.current)\n        }}\n        onPointerLeave={() => {\n          pointer.current = null\n        }}\n        onPointerUp={handlers.onPointerUp}\n        onPointerCancel={handlers.onPointerCancel}\n        onDoubleClick={(e) => {\n          if (!onBackground(e.target, e.currentTarget)) return\n          const at = toCanvas(e, surface.current)\n          addAt(at.x - STICKY_DEFAULT_SIZE.width / 2, at.y - 14)\n        }}\n        onContextMenu={(e) => {\n          // On a note, the browser's own menu (Copy, Paste, spelling) stays.\n          if (!onBackground(e.target, e.currentTarget)) return\n          e.preventDefault()\n          setMenu({ x: e.clientX, y: e.clientY, at: toCanvas(e, surface.current) })\n        }}\n        onKeyDown={(e) => {\n          if (editable(e.target)) return\n          if ((e.key === \"Delete\" || e.key === \"Backspace\") && board.selected.length) {\n            e.preventDefault()\n            board.remove(board.selected)\n          } else if (e.key === \"Escape\") {\n            board.clearSelection()\n          } else if (e.key === \"a\" && (e.metaKey || e.ctrlKey)) {\n            e.preventDefault()\n            board.setSelected(board.notes.map((n) => n.id))\n          }\n        }}\n        {...props}\n      >\n        <div className=\"absolute top-0 left-0\" style={{ transform: `translate(${pan.x}px, ${pan.y}px)` }}>\n          {board.ready &&\n            inPlace.map((note) => (\n              <StickyNote\n                key={note.id}\n                note={note}\n                semantic={semantic}\n                selected={board.selected.includes(note.id)}\n                style={{ zIndex: layers.get(note.id) }}\n                onNoteChange={(next) => board.update(note.id, next, { touch: false })}\n                onDelete={() => board.remove(note.id)}\n                onPointerDown={(e) => {\n                  board.select(note.id, { additive: e.shiftKey })\n                  board.raise(note.id)\n                }}\n              >\n                {renderNote ? renderNote(note, { autoFocus: note.id === fresh }) : <DefaultNote autoFocus={note.id === fresh} showDate={showDate} />}\n              </StickyNote>\n            ))}\n        </div>\n        {children}\n      </div>\n      {menu && (\n        <BoardMenu x={menu.x} y={menu.y} onClose={closeMenu}>\n          <BoardMenuItem\n            onSelect={() => {\n              // As in Murmur: the corner just up and left of the pointer, so it lands on the header.\n              addAt(menu.at.x - 20, menu.at.y - 14)\n              closeMenu()\n            }}\n          >\n            New note here\n          </BoardMenuItem>\n        </BoardMenu>\n      )}\n    </StickyBoardContext.Provider>\n  )\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "See https://stickies.live/docs#sticky-board for usage.",
  "categories": [
    "stickies"
  ],
  "type": "registry:block"
}