{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-presence",
  "title": "Data Grid Presence",
  "author": "gridcn",
  "description": "Multiplayer presence add-on for the gridcn data grid: useDataGridPresence registers an overlay plugin that paints remote users' live selections as named, colored highlights, with zero core re-renders.",
  "dependencies": [
    "zustand@^5.0.15"
  ],
  "registryDependencies": [
    "@gridcn/data-grid"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-presence/data-grid-presence.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\r\nexport {\r\n  useDataGridPresence,\r\n  useDataGridPresenceHighlights,\r\n  type ExcessRectsContext,\r\n  type UseDataGridPresenceOptions,\r\n  type UseDataGridPresenceResult,\r\n} from \"./use-data-grid-presence\";\r\nexport { toPresenceEntries, type ToPresenceEntriesOptions } from \"./to-presence-entries\";\r\nexport { MAX_RESOLVED_RECTS } from \"./presence-overlay\";\r\nexport { isRowIdPresenceHighlight, isRowIdRangePresenceHighlight } from \"./presence-store\";\r\nexport {\r\n  type ViewRangePresenceHighlight,\r\n  type RowIdPresenceHighlight,\r\n  type RowIdRangePresenceHighlight,\r\n  type PresenceHighlightEntry,\r\n  type PresenceStoreApi,\r\n} from \"./presence-store\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-presence/data-grid-presence.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-presence/use-data-grid-presence.ts",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from \"react\";\nimport { useDataGridRowIdToViewRow, useDataGridVisibleColumns, type DataGridPlugin, type OverlayPluginCtx } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev, useDataGridStoreApi, viewRowsMoved, visibleColumnsMoved } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport {\n  createPresenceStore,\n  isRowIdPresenceHighlight,\n  isRowIdRangePresenceHighlight,\n  usePresenceHighlights,\n  warnDev,\n  type PresenceHighlightEntry,\n  type PresenceStoreApi,\n  type RowIdPresenceHighlight,\n  type RowIdRangePresenceHighlight,\n} from \"./presence-store\";\nimport { renderPresenceOverlay, resolveHighlights } from \"./presence-overlay\";\n\n/** Options for {@link useDataGridPresence}. */\nexport type UseDataGridPresenceOptions = {\n  /** Cap on the rects one range entry may paint (default {@link MAX_RESOLVED_RECTS}, 1024). Lower it to protect a dense overlay, raise it for a known-large remote selection. */\n  maxRects?: number;\n  /**\n   * Called after the overlay commits (not while it renders), once each time a range entry's\n   * `(kept, total)` changes while its fragments exceed the cap — downsample the remote selection or\n   * filter it. It is safe to set React state in it.\n   */\n  onExcessRects?: (ctx: ExcessRectsContext) => void;\n};\n\n/** What {@link UseDataGridPresenceOptions.onExcessRects} receives. */\nexport type ExcessRectsContext = {\n  entry: RowIdRangePresenceHighlight;\n  /** Rects painted: the `maxRects` cap. */\n  kept: number;\n  /** Rects the entry resolves to. */\n  total: number;\n};\n\n/** Return value of {@link useDataGridPresence}. */\nexport type UseDataGridPresenceResult = {\n  /** One entry of the grid's `plugins` prop — the plugin's `Overlay` paints the highlights, its `Mount` dev-warns once when rows/columns move under an active view-index entry. Stable for the component's lifetime. An inline `plugins={[plugin]}` is fine: re-resolution is gated on entry identity (name + member references), not on the array's. */\n  plugin: DataGridPlugin<unknown>;\n  /**\n   * The real (imperative) mechanism: call directly from your websocket/CRDT handler. Replaces the whole list. Keeps the first\n   * 1,000 entries and the first 10,000 ids of a range entry, cuts a label at 64 characters, and drops a malformed entry (dev-warned).\n   */\n  setPresenceHighlights(highlights: readonly PresenceHighlightEntry[]): void;\n  /** Removes one entry by `id` (a peer's range closed) — prefer this over resending the whole snapshot. */\n  removePresenceHighlight(id: string): void;\n  /** Removes every entry (a peer disconnected or the session ended). */\n  clearPresenceHighlights(): void;\n  /** Opaque handle for {@link useDataGridPresenceHighlights} — pass it through if some other component needs the read-back subscription (e.g. an inspector panel); most consumers never need this. */\n  storeApi: PresenceStoreApi;\n};\n\n/**\n * Multiplayer presence, as a single hook. Owns its own store — a plain Zustand vanilla store local\n * to this hook instance, NOT part of the grid's own store, so core stays entirely unaware of\n * presence past the generic `plugins` seam.\n *\n * Zero-cell-render contract preserved: `plugin`'s identity never changes across renders (memoized on the store), and the plugin's `Overlay` component's own\n * `usePresenceHighlights` subscription only re-renders `DataGridOverlays` (the component that\n * renders the `Overlay` inside its own tree) — never rows or cells.\n *\n * A hook (not a `<DataGridPresence>` component) is the simplest wiring here: the plugin must be\n * threaded into `plugins` on `DataGridProvider`, which sits ABOVE anywhere a child component\n * could register it — a hook called once in the consumer's own component (before rendering the\n * provider) avoids that inversion entirely, with no new context needed.\n */\nexport function useDataGridPresence(options: UseDataGridPresenceOptions = {}): UseDataGridPresenceResult {\n  const [store] = useState(() => createPresenceStore());\n\n  // the plugin closures are memoized once; option callbacks read through refs so a new callback\n  // identity (a re-rendering consumer) never re-creates the plugin\n  const maxRectsRef = useRef(options.maxRects);\n  maxRectsRef.current = options.maxRects;\n  const onExcessRectsRef = useRef(options.onExcessRects);\n  onExcessRectsRef.current = options.onExcessRects;\n\n  const plugin = useMemo<DataGridPlugin<unknown>>(\n    () => ({\n      name: \"presence\",\n      Overlay: createPresenceOverlay(store, maxRectsRef, onExcessRectsRef),\n      Mount: createPresenceMount(store),\n    }),\n    [store],\n  );\n\n  return {\n    plugin,\n    setPresenceHighlights: store.getState().setPresenceHighlights,\n    removePresenceHighlight: store.getState().removePresenceHighlight,\n    clearPresenceHighlights: store.getState().clearPresenceHighlights,\n    storeApi: store,\n  };\n}\n\n/** The plugin's overlay component, closed over the add-on's local store; its hooks subscribe only `DataGridOverlays` (the component rendering it). */\nfunction createPresenceOverlay(\n  store: PresenceStoreApi,\n  maxRectsRef: { current: number | undefined },\n  onExcessRectsRef: { current: ((ctx: ExcessRectsContext) => void) | undefined },\n): ComponentType<OverlayPluginCtx> {\n  // per-instance (per plugin closure) once-warns: the overlay re-runs on every DataGridOverlays\n  // render, so a persistently hidden/unknown column must not re-warn on every render\n  const warnedColumns = new Set<string>();\n  const warnedRangeIssues = new Set<string>();\n  const warnDroppedColumn = (entry: RowIdPresenceHighlight): void => {\n    const key = `${entry.id}:${entry.columnId}`;\n    if (warnedColumns.has(key)) return;\n    warnedColumns.add(key);\n    warnDev(`presence entry \"${entry.id}\" references column \"${entry.columnId}\" which is not in the visible columns (hidden or unknown); the entry is dropped`);\n  };\n  const warnUnresolvedColumns = (entry: RowIdRangePresenceHighlight, unresolvedCount: number): void => {\n    const key = `unresolved:${entry.id}`;\n    if (warnedRangeIssues.has(key)) return;\n    warnedRangeIssues.add(key);\n    warnDev(`presence entry \"${entry.id}\" has ${unresolvedCount} columnId(s) not in the visible columns (hidden or unknown); those cells are dropped`);\n  };\n  const reportedExcess = new Map<string, string>();\n  const callExcessRects = (ctx: ExcessRectsContext): void => {\n    try {\n      onExcessRectsRef.current?.(ctx);\n    } catch (error) {\n      console.error(\"[data-grid-presence] onExcessRects threw\", error);\n    }\n  };\n  const warnExcessRects = (entry: RowIdRangePresenceHighlight, kept: number, total: number): void => {\n    const key = `excess:${entry.id}`;\n    if (warnedRangeIssues.has(key)) return;\n    warnedRangeIssues.add(key);\n    warnDev(`presence entry \"${entry.id}\" resolves to ${total} fragments, above the ${kept}-rect budget; the excess is not painted (downsample the remote selection or filter it)`);\n  };\n\n  function PresenceOverlay(ctx: OverlayPluginCtx): ReactNode {\n    const highlights = usePresenceHighlights(store);\n    const rowIdToViewRow = useDataGridRowIdToViewRow();\n    const visibleColumns = useDataGridVisibleColumns();\n    // memoized on the inputs' identity: local selection/keystroke re-renders of DataGridOverlays\n    // must not re-run the resolve math or re-allocate the rect objects the memoized overlay nodes\n    // compare. maxRects is read through the ref but placed in the deps so a live change re-resolves\n    // on the next overlay render.\n    const maxRects = maxRectsRef.current;\n    const { resolved, excess } = useMemo(() => {\n      const excess: ExcessRectsContext[] = [];\n      const resolved = resolveHighlights(\n        highlights,\n        rowIdToViewRow,\n        visibleColumns,\n        warnDroppedColumn,\n        warnUnresolvedColumns,\n        (entry, kept, total) => {\n          warnExcessRects(entry, kept, total);\n          excess.push({ entry, kept, total });\n        },\n        maxRects,\n      );\n      return { resolved, excess };\n    }, [highlights, rowIdToViewRow, visibleColumns, warnDroppedColumn, warnUnresolvedColumns, warnExcessRects, maxRects]);\n    useEffect(() => {\n      const current = new Set<string>();\n      for (const ctx of excess) {\n        current.add(ctx.entry.id);\n        const signature = `${ctx.kept}/${ctx.total}`;\n        if (reportedExcess.get(ctx.entry.id) === signature) continue;\n        reportedExcess.set(ctx.entry.id, signature);\n        callExcessRects(ctx);\n      }\n      for (const id of reportedExcess.keys()) if (!current.has(id)) reportedExcess.delete(id);\n    }, [excess]);\n    return renderPresenceOverlay(resolved, ctx);\n  }\n  return PresenceOverlay;\n}\n\n/** The plugin's mount component: dev-warns once when a row-moving or column-moving store write lands while a view-index entry is active — that entry's highlight position is now stale (view-index entries follow their rect, not their rows). */\nfunction createPresenceMount(store: PresenceStoreApi): ComponentType {\n  function PresenceMount(): ReactNode {\n    const gridStoreApi = useDataGridStoreApi();\n    useEffect(() => {\n      if (!isDev()) return;\n      let warned = false;\n      const viewSpaceActive = () =>\n        store.getState().highlights.some((entry) => !isRowIdPresenceHighlight(entry) && !isRowIdRangePresenceHighlight(entry));\n      const unsubscribe = gridStoreApi.subscribe((s, prev) => {\n        if (warned || !viewSpaceActive()) return;\n        if (viewRowsMoved(prev, s.viewIndex, s.data, s.getRowId) || visibleColumnsMoved(prev.visibleColumns, s.visibleColumns)) {\n          warned = true;\n          warnDev(\"rows or columns moved while a view-space presence entry is active — its highlight position is now stale; use rowId-native presence entries for a live feed\");\n        }\n      });\n      return unsubscribe;\n    }, [gridStoreApi, store]);\n    return null;\n  }\n  return PresenceMount;\n}\n\n/** Read-back subscription (opt-in): re-renders ONLY the calling component on highlight changes — pass `storeApi` from {@link useDataGridPresence}'s return value. Use it to build your own UI (e.g. an inspector panel) off the same state the grid paints. */\nexport function useDataGridPresenceHighlights(storeApi: PresenceStoreApi): readonly PresenceHighlightEntry[] {\n  return usePresenceHighlights(storeApi);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-presence/use-data-grid-presence.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-presence/presence-store.ts",
      "content": "\"use client\";\n\nimport { createStore, type StoreApi } from \"zustand/vanilla\";\nimport { useStore } from \"zustand\";\nimport type { GridRect } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/**\n * One remote user's (or cursor's) selection painted into the grid (multiplayer presence),\n * VIEW-space (same coordinate system as `GridSelection.current.range`): indices into the current\n * sorted/filtered display order, not the raw `data` array. A rowId-keyed remote peer must map\n * rowId -> view index itself before building this — either with {@link RowIdPresenceHighlight}\n * (the plugin resolves it for you) or by hand via `useDataGridRowIdToViewRow()`.\n */\nexport type ViewRangePresenceHighlight = {\n  /**\n   * Unique id PER ENTRY — the `id` must be unique per entry: a user with a multi-range selection\n   * sends one entry per range, each with its own id. Entries are keyed by position, not id, so\n   * duplicate ids still render, but `removePresenceHighlight(id)` removes every entry with that id.\n   */\n  id: string;\n  /** Any CSS color, including `var(--color-primary)`; painted at fixed alpha for the fill, full opacity for the border/chip. An invalid color or an undefined token paints as `var(--color-primary)`. The chip text is black on light colors and white on dark ones. */\n  color: string;\n  range: GridRect;\n  /** Optional name chip anchored at the range's top-left corner, only rendered while that corner is on-window. */\n  label?: string;\n};\n\n/**\n * rowId-native alternative to {@link ViewRangePresenceHighlight}: a single cell keyed by stable rowId + columnId instead of a view-index rect.\n * The plugin resolves `rowId` -> view row itself at paint time via `useDataGridRowIdToViewRow()`, so\n * a locally-active sort/filter never mispaints it; an entry whose `rowId` fell out of the current\n * view (filtered out) is dropped silently, same contract as the manual mapping it replaces.\n */\nexport type RowIdPresenceHighlight = {\n  /** Unique id PER ENTRY — must be unique per entry (a multi-range selection sends one entry per cell/range, each with its own id). */\n  id: string;\n  /** Any CSS color, including `var(--color-primary)`; painted at fixed alpha for the fill, full opacity for the border/chip. An invalid color or an undefined token paints as `var(--color-primary)`. The chip text is black on light colors and white on dark ones. */\n  color: string;\n  rowId: string;\n  columnId: string;\n  /** Optional name chip anchored at the resolved cell, only rendered while it's on-window. */\n  label?: string;\n};\n\n/**\n * rowId-native alternative to {@link ViewRangePresenceHighlight}: a multi-cell selection keyed by stable\n * rowIds × columnIds instead of a view-index rect. The plugin resolves every id against the\n * receiver's current view at paint time, so a local sort or filter never mispaints it. Ids that\n * fell out of the view are dropped; the surviving cells paint one rect per contiguous run.\n */\nexport type RowIdRangePresenceHighlight = {\n  /** Unique id PER ENTRY — must be unique per entry (a multi-range selection sends one entry per range, each with its own id). */\n  id: string;\n  /** Any CSS color, including `var(--color-primary)`; painted at fixed alpha for the fill, full opacity for the border/chip. An invalid color or an undefined token paints as `var(--color-primary)`. The chip text is black on light colors and white on dark ones. */\n  color: string;\n  /** Stable row ids of the selected rows; any order, duplicates allowed. */\n  rowIds: string[];\n  /** Stable column ids of the selected columns; any order, duplicates allowed. */\n  columnIds: string[];\n  /** Optional name chip anchored at each resolved fragment's top-left corner, only rendered while that corner is on-window. */\n  label?: string;\n};\n\n/** Any coordinate form a highlight entry can take — {@link ViewRangePresenceHighlight} (view-index rect), {@link RowIdPresenceHighlight} (rowId-native single cell), or {@link RowIdRangePresenceHighlight} (rowId-native range), distinguished by `rowId` / `rowIds`. When an entry carries BOTH `rowId` and `rowIds`, the single-cell form wins. */\nexport type PresenceHighlightEntry = ViewRangePresenceHighlight | RowIdPresenceHighlight | RowIdRangePresenceHighlight;\n\n/**\n * True when `entry` is the rowId-native form — the discriminant used by the plugin to route to the\n * right resolution path. `rowId` must be a non-empty STRING: a missing/null `rowId` (foreign JSON\n * that lost it) is NOT the rowId-native form and falls through to the view-index `range` check\n * instead of being silently misrouted to the rowId path.\n */\nexport function isRowIdPresenceHighlight(entry: PresenceHighlightEntry): entry is RowIdPresenceHighlight {\n  const rowId = (entry as Partial<RowIdPresenceHighlight>).rowId;\n  return typeof rowId === \"string\" && rowId.length > 0;\n}\n\n/**\n * True when `entry` is the rowId-native RANGE form — the discriminant that routes it away from the\n * single-cell and view-index paths. `rowIds` must be an ARRAY of strings: a missing/foreign\n * `rowIds` is NOT the range form and falls through to the `rowId`/`range` checks instead of being\n * misrouted.\n */\nexport function isRowIdRangePresenceHighlight(entry: PresenceHighlightEntry): entry is RowIdRangePresenceHighlight {\n  const rowIds = (entry as Partial<RowIdRangePresenceHighlight>).rowIds;\n  return Array.isArray(rowIds) && rowIds.every((id) => typeof id === \"string\");\n}\n\n/** A well-formed view-index `range`: all four coordinates finite (catches missing, null, and NaN). */\nfunction isValidRange(range: unknown): range is GridRect {\n  if (typeof range !== \"object\" || range === null) return false;\n  const r = range as Partial<GridRect>;\n  return Number.isFinite(r.x) && Number.isFinite(r.y) && Number.isFinite(r.width) && Number.isFinite(r.height);\n}\n\n/** Dev-only warning, core's `warnDev` pattern with this add-on's own prefix (import-boundary rule: add-ons import only from core's block-root barrel). */\nexport function warnDev(message: string): void {\n  if (isDev()) console.warn(`[data-grid-presence] ${message}`);\n}\n\n/** Shared empty-array identity for the no-highlights state, so a grid with none never allocates a fresh `[]` per render. */\nconst EMPTY_HIGHLIGHTS: readonly PresenceHighlightEntry[] = [];\n\n/** This add-on's own state slice: just the highlight list. Deliberately NOT part of the core store — core knows nothing about presence past the generic `plugins` seam it renders through. */\nexport type PresenceStoreState = {\n  highlights: readonly PresenceHighlightEntry[];\n  setPresenceHighlights(highlights: readonly PresenceHighlightEntry[]): void;\n  /** Removes the entry with this `id`; no-op (and the same list identity) when no entry matches. */\n  removePresenceHighlight(id: string): void;\n  /** Removes every entry — a peer disconnect or session end. */\n  clearPresenceHighlights(): void;\n};\n\nexport type PresenceStoreApi = StoreApi<PresenceStoreState>;\n\n/** Upper bounds on peer-supplied data; entries past a bound are dropped or truncated. */\nexport const MAX_PRESENCE_ENTRIES = 1000;\nconst MAX_PRESENCE_ID_LENGTH = 256;\nconst MAX_PRESENCE_COLOR_LENGTH = 128;\nconst MAX_PRESENCE_LABEL_LENGTH = 64;\nconst MAX_PRESENCE_IDS = 10_000;\n\nfunction isBoundedString(value: unknown, max: number): value is string {\n  return typeof value === \"string\" && value.length > 0 && value.length <= max;\n}\n\nfunction boundedIdList(value: unknown, max: number): string[] | null {\n  if (!Array.isArray(value)) return null;\n  const ids = value.length > MAX_PRESENCE_IDS ? value.slice(0, MAX_PRESENCE_IDS) : value;\n  return ids.every((id) => isBoundedString(id, max)) ? ids : null;\n}\n\nfunction safeKey(entry: unknown): string {\n  try {\n    return String(JSON.stringify(entry)).slice(0, MAX_PRESENCE_ID_LENGTH);\n  } catch {\n    return typeof entry;\n  }\n}\n\n/** Returns a fresh, validated copy of a peer entry (only known fields), or the reason it was dropped. A malformed `color` falls back to the primary color; a non-string `label` is removed and a long one truncated. */\nfunction sanitizeEntry(entry: unknown): PresenceHighlightEntry | string {\n  if (!entry || typeof entry !== \"object\") return \"not an object\";\n  const e = entry as Partial<Record<\"id\" | \"color\" | \"label\" | \"rowId\" | \"columnId\" | \"rowIds\" | \"columnIds\" | \"range\", unknown>>;\n  if (!isBoundedString(e.id, MAX_PRESENCE_ID_LENGTH)) return \"missing or oversized id\";\n  const base = {\n    id: e.id,\n    color: isBoundedString(e.color, MAX_PRESENCE_COLOR_LENGTH) ? e.color : \"var(--color-primary)\",\n    ...(typeof e.label === \"string\" && e.label.length > 0 ? { label: e.label.slice(0, MAX_PRESENCE_LABEL_LENGTH) } : {}),\n  };\n  if (isRowIdPresenceHighlight(e as PresenceHighlightEntry)) {\n    if (!isBoundedString(e.rowId, MAX_PRESENCE_ID_LENGTH) || !isBoundedString(e.columnId, MAX_PRESENCE_ID_LENGTH)) return \"rowId-native entries need a bounded rowId and columnId\";\n    return { ...base, rowId: e.rowId, columnId: e.columnId };\n  }\n  if (isRowIdRangePresenceHighlight(e as PresenceHighlightEntry)) {\n    const rowIds = boundedIdList(e.rowIds, MAX_PRESENCE_ID_LENGTH);\n    const columnIds = boundedIdList(e.columnIds, MAX_PRESENCE_ID_LENGTH);\n    if (!rowIds || !columnIds) return \"rowId-native range entries need string arrays rowIds and columnIds\";\n    if (rowIds.length === 0 || columnIds.length === 0) return \"empty rowIds/columnIds paint nothing\";\n    return { ...base, rowIds, columnIds };\n  }\n  if (!isValidRange(e.range)) return \"missing or malformed range (need finite x, y, width, height)\";\n  const { x, y, width, height } = e.range;\n  return { ...base, range: { x, y, width, height } };\n}\n\n/**\n * One store instance per `useDataGridPresence()` call, mirroring core's one-store-per-grid pattern\n * (store.tsx's `createDataGridStore`). `setPresenceHighlights` REPLACES the whole list (snapshot\n * semantics) and validates/coerces foreign entries on the way in: malformed entries (non-object,\n * missing/malformed `range`) and rowId-native entries without a usable `columnId` (single cell) or\n * `columnIds` string array (range) are DROPPED with a per-instance dev warning instead of painting\n * garbage or failing silently (same for range entries with empty `rowIds`/`columnIds` arrays).\n * View-dependent drops (rowId filtered out of view, hidden/unknown column) happen at resolve\n * time in the plugin.\n */\nexport function createPresenceStore(): PresenceStoreApi {\n  const warned = new Set<string>();\n  const warnOnce = (key: () => string, message: string): void => {\n    if (!isDev()) return;\n    const k = key();\n    if (warned.has(k)) return;\n    warned.add(k);\n    warnDev(message);\n  };\n  return createStore<PresenceStoreState>((set) => ({\n    highlights: EMPTY_HIGHLIGHTS,\n    setPresenceHighlights(highlights) {\n      const cleaned: PresenceHighlightEntry[] = [];\n      if (!Array.isArray(highlights)) {\n        warnOnce(() => \"not-array\", \"setPresenceHighlights: ignored a payload that is not an array\");\n        set({ highlights: EMPTY_HIGHLIGHTS });\n        return;\n      }\n      for (const entry of highlights.slice(0, MAX_PRESENCE_ENTRIES)) {\n        const result = sanitizeEntry(entry);\n        if (typeof result === \"string\") warnOnce(() => `${result}:${safeKey(entry)}`, `setPresenceHighlights: dropped an entry — ${result}`);\n        else cleaned.push(result);\n      }\n      if (highlights.length > MAX_PRESENCE_ENTRIES) {\n        warnOnce(() => \"entries\", `setPresenceHighlights: kept the first ${MAX_PRESENCE_ENTRIES} entries and dropped the rest`);\n      }\n      set({ highlights: cleaned });\n    },\n    removePresenceHighlight(id) {\n      set((s) => (s.highlights.some((h) => h.id === id) ? { highlights: s.highlights.filter((h) => h.id !== id) } : s));\n    },\n    clearPresenceHighlights() {\n      set({ highlights: EMPTY_HIGHLIGHTS });\n    },\n  }));\n}\n\n/** Every active multiplayer presence highlight; consumed ONLY by the overlay plugin — never by row/cell subscriptions, preserving the zero-cell-render contract. */\nexport function usePresenceHighlights(store: PresenceStoreApi): readonly PresenceHighlightEntry[] {\n  return useStore(store, (s) => s.highlights);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-presence/presence-store.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-presence/presence-overlay.tsx",
      "content": "\"use client\";\n\nimport { Fragment, memo, type CSSProperties, type ReactNode } from \"react\";\nimport type { GridRect, OverlayPluginCtx } from \"@/registry/default/components/data-grid/data-grid\";\nimport { GRID_LAYER, hasAnyPin } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport {\n  isRowIdPresenceHighlight,\n  isRowIdRangePresenceHighlight,\n  type ViewRangePresenceHighlight,\n  type PresenceHighlightEntry,\n  type RowIdPresenceHighlight,\n  type RowIdRangePresenceHighlight,\n} from \"./presence-store\";\n\n/** Default cap on the rects ONE range entry may paint (per contiguous fragment): a remote selection of scattered rows must not turn the overlay layer into thousands of divs. Override it with `useDataGridPresence({ maxRects })`; excess fragments are dropped and reported via the `onExcessRects` option. */\nexport const MAX_RESOLVED_RECTS = 1024;\n\nconst FALLBACK_PRESENCE_COLOR = \"var(--color-primary)\";\n\n/** Returns `color` when the browser parses it as a CSS color, else `var(--color-primary)`; passes through where `CSS.supports` is missing (SSR, jsdom). */\nexport function safePresenceColor(color: string): string {\n  if (typeof CSS === \"undefined\" || typeof CSS.supports !== \"function\") return color;\n  return CSS.supports(\"color\", color) ? color : FALLBACK_PRESENCE_COLOR;\n}\n\n/** One remote user's selection-range fill + border, grid-line placed like core's own RangeOverlay; color comes from the highlight itself via `--presence-color`, not a shadcn token. Memoized: the resolved rects keep identity across overlay renders (see `createPresenceOverlay`'s memo), so an unchanged highlight never re-renders its divs on a local keystroke. */\nconst PresenceHighlightOverlay = memo(function PresenceHighlightOverlay({\n  rect,\n  color,\n  windowStart,\n  colOffset,\n  pinStyle,\n}: {\n  rect: GridRect;\n  color: string;\n  windowStart: number;\n  colOffset: number;\n  pinStyle?: CSSProperties;\n}) {\n  const safeColor = safePresenceColor(color);\n  return (\n    <div\n      data-grid-presence-overlay=\"\"\n      data-pinned={pinStyle ? \"\" : undefined}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none border border-[color-mix(in_oklch,var(--presence-color,var(--color-primary))_100%,transparent)] bg-[color-mix(in_oklch,var(--presence-color,var(--color-primary))_12%,transparent)]\"\n      style={{\n        // positioned: cells are position:relative, so a static overlay would paint below them;\n        // out-of-flow when unpinned, so moving it does not re-lay out the canvas grid\n        position: \"absolute\",\n        inset: 0,\n        \"--presence-color\": safeColor,\n        gridColumnStart: rect.x + colOffset,\n        gridColumnEnd: rect.x + rect.width + colOffset,\n        gridRowStart: rect.y - windowStart + 1,\n        gridRowEnd: rect.y + rect.height - windowStart + 1,\n        ...(pinStyle ? { inset: undefined, ...pinStyle, zIndex: GRID_LAYER.pinnedOverlaySegment } : {}),\n      } as CSSProperties}\n    />\n  );\n});\n\n/** The remote user's name chip, anchored at a highlight range's top-left VISIBLE corner — only rendered by the caller when that corner survives the window clamp. */\nconst PresenceLabelChip = memo(function PresenceLabelChip({\n  rect,\n  color,\n  label,\n  windowStart,\n  colOffset,\n  pinStyle,\n}: {\n  rect: GridRect;\n  color: string;\n  label: string;\n  windowStart: number;\n  colOffset: number;\n  pinStyle?: CSSProperties;\n}) {\n  const safeColor = safePresenceColor(color);\n  return (\n    <div\n      data-grid-presence-label=\"\"\n      data-pinned={pinStyle ? \"\" : undefined}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none z-20 flex items-start justify-start\"\n      style={{\n        \"--presence-color\": safeColor,\n        gridColumnStart: rect.x + colOffset,\n        gridColumnEnd: rect.x + colOffset + 1,\n        gridRowStart: rect.y - windowStart + 1,\n        gridRowEnd: rect.y - windowStart + 2,\n        ...pinStyle,\n      } as CSSProperties}\n    >\n      <span\n        // Lightness below 0.62 gives white text, above gives black; white stays where relative color syntax is missing.\n        className=\"-translate-y-1/2 rounded-sm bg-(--presence-color,var(--color-primary)) px-1.5 py-0.5 text-xs font-medium whitespace-nowrap text-(--presence-label-foreground,white) shadow-sm supports-[color:oklch(from_red_l_c_h)]:text-(--presence-label-foreground,oklch(from_var(--presence-color,var(--color-primary))_clamp(0,calc((0.62-l)*1000),1)_0_h_/_1))\"\n      >\n        {label}\n      </span>\n    </div>\n  );\n});\n\n/**\n * Resolves rowId-native entries to view-index {@link ViewRangePresenceHighlight}s via the caller's\n * `rowId -> view row` map. A single-cell entry resolves to a 1×1 rect; a range entry paints one\n * rect per contiguous run of resolved rows × resolved columns.\n *\n * A rowId outside the current view is dropped silently (the rowId-native contract). An unresolved\n * column dev-warns once per instance. Column lookup is a linear scan over `visibleColumns`:\n * entry counts are small. A range entry paints at most `maxRects` fragments; the excess is\n * dropped and reported via `onExcessRects`.\n * Pure (no hooks), so tests can call it without React.\n */\nexport function resolveHighlights(\n  entries: readonly PresenceHighlightEntry[],\n  rowIdToViewRow: ReadonlyMap<string, number>,\n  visibleColumns: readonly { id: string }[],\n  onDroppedColumn?: (entry: RowIdPresenceHighlight) => void,\n  onUnresolvedColumns?: (entry: RowIdRangePresenceHighlight, unresolvedCount: number) => void,\n  onExcessRects?: (entry: RowIdRangePresenceHighlight, kept: number, total: number) => void,\n  maxRects: number = MAX_RESOLVED_RECTS,\n): ViewRangePresenceHighlight[] {\n  const resolved: ViewRangePresenceHighlight[] = [];\n  const columnIndex = new Map<string, number>();\n  visibleColumns.forEach((c, i) => {\n    if (!columnIndex.has(c.id)) columnIndex.set(c.id, i);\n  });\n  for (const entry of entries) {\n    if (isRowIdPresenceHighlight(entry)) {\n      const viewRow = rowIdToViewRow.get(entry.rowId);\n      if (viewRow === undefined) continue;\n      const col = columnIndex.get(entry.columnId) ?? -1;\n      if (col === -1) {\n        onDroppedColumn?.(entry);\n        continue;\n      }\n      resolved.push({\n        id: entry.id,\n        color: entry.color,\n        range: { x: col, y: viewRow, width: 1, height: 1 },\n        label: entry.label,\n      });\n      continue;\n    }\n    if (isRowIdRangePresenceHighlight(entry)) {\n      const viewRows = entry.rowIds.map((rowId) => rowIdToViewRow.get(rowId)).filter((v): v is number => v !== undefined);\n      const colIndexes = entry.columnIds.map((columnId) => columnIndex.get(columnId) ?? -1);\n      const viewCols = colIndexes.filter((col) => col !== -1);\n      if (viewRows.length === 0 || viewCols.length === 0) continue;\n      if (colIndexes.some((col) => col === -1)) {\n        onUnresolvedColumns?.(entry, colIndexes.filter((col) => col === -1).length);\n      }\n      const rowRuns = contiguousRuns(viewRows);\n      const colRuns = contiguousRuns(viewCols);\n      const total = rowRuns.length * colRuns.length;\n      let painted = 0;\n      let capped = false;\n      for (const rowRun of rowRuns) {\n        for (const colRun of colRuns) {\n          if (painted >= maxRects) {\n            capped = true;\n            break;\n          }\n          resolved.push({\n            id: entry.id,\n            color: entry.color,\n            range: { x: colRun.min, y: rowRun.min, width: colRun.length, height: rowRun.length },\n            label: entry.label,\n          });\n          painted += 1;\n        }\n        if (capped) break;\n      }\n      if (capped) onExcessRects?.(entry, maxRects, total);\n      continue;\n    }\n    resolved.push(entry);\n  }\n  return resolved;\n}\n\n/** Ascending runs of contiguity in a number list: [0, 1, 3] -> [{ min: 0, length: 2 }, { min: 3, length: 1 }]; duplicates collapse. */\nfunction contiguousRuns(values: number[]): { min: number; length: number }[] {\n  const runs: { min: number; length: number }[] = [];\n  let start = Number.POSITIVE_INFINITY;\n  let prev = Number.NEGATIVE_INFINITY;\n  for (const v of [...values].sort((a, b) => a - b)) {\n    if (v === prev) continue;\n    if (v !== prev + 1) {\n      if (start !== Number.POSITIVE_INFINITY) runs.push({ min: start, length: prev - start + 1 });\n      start = v;\n    }\n    prev = v;\n  }\n  if (start !== Number.POSITIVE_INFINITY) runs.push({ min: start, length: prev - start + 1 });\n  return runs;\n}\n\n/**\n * Renders every active highlight into the overlay layer using the SAME window-clamp + pin-zone\n * segmentation pipeline core's own built-in overlays use (via `ctx`), so a highlight spanning a\n * pinned column splits into pinned/unpinned segments and paints at the pinned cell's actual screen\n * position exactly like a selection range does. The plugin's `Overlay` calls this function.\n * `highlights` must already be resolved to view-index (see {@link resolveHighlights}) — the caller\n * (`createPresenceOverlay`) does that resolution itself since it's the one already subscribed to core\n * hooks inside `DataGridOverlays`'s render, keeping this function a plain (hook-free) renderer.\n */\nexport function renderPresenceOverlay(highlights: readonly ViewRangePresenceHighlight[], ctx: OverlayPluginCtx): ReactNode {\n  const { windowStart, clampRowStart, clampRowEnd, colCount, colOffset, pinTrack, splitRectByPinZones, clampRectToWindow } = ctx;\n  const pinned = hasAnyPin(pinTrack) ? pinTrack : undefined;\n  const segment = (rect: GridRect) => (pinned ? splitRectByPinZones(rect, pinned) : [{ rect, pinStyle: undefined }]);\n\n  return (\n    <>\n      {/* entries are keyed by POSITION, not `id`: the id contract is \"unique per entry\", but a\n          peer sending duplicate ids must not break reconciliation (unsupported duplicate React\n          keys) — position is always unique per sibling */}\n      {highlights.map((highlight, i) => {\n        const clamped = clampRectToWindow(highlight.range, clampRowStart, clampRowEnd, colCount);\n        if (!clamped) return null;\n        // top-left corner chip only shows while that exact cell survives the clamp (same guard idea as core's own fill-handle corner check).\n        const topLeftOnWindow = clamped.x === highlight.range.x && clamped.y === highlight.range.y;\n        const topLeftPinStyle = pinned && pinned.pins[highlight.range.x]\n          ? segment({ x: highlight.range.x, y: highlight.range.y, width: 1, height: 1 })[0]?.pinStyle\n          : undefined;\n        return (\n          <Fragment key={i}>\n            {segment(clamped).map((seg, j) => (\n              <PresenceHighlightOverlay\n                key={`presence-${i}-${j}`}\n                rect={seg.rect}\n                color={highlight.color}\n                windowStart={windowStart}\n                colOffset={colOffset}\n                pinStyle={seg.pinStyle}\n              />\n            ))}\n            {topLeftOnWindow && highlight.label && (\n              <PresenceLabelChip\n                rect={{ x: highlight.range.x, y: highlight.range.y, width: 1, height: 1 }}\n                color={highlight.color}\n                label={highlight.label}\n                windowStart={windowStart}\n                colOffset={colOffset}\n                pinStyle={topLeftPinStyle}\n              />\n            )}\n          </Fragment>\n        );\n      })}\n    </>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-presence/presence-overlay.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-presence/to-presence-entries.ts",
      "content": "import type { SelectionChangeDetails, SelectionState } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport type { RowIdRangePresenceHighlight } from \"./presence-store\";\r\n\r\n/** Options for {@link toPresenceEntries}. */\r\nexport type ToPresenceEntriesOptions = {\r\n  /** Unique id of this peer's entry. */\r\n  id: string;\r\n  /** Any CSS color. */\r\n  color: string;\r\n  /** Visible column ids in display order; they order the column span of each range, so reordered columns stay right. */\r\n  columnIds: readonly string[];\r\n  /** Optional name chip. */\r\n  label?: string;\r\n};\r\n\r\n/**\r\n * Turns a local selection into the presence entries to send to peers: one row-id range entry\r\n * with the selected rows and the columns that the ranges, the column channel, or a checked row\r\n * cover. Returns `[]` when nothing is selected. Call it in `onSelectionChange(selection, details)`.\r\n */\r\nexport function toPresenceEntries(selection: SelectionState, details: SelectionChangeDetails, options: ToPresenceEntriesOptions): RowIdRangePresenceHighlight[] {\r\n  const { id, color, columnIds, label } = options;\r\n  const covered = new Set<string>(selection.columnIds);\r\n  if (selection.rowIds.length > 0) for (const columnId of columnIds) covered.add(columnId);\r\n  for (const range of selection.range ? [selection.range, ...selection.rangeStack] : selection.rangeStack) {\r\n    const from = columnIds.indexOf(range.start.columnId);\r\n    const to = columnIds.indexOf(range.end.columnId);\r\n    if (from < 0 || to < 0) continue;\r\n    for (const columnId of columnIds.slice(Math.min(from, to), Math.max(from, to) + 1)) covered.add(columnId);\r\n  }\r\n  const spanned = columnIds.filter((columnId) => covered.has(columnId));\r\n  const rowIds = details.getRowIds();\r\n  if (rowIds.length === 0 || spanned.length === 0) return [];\r\n  return [{ id, color, rowIds, columnIds: spanned, ...(label !== undefined ? { label } : {}) }];\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-presence/to-presence-entries.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
