{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-comments",
  "title": "Data Grid Comments",
  "author": "gridcn",
  "description": "Cell comments add-on for the gridcn data grid: useDataGridComments adds comments addressed by row id and column id, a corner marker, a comments popover with keyboard access (Shift+F2), optimistic versioned saves through onCommentSave, echo matching for applyRemote, and fetchComments for the rendered rows.",
  "dependencies": [
    "zustand@^5.0.15",
    "@base-ui/react@^1.8.0"
  ],
  "registryDependencies": [
    "@gridcn/data-grid",
    "button",
    "textarea",
    "separator"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-comments/data-grid-comments.ts",
      "content": "/** Public entry point: the only module consumers and docs import from. */\r\nexport { useDataGridComments } from \"./use-data-grid-comments\";\r\nexport type { DataGridCommentsLabels } from \"./labels\";\r\nexport type {\r\n  ApplyRemoteSkipReason,\r\n  ApplyRemoteVerdict,\r\n  CellComment,\r\n  CommentAction,\r\n  CommentAuthor,\r\n  CommentChange,\r\n  CommentCreateGateCtx,\r\n  CommentFetchCtx,\r\n  CommentFetchErrorCtx,\r\n  CommentGateCtx,\r\n  CommentMenuItem,\r\n  CommentMenuItemsResolver,\r\n  CommentRejectedCtx,\r\n  CommentRejectReason,\r\n  CommentSaveAck,\r\n  CommentSaveCtx,\r\n  CommentSaveRejectReason,\r\n  CommentSaveResult,\r\n  CommentSource,\r\n  CommentsChangeCtx,\r\n  OrphanedCommentsCtx,\r\n  UseDataGridCommentsOptions,\r\n  UseDataGridCommentsResult,\r\n} from \"./types\";\r\n\r\n// Relative on purpose: the shadcn CLI rewrites import paths, never augmentation module names.\r\ndeclare module \"../data-grid/types\" {\r\n  interface GridActions {\r\n    openComments: true;\r\n  }\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/data-grid-comments.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/use-data-grid-comments.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport type { DataGridPlugin } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { createCommentEngine, type CommentEngine } from \"./comment-engine\";\nimport { createCommentsMount } from \"./comments-mount\";\nimport { createCommentsOverlay } from \"./comments-overlay\";\nimport { sameRecord } from \"./comment-state\";\nimport { commentMenuItems, createMenuItemsResolver } from \"./menu-items\";\nimport type { CellComment, UseDataGridCommentsOptions, UseDataGridCommentsResult } from \"./types\";\n\nconst RENDER_OPTION_KEYS = [\"hideResolved\", \"labels\", \"className\", \"allowWhenReadOnly\", \"readOnly\", \"enableResolve\", \"enableEdit\", \"enableDelete\", \"canEdit\", \"canDelete\", \"canResolve\", \"canCreate\", \"fetchComments\"] as const;\n\nfunction renderOptionsChanged(previous: UseDataGridCommentsOptions, next: UseDataGridCommentsOptions): boolean {\n  if (previous.currentUser?.id !== next.currentUser?.id || previous.currentUser?.name !== next.currentUser?.name || previous.currentUser?.color !== next.currentUser?.color) return true;\n  return RENDER_OPTION_KEYS.some((key) => previous[key] !== next[key]);\n}\n\ntype Instance = {\n  engine: CommentEngine;\n  /** The latest options and the last controlled prop; written in an effect, read by callbacks. */\n  live: { options: UseDataGridCommentsOptions; prop: UseDataGridCommentsOptions[\"comments\"] };\n  result: UseDataGridCommentsResult;\n  seeded: boolean;\n};\n\ntype Live = Instance[\"live\"];\n\nfunction plainSeed(seed: UseDataGridCommentsOptions[\"defaultComments\"]): readonly CellComment[] | undefined {\n  return typeof seed === \"function\" ? undefined : seed;\n}\n\n/** A function seed runs once on the client after mount, so a seed that reads `localStorage` matches the server render; a throw starts the comments empty. */\nfunction readFunctionSeed(seed: UseDataGridCommentsOptions[\"defaultComments\"]): readonly CellComment[] | undefined {\n  if (typeof seed !== \"function\") return undefined;\n  try {\n    return seed();\n  } catch (error) {\n    if (isDev()) console.warn(`[data-grid-comments] defaultComments threw, so the comments start empty: ${String(error)}`);\n    return undefined;\n  }\n}\n\nfunction seedOnce(instance: Instance, seed: UseDataGridCommentsOptions[\"defaultComments\"]): void {\n  if (instance.seeded) return;\n  instance.seeded = true;\n  const records = readFunctionSeed(seed);\n  if (records) instance.engine.seed(records);\n}\n\nfunction assignOptions(live: Live, options: UseDataGridCommentsOptions): UseDataGridCommentsOptions {\n  const previous = live.options;\n  live.options = options;\n  return previous;\n}\n\nfunction sameComments(a: UseDataGridCommentsOptions[\"comments\"], b: UseDataGridCommentsOptions[\"comments\"]): boolean {\n  if (a === b) return true;\n  if (!a || !b || a.length !== b.length) return false;\n  try {\n    return a.every((record, i) => sameRecord(record, b[i]!));\n  } catch {\n    return false;\n  }\n}\n\nfunction assignProp(live: Live, prop: UseDataGridCommentsOptions[\"comments\"]): void {\n  live.prop = prop;\n}\n\nfunction createInstance(options: UseDataGridCommentsOptions): Instance {\n  const live = { options, prop: options.comments };\n  const getOptions = (): UseDataGridCommentsOptions => live.options;\n  const engine = createCommentEngine({\n    getOptions,\n    controlled: options.comments !== undefined,\n    initialComments: options.comments ?? plainSeed(options.defaultComments),\n  });\n  const plugin: DataGridPlugin = {\n    name: \"comments\",\n    Overlay: createCommentsOverlay(engine, getOptions),\n    Mount: createCommentsMount(engine, getOptions),\n    onDataChange: (next, change, ctx) => engine.observeDataChange(next, change, { getRowId: ctx.api.store.getState().getRowId }),\n    commands: {\n      openComments: {\n        when: (ctx) => ctx.row !== undefined && ctx.cell !== null,\n        run: (ctx) => {\n          if (ctx.cell) engine.openComments(ctx.cell, \"keyboard\");\n        },\n      },\n    },\n    keymap: { openComments: [\"shift+F2\"] },\n    cellMenuItems: (ctx) => commentMenuItems(engine, ctx),\n  };\n  const result: UseDataGridCommentsResult = {\n    plugin,\n    applyRemote: engine.applyRemote,\n    getComments: engine.getComments,\n    removeComments: (target) => engine.removeComments(target.rowIds),\n    refetchComments: (target) => engine.refetch(target?.rowIds),\n    openComments: (ref) => engine.openComments(ref, \"keyboard\"),\n    closeComments: () => engine.store.close(),\n    getCommentMenuItems: createMenuItemsResolver(engine),\n  };\n  return { engine, live, result, seeded: false };\n}\n\n/**\n * Cell comments as a single hook: markers, the comments popover, optimistic writes with versions,\n * and echo handling. The hook is called outside the provider; pass `plugin` to the grid's `plugins`.\n * The app owns transport and save (`onCommentSave`, `applyRemote`, `fetchComments`).\n */\nexport function useDataGridComments(options: UseDataGridCommentsOptions = {}): UseDataGridCommentsResult {\n  const [instance] = useState(() => createInstance(options));\n  const { engine, live } = instance;\n\n  useEffect(() => {\n    const previous = assignOptions(live, options);\n    if (renderOptionsChanged(previous, options)) engine.store.bumpContent();\n    if (options.comments !== undefined && !sameComments(options.comments, live.prop)) {\n      assignProp(live, options.comments);\n      engine.syncProp(options.comments);\n    }\n  });\n\n  useEffect(() => {\n    seedOnce(instance, options.defaultComments);\n    engine.start();\n    return () => engine.dispose();\n  }, [engine, instance]);\n\n  return instance.result;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/use-data-grid-comments.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/types.ts",
      "content": "import type { DataChange, DataGridPlugin } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport type { DataGridCommentsLabels } from \"./labels\";\r\n\r\n/** Who wrote or resolved a comment. A per-record snapshot: the identity is `id`, and a later rename changes only new writes. */\r\nexport type CommentAuthor = {\r\n  /** 1..128 characters, no control characters. */\r\n  id: string;\r\n  /** Display name, at most 80 characters; control and bidi-override characters are stripped. */\r\n  name?: string;\r\n  /** CSS color of the author chip, at most 64 characters; an invalid color falls back to a theme token. */\r\n  color?: string;\r\n};\r\n\r\n/** One comment on one cell. The cell is addressed by `rowId` and `columnId`, never by a view index. */\r\nexport type CellComment = {\r\n  /** Client-generated key (`createId`); the permanent identity and the create idempotency key. */\r\n  id: string;\r\n  rowId: string;\r\n  columnId: string;\r\n  /** 1..`maxTextLength` characters after trim. */\r\n  text: string;\r\n  /** Absent for an anonymous comment. A server may add it once; it never changes or goes away after that. */\r\n  author?: CommentAuthor;\r\n  /** Epoch milliseconds. */\r\n  createdAt: number;\r\n  /** Epoch milliseconds; the server should stamp it. */\r\n  updatedAt: number;\r\n  /** Integer 1..1,000,000,000; +1 per accepted write (a stamping server may return a higher one). */\r\n  version: number;\r\n  /** Id of the write that produced this version; generated by the add-on. */\r\n  writeId?: string;\r\n  resolved: boolean;\r\n  resolvedBy?: CommentAuthor;\r\n  resolvedAt?: number;\r\n};\r\n\r\n/** One write as a transport sees it. Resolve and reopen are `upsert` with `resolved` changed. A delete is a tombstone. */\r\nexport type CommentChange =\r\n  | { kind: \"upsert\"; comment: CellComment; baseVersion?: number }\r\n  | { kind: \"delete\"; id: string; rowId: string; columnId: string; version: number; writeId?: string; baseVersion?: number };\r\n\r\n/** What made a store write: an acknowledgement, a remote batch, a fetch answer, a row id swap, or `removeComments`. */\r\nexport type CommentSource = \"ack\" | \"remote\" | \"fetch\" | \"id-swap\" | \"remove\";\r\n\r\n/** What a comment write does. */\r\nexport type CommentAction = \"create\" | \"update\" | \"delete\" | \"resolve\" | \"reopen\";\r\n\r\n/** Context of `onCommentsChange`. */\r\nexport type CommentsChangeCtx = { changes: readonly CommentChange[]; source: CommentSource };\r\n\r\n/** Context of `onCommentSave`. */\r\nexport type CommentSaveCtx = {\r\n  action: CommentAction;\r\n  /** Carries `baseVersion`, `writeId`, and the new record. */\r\n  change: CommentChange;\r\n  /** The last confirmed record before the write. */\r\n  prev?: CellComment;\r\n};\r\n\r\n/** Reasons a transport may reject a write with. */\r\nexport type CommentSaveRejectReason = \"stale\" | \"forbidden\" | \"invalid\" | \"limit\";\r\n\r\n/** What `onCommentSave` may answer. */\r\nexport type CommentSaveAck =\r\n  | { comment?: CellComment | null }\r\n  | { rejected: { reason: CommentSaveRejectReason; message?: string; current?: CellComment | null } };\r\n\r\n/** Return type of `onCommentSave`: `void` accepts the write exactly as sent. */\r\nexport type CommentSaveResult = void | CommentSaveAck | Promise<void | CommentSaveAck>;\r\n\r\n/** Every reason a write is refused or reverted. */\r\nexport type CommentRejectReason = CommentSaveRejectReason | \"read-only\" | \"row-busy\" | \"error\";\r\n\r\n/** Context of `onCommentRejected`. */\r\nexport type CommentRejectedCtx = {\r\n  action: CommentAction;\r\n  /** Absent when the write was refused before a record existed (invalid `createId` or `currentUser`). */\r\n  change?: CommentChange;\r\n  reason: CommentRejectReason;\r\n  message?: string;\r\n  current?: CellComment | null;\r\n  error?: unknown;\r\n};\r\n\r\n/** Context of the `canEdit`, `canDelete`, and `canResolve` gates. `action` tells resolve from reopen. `user` is absent without `currentUser`. `signal` aborts on unmount or when the request is superseded. */\r\nexport type CommentGateCtx = { comment: CellComment; action: CommentAction; user?: CommentAuthor; signal: AbortSignal };\r\n\r\n/** Context of the `canCreate` gate. `user` is absent without `currentUser`. */\r\nexport type CommentCreateGateCtx = { rowId: string; columnId: string; user?: CommentAuthor; signal: AbortSignal };\r\n\r\n/** Context of `fetchComments`. */\r\nexport type CommentFetchCtx = { rowIds: readonly string[]; signal: AbortSignal };\r\n\r\n/** Context of `onFetchError`. */\r\nexport type CommentFetchErrorCtx = { reason: \"error\" | \"limit\"; rowIds: readonly string[]; error?: unknown };\r\n\r\n/** Context of `onOrphanedComments`: comments whose rows were deleted. They stay in the store. */\r\nexport type OrphanedCommentsCtx = { comments: readonly CellComment[]; rowIds: readonly string[]; source: DataChange<unknown>[\"source\"] };\r\n\r\n/** Why `applyRemote` skipped a change. */\r\nexport type ApplyRemoteSkipReason = \"stale\" | \"duplicate\" | \"invalid\" | \"limit\" | \"tombstoned\" | \"unknown\";\r\n\r\n/** What `applyRemote` did with a batch. */\r\nexport type ApplyRemoteVerdict = {\r\n  applied: number;\r\n  skippedCount: number;\r\n  /** The first 100 skipped changes. */\r\n  skipped: readonly { index: number; reason: ApplyRemoteSkipReason }[];\r\n  /** Changes beyond the batch limit, ignored. */\r\n  truncated: number;\r\n};\r\n\r\n/** The context-menu item shape the add-on contributes. */\r\nexport type CommentMenuItem = {\r\n  id: string;\r\n  label: string;\r\n  onClick: () => void;\r\n};\r\n\r\n/** The separator before the comments item. */\r\nexport type CommentMenuSeparator = { id: string; separator: true };\r\n\r\n/** Structurally compatible with the context-menu add-on's `CellMenuItemsResolver`; pass it as `getCellMenuItems`. */\r\nexport type CommentMenuItemsResolver = <TItem extends { id: string }>(\r\n  ctx: { rowId: string; columnId: string; viewRowIndex: number },\r\n  defaults: TItem[],\r\n) => (TItem | CommentMenuItem | CommentMenuSeparator)[];\r\n\r\n/** Options of {@link useDataGridComments}. */\r\nexport type UseDataGridCommentsOptions = {\r\n  /** The user who writes. Without it, writes are anonymous. Only `id` is required. A present but invalid value refuses every write. */\r\n  currentUser?: CommentAuthor;\r\n  /** Blocks every comment write and hides the composer and the actions. Default `false`. */\r\n  readOnly?: boolean;\r\n  /** Shows resolve and reopen. `false` ignores the `resolved` state in the UI and refuses resolve and reopen. Default `true`. */\r\n  enableResolve?: boolean;\r\n  /** Shows edit. `false` removes the Edit action and refuses edits with the reason `\"forbidden\"`. Default `true`. */\r\n  enableEdit?: boolean;\r\n  /** Shows delete. `false` removes the Delete action and refuses deletes with the reason `\"forbidden\"`. Default `true`. */\r\n  enableDelete?: boolean;\r\n  /** Controlled confirmed comments. Keep the reference stable between renders. */\r\n  comments?: readonly CellComment[];\r\n  /** One-shot seed. A function runs once on the client after mount. */\r\n  defaultComments?: readonly CellComment[] | (() => readonly CellComment[]);\r\n  /** State channel: one call per store write, `next` holds confirmed records only. With `fetchComments` it is a partial cache: save from `ctx.changes`. */\r\n  onCommentsChange?: (next: readonly CellComment[], ctx: CommentsChangeCtx) => void;\r\n  /** Saves one write. Return nothing to accept it as sent, `{ comment }` for the authoritative record, `{ rejected }` or throw to revert. */\r\n  onCommentSave?: (ctx: CommentSaveCtx) => CommentSaveResult;\r\n  /** Called once per refused or reverted write. */\r\n  onCommentRejected?: (ctx: CommentRejectedCtx) => void;\r\n  /** Broadcast seam: fires once per confirmed local write. It cannot refuse. */\r\n  onLocalChange?: (change: CommentChange) => void;\r\n  /** Gate for creating a comment. Default: anyone. */\r\n  canCreate?: (ctx: CommentCreateGateCtx) => boolean | Promise<boolean>;\r\n  /** Gate for editing. Default: the author, or anyone when the comment has no author. */\r\n  canEdit?: (ctx: CommentGateCtx) => boolean | Promise<boolean>;\r\n  /** Gate for deleting. Default: the author, or anyone when the comment has no author. */\r\n  canDelete?: (ctx: CommentGateCtx) => boolean | Promise<boolean>;\r\n  /** Gate for resolving and reopening; `ctx.action` tells them apart. Default: anyone. */\r\n  canResolve?: (ctx: CommentGateCtx) => boolean | Promise<boolean>;\r\n  /** Loads the comments of the rendered rows. */\r\n  fetchComments?: (ctx: CommentFetchCtx) => Promise<readonly CellComment[]>;\r\n  /** Called for a failed fetch request or for records dropped for a bound. */\r\n  onFetchError?: (ctx: CommentFetchErrorCtx) => void;\r\n  /** Called when rows with comments are deleted. */\r\n  onOrphanedComments?: (ctx: OrphanedCommentsCtx) => void;\r\n  /** Default: `crypto.randomUUID` with a fallback outside secure contexts. */\r\n  createId?: () => string;\r\n  /** Applied to local text before the bounds are checked. */\r\n  normalizeText?: (text: string) => string;\r\n  /** Default 2,000; ceiling 20,000. */\r\n  maxTextLength?: number;\r\n  /** Default 50; ceiling 500. */\r\n  maxCommentsPerCell?: number;\r\n  /** Default 50,000; ceiling 500,000. */\r\n  maxComments?: number;\r\n  /** Uncontrolled fetch cache bound in rows. Default 2,000; ceiling 20,000. */\r\n  maxCachedRows?: number;\r\n  /** Let comment writes through on a `readOnly` grid. Default `false`. */\r\n  allowWhenReadOnly?: boolean;\r\n  /** Hide the markers of resolved-only cells. Default `false`. */\r\n  hideResolved?: boolean;\r\n  /** Overrides the strings of the comments UI. A key set to `undefined` keeps its default. */\r\n  labels?: Partial<DataGridCommentsLabels>;\r\n  /** Class of the popover root, merged with `cn`. */\r\n  className?: string;\r\n};\r\n\r\n/** Return value of {@link useDataGridComments}. */\r\nexport type UseDataGridCommentsResult = {\r\n  /** One entry of the grid's `plugins`. Stable for the component's lifetime. */\r\n  plugin: DataGridPlugin;\r\n  /** Applies records another client wrote. Works in controlled and uncontrolled mode. */\r\n  applyRemote(changes: readonly CommentChange[]): ApplyRemoteVerdict;\r\n  /** A bounded snapshot, not reactive. Partial under the fetch cache. */\r\n  getComments(): readonly CellComment[];\r\n  /** Forgets the comments of these rows (emits `onCommentsChange` with source `\"remove\"`). Returns how many were removed. */\r\n  removeComments(target: { rowIds: readonly string[] }): number;\r\n  /** Marks rows unfetched and loads them again. */\r\n  refetchComments(target?: { rowIds?: readonly string[] }): void;\r\n  /** Opens the popover for a cell. `false` for a hole, a filtered-out row, or a hidden column. */\r\n  openComments(ref: { rowId: string; columnId: string }): boolean;\r\n  closeComments(): void;\r\n  /** Pass as the context menu's `getCellMenuItems` to add a \"Comments…\" item. */\r\n  getCommentMenuItems: CommentMenuItemsResolver;\r\n};\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/types.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/labels.ts",
      "content": "import { mergeLabelLayers, type DataGridCommentsLabels } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\nexport type { DataGridCommentsLabels } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\nconst by = (name: string): string => (name ? ` by ${name}` : \"\");\r\nconst openHint = (chord: string): string => (chord ? ` Press ${chord} to open.` : \"\");\r\n\r\nexport const DEFAULT_COMMENTS_LABELS: DataGridCommentsLabels = {\r\n  popover: (columnTitle, cellText) => (cellText ? `Comments on ${columnTitle}: ${cellText}` : `Comments on ${columnTitle}`),\r\n  locale: \"en-US\",\r\n  commentList: \"Comments\",\r\n  composer: \"Write a comment\",\r\n  editComposer: \"Edit comment\",\r\n  composerPlaceholder: \"Write a comment…\",\r\n  submit: \"Comment\",\r\n  cancel: \"Cancel\",\r\n  save: \"Save\",\r\n  editAction: \"Edit\",\r\n  deleteAction: \"Delete\",\r\n  confirmDeleteAction: \"Delete?\",\r\n  resolveAction: \"Resolve\",\r\n  reopenAction: \"Reopen\",\r\n  edit: (name, time) => `Edit comment${by(name)}, ${time}`,\r\n  remove: (name, time) => `Delete comment${by(name)}, ${time}`,\r\n  confirmRemove: (name, time) => `Confirm delete of comment${by(name)}, ${time}`,\r\n  resolve: (name, time) => `Resolve comment${by(name)}, ${time}`,\r\n  reopen: (name, time) => `Reopen comment${by(name)}, ${time}`,\r\n  resolved: \"Resolved\",\r\n  saving: \"Saving\",\r\n  loading: \"Loading comments…\",\r\n  loadFailed: \"Could not load comments\",\r\n  retry: \"Retry\",\r\n  discard: \"Discard\",\r\n  saveMine: \"Save my version\",\r\n  changedByOther: \"Changed by someone else\",\r\n  readOnlyHint: \"Comments are read-only.\",\r\n  rowBusyHint: \"This row is still saving. Try again in a moment.\",\r\n  refused: \"You cannot do this.\",\r\n  failed: \"The comment could not be saved.\",\r\n  counter: (used, max) => `${used} / ${max}`,\r\n  menuItem: \"Comments…\",\r\n  noComments: \"No comments yet.\",\r\n  announce: (count, unresolved, chord) => `${count} ${count === 1 ? \"comment\" : \"comments\"}, ${unresolved} unresolved.${openHint(chord)}`,\r\n  announceCount: (count, chord) => `${count} ${count === 1 ? \"comment\" : \"comments\"}.${openHint(chord)}`,\r\n  announceAdded: (name) => (name ? `Comment added by ${name}` : \"Comment added\"),\r\n  unknownAuthor: \"Unknown\",\r\n};\r\n\r\n/** What the grid contributes to the comments labels: its locale and its `labels.comments` overrides. */\r\nexport type GridCommentsLabelLayer = { locale?: string; comments?: Partial<DataGridCommentsLabels> };\r\n\r\n/** The default labels, then the grid's locale and `labels.comments`, then `overrides`; a key set to `undefined` keeps the layer below. */\r\nexport function resolveCommentsLabels(grid: GridCommentsLabelLayer | undefined, overrides?: Partial<DataGridCommentsLabels>): DataGridCommentsLabels {\r\n  return mergeLabelLayers<DataGridCommentsLabels>(DEFAULT_COMMENTS_LABELS, { locale: grid?.locale }, grid?.comments, overrides);\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/labels.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/own-cell.ts",
      "content": "import { GRID_ATTR, GRID_ROLE_SELECTOR, dataIndexAt, rowIdAtViewRow, type DataGridReadState } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\n\r\n/** The view row that shows the data row `rowId`, or -1; a group row never matches (it is not a place for a comment). */\r\nexport function viewRowOfRowId(state: DataGridReadState, rowId: string): number {\r\n  for (let viewRow = 0; viewRow < state.viewIndex.length; viewRow++) {\r\n    if (dataIndexAt(state, viewRow) !== undefined && rowIdAtViewRow(state, viewRow) === rowId) return viewRow;\r\n  }\r\n  return -1;\r\n}\r\n\r\n/** The cell of this grid at a view row and column; a nested grid's cell with the same coordinates never matches. */\r\nexport function findOwnCell(scroll: HTMLElement | null, viewRow: number, columnId: string): HTMLElement | null {\r\n  if (!scroll) return null;\r\n  const grid = scroll.closest(GRID_ROLE_SELECTOR);\r\n  const cells = scroll.querySelectorAll<HTMLElement>(`[${GRID_ATTR.rowIndex}=\"${viewRow}\"] [data-column-id=\"${CSS.escape(columnId)}\"]`);\r\n  return Array.from(cells).find((cell) => cell.closest(GRID_ROLE_SELECTOR) === grid) ?? null;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/own-cell.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/validate.ts",
      "content": "import { toSafeText } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport type { AckOutcome } from \"./comment-state\";\r\nimport type { CellComment, CommentAuthor, CommentChange } from \"./types\";\r\n\r\nconst MAX_ID_LENGTH = 128;\r\nconst MAX_NAME_LENGTH = 80;\r\nconst MAX_COLOR_LENGTH = 64;\r\nexport const MAX_VERSION = 1_000_000_000;\r\nconst MAX_EPOCH_MS = 8.64e15;\r\n\r\nexport type Bounds = {\r\n  maxTextLength: number;\r\n  maxCommentsPerCell: number;\r\n  maxComments: number;\r\n  maxCachedRows: number;\r\n};\r\n\r\nexport const DEFAULT_BOUNDS: Bounds = { maxTextLength: 2000, maxCommentsPerCell: 50, maxComments: 50_000, maxCachedRows: 2000 };\r\nconst BOUND_CEILINGS: Bounds = { maxTextLength: 20_000, maxCommentsPerCell: 500, maxComments: 500_000, maxCachedRows: 20_000 };\r\n\r\nfunction bound(value: number | undefined, fallback: number, ceiling: number): number {\r\n  if (value === undefined || !Number.isInteger(value) || value <= 0) return fallback;\r\n  return Math.min(value, ceiling);\r\n}\r\n\r\n/** NaN, zero, negative, and fractional values fall back to the default; large values clamp to the ceiling. */\r\nexport function resolveBounds(options: Partial<Bounds>): Bounds {\r\n  return {\r\n    maxTextLength: bound(options.maxTextLength, DEFAULT_BOUNDS.maxTextLength, BOUND_CEILINGS.maxTextLength),\r\n    maxCommentsPerCell: bound(options.maxCommentsPerCell, DEFAULT_BOUNDS.maxCommentsPerCell, BOUND_CEILINGS.maxCommentsPerCell),\r\n    maxComments: bound(options.maxComments, DEFAULT_BOUNDS.maxComments, BOUND_CEILINGS.maxComments),\r\n    maxCachedRows: bound(options.maxCachedRows, DEFAULT_BOUNDS.maxCachedRows, BOUND_CEILINGS.maxCachedRows),\r\n  };\r\n}\r\n\r\n// eslint-disable-next-line no-control-regex\r\nconst CONTROL = /[\\u0000-\\u001f\\u007f-\\u009f]/;\r\nconst BIDI_OVERRIDE_G = /[\\u202a-\\u202e\\u2066-\\u2069]/g;\r\n// eslint-disable-next-line no-control-regex\r\nconst CONTROL_OR_BIDI_G = /[\\u0000-\\u001f\\u007f-\\u009f‎‏\\u202a-\\u202e\\u061c\\u2066-\\u2069]/g;\r\n\r\ntype Raw = {\r\n  id?: unknown; name?: unknown; color?: unknown; rowId?: unknown; columnId?: unknown; text?: unknown; createdAt?: unknown;\r\n  updatedAt?: unknown; version?: unknown; resolved?: unknown; author?: unknown; writeId?: unknown; resolvedBy?: unknown;\r\n  resolvedAt?: unknown; kind?: unknown; baseVersion?: unknown; comment?: unknown;\r\n};\r\n\r\nexport function isSafeId(value: unknown): value is string {\r\n  return typeof value === \"string\" && value.length > 0 && value.length <= MAX_ID_LENGTH && !CONTROL.test(value);\r\n}\r\n\r\n/** Strips control and bidi-override characters and bounds the length. */\r\nexport function sanitizeName(value: unknown): string | undefined {\r\n  if (typeof value !== \"string\") return undefined;\r\n  const clean = value.slice(0, MAX_NAME_LENGTH * 2).replace(CONTROL_OR_BIDI_G, \"\").trim().slice(0, MAX_NAME_LENGTH);\r\n  return clean === \"\" ? undefined : clean;\r\n}\r\n\r\n/** Validates an author into a fresh frozen object, or `null`. */\r\nexport function validateAuthor(value: unknown): CommentAuthor | null {\r\n  try {\r\n    return readAuthor(value);\r\n  } catch {\r\n    return null;\r\n  }\r\n}\r\n\r\nfunction readAuthor(value: unknown): CommentAuthor | null {\r\n  if (typeof value !== \"object\" || value === null) return null;\r\n  const raw = value as Raw;\r\n  const id = raw.id;\r\n  const rawName = raw.name;\r\n  const color = raw.color;\r\n  if (!isSafeId(id)) return null;\r\n  const author: CommentAuthor = { id };\r\n  const name = sanitizeName(rawName);\r\n  if (name !== undefined) author.name = name;\r\n  if (typeof color === \"string\" && color.length > 0 && color.length <= MAX_COLOR_LENGTH && !CONTROL.test(color)) author.color = color;\r\n  return Object.freeze(author);\r\n}\r\n\r\nfunction isEpoch(value: unknown): value is number {\r\n  return typeof value === \"number\" && Math.abs(value) <= MAX_EPOCH_MS;\r\n}\r\n\r\nexport function isVersion(value: unknown): value is number {\r\n  return typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= MAX_VERSION;\r\n}\r\n\r\n/** `toSafeText` minus bidi overrides, plus trim: the text a write stores. The caller checks the bounds on the result. */\r\nexport function cleanText(value: unknown): string {\r\n  return toSafeText(value).replace(BIDI_OVERRIDE_G, \"\").trim();\r\n}\r\n\r\n/** Validates one record into a fresh frozen object (each field read once), or `null`. Text over `maxTextLength` is a breach, never truncated. */\r\nexport function validateComment(value: unknown, bounds: Bounds): CellComment | null {\r\n  try {\r\n    return readComment(value, bounds);\r\n  } catch {\r\n    return null;\r\n  }\r\n}\r\n\r\nfunction readComment(value: unknown, bounds: Bounds): CellComment | null {\r\n  if (typeof value !== \"object\" || value === null) return null;\r\n  const raw = value as Raw;\r\n  const id = raw.id;\r\n  const rowId = raw.rowId;\r\n  const columnId = raw.columnId;\r\n  const rawText = raw.text;\r\n  const createdAt = raw.createdAt;\r\n  const updatedAt = raw.updatedAt;\r\n  const version = raw.version;\r\n  const resolved = raw.resolved;\r\n  const rawAuthor = raw.author;\r\n  const writeId = raw.writeId;\r\n  const rawResolvedBy = raw.resolvedBy;\r\n  const resolvedAt = raw.resolvedAt;\r\n  if (!isSafeId(id) || !isSafeId(rowId) || !isSafeId(columnId)) return null;\r\n  if (typeof rawText !== \"string\" || rawText.length > bounds.maxTextLength * 4) return null;\r\n  const text = rawText.replace(BIDI_OVERRIDE_G, \"\").trim();\r\n  if (text.length < 1 || text.length > bounds.maxTextLength) return null;\r\n  if (!isEpoch(createdAt) || !isEpoch(updatedAt) || !isVersion(version) || typeof resolved !== \"boolean\") return null;\r\n  const record: CellComment = { id, rowId, columnId, text, createdAt, updatedAt, version, resolved };\r\n  if (rawAuthor !== undefined) {\r\n    const author = validateAuthor(rawAuthor);\r\n    if (!author) return null;\r\n    record.author = author;\r\n  }\r\n  if (writeId !== undefined) {\r\n    if (!isSafeId(writeId)) return null;\r\n    record.writeId = writeId;\r\n  }\r\n  if (rawResolvedBy !== undefined) {\r\n    const resolvedBy = validateAuthor(rawResolvedBy);\r\n    if (!resolvedBy) return null;\r\n    record.resolvedBy = resolvedBy;\r\n  }\r\n  if (resolvedAt !== undefined) {\r\n    if (!isEpoch(resolvedAt)) return null;\r\n    record.resolvedAt = resolvedAt;\r\n  }\r\n  return Object.freeze(record);\r\n}\r\n\r\n/** Validates a change (an upsert with a record, or a delete tombstone) into a fresh frozen object, or `null`. */\r\nexport function validateChange(value: unknown, bounds: Bounds): CommentChange | null {\r\n  try {\r\n    return readChange(value, bounds);\r\n  } catch {\r\n    return null;\r\n  }\r\n}\r\n\r\nfunction readChange(value: unknown, bounds: Bounds): CommentChange | null {\r\n  if (typeof value !== \"object\" || value === null) return null;\r\n  const raw = value as Raw;\r\n  const kind = raw.kind;\r\n  const baseVersion = raw.baseVersion;\r\n  if (baseVersion !== undefined && !(typeof baseVersion === \"number\" && Number.isInteger(baseVersion) && baseVersion >= 0 && baseVersion <= MAX_VERSION)) return null;\r\n  if (kind === \"upsert\") {\r\n    const comment = validateComment(raw.comment, bounds);\r\n    if (!comment) return null;\r\n    return Object.freeze(baseVersion === undefined ? { kind: \"upsert\" as const, comment } : { kind: \"upsert\" as const, comment, baseVersion });\r\n  }\r\n  if (kind === \"delete\") {\r\n    const id = raw.id;\r\n    const rowId = raw.rowId;\r\n    const columnId = raw.columnId;\r\n    const version = raw.version;\r\n    const writeId = raw.writeId;\r\n    if (!isSafeId(id) || !isSafeId(rowId) || !isSafeId(columnId) || !isVersion(version)) return null;\r\n    if (writeId !== undefined && !isSafeId(writeId)) return null;\r\n    const change: CommentChange = { kind: \"delete\", id, rowId, columnId, version };\r\n    if (writeId !== undefined) change.writeId = writeId;\r\n    if (baseVersion !== undefined) change.baseVersion = baseVersion;\r\n    return Object.freeze(change);\r\n  }\r\n  return null;\r\n}\r\n\r\n/** Reads an `onCommentSave` answer: unknown shapes accept the write as sent, records pass `validateComment`. */\r\nexport function parseSaveAnswer(raw: unknown, bounds: Bounds): AckOutcome {\r\n  if (raw === undefined || raw === null) return { kind: \"void\", server: true };\r\n  if (typeof raw !== \"object\") return { kind: \"void\", server: true };\r\n  const record = raw as { comment?: unknown; rejected?: { reason?: unknown; message?: unknown; current?: unknown } };\r\n  if (record.rejected && typeof record.rejected === \"object\") {\r\n    const { reason, message, current } = record.rejected;\r\n    const allowed = reason === \"stale\" || reason === \"forbidden\" || reason === \"invalid\" || reason === \"limit\";\r\n    const out: Extract<AckOutcome, { kind: \"rejected\" }> = { kind: \"rejected\", reason: allowed ? reason : \"invalid\" };\r\n    if (typeof message === \"string\") out.message = message.slice(0, 200);\r\n    if (current === null) out.current = null;\r\n    else if (current !== undefined) {\r\n      const valid = validateComment(current, bounds);\r\n      if (valid) out.current = valid;\r\n    }\r\n    return out;\r\n  }\r\n  if (\"comment\" in record) {\r\n    if (record.comment === null) return { kind: \"record\", comment: null };\r\n    if (record.comment === undefined) return { kind: \"void\", server: true };\r\n    const valid = validateComment(record.comment, bounds);\r\n    return valid ? { kind: \"record\", comment: valid } : { kind: \"invalid\" };\r\n  }\r\n  return { kind: \"void\", server: true };\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/validate.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/create-id.ts",
      "content": "function randomHex(bytes: number): string {\r\n  const values = new Uint8Array(bytes);\r\n  if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") crypto.getRandomValues(values);\r\n  else for (let i = 0; i < bytes; i += 1) values[i] = Math.floor(Math.random() * 256);\r\n  return Array.from(values, (v) => v.toString(16).padStart(2, \"0\")).join(\"\");\r\n}\r\n\r\n/** `crypto.randomUUID` where it exists, a `getRandomValues` fallback on plain-http hosts. */\r\nexport function defaultCreateId(): string {\r\n  if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\r\n  return randomHex(16);\r\n}\r\n\r\n/** A write id generator: a random prefix per instance (drawn on the first write, never during render) plus a random suffix, so a peer cannot predict or forge an echo. */\r\nexport function createWriteIdGenerator(): () => string {\r\n  let prefix: string | undefined;\r\n  return () => {\r\n    prefix ??= randomHex(6);\r\n    return `${prefix}-${randomHex(8)}`;\r\n  };\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/create-id.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/default-gate.ts",
      "content": "import type { CellComment, CommentAuthor } from \"./types\";\n\n/** The default `canEdit` and `canDelete`: anyone on a comment with no author, otherwise the author. */\nexport function defaultCanModify(comment: CellComment, user: CommentAuthor | undefined): boolean {\n  return comment.author === undefined || comment.author.id === user?.id;\n}\n\n/** An author may be added once to a comment that has none; any other change is invalid. */\nexport function authorChangeAllowed(current: CommentAuthor | undefined, next: CommentAuthor | undefined): boolean {\n  if (current === undefined) return true;\n  return next !== undefined && next.id === current.id;\n}\n\n/** The name a label or announcement shows: empty for an anonymous comment. */\nexport function authorLabelName(author: CommentAuthor | undefined, unknownAuthor: string): string {\n  return author === undefined ? \"\" : (author.name ?? unknownAuthor);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/default-gate.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-state.ts",
      "content": "import type {\n  ApplyRemoteSkipReason,\n  ApplyRemoteVerdict,\n  CellComment,\n  CommentAction,\n  CommentChange,\n  CommentRejectedCtx,\n  CommentRejectReason,\n  CommentSaveRejectReason,\n  CommentSource,\n} from \"./types\";\nimport type { Bounds } from \"./validate\";\n\nexport const TOMBSTONE_TTL_MS = 10 * 60_000;\nexport const MAX_TOMBSTONES = 10_000;\nexport const MAX_REMOTE_BATCH = 10_000;\nexport const MAX_ALIASES = 10_000;\nexport const MAX_DRAFTS = 50;\nexport const MAX_FETCH_LOG = 1000;\nexport const OWN_WRITE_GRACE_MS = 30_000;\nexport const EMITTED_MEMORY_MS = 30_000;\nexport const MAX_EMITTED = 10_000;\nexport const MAX_LISTED_SKIPS = 100;\n\nexport type Pending = {\n  writeId: string;\n  action: CommentAction;\n  baseVersion: number;\n  baseWriteId: string | undefined;\n  change: CommentChange;\n  /** The optimistic record shown while saving; the confirmed record for a delete. */\n  record: CellComment;\n  superseded: boolean;\n};\n\nexport type Conflict = {\n  id: string;\n  rowId: string;\n  columnId: string;\n  action: CommentAction;\n  reason: CommentRejectReason;\n  message?: string;\n  writeId: string;\n  baseVersion: number;\n  baseWriteId: string | undefined;\n  change: CommentChange;\n  record: CellComment;\n  /** The write's outcome is unknown: an echo of `writeId` still confirms it. */\n  thrown: boolean;\n  /** The text the user had submitted. */\n  text?: string;\n  /** Version of the record the conflict UI shows; \"Save my version\" writes on top of it. */\n  shownVersion: number;\n  /** A stale answer without `current`: nothing but Discard is offered. */\n  discardOnly: boolean;\n};\n\nexport type Draft = {\n  key: string;\n  kind: \"new\" | \"edit\";\n  commentId?: string;\n  rowId: string;\n  columnId: string;\n  text: string;\n  baseVersion: number;\n  baseWriteId: string | undefined;\n};\n\nexport type Tombstone = { id: string; rowId: string; columnId: string; version: number; expiresAt: number };\n\nexport type FetchRequest = { rowIds: Set<string>; startSeq: number; overflow: boolean; remapped: boolean; log: number };\n\nexport type CommentsState = {\n  bounds: Bounds;\n  controlled: boolean;\n  confirmed: Map<string, CellComment>;\n  serverConfirmed: Map<string, number>;\n  tombstones: Map<string, Tombstone>;\n  pending: Map<string, Pending>;\n  conflicts: Map<string, Conflict>;\n  drafts: Map<string, Draft>;\n  index: Map<string, Map<string, Set<string>>>;\n  touched: Map<string, number>;\n  ownConfirmedAt: Map<string, number>;\n  seq: number;\n  aliases: Map<string, string>;\n  requests: Map<number, FetchRequest>;\n  rowRequest: Map<string, number>;\n  fetchedRows: Set<string>;\n  propRaw: Map<string, CellComment>;\n  rawOf: Map<string, { valid: CellComment; raw: CellComment }>;\n  emitted: Map<string, number>;\n  /** Count of prop or seed records dropped by validation or a bound, for the development warning. */\n  dropped: number;\n};\n\nexport type Emit =\n  | { t: \"change\"; changes: CommentChange[]; source: CommentSource }\n  | { t: \"local\"; change: CommentChange }\n  | { t: \"rejected\"; ctx: CommentRejectedCtx }\n  | { t: \"refetch\"; rowIds: string[] }\n  | { t: \"warn\"; message: string; unlessFetch?: boolean };\n\nexport type AckOutcome =\n  | { kind: \"void\"; server: boolean }\n  | { kind: \"record\"; comment: CellComment | null }\n  | { kind: \"rejected\"; reason: CommentSaveRejectReason; message?: string; current?: CellComment | null }\n  | { kind: \"throw\"; error: unknown }\n  | { kind: \"invalid\" };\n\nexport type CommentEvent =\n  | { type: \"localWrite\"; action: CommentAction; change: CommentChange; record: CellComment; baseWriteId: string | undefined; now: number }\n  | { type: \"ack\"; id: string; writeId: string; outcome: AckOutcome; now: number }\n  | { type: \"remote\"; changes: readonly { index: number; change: CommentChange }[]; invalid: readonly number[]; truncated: number; now: number }\n  | { type: \"fetchStart\"; requestId: number; rowIds: readonly string[] }\n  | { type: \"fetchAnswer\"; requestId: number; records: readonly CellComment[]; rawIds: ReadonlySet<string>; now: number }\n  | { type: \"fetchFail\"; requestId: number }\n  | { type: \"propChange\"; next: readonly CellComment[]; now: number }\n  | { type: \"remove\"; rowIds: readonly string[]; now: number }\n  | { type: \"evict\"; rowIds: readonly string[]; keepRows: ReadonlySet<string> }\n  | { type: \"idSwap\"; map: ReadonlyMap<string, string> }\n  | { type: \"invalidateRows\"; rowIds: readonly string[] | null }\n  | { type: \"expire\"; now: number };\n\nexport type ReduceResult = { emits: Emit[]; verdict?: ApplyRemoteVerdict; ok?: boolean; removed?: number; limited?: number };\n\nexport type Ctx = { st: CommentsState; out: Emit[]; changes: CommentChange[]; now: number };\nexport type Skip = ApplyRemoteSkipReason;\n\nexport function createCommentsState(bounds: Bounds, controlled: boolean): CommentsState {\n  return {\n    bounds,\n    controlled,\n    confirmed: new Map(),\n    serverConfirmed: new Map(),\n    tombstones: new Map(),\n    pending: new Map(),\n    conflicts: new Map(),\n    drafts: new Map(),\n    index: new Map(),\n    touched: new Map(),\n    ownConfirmedAt: new Map(),\n    seq: 0,\n    aliases: new Map(),\n    requests: new Map(),\n    rowRequest: new Map(),\n    fetchedRows: new Set(),\n    propRaw: new Map(),\n    rawOf: new Map(),\n    emitted: new Map(),\n    dropped: 0,\n  };\n}\n\nexport const newDraftKey = (rowId: string, columnId: string): string => `n\\u0001${rowId}\\u0001${columnId}`;\nexport const editDraftKey = (id: string): string => `e\\u0001${id}`;\n\nexport function sameAuthor(a: CellComment[\"author\"] | undefined, b: CellComment[\"author\"] | undefined): boolean {\n  if (a === b) return true;\n  if (!a || !b) return false;\n  return a.id === b.id && a.name === b.name && a.color === b.color;\n}\n\n/** Equality over every typed field of a record. */\nexport function sameRecord(a: CellComment, b: CellComment): boolean {\n  return (\n    a === b ||\n    (a.id === b.id &&\n      a.rowId === b.rowId &&\n      a.columnId === b.columnId &&\n      a.text === b.text &&\n      a.version === b.version &&\n      a.writeId === b.writeId &&\n      a.createdAt === b.createdAt &&\n      a.updatedAt === b.updatedAt &&\n      a.resolved === b.resolved &&\n      a.resolvedAt === b.resolvedAt &&\n      sameAuthor(a.author, b.author) &&\n      sameAuthor(a.resolvedBy, b.resolvedBy))\n  );\n}\n\n/** Orders the comments of one cell: `(createdAt, id)` ascending. */\nexport function compareComments(a: CellComment, b: CellComment): number {\n  return a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);\n}\n\n/** The record the UI shows for an id: the optimistic record of a live pending write, else the confirmed record. */\nexport function displayRecord(st: CommentsState, id: string): CellComment | undefined {\n  const p = st.pending.get(id);\n  if (p && !p.superseded) return p.record;\n  return st.confirmed.get(id);\n}\n\n/** The comments of one cell in display order, with their saving flag. */\nexport function cellComments(st: CommentsState, rowId: string, columnId: string): { comment: CellComment; saving: boolean }[] {\n  const ids = st.index.get(rowId)?.get(columnId);\n  if (!ids) return [];\n  const list: { comment: CellComment; saving: boolean }[] = [];\n  for (const id of ids) {\n    const comment = displayRecord(st, id);\n    if (comment) list.push({ comment, saving: st.pending.get(id)?.superseded === false });\n  }\n  return list.sort((x, y) => compareComments(x.comment, y.comment));\n}\n\nexport function bump(c: Ctx, id: string): void {\n  if (c.st.touched.size > 50_000 && c.st.requests.size === 0) c.st.touched.clear();\n  c.st.seq += 1;\n  c.st.touched.set(id, c.st.seq);\n}\n\nexport function indexAdd(st: CommentsState, id: string, rowId: string, columnId: string): void {\n  let columns = st.index.get(rowId);\n  if (!columns) st.index.set(rowId, (columns = new Map<string, Set<string>>()));\n  let ids = columns.get(columnId);\n  if (!ids) columns.set(columnId, (ids = new Set<string>()));\n  ids.add(id);\n}\n\nexport function indexRemove(st: CommentsState, id: string, rowId: string, columnId: string): void {\n  const columns = st.index.get(rowId);\n  const ids = columns?.get(columnId);\n  if (!columns || !ids) return;\n  ids.delete(id);\n  if (ids.size === 0) columns.delete(columnId);\n  if (columns.size === 0) st.index.delete(rowId);\n}\n\nexport function syncIndex(st: CommentsState, id: string, rowId: string, columnId: string): void {\n  if (st.confirmed.has(id) || st.pending.has(id)) indexAdd(st, id, rowId, columnId);\n  else indexRemove(st, id, rowId, columnId);\n}\n\nexport function resolveAlias(st: CommentsState, rowId: string): string {\n  let current = rowId;\n  for (let hop = 0; hop < 5; hop += 1) {\n    const next = st.aliases.get(current);\n    if (next === undefined) break;\n    current = next;\n  }\n  return current;\n}\n\nexport function withAlias(st: CommentsState, rec: CellComment): CellComment {\n  const rowId = resolveAlias(st, rec.rowId);\n  return rowId === rec.rowId ? rec : Object.freeze({ ...rec, rowId });\n}\n\nexport function changeAlias(st: CommentsState, change: CommentChange): CommentChange {\n  if (change.kind === \"upsert\") {\n    const comment = withAlias(st, change.comment);\n    return comment === change.comment ? change : Object.freeze({ ...change, comment });\n  }\n  const rowId = resolveAlias(st, change.rowId);\n  return rowId === change.rowId ? change : Object.freeze({ ...change, rowId });\n}\n\nexport function addrOf(st: CommentsState, id: string): { rowId: string; columnId: string } | undefined {\n  const c = st.confirmed.get(id);\n  if (c) return c;\n  const t = st.tombstones.get(id);\n  if (t) return t;\n  const p = st.pending.get(id);\n  return p?.record;\n}\n\nexport function cellCount(st: CommentsState, rowId: string, columnId: string): number {\n  return st.index.get(rowId)?.get(columnId)?.size ?? 0;\n}\n\nexport function noteRowActivity(st: CommentsState, rowId: string): void {\n  const requestId = st.rowRequest.get(rowId);\n  if (requestId === undefined) return;\n  const req = st.requests.get(requestId);\n  if (!req) return;\n  req.log += 1;\n  if (req.log > MAX_FETCH_LOG) req.overflow = true;\n}\n\nexport function addTombstone(c: Ctx, id: string, rowId: string, columnId: string, version: number): void {\n  const { st } = c;\n  const prior = st.tombstones.get(id);\n  st.tombstones.delete(id);\n  st.tombstones.set(id, { id, rowId, columnId, version: Math.max(version, prior?.version ?? 0), expiresAt: c.now + TOMBSTONE_TTL_MS });\n  while (st.tombstones.size > MAX_TOMBSTONES) {\n    const oldest = st.tombstones.keys().next().value;\n    if (oldest === undefined) break;\n    st.tombstones.delete(oldest);\n  }\n}\n\nexport function markEmitted(c: Ctx, id: string): void {\n  if (!c.st.controlled) return;\n  c.st.emitted.delete(id);\n  c.st.emitted.set(id, c.now);\n  while (c.st.emitted.size > MAX_EMITTED) {\n    const oldest = c.st.emitted.keys().next().value;\n    if (oldest === undefined) break;\n    c.st.emitted.delete(oldest);\n  }\n}\n\nexport function setConfirmed(c: Ctx, rec: CellComment, server: boolean, silent = false): void {\n  const { st } = c;\n  const prev = st.confirmed.get(rec.id);\n  if (prev && (prev.rowId !== rec.rowId || prev.columnId !== rec.columnId)) indexRemove(st, rec.id, prev.rowId, prev.columnId);\n  st.confirmed.set(rec.id, rec);\n  st.ownConfirmedAt.delete(rec.id);\n  if (server) st.serverConfirmed.set(rec.id, rec.version);\n  else st.serverConfirmed.delete(rec.id);\n  const tomb = st.tombstones.get(rec.id);\n  if (tomb && rec.version > tomb.version) st.tombstones.delete(rec.id);\n  syncIndex(st, rec.id, rec.rowId, rec.columnId);\n  bump(c, rec.id);\n  noteRowActivity(st, rec.rowId);\n  if (!silent) {\n    c.changes.push({ kind: \"upsert\", comment: rec });\n    markEmitted(c, rec.id);\n  }\n}\n\nexport function removeConfirmed(c: Ctx, id: string, version: number, writeId: string | undefined, opts: { tombstone: boolean; silent?: boolean }): void {\n  const { st } = c;\n  const prev = st.confirmed.get(id);\n  if (!prev) return;\n  st.confirmed.delete(id);\n  st.serverConfirmed.delete(id);\n  st.rawOf.delete(id);\n  syncIndex(st, id, prev.rowId, prev.columnId);\n  bump(c, id);\n  noteRowActivity(st, prev.rowId);\n  if (opts.tombstone) addTombstone(c, id, prev.rowId, prev.columnId, version);\n  if (!opts.silent) {\n    const change: CommentChange = { kind: \"delete\", id, rowId: prev.rowId, columnId: prev.columnId, version };\n    if (writeId !== undefined) change.writeId = writeId;\n    c.changes.push(change);\n    markEmitted(c, id);\n  }\n}\n\n/** Sets or replaces a draft (the composer, an edit). The least recently edited of more than 50 drafts is dropped. */\nexport function putDraft(st: CommentsState, draft: Draft): void {\n  st.drafts.delete(draft.key);\n  st.drafts.set(draft.key, draft);\n  while (st.drafts.size > MAX_DRAFTS) {\n    const oldest = st.drafts.keys().next().value;\n    if (oldest === undefined) break;\n    st.drafts.delete(oldest);\n  }\n}\n\nexport function discardDraft(st: CommentsState, key: string): void {\n  st.drafts.delete(key);\n}\n\nexport function setConflict(st: CommentsState, conflict: Conflict): void {\n  st.conflicts.delete(conflict.id);\n  st.conflicts.set(conflict.id, conflict);\n  while (st.conflicts.size > MAX_DRAFTS) {\n    const oldest = st.conflicts.keys().next().value;\n    if (oldest === undefined) break;\n    st.conflicts.delete(oldest);\n  }\n}\n\nexport function discardConflict(st: CommentsState, id: string): void {\n  st.conflicts.delete(id);\n}\n\n/** Moves the text of an open edit draft or conflict to the new-comment draft of the cell, so a deleted comment never takes typed text with it. */\nexport function keepDraftText(st: CommentsState, id: string, rowId: string, columnId: string): void {\n  const text = st.drafts.get(editDraftKey(id))?.text ?? st.conflicts.get(id)?.text;\n  const key = newDraftKey(rowId, columnId);\n  if (text && !st.drafts.has(key)) putDraft(st, { key, kind: \"new\", rowId, columnId, text, baseVersion: 0, baseWriteId: undefined });\n}\n\nexport function dropCommentUi(st: CommentsState, id: string): void {\n  st.conflicts.delete(id);\n  st.drafts.delete(editDraftKey(id));\n}\n\nexport function rebaseDraft(st: CommentsState, p: Pending, confirmed: CellComment): void {\n  const draft = st.drafts.get(editDraftKey(p.change.kind === \"upsert\" ? p.change.comment.id : (p.change as { id: string }).id));\n  if (draft && draft.baseVersion === p.baseVersion && draft.baseWriteId === p.baseWriteId && confirmed.version === p.baseVersion + 1) {\n    draft.baseVersion = confirmed.version;\n    draft.baseWriteId = confirmed.writeId;\n  }\n}\n\n/** The confirmed records; a record the add-on never changed keeps the app object it came from. */\nexport function confirmedSnapshot(st: CommentsState): CellComment[] {\n  const list: CellComment[] = [];\n  for (const [id, record] of st.confirmed) {\n    const origin = st.rawOf.get(id);\n    list.push(origin && origin.valid === record ? origin.raw : record);\n  }\n  return list;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-state.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-reducer.ts",
      "content": "import type { ApplyRemoteVerdict, CellComment, CommentChange, CommentRejectedCtx, CommentRejectReason, CommentSource } from \"./types\";\nimport { validateComment } from \"./validate\";\nimport { authorChangeAllowed } from \"./default-gate\";\nimport {\n  addrOf,\n  addTombstone,\n  bump,\n  cellCount,\n  changeAlias,\n  dropCommentUi,\n  editDraftKey,\n  EMITTED_MEMORY_MS,\n  indexAdd,\n  indexRemove,\n  keepDraftText,\n  MAX_ALIASES,\n  MAX_LISTED_SKIPS,\n  newDraftKey,\n  OWN_WRITE_GRACE_MS,\n  putDraft,\n  rebaseDraft,\n  removeConfirmed,\n  sameRecord,\n  setConfirmed,\n  setConflict,\n  syncIndex,\n  withAlias,\n  type AckOutcome,\n  type CommentEvent,\n  type CommentsState,\n  type Conflict,\n  type Ctx,\n  type Emit,\n  type Pending,\n  type ReduceResult,\n  type Skip,\n} from \"./comment-state\";\n\nfunction pushLocal(c: Ctx, change: CommentChange): void {\n  c.out.push({ t: \"local\", change });\n}\n\nfunction authoritativeChange(rec: CellComment, p: Pending): CommentChange {\n  return { kind: \"upsert\", comment: rec, baseVersion: p.baseVersion };\n}\n\n/** Rule 4(a)/(6): a write is confirmed by `rec`. */\nfunction confirmPendingUpsert(c: Ctx, p: Pending, rec: CellComment, server: boolean, silent: boolean): void {\n  const { st } = c;\n  st.pending.delete(rec.id);\n  setConfirmed(c, rec, server, silent);\n  st.ownConfirmedAt.set(rec.id, c.now);\n  const conflict = st.conflicts.get(rec.id);\n  if (conflict && (conflict.writeId === p.writeId || conflict.thrown)) st.conflicts.delete(rec.id);\n  rebaseDraft(st, p, rec);\n  pushLocal(c, authoritativeChange(rec, p));\n}\n\nfunction confirmPendingDelete(c: Ctx, p: Pending, version: number, silent: boolean): void {\n  const { st } = c;\n  const id = p.record.id;\n  st.pending.delete(id);\n  removeConfirmed(c, id, version, p.writeId, { tombstone: true, silent });\n  if (!st.confirmed.has(id)) addTombstone(c, id, p.record.rowId, p.record.columnId, version);\n  st.conflicts.delete(id);\n  st.drafts.delete(editDraftKey(id));\n  syncIndex(st, id, p.record.rowId, p.record.columnId);\n  pushLocal(c, { kind: \"delete\", id, rowId: p.record.rowId, columnId: p.record.columnId, version, writeId: p.writeId, baseVersion: p.baseVersion });\n}\n\n/** The thrown write whose echo still confirms it. */\nfunction thrownEcho(st: CommentsState, id: string, writeId: string | undefined, version: number): Conflict | undefined {\n  const conflict = st.conflicts.get(id);\n  if (!conflict || !conflict.thrown || writeId === undefined || conflict.writeId !== writeId) return undefined;\n  return version >= conflict.baseVersion + 1 ? conflict : undefined;\n}\n\nfunction conflictAsPending(conflict: Conflict): Pending {\n  return {\n    writeId: conflict.writeId,\n    action: conflict.action,\n    baseVersion: conflict.baseVersion,\n    baseWriteId: conflict.baseWriteId,\n    change: conflict.change,\n    record: conflict.record,\n    superseded: false,\n  };\n}\n\nfunction tieWins(st: CommentsState, current: CellComment, incoming: CellComment, incomingServer: boolean, fetchUntouched: boolean): boolean {\n  if (fetchUntouched) return true;\n  const currentServer = st.serverConfirmed.get(current.id) === current.version;\n  if (incomingServer && !currentServer) return true;\n  if (!incomingServer && currentServer) return false;\n  if (incoming.updatedAt !== current.updatedAt) return incoming.updatedAt > current.updatedAt;\n  return (incoming.writeId ?? \"\") > (current.writeId ?? \"\");\n}\n\ntype UpsertOpts = { server: boolean; fetchUntouched?: boolean };\n\n/** Rules 3 to 5 for one incoming upsert of a known or unknown id. */\nfunction applyUpsert(c: Ctx, raw: CellComment, opts: UpsertOpts): \"applied\" | Skip {\n  const { st } = c;\n  const rec = withAlias(st, raw);\n  const id = rec.id;\n  const known = addrOf(st, id);\n  if (known && (known.rowId !== rec.rowId || known.columnId !== rec.columnId)) return \"invalid\";\n  const confirmed = st.confirmed.get(id);\n  if (confirmed && !authorChangeAllowed(confirmed.author, rec.author)) return \"invalid\";\n  const p = st.pending.get(id);\n  if (p && !p.superseded && p.action !== \"delete\" && rec.writeId !== undefined && rec.writeId === p.writeId && rec.version >= p.baseVersion + 1) {\n    confirmPendingUpsert(c, p, rec, opts.server, false);\n    return \"applied\";\n  }\n  const thrown = thrownEcho(st, id, rec.writeId, rec.version);\n  if (thrown && thrown.action !== \"delete\") {\n    confirmPendingUpsert(c, conflictAsPending(thrown), rec, opts.server, false);\n    return \"applied\";\n  }\n  const tomb = st.tombstones.get(id);\n  if (tomb) {\n    const resurrect = rec.version === tomb.version && opts.fetchUntouched === true;\n    if (rec.version < tomb.version || (rec.version === tomb.version && !resurrect)) return \"tombstoned\";\n  }\n  if (confirmed) {\n    if (rec.version < confirmed.version) return \"stale\";\n    const addsAuthor = confirmed.author === undefined && rec.author !== undefined;\n    if (rec.version === confirmed.version && !(addsAuthor && rec.writeId === confirmed.writeId)) {\n      if (rec.writeId !== undefined && rec.writeId === confirmed.writeId) return \"duplicate\";\n      if (!tieWins(st, confirmed, rec, opts.server, opts.fetchUntouched === true)) return \"stale\";\n    }\n  } else if (!tomb || rec.version > tomb.version || opts.fetchUntouched) {\n    if (st.confirmed.size + st.pending.size >= st.bounds.maxComments) return \"limit\";\n    if (cellCount(st, rec.rowId, rec.columnId) >= st.bounds.maxCommentsPerCell) return \"limit\";\n  }\n  setConfirmed(c, rec, opts.server);\n  return \"applied\";\n}\n\n/** Marks the pending write superseded and offers its text as a draft for a new comment. */\nfunction supersedePending(c: Ctx, p: Pending): void {\n  const { st } = c;\n  p.superseded = true;\n  if ((p.action === \"update\" || p.action === \"create\") && p.record.text) {\n    const key = newDraftKey(p.record.rowId, p.record.columnId);\n    if (!st.drafts.has(key)) putDraft(st, { key, kind: \"new\", rowId: p.record.rowId, columnId: p.record.columnId, text: p.record.text, baseVersion: 0, baseWriteId: undefined });\n  }\n}\n\nfunction applyDelete(c: Ctx, change: Extract<CommentChange, { kind: \"delete\" }>, opts: UpsertOpts): \"applied\" | Skip {\n  const { st } = c;\n  const d = changeAlias(st, change) as Extract<CommentChange, { kind: \"delete\" }>;\n  const id = d.id;\n  const known = addrOf(st, id);\n  if (known && (known.rowId !== d.rowId || known.columnId !== d.columnId)) return \"invalid\";\n  const p = st.pending.get(id);\n  if (p && !p.superseded && p.action === \"delete\" && d.writeId !== undefined && d.writeId === p.writeId && d.version >= p.baseVersion + 1) {\n    confirmPendingDelete(c, p, d.version, false);\n    return \"applied\";\n  }\n  const thrown = thrownEcho(st, id, d.writeId, d.version);\n  if (thrown && thrown.action === \"delete\") {\n    confirmPendingDelete(c, conflictAsPending(thrown), d.version, false);\n    return \"applied\";\n  }\n  const tomb = st.tombstones.get(id);\n  if (tomb && d.version <= tomb.version) return \"duplicate\";\n  const confirmed = st.confirmed.get(id);\n  if (!confirmed) {\n    const inFlight = st.rowRequest.has(d.rowId);\n    if (!inFlight && !p) return \"unknown\";\n    addTombstone(c, id, d.rowId, d.columnId, d.version);\n    if (p && !p.superseded) supersedePending(c, p);\n    return \"applied\";\n  }\n  if (d.version < confirmed.version) return \"stale\";\n  if (d.version === confirmed.version && d.writeId !== undefined && d.writeId === confirmed.writeId) return \"duplicate\";\n  removeConfirmed(c, id, d.version, d.writeId, { tombstone: true });\n  if (p && !p.superseded) supersedePending(c, p);\n  keepDraftText(st, id, confirmed.rowId, confirmed.columnId);\n  dropCommentUi(st, id);\n  if (opts.server) st.ownConfirmedAt.delete(id);\n  return \"applied\";\n}\n\nfunction finish(c: Ctx, source: CommentSource): void {\n  if (c.changes.length > 0) c.out.push({ t: \"change\", changes: c.changes, source });\n}\n\nfunction rollback(c: Ctx, p: Pending, ctx: { reason: CommentRejectReason; message?: string; current?: CellComment | null; error?: unknown; thrown: boolean; discardOnly?: boolean }): void {\n  const { st } = c;\n  const id = p.record.id;\n  st.pending.delete(id);\n  syncIndex(st, id, p.record.rowId, p.record.columnId);\n  const text = p.action === \"create\" || p.action === \"update\" ? p.record.text : undefined;\n  const confirmed = st.confirmed.get(id);\n  setConflict(st, {\n    id,\n    rowId: p.record.rowId,\n    columnId: p.record.columnId,\n    action: p.action,\n    reason: ctx.reason,\n    message: ctx.message,\n    writeId: p.writeId,\n    baseVersion: p.baseVersion,\n    baseWriteId: p.baseWriteId,\n    change: p.change,\n    record: p.record,\n    thrown: ctx.thrown,\n    text,\n    shownVersion: confirmed?.version ?? p.baseVersion,\n    discardOnly: ctx.discardOnly === true,\n  });\n  if (text !== undefined) {\n    const asNew = p.action === \"create\" || !st.confirmed.has(id);\n    const key = asNew ? newDraftKey(p.record.rowId, p.record.columnId) : editDraftKey(id);\n    putDraft(st, { key, kind: asNew ? \"new\" : \"edit\", commentId: asNew ? undefined : id, rowId: p.record.rowId, columnId: p.record.columnId, text, baseVersion: asNew ? 0 : p.baseVersion, baseWriteId: asNew ? undefined : p.baseWriteId });\n  }\n  const rejected: CommentRejectedCtx = { action: p.action, change: p.change, reason: ctx.reason };\n  if (ctx.message !== undefined) rejected.message = ctx.message;\n  if (ctx.current !== undefined) rejected.current = ctx.current;\n  if (ctx.error !== undefined) rejected.error = ctx.error;\n  c.out.push({ t: \"rejected\", ctx: rejected });\n}\n\nfunction handleAck(c: Ctx, id: string, writeId: string, outcome: AckOutcome): void {\n  const { st } = c;\n  const p = st.pending.get(id);\n  if (!p || p.writeId !== writeId) {\n    if (outcome.kind === \"record\" && outcome.comment) applyUpsert(c, outcome.comment, { server: true });\n    else if (outcome.kind === \"rejected\" && outcome.current && outcome.current.writeId === writeId) applyUpsert(c, outcome.current, { server: true });\n    return;\n  }\n  if (p.superseded) {\n    st.pending.delete(id);\n    syncIndex(st, id, p.record.rowId, p.record.columnId);\n    return;\n  }\n  const confirmed = st.confirmed.get(id);\n  const tomb = st.tombstones.get(id);\n  const nextVersion = p.baseVersion + 1;\n  const supersede = (): void => {\n    st.pending.delete(id);\n    syncIndex(st, id, p.record.rowId, p.record.columnId);\n  };\n\n  if (outcome.kind === \"throw\") return rollback(c, p, { reason: \"error\", error: outcome.error, thrown: true });\n  if (outcome.kind === \"invalid\") return rollback(c, p, { reason: \"invalid\", thrown: false });\n\n  if (outcome.kind === \"rejected\") {\n    const current = outcome.current;\n    if (outcome.reason === \"stale\") {\n      if (current && current.writeId === p.writeId) {\n        applyUpsert(c, current, { server: true });\n        if (st.pending.get(id) === p) confirmPendingUpsert(c, p, withAlias(st, current), true, false);\n        return;\n      }\n      if (current === null && p.action === \"delete\") return confirmPendingDelete(c, p, Math.max(nextVersion, confirmed?.version ?? 0), false);\n      if (current) {\n        st.pending.delete(id);\n        applyUpsert(c, current, { server: true });\n        st.pending.set(id, p);\n        rollback(c, p, { reason: \"stale\", message: outcome.message, current, thrown: false });\n        return;\n      }\n      if (current === null) {\n        st.pending.delete(id);\n        const known = st.confirmed.get(id);\n        if (known) removeConfirmed(c, id, known.version + 1, undefined, { tombstone: true });\n        st.pending.set(id, p);\n        rollback(c, p, { reason: \"stale\", message: outcome.message, current: null, thrown: false });\n        return;\n      }\n      c.out.push({ t: \"refetch\", rowIds: [p.record.rowId] });\n      c.out.push({ t: \"warn\", message: \"a stale rejection without `current` leaves Discard only; return `current` from the save, or set `fetchComments`\", unlessFetch: true });\n      return rollback(c, p, { reason: \"stale\", message: outcome.message, thrown: false, discardOnly: true });\n    }\n    return rollback(c, p, { reason: outcome.reason, message: outcome.message, current: outcome.current, thrown: false });\n  }\n\n  const asDelete = p.action === \"delete\" || (outcome.kind === \"record\" && outcome.comment === null);\n  if (asDelete) {\n    if (!confirmed) return supersede();\n    if (confirmed.version > nextVersion) return supersede();\n    return confirmPendingDelete(c, p, nextVersion, false);\n  }\n\n  const server = outcome.kind === \"void\" ? outcome.server : true;\n  if (tomb && !confirmed) return supersede();\n  if (outcome.kind === \"record\" && outcome.comment) {\n    const rec = withAlias(st, outcome.comment);\n    if (rec.id !== id || rec.rowId !== p.record.rowId || rec.columnId !== p.record.columnId) return rollback(c, p, { reason: \"invalid\", thrown: false });\n    if (rec.author === undefined && (confirmed ?? p.record).author !== undefined) return rollback(c, p, { reason: \"invalid\", thrown: false });\n    if (confirmed && rec.version < confirmed.version) return supersede();\n    if (confirmed && rec.version === confirmed.version && confirmed.writeId !== rec.writeId && !tieWins(st, confirmed, rec, true, false)) return supersede();\n    return confirmPendingUpsert(c, p, rec, true, false);\n  }\n  if (confirmed && confirmed.version > nextVersion) return supersede();\n  if (confirmed && confirmed.version === nextVersion && confirmed.writeId !== p.writeId && !tieWins(st, confirmed, p.record, server, false)) return supersede();\n  confirmPendingUpsert(c, p, p.record, server, false);\n}\n\nfunction handleLocalWrite(c: Ctx, e: Extract<CommentEvent, { type: \"localWrite\" }>): boolean {\n  const { st } = c;\n  const id = e.record.id;\n  if (st.pending.has(id)) return false;\n  if (e.action === \"create\") {\n    if (st.confirmed.has(id) || st.tombstones.has(id)) return false;\n    if (st.confirmed.size + st.pending.size >= st.bounds.maxComments) return false;\n    if (cellCount(st, e.record.rowId, e.record.columnId) >= st.bounds.maxCommentsPerCell) return false;\n  } else if (!st.confirmed.has(id)) {\n    return false;\n  }\n  st.pending.set(id, {\n    writeId: e.change.kind === \"upsert\" ? (e.change.comment.writeId as string) : (e.change.writeId as string),\n    action: e.action,\n    baseVersion: e.change.baseVersion ?? 0,\n    baseWriteId: e.baseWriteId,\n    change: e.change,\n    record: e.record,\n    superseded: false,\n  });\n  const conflict = st.conflicts.get(id);\n  if (conflict) st.conflicts.delete(id);\n  syncIndex(st, id, e.record.rowId, e.record.columnId);\n  bump(c, id);\n  return true;\n}\n\nfunction handleRemote(c: Ctx, e: Extract<CommentEvent, { type: \"remote\" }>): ApplyRemoteVerdict {\n  const skipped: { index: number; reason: Skip }[] = [];\n  let skippedCount = 0;\n  let applied = 0;\n  const note = (index: number, reason: Skip): void => {\n    skippedCount += 1;\n    if (skipped.length < MAX_LISTED_SKIPS) skipped.push({ index, reason });\n  };\n  for (const index of e.invalid) note(index, \"invalid\");\n  for (const { index, change } of e.changes) {\n    const result = change.kind === \"upsert\" ? applyUpsert(c, change.comment, { server: false }) : applyDelete(c, change, { server: false });\n    if (result === \"applied\") applied += 1;\n    else note(index, result);\n  }\n  skipped.sort((a, b) => a.index - b.index);\n  return { applied, skippedCount, skipped, truncated: e.truncated };\n}\n\nfunction handleFetchAnswer(c: Ctx, e: Extract<CommentEvent, { type: \"fetchAnswer\" }>): number {\n  const { st } = c;\n  const req = st.requests.get(e.requestId);\n  if (!req) return 0;\n  st.requests.delete(e.requestId);\n  for (const row of req.rowIds) if (st.rowRequest.get(row) === e.requestId) st.rowRequest.delete(row);\n  if (req.overflow || req.remapped) {\n    c.out.push({ t: \"refetch\", rowIds: Array.from(req.rowIds) });\n    return 0;\n  }\n  let limited = 0;\n  for (const record of e.records) {\n    if (!req.rowIds.has(record.rowId)) continue;\n    const untouched = (st.touched.get(record.id) ?? 0) <= req.startSeq;\n    if (applyUpsert(c, record, { server: true, fetchUntouched: untouched }) === \"limit\") limited += 1;\n  }\n  for (const row of req.rowIds) {\n    const columns = st.index.get(row);\n    if (columns) {\n      for (const ids of Array.from(columns.values())) {\n        for (const id of Array.from(ids)) {\n          const rec = st.confirmed.get(id);\n          if (!rec || e.rawIds.has(id)) continue;\n          if ((st.touched.get(id) ?? 0) > req.startSeq) continue;\n          if (st.pending.has(id) || st.conflicts.has(id) || st.drafts.has(editDraftKey(id))) continue;\n          const own = st.ownConfirmedAt.get(id);\n          if (own !== undefined && c.now - own < OWN_WRITE_GRACE_MS) continue;\n          removeConfirmed(c, id, rec.version, undefined, { tombstone: false });\n        }\n      }\n    }\n    st.fetchedRows.add(row);\n  }\n  const cap = Math.max(st.bounds.maxCachedRows * 4, 4000);\n  while (st.fetchedRows.size > cap) {\n    const oldest = st.fetchedRows.values().next().value;\n    if (oldest === undefined) break;\n    st.fetchedRows.delete(oldest);\n  }\n  return limited;\n}\n\nfunction forgetSilently(c: Ctx, id: string): void {\n  const { st } = c;\n  const rec = st.confirmed.get(id);\n  if (!rec) return;\n  removeConfirmed(c, id, rec.version, undefined, { tombstone: false, silent: true });\n  st.fetchedRows.delete(rec.rowId);\n}\n\nfunction processPropRecord(c: Ctx, raw: CellComment): void {\n  const { st } = c;\n  const valid = validateComment(raw, st.bounds);\n  if (!valid) {\n    st.dropped += 1;\n    return;\n  }\n  const rec = withAlias(st, valid);\n  st.emitted.delete(rec.id);\n  const p = st.pending.get(rec.id);\n  if (p && !p.superseded && p.action !== \"delete\" && rec.writeId !== undefined && rec.writeId === p.writeId && rec.version >= p.baseVersion + 1) {\n    confirmPendingUpsert(c, p, rec, true, true);\n    st.rawOf.set(rec.id, { valid: rec, raw });\n    return;\n  }\n  const confirmed = st.confirmed.get(rec.id);\n  if (confirmed && sameRecord(confirmed, rec)) {\n    st.rawOf.set(rec.id, { valid: confirmed, raw });\n    return;\n  }\n  if (!confirmed && st.confirmed.size + st.pending.size >= st.bounds.maxComments) {\n    st.dropped += 1;\n    return;\n  }\n  if (!confirmed && cellCount(st, rec.rowId, rec.columnId) >= st.bounds.maxCommentsPerCell) {\n    st.dropped += 1;\n    return;\n  }\n  setConfirmed(c, rec, true, true);\n  st.rawOf.set(rec.id, { valid: rec, raw });\n}\n\nfunction handlePropChange(c: Ctx, next: readonly CellComment[]): void {\n  const { st } = c;\n  const nextMap = new Map<string, CellComment>();\n  for (const record of next) {\n    if (typeof record !== \"object\" || record === null) {\n      st.dropped += 1;\n      continue;\n    }\n    let id: unknown;\n    try {\n      id = (record as { id?: unknown }).id;\n    } catch {\n      st.dropped += 1;\n      continue;\n    }\n    if (typeof id === \"string\" && !nextMap.has(id)) nextMap.set(id, record);\n  }\n  const previous = st.propRaw;\n  st.propRaw = nextMap;\n  for (const [id, record] of nextMap) {\n    const before = previous.get(id);\n    if (before === record) continue;\n    if (before && typeof before === \"object\" && sameRecord(before, record)) continue;\n    processPropRecord(c, record);\n  }\n  for (const id of previous.keys()) {\n    if (nextMap.has(id)) continue;\n    st.emitted.delete(id);\n    st.rawOf.delete(id);\n    forgetSilently(c, id);\n  }\n}\n\nfunction reconcileEmitted(c: Ctx): void {\n  const { st } = c;\n  for (const [id, at] of Array.from(st.emitted)) {\n    if (c.now - at < EMITTED_MEMORY_MS) continue;\n    st.emitted.delete(id);\n    const fromProp = st.propRaw.get(id);\n    if (!fromProp) {\n      forgetSilently(c, id);\n      continue;\n    }\n    const current = st.confirmed.get(id);\n    if (!current || !sameRecord(current, fromProp)) processPropRecord(c, fromProp);\n  }\n}\n\nfunction handleRemove(c: Ctx, rowIds: readonly string[]): number {\n  const { st } = c;\n  let removed = 0;\n  for (const row of rowIds) {\n    st.fetchedRows.delete(row);\n    const columns = st.index.get(row);\n    if (!columns) continue;\n    const ids = Array.from(columns.values()).flatMap((set) => Array.from(set));\n    for (const id of ids) {\n      const confirmed = st.confirmed.get(id);\n      const p = st.pending.get(id);\n      const known = confirmed ?? p?.record;\n      if (!known) continue;\n      const version = Math.max(confirmed?.version ?? 0, (p?.baseVersion ?? 0) + 1);\n      st.pending.delete(id);\n      if (confirmed) removeConfirmed(c, id, version, undefined, { tombstone: true });\n      else {\n        addTombstone(c, id, known.rowId, known.columnId, version);\n        syncIndex(st, id, known.rowId, known.columnId);\n        c.changes.push({ kind: \"delete\", id, rowId: known.rowId, columnId: known.columnId, version });\n        bump(c, id);\n      }\n      dropCommentUi(st, id);\n      st.drafts.delete(newDraftKey(known.rowId, known.columnId));\n      removed += 1;\n    }\n  }\n  return removed;\n}\n\nfunction handleEvict(c: Ctx, e: Extract<CommentEvent, { type: \"evict\" }>): void {\n  const { st } = c;\n  for (const row of e.rowIds) {\n    if (e.keepRows.has(row)) continue;\n    const columns = st.index.get(row);\n    let blocked = false;\n    if (columns) {\n      for (const ids of columns.values()) {\n        for (const id of ids) {\n          if (st.pending.has(id) || st.conflicts.has(id) || st.drafts.has(editDraftKey(id))) blocked = true;\n        }\n        for (const column of columns.keys()) if (st.drafts.has(newDraftKey(row, column))) blocked = true;\n      }\n    }\n    if (blocked) continue;\n    if (columns) {\n      for (const id of Array.from(columns.values()).flatMap((set) => Array.from(set))) {\n        const rec = st.confirmed.get(id);\n        if (rec) removeConfirmed(c, id, rec.version, undefined, { tombstone: false, silent: true });\n      }\n    }\n    st.fetchedRows.delete(row);\n  }\n}\n\nfunction handleIdSwap(c: Ctx, map: ReadonlyMap<string, string>): void {\n  const { st } = c;\n  for (const [oldId, newId] of map) {\n    if (oldId === newId) continue;\n    st.aliases.set(oldId, newId);\n    while (st.aliases.size > MAX_ALIASES) {\n      const oldest = st.aliases.keys().next().value;\n      if (oldest === undefined) break;\n      st.aliases.delete(oldest);\n    }\n    const columns = st.index.get(oldId);\n    const ids = columns ? Array.from(columns.values()).flatMap((set) => Array.from(set)) : [];\n    for (const id of ids) {\n      const confirmed = st.confirmed.get(id);\n      if (confirmed) {\n        const moved = Object.freeze({ ...confirmed, rowId: newId });\n        indexRemove(st, id, oldId, confirmed.columnId);\n        st.confirmed.set(id, moved);\n        indexAdd(st, id, newId, moved.columnId);\n        st.rawOf.delete(id);\n        c.changes.push({ kind: \"upsert\", comment: moved });\n        bump(c, id);\n      }\n      const p = st.pending.get(id);\n      if (p) {\n        const record = Object.freeze({ ...p.record, rowId: newId });\n        const change: CommentChange = p.change.kind === \"upsert\" ? { ...p.change, comment: record } : { ...p.change, rowId: newId };\n        st.pending.set(id, { ...p, record, change });\n        if (!confirmed) {\n          indexRemove(st, id, oldId, p.record.columnId);\n          indexAdd(st, id, newId, record.columnId);\n        }\n      }\n      const conflict = st.conflicts.get(id);\n      if (conflict) st.conflicts.set(id, { ...conflict, rowId: newId });\n      const draft = st.drafts.get(editDraftKey(id));\n      if (draft) draft.rowId = newId;\n    }\n    if (columns) {\n      for (const column of columns.keys()) {\n        const key = newDraftKey(oldId, column);\n        const draft = st.drafts.get(key);\n        if (draft) {\n          st.drafts.delete(key);\n          putDraft(st, { ...draft, key: newDraftKey(newId, column), rowId: newId });\n        }\n      }\n    }\n    for (const [id, tomb] of st.tombstones) if (tomb.rowId === oldId) st.tombstones.set(id, { ...tomb, rowId: newId });\n    if (st.fetchedRows.delete(oldId)) st.fetchedRows.add(newId);\n    const requestId = st.rowRequest.get(oldId);\n    if (requestId !== undefined) {\n      const req = st.requests.get(requestId);\n      if (req) req.remapped = true;\n    }\n  }\n}\n\n/** Applies one event to the state. The reducer mutates `st` in place (copying 100k records per event would break the cost budget) and is deterministic: time and ids arrive in the event. */\nexport function reduce(st: CommentsState, event: CommentEvent): ReduceResult {\n  const out: Emit[] = [];\n  const c: Ctx = { st, out, changes: [], now: \"now\" in event ? event.now : 0 };\n  switch (event.type) {\n    case \"localWrite\": {\n      const ok = handleLocalWrite(c, event);\n      return { emits: out, ok };\n    }\n    case \"ack\":\n      handleAck(c, event.id, event.writeId, event.outcome);\n      finish(c, \"ack\");\n      return { emits: out };\n    case \"remote\": {\n      const verdict = handleRemote(c, event);\n      finish(c, \"remote\");\n      return { emits: out, verdict };\n    }\n    case \"fetchStart\": {\n      const rowIds = new Set(event.rowIds);\n      st.requests.set(event.requestId, { rowIds, startSeq: st.seq, overflow: false, remapped: false, log: 0 });\n      for (const row of rowIds) st.rowRequest.set(row, event.requestId);\n      return { emits: out };\n    }\n    case \"fetchAnswer\": {\n      const limited = handleFetchAnswer(c, event);\n      finish(c, \"fetch\");\n      return { emits: out, limited };\n    }\n    case \"fetchFail\": {\n      const req = st.requests.get(event.requestId);\n      if (req) {\n        st.requests.delete(event.requestId);\n        for (const row of req.rowIds) if (st.rowRequest.get(row) === event.requestId) st.rowRequest.delete(row);\n      }\n      return { emits: out };\n    }\n    case \"propChange\":\n      handlePropChange(c, event.next);\n      return { emits: out };\n    case \"remove\": {\n      const removed = handleRemove(c, event.rowIds);\n      finish(c, \"remove\");\n      return { emits: out, removed };\n    }\n    case \"evict\":\n      handleEvict(c, event);\n      return { emits: out };\n    case \"idSwap\":\n      handleIdSwap(c, event.map);\n      finish(c, \"id-swap\");\n      return { emits: out };\n    case \"invalidateRows\": {\n      if (event.rowIds === null) st.fetchedRows.clear();\n      else for (const row of event.rowIds) st.fetchedRows.delete(row);\n      for (const req of st.requests.values()) {\n        if (event.rowIds === null || event.rowIds.some((row) => req.rowIds.has(row))) req.remapped = true;\n      }\n      return { emits: out };\n    }\n    case \"expire\": {\n      for (const [id, tomb] of st.tombstones) if (tomb.expiresAt <= event.now) st.tombstones.delete(id);\n      for (const [id, at] of st.ownConfirmedAt) if (event.now - at >= OWN_WRITE_GRACE_MS) st.ownConfirmedAt.delete(id);\n      if (st.controlled) reconcileEmitted(c);\n      return { emits: out };\n    }\n  }\n}\n\n/** The confirmed records as `next` for `onCommentsChange`; records the add-on did not change keep the app's original objects. */\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-reducer.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-store.ts",
      "content": "import { createStore, type StoreApi } from \"zustand/vanilla\";\r\nimport { reduce } from \"./comment-reducer\";\r\nimport { createCommentsState, type CommentEvent, type CommentsState, type ReduceResult } from \"./comment-state\";\r\nimport type { Bounds } from \"./validate\";\r\n\r\nexport type OpenTarget = { rowId: string; columnId: string; by: \"keyboard\" | \"pointer\" | \"menu\"; nonce: number };\r\n\r\n/** The numeric channels the UI subscribes to. `revision` moves with comment content, `draftRevision` with drafts and conflicts only. */\r\nexport type CommentUiState = {\r\n  revision: number;\r\n  draftRevision: number;\r\n  open: OpenTarget | null;\r\n  announcement: { text: string; nonce: number };\r\n};\r\n\r\nexport type CommentStore = {\r\n  core: CommentsState;\r\n  ui: StoreApi<CommentUiState>;\r\n  /** Row ids of the rendered, non-hole rows; a plain field so reporting never renders. */\r\n  visibleRowIds: readonly string[];\r\n  setVisibleRowIds(ids: readonly string[]): void;\r\n  onVisibleChange: (() => void) | null;\r\n  dispatch(event: CommentEvent): ReduceResult;\r\n  bumpDrafts(): void;\r\n  bumpContent(): void;\r\n  open(target: { rowId: string; columnId: string }, by: OpenTarget[\"by\"]): void;\r\n  close(): void;\r\n  announce(text: string): void;\r\n};\r\n\r\nconst QUIET_EVENTS = new Set<CommentEvent[\"type\"]>([\"fetchStart\", \"invalidateRows\"]);\r\n\r\nexport function createCommentStore(bounds: Bounds, controlled: boolean): CommentStore {\r\n  const core = createCommentsState(bounds, controlled);\r\n  const ui = createStore<CommentUiState>(() => ({ revision: 0, draftRevision: 0, open: null, announcement: { text: \"\", nonce: 0 } }));\r\n  let nonce = 0;\r\n  const store: CommentStore = {\r\n    core,\r\n    ui,\r\n    visibleRowIds: [],\r\n    onVisibleChange: null,\r\n    setVisibleRowIds(ids) {\r\n      store.visibleRowIds = ids;\r\n      store.onVisibleChange?.();\r\n    },\r\n    dispatch(event) {\r\n      const seqBefore = core.seq;\r\n      const result = reduce(core, event);\r\n      const idle = event.type === \"propChange\" || event.type === \"expire\" || event.type === \"remote\";\r\n      if (!QUIET_EVENTS.has(event.type) && (!idle || core.seq !== seqBefore)) ui.setState((s) => ({ revision: s.revision + 1, draftRevision: s.draftRevision + 1 }));\r\n      return result;\r\n    },\r\n    bumpDrafts() {\r\n      ui.setState((s) => ({ draftRevision: s.draftRevision + 1 }));\r\n    },\r\n    bumpContent() {\r\n      ui.setState((s) => ({ revision: s.revision + 1, draftRevision: s.draftRevision + 1 }));\r\n    },\r\n    open(target, by) {\r\n      nonce += 1;\r\n      ui.setState({ open: { rowId: target.rowId, columnId: target.columnId, by, nonce } });\r\n    },\r\n    close() {\r\n      if (ui.getState().open !== null) ui.setState({ open: null });\r\n    },\r\n    announce(text) {\r\n      ui.setState((s) => ({ announcement: { text, nonce: s.announcement.nonce + 1 } }));\r\n    },\r\n  };\r\n  return store;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-store.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-fetch.ts",
      "content": "import type { CommentStore } from \"./comment-store\";\r\nimport type { ReduceResult, CommentEvent } from \"./comment-state\";\r\nimport type { CellComment, UseDataGridCommentsOptions } from \"./types\";\r\nimport { validateComment, type Bounds } from \"./validate\";\r\n\r\nexport const FETCH_DEBOUNCE_MS = 150;\r\nexport const FETCH_BATCH = 200;\r\nexport const FETCH_IN_FLIGHT = 2;\r\nexport const FETCH_RETRY_GAP_MS = 2000;\r\nexport const FETCH_TIMEOUT_MS = 30_000;\r\nexport const MAX_FETCH_ANSWER = 10_000;\r\nconst MAX_FAILED_ROWS = 10_000;\r\n\r\nexport type FetchState = \"idle\" | \"loading\" | \"failed\" | \"ready\";\r\n\r\nexport type FetchDeps = {\r\n  store: CommentStore;\r\n  controlled: boolean;\r\n  now(): number;\r\n  optionsOf(): UseDataGridCommentsOptions;\r\n  dispatch(event: CommentEvent): ReduceResult;\r\n  refreshBounds(): Bounds;\r\n  isBusy(rowId: string): boolean;\r\n  isDisposed(): boolean;\r\n  warn(key: string, message: string): void;\r\n  callSafely(fn: () => void): void;\r\n};\r\n\r\nexport type FetchScheduler = {\r\n  schedule(): void;\r\n  onVisibleChange(): void;\r\n  /** Marks rows (or every row) unfetched and loads the rendered ones again. */\r\n  refetch(rowIds: readonly string[] | null): void;\r\n  clearFailed(rowIds: readonly string[]): void;\r\n  remapRows(map: ReadonlyMap<string, string>): void;\r\n  fetchState(rowId: string): FetchState;\r\n  retryFetch(rowId: string): void;\r\n  dispose(): void;\r\n};\r\n\r\n/** Loads the comments of the rendered rows through `fetchComments`: debounced, batched, bounded, and retried. */\r\nexport function createFetchScheduler(deps: FetchDeps): FetchScheduler {\r\n  const { store, now, optionsOf, dispatch, refreshBounds, isBusy, isDisposed, warn, callSafely } = deps;\r\n  const core = store.core;\r\n  const failedRows = new Set<string>();\r\n  const failedAt = new Map<string, number>();\r\n  const recency = new Map<string, number>();\r\n  const controllers = new Map<number, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>();\r\n  const retryHalf = new Map<string, number>();\r\n  let requestSeq = 0;\r\n  let inFlight = 0;\r\n  let debounce: ReturnType<typeof setTimeout> | null = null;\r\n  let retryTimer: ReturnType<typeof setTimeout> | null = null;\r\n\r\n  const unfetchedVisible = (): string[] => {\r\n    const ts = now();\r\n    const rows: string[] = [];\r\n    for (const row of store.visibleRowIds) {\r\n      if (core.fetchedRows.has(row) || core.rowRequest.has(row) || isBusy(row)) continue;\r\n      if (failedRows.has(row)) continue;\r\n      const failed = failedAt.get(row);\r\n      if (failed !== undefined && ts - failed < FETCH_RETRY_GAP_MS) continue;\r\n      rows.push(row);\r\n    }\r\n    return rows;\r\n  };\r\n\r\n  function schedule(): void {\r\n    if (isDisposed() || !optionsOf().fetchComments) return;\r\n    if (debounce !== null) clearTimeout(debounce);\r\n    debounce = setTimeout(() => {\r\n      debounce = null;\r\n      runFetches();\r\n    }, FETCH_DEBOUNCE_MS);\r\n  }\r\n\r\n  function runFetches(): void {\r\n    const fetcher = optionsOf().fetchComments;\r\n    if (isDisposed() || !fetcher) return;\r\n    const rows = unfetchedVisible();\r\n    let cursor = 0;\r\n    while (inFlight < FETCH_IN_FLIGHT && cursor < rows.length) {\r\n      let size = FETCH_BATCH;\r\n      for (const row of rows.slice(cursor, cursor + FETCH_BATCH)) size = Math.min(size, retryHalf.get(row) ?? FETCH_BATCH);\r\n      const batch = rows.slice(cursor, cursor + Math.max(1, size));\r\n      cursor += batch.length;\r\n      startFetch(fetcher, batch);\r\n    }\r\n  }\r\n\r\n  function noteFailure(rowIds: readonly string[], reason: \"error\" | \"limit\"): void {\r\n    const ts = now();\r\n    for (const row of rowIds) failedAt.set(row, ts);\r\n    while (failedAt.size > MAX_FAILED_ROWS) {\r\n      const oldest = failedAt.keys().next().value;\r\n      if (oldest === undefined) break;\r\n      failedAt.delete(oldest);\r\n    }\r\n    if (reason !== \"limit\") return;\r\n    if (rowIds.length === 1) failedRows.add(rowIds[0] as string);\r\n    else for (const row of rowIds) retryHalf.set(row, Math.max(1, Math.floor(rowIds.length / 2)));\r\n  }\r\n\r\n  function applyAnswer(requestId: number, rowIds: string[], answer: readonly unknown[]): void {\r\n    const bounds = refreshBounds();\r\n    const rawIds = new Set<string>();\r\n    const records: CellComment[] = [];\r\n    let invalid = 0;\r\n    for (const raw of answer) {\r\n      let id: unknown;\r\n      try {\r\n        id = (raw as { id?: unknown } | null)?.id;\r\n      } catch {\r\n        id = undefined;\r\n      }\r\n      if (typeof id === \"string\") rawIds.add(id);\r\n      const valid = validateComment(raw, bounds);\r\n      if (valid) records.push(valid);\r\n      else invalid += 1;\r\n    }\r\n    if (invalid > 0) warn(\"fetch-invalid\", `${invalid} fetched record(s) were dropped (invalid)`);\r\n    for (const row of rowIds) {\r\n      failedAt.delete(row);\r\n      retryHalf.delete(row);\r\n    }\r\n    const result = dispatch({ type: \"fetchAnswer\", requestId, records, rawIds, now: now() });\r\n    if (result.limited) {\r\n      const handler = optionsOf().onFetchError;\r\n      if (handler) callSafely(() => handler({ reason: \"limit\", rowIds }));\r\n    }\r\n    evictIfNeeded();\r\n    store.bumpContent();\r\n    schedule();\r\n  }\r\n\r\n  function startFetch(fetcher: NonNullable<UseDataGridCommentsOptions[\"fetchComments\"]>, rowIds: string[]): void {\r\n    requestSeq += 1;\r\n    const requestId = requestSeq;\r\n    const controller = new AbortController();\r\n    inFlight += 1;\r\n    dispatch({ type: \"fetchStart\", requestId, rowIds });\r\n    store.bumpContent();\r\n    let finished = false;\r\n    const finish = (): boolean => {\r\n      if (finished) return false;\r\n      finished = true;\r\n      const entry = controllers.get(requestId);\r\n      if (entry) clearTimeout(entry.timer);\r\n      controllers.delete(requestId);\r\n      inFlight -= 1;\r\n      return true;\r\n    };\r\n    const fail = (error: unknown, reason: \"error\" | \"limit\"): void => {\r\n      if (!finish()) return;\r\n      dispatch({ type: \"fetchFail\", requestId });\r\n      noteFailure(rowIds, reason);\r\n      store.bumpContent();\r\n      const handler = optionsOf().onFetchError;\r\n      if (handler) callSafely(() => handler({ reason, rowIds, error }));\r\n      if (!isDisposed()) {\r\n        if (retryTimer !== null) clearTimeout(retryTimer);\r\n        retryTimer = setTimeout(schedule, FETCH_RETRY_GAP_MS);\r\n      }\r\n    };\r\n    const settleAborted = (): void => {\r\n      if (finish()) dispatch({ type: \"fetchFail\", requestId });\r\n    };\r\n    const timer = setTimeout(() => {\r\n      controller.abort();\r\n      fail(new Error(\"comments fetch timed out\"), \"error\");\r\n    }, FETCH_TIMEOUT_MS);\r\n    controllers.set(requestId, { controller, timer });\r\n    let promise: Promise<readonly CellComment[]>;\r\n    try {\r\n      promise = Promise.resolve(fetcher({ rowIds, signal: controller.signal }));\r\n    } catch (error) {\r\n      fail(error, \"error\");\r\n      return;\r\n    }\r\n    promise.then(\r\n      (answer) => {\r\n        if (finished || isDisposed() || controller.signal.aborted) return settleAborted();\r\n        if (!Array.isArray(answer)) return fail(new Error(\"fetchComments must resolve to an array\"), \"error\");\r\n        if (answer.length > MAX_FETCH_ANSWER) return fail(undefined, \"limit\");\r\n        finish();\r\n        applyAnswer(requestId, rowIds, answer);\r\n      },\r\n      (error: unknown) => {\r\n        if (isDisposed() || controller.signal.aborted) return settleAborted();\r\n        fail(error, \"error\");\r\n      },\r\n    );\r\n  }\r\n\r\n  function evictIfNeeded(): void {\r\n    if (deps.controlled) return;\r\n    const limit = refreshBounds().maxCachedRows;\r\n    if (core.index.size <= limit) return;\r\n    const visible = new Set(store.visibleRowIds);\r\n    const open = store.ui.getState().open;\r\n    if (open) visible.add(open.rowId);\r\n    const candidates: string[] = [];\r\n    let over = core.index.size - limit;\r\n    for (const row of recency.keys()) {\r\n      if (over <= 0) break;\r\n      if (visible.has(row) || !core.index.has(row)) continue;\r\n      candidates.push(row);\r\n      over -= 1;\r\n    }\r\n    if (candidates.length === 0) return;\r\n    dispatch({ type: \"evict\", rowIds: candidates, keepRows: visible });\r\n    for (const row of candidates) if (!core.index.has(row)) recency.delete(row);\r\n  }\r\n\r\n  function abortUnrendered(): void {\r\n    const visible = new Set(store.visibleRowIds);\r\n    for (const [requestId, req] of core.requests) {\r\n      let any = false;\r\n      for (const row of req.rowIds) if (visible.has(row)) any = true;\r\n      if (any) continue;\r\n      controllers.get(requestId)?.controller.abort();\r\n    }\r\n  }\r\n\r\n  return {\r\n    schedule,\r\n    onVisibleChange() {\r\n      for (const row of store.visibleRowIds) {\r\n        recency.delete(row);\r\n        recency.set(row, now());\r\n      }\r\n      const recencyCap = Math.max(refreshBounds().maxCachedRows * 4, 4000);\r\n      while (recency.size > recencyCap) {\r\n        const oldest = recency.keys().next().value;\r\n        if (oldest === undefined) break;\r\n        recency.delete(oldest);\r\n      }\r\n      abortUnrendered();\r\n      schedule();\r\n    },\r\n    refetch(rowIds) {\r\n      if (rowIds) for (const row of rowIds) failedRows.delete(row);\r\n      else failedRows.clear();\r\n      dispatch({ type: \"invalidateRows\", rowIds });\r\n      store.bumpContent();\r\n      schedule();\r\n    },\r\n    clearFailed(rowIds) {\r\n      for (const row of rowIds) failedRows.delete(row);\r\n    },\r\n    remapRows(map) {\r\n      for (const [oldId, newId] of map) {\r\n        if (failedRows.delete(oldId)) failedRows.add(newId);\r\n        if (recency.delete(oldId)) recency.set(newId, now());\r\n      }\r\n    },\r\n    fetchState(rowId) {\r\n      if (!optionsOf().fetchComments) return \"ready\";\r\n      if (core.fetchedRows.has(rowId)) return \"ready\";\r\n      if (failedRows.has(rowId) || (failedAt.has(rowId) && !core.rowRequest.has(rowId))) return \"failed\";\r\n      return core.rowRequest.has(rowId) ? \"loading\" : \"idle\";\r\n    },\r\n    retryFetch(rowId) {\r\n      failedRows.delete(rowId);\r\n      failedAt.delete(rowId);\r\n      retryHalf.delete(rowId);\r\n      store.bumpContent();\r\n      schedule();\r\n    },\r\n    dispose() {\r\n      if (debounce !== null) clearTimeout(debounce);\r\n      if (retryTimer !== null) clearTimeout(retryTimer);\r\n      debounce = null;\r\n      retryTimer = null;\r\n      for (const { controller, timer } of controllers.values()) {\r\n        clearTimeout(timer);\r\n        controller.abort();\r\n      }\r\n      controllers.clear();\r\n    },\r\n  };\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-fetch.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-engine.ts",
      "content": "import { isDev, isThenable } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport type { DataChange } from \"@/registry/default/components/data-grid/data-grid\";\nimport {\n  cellComments,\n  confirmedSnapshot,\n  discardConflict,\n  discardDraft,\n  editDraftKey,\n  MAX_REMOTE_BATCH,\n  newDraftKey,\n  putDraft,\n  type AckOutcome,\n  type Conflict,\n  type Draft,\n  type Emit,\n} from \"./comment-state\";\nimport { createFetchScheduler } from \"./comment-fetch\";\nimport { defaultCanModify, authorLabelName } from \"./default-gate\";\nimport { createCommentStore, type CommentStore } from \"./comment-store\";\nimport { createWriteIdGenerator, defaultCreateId } from \"./create-id\";\nimport { resolveCommentsLabels, type DataGridCommentsLabels, type GridCommentsLabelLayer } from \"./labels\";\nimport type {\n  ApplyRemoteVerdict,\n  CellComment,\n  CommentAction,\n  CommentAuthor,\n  CommentChange,\n  CommentRejectedCtx,\n  CommentRejectReason,\n  OrphanedCommentsCtx,\n  UseDataGridCommentsOptions,\n} from \"./types\";\nimport { cleanText, isSafeId, parseSaveAnswer, resolveBounds, validateAuthor, validateChange, type Bounds } from \"./validate\";\n\nconst MAX_BUSY_ROWS = 10_000;\nconst EXPIRE_INTERVAL_MS = 60_000;\n\n/** What the engine needs to know about the grid it is mounted in; the Mount component supplies it. */\nexport type GridAdapter = {\n  readOnly(): boolean;\n  /** `\"saving\"` while the row's `onSave` promise is pending. */\n  saveStatus(rowId: string): string | undefined;\n  /** Scrolls to the cell, makes it active, and opens the popover once the cell renders; `false` for a hole, a filtered-out row, or a hidden column. */\n  open(ref: { rowId: string; columnId: string }, by: \"keyboard\" | \"pointer\" | \"menu\"): boolean;\n  /** The grid's locale and its `labels.comments` overrides. */\n  gridLabels(): GridCommentsLabelLayer;\n};\n\n/** The writer: none (anonymous), a valid user, or a present but invalid `currentUser`. */\nexport type CommentUserState = { kind: \"anonymous\" } | { kind: \"user\"; user: CommentAuthor } | { kind: \"invalid\" };\n\nexport type WriteResult =\n  | { ok: true; settled: Promise<void> }\n  | { ok: false; reason: CommentRejectReason | \"pending\" };\n\nexport type WriteBase = { version: number; writeId: string | undefined };\n\ntype WriteSpec = {\n  action: CommentAction;\n  rowId: string;\n  columnId: string;\n  id?: string;\n  text?: string;\n  base?: WriteBase;\n  reuse?: Conflict;\n  forceBase?: number;\n};\n\nexport type CommentEngine = {\n  store: CommentStore;\n  attachGrid(adapter: GridAdapter | null): () => void;\n  bounds(): Bounds;\n  applyRemote(changes: readonly CommentChange[]): ApplyRemoteVerdict;\n  getComments(): readonly CellComment[];\n  removeComments(rowIds: readonly string[]): number;\n  refetch(rowIds?: readonly string[]): void;\n  syncProp(next: readonly CellComment[]): void;\n  create(input: { rowId: string; columnId: string; text: string }): Promise<WriteResult>;\n  edit(id: string, text: string, base?: WriteBase): Promise<WriteResult>;\n  remove(id: string, base?: WriteBase): Promise<WriteResult>;\n  setResolved(id: string, resolved: boolean, base?: WriteBase): Promise<WriteResult>;\n  retry(id: string, text?: string): Promise<WriteResult>;\n  saveMine(id: string, text: string): Promise<WriteResult>;\n  discard(id: string): void;\n  setDraft(draft: Omit<Draft, \"key\"> & { key?: string }): void;\n  discardDraft(key: string): void;\n  isRowBusy(rowId: string): boolean;\n  fetchState(rowId: string): \"idle\" | \"loading\" | \"failed\" | \"ready\";\n  retryFetch(rowId: string): void;\n  observeDataChange(next: readonly unknown[], change: DataChange<unknown>, ctx: { getRowId(row: unknown, index: number): string }): void;\n  kickFetch(): void;\n  noteRowsRendered(rowIds: readonly string[]): void;\n  currentUser(): CommentUserState;\n  /** The comments labels: defaults, then the grid's locale and `labels.comments`, then the hook's `labels`. */\n  labels(): DataGridCommentsLabels;\n  /** Applies a function seed once after mount; a controlled engine ignores it. */\n  seed(records: readonly CellComment[]): void;\n  isDisposed(): boolean;\n  openComments(ref: { rowId: string; columnId: string }, by?: \"keyboard\" | \"pointer\" | \"menu\"): boolean;\n  start(): void;\n  dispose(): void;\n};\n\nexport type EngineConfig = {\n  getOptions(): UseDataGridCommentsOptions;\n  now?: () => number;\n  initialComments?: readonly CellComment[];\n  controlled: boolean;\n};\n\nfunction createWarnOnce(): (key: string, message: string) => void {\n  const warned = new Set<string>();\n  return (key, message) => {\n    if (!isDev() || warned.has(key)) return;\n    warned.add(key);\n    console.warn(`[data-grid-comments] ${message}`);\n  };\n}\n\nfunction callSafely(fn: () => void): void {\n  try {\n    fn();\n  } catch (error) {\n    if (isDev()) console.error(\"[data-grid-comments] a callback threw\", error);\n  }\n}\n\nexport function createCommentEngine(config: EngineConfig): CommentEngine {\n  const now = config.now ?? (() => Date.now());\n  const optionsOf = (): UseDataGridCommentsOptions => config.getOptions();\n  const initial = optionsOf();\n  let bounds = resolveBounds(initial);\n  const store = createCommentStore(bounds, config.controlled);\n  const core = store.core;\n  const nextWriteId = createWriteIdGenerator();\n  const warnOnce = createWarnOnce();\n  let grid: GridAdapter | null = null;\n  let disposed = false;\n  const busyRows = new Set<string>();\n  const gateControllers = new Map<string, AbortController>();\n\n  const refreshBounds = (): Bounds => {\n    const next = resolveBounds(optionsOf());\n    if (next.maxTextLength !== bounds.maxTextLength || next.maxCommentsPerCell !== bounds.maxCommentsPerCell || next.maxComments !== bounds.maxComments || next.maxCachedRows !== bounds.maxCachedRows) {\n      bounds = next;\n      core.bounds = next;\n    }\n    return bounds;\n  };\n\n  // --- callbacks --------------------------------------------------------------------------------\n\n  const queue: Emit[] = [];\n  let firing = false;\n\n  const handleEmit = (emit: Emit): void => {\n    const o = optionsOf();\n    switch (emit.t) {\n      case \"change\": {\n        noteRemoteAdded(emit);\n        if (o.onCommentsChange) {\n          const handler = o.onCommentsChange;\n          const next = confirmedSnapshot(core);\n          callSafely(() => handler(next, { changes: emit.changes, source: emit.source }));\n        }\n        return;\n      }\n      case \"local\":\n        if (o.onLocalChange) {\n          const handler = o.onLocalChange;\n          callSafely(() => handler(emit.change));\n        }\n        return;\n      case \"rejected\":\n        if (o.onCommentRejected) {\n          const handler = o.onCommentRejected;\n          callSafely(() => handler(emit.ctx));\n        }\n        return;\n      case \"refetch\":\n        fetcher.clearFailed(emit.rowIds);\n        fetcher.schedule();\n        return;\n      case \"warn\":\n        if (!(emit.unlessFetch && o.fetchComments)) warnOnce(emit.message, emit.message);\n    }\n  };\n\n  const fire = (emits: readonly Emit[]): void => {\n    queue.push(...emits);\n    if (firing) return;\n    firing = true;\n    try {\n      for (let emit = queue.shift(); emit !== undefined; emit = queue.shift()) handleEmit(emit);\n    } finally {\n      firing = false;\n    }\n  };\n\n  function noteRemoteAdded(emit: Extract<Emit, { t: \"change\" }>): void {\n    if (emit.source !== \"remote\" && emit.source !== \"fetch\") return;\n    const open = store.ui.getState().open;\n    if (!open) return;\n    for (const change of emit.changes) {\n      if (change.kind !== \"upsert\") continue;\n      const c = change.comment;\n      if (c.rowId !== open.rowId || c.columnId !== open.columnId) continue;\n      if (c.version !== 1) continue;\n      const labels = engine.labels();\n      store.announce(labels.announceAdded(authorLabelName(c.author, labels.unknownAuthor)));\n      return;\n    }\n  }\n\n  const dispatch = (event: Parameters<CommentStore[\"dispatch\"]>[0]) => {\n    const result = store.dispatch(event);\n    fire(result.emits);\n    return result;\n  };\n\n  // --- seed and prop ----------------------------------------------------------------------------\n\n  function applySeed(records: readonly CellComment[]): void {\n    if (records.length === 0) return;\n    dispatch({ type: \"propChange\", next: records, now: 0 });\n    if (!config.controlled) {\n      core.propRaw = new Map();\n      core.rawOf = new Map();\n    }\n    if (core.dropped > 0) warnOnce(\"seed-dropped\", `${core.dropped} seed record(s) were dropped (invalid or over a bound)`);\n  }\n  if (config.initialComments) applySeed(config.initialComments);\n\n  let expireTimer: ReturnType<typeof setInterval> | null = null;\n  const startExpire = (): void => {\n    if (expireTimer !== null || typeof setInterval === \"undefined\") return;\n    expireTimer = setInterval(() => dispatch({ type: \"expire\", now: now() }), EXPIRE_INTERVAL_MS);\n  };\n\n  // --- busy rows --------------------------------------------------------------------------------\n\n  function isBusy(rowId: string): boolean {\n    if (!busyRows.has(rowId)) return false;\n    if (grid?.saveStatus(rowId) === \"saving\") return true;\n    busyRows.delete(rowId);\n    return false;\n  }\n\n  const fetcher = createFetchScheduler({\n    store,\n    controlled: config.controlled,\n    now,\n    optionsOf,\n    dispatch,\n    refreshBounds,\n    isBusy,\n    isDisposed: () => disposed,\n    warn: warnOnce,\n    callSafely,\n  });\n  store.onVisibleChange = fetcher.onVisibleChange;\n\n  // --- writes -----------------------------------------------------------------------------------\n\n  function userState(): CommentUserState {\n    const user = optionsOf().currentUser;\n    if (user === undefined) return { kind: \"anonymous\" };\n    const valid = validateAuthor(user);\n    if (valid) return { kind: \"user\", user: valid };\n    warnOnce(\"invalid-user\", \"`currentUser` is present but invalid (`id` must be 1..128 characters without control characters); every comment write is refused\");\n    return { kind: \"invalid\" };\n  }\n\n  const userOf = (state: CommentUserState): CommentAuthor | undefined => (state.kind === \"user\" ? state.user : undefined);\n\n  function writeIsBlocked(rowId: string): CommentRejectReason | null {\n    const o = optionsOf();\n    if (o.readOnly === true) return \"read-only\";\n    if (grid?.readOnly() && !o.allowWhenReadOnly) return \"read-only\";\n    if (userState().kind === \"invalid\") return \"invalid\";\n    if (isBusy(rowId)) return \"row-busy\";\n    return null;\n  }\n\n  function rejectBeforeWrite(action: CommentAction, reason: CommentRejectReason, change?: CommentChange, message?: string): WriteResult {\n    const handler = optionsOf().onCommentRejected;\n    if (handler) {\n      const ctx: CommentRejectedCtx = { action, reason };\n      if (change) ctx.change = change;\n      if (message) ctx.message = message;\n      callSafely(() => handler(ctx));\n    }\n    return { ok: false, reason };\n  }\n\n  const gateKey = (spec: WriteSpec): string => spec.id ?? newDraftKey(spec.rowId, spec.columnId);\n\n  async function runGate(spec: WriteSpec, user: CommentAuthor | undefined, prev: CellComment | undefined): Promise<boolean | \"error\" | \"superseded\"> {\n    const o = optionsOf();\n    const key = gateKey(spec);\n    gateControllers.get(key)?.abort();\n    const controller = new AbortController();\n    gateControllers.set(key, controller);\n    try {\n      let verdict: boolean | Promise<boolean>;\n      if (spec.action === \"create\") {\n        verdict = o.canCreate ? o.canCreate({ rowId: spec.rowId, columnId: spec.columnId, user, signal: controller.signal }) : true;\n      } else {\n        const comment = prev as CellComment;\n        if (spec.action === \"update\" || spec.action === \"delete\") {\n          const gate = spec.action === \"update\" ? o.canEdit : o.canDelete;\n          verdict = gate ? gate({ comment, action: spec.action, user, signal: controller.signal }) : defaultCanModify(comment, user);\n        } else {\n          verdict = o.canResolve ? o.canResolve({ comment, action: spec.action, user, signal: controller.signal }) : true;\n        }\n      }\n      const result = isThenable(verdict) ? await verdict : verdict;\n      if (controller.signal.aborted) return disposed ? false : \"superseded\";\n      return result === true;\n    } catch {\n      return \"error\";\n    } finally {\n      if (gateControllers.get(key) === controller) gateControllers.delete(key);\n    }\n  }\n\n  async function execute(spec: WriteSpec): Promise<WriteResult> {\n    const o = optionsOf();\n    refreshBounds();\n    const prev = spec.id ? core.confirmed.get(spec.id) : undefined;\n    if (spec.action !== \"create\" && !prev) return rejectBeforeWrite(spec.action, \"invalid\");\n    if (spec.id && core.pending.has(spec.id)) return { ok: false, reason: \"pending\" };\n    const blocked = writeIsBlocked(spec.rowId);\n    if (blocked) return rejectBeforeWrite(spec.action, blocked);\n    if ((spec.action === \"resolve\" || spec.action === \"reopen\") && o.enableResolve === false) return rejectBeforeWrite(spec.action, \"forbidden\");\n    if ((spec.action === \"update\" && o.enableEdit === false) || (spec.action === \"delete\" && o.enableDelete === false)) return rejectBeforeWrite(spec.action, \"forbidden\");\n    const user = userOf(userState());\n\n    let id = spec.id;\n    if (spec.action === \"create\") {\n      try {\n        id = spec.reuse ? spec.reuse.id : (o.createId ?? defaultCreateId)();\n      } catch {\n        return rejectBeforeWrite(\"create\", \"error\");\n      }\n      if (!isSafeId(id) || core.confirmed.has(id) || core.tombstones.has(id) || core.pending.has(id)) return rejectBeforeWrite(\"create\", \"invalid\");\n    }\n    const commentId = id as string;\n\n    let text: string | undefined;\n    if (spec.text !== undefined) {\n      if (spec.text.length > bounds.maxTextLength * 4) return rejectBeforeWrite(spec.action, \"limit\");\n      let normalized = spec.text;\n      if (o.normalizeText) {\n        try {\n          normalized = o.normalizeText(spec.text);\n        } catch {\n          return rejectBeforeWrite(spec.action, \"error\");\n        }\n      }\n      text = cleanText(normalized);\n      if (text.length < 1) return rejectBeforeWrite(spec.action, \"invalid\");\n      if (text.length > bounds.maxTextLength) return rejectBeforeWrite(spec.action, \"limit\");\n    }\n\n    const verdict = await runGate({ ...spec, id: spec.action === \"create\" ? undefined : commentId }, user, prev);\n    if (disposed) return { ok: false, reason: \"error\" };\n    if (verdict === \"superseded\") return { ok: false, reason: \"pending\" };\n    if (verdict === \"error\") return rejectBeforeWrite(spec.action, \"error\");\n    if (verdict === false) return rejectBeforeWrite(spec.action, \"forbidden\");\n\n    // after the await: re-read the store and re-check\n    const blockedLate = writeIsBlocked(spec.rowId);\n    if (blockedLate) return rejectBeforeWrite(spec.action, blockedLate);\n    const userNow = userOf(userState());\n    const confirmedNow = core.confirmed.get(commentId);\n    if (spec.action !== \"create\" && !confirmedNow) return rejectBeforeWrite(spec.action, \"invalid\");\n    if (core.pending.has(commentId)) return { ok: false, reason: \"pending\" };\n    if (spec.action === \"create\" && (core.confirmed.has(commentId) || core.tombstones.has(commentId))) return rejectBeforeWrite(\"create\", \"invalid\");\n\n    const ts = now();\n    const writeId = spec.reuse ? spec.reuse.writeId : nextWriteId();\n    const baseVersion = spec.reuse ? spec.reuse.baseVersion : (spec.forceBase ?? confirmedNow?.version ?? 0);\n    const base = confirmedNow;\n    let record: CellComment;\n    let change: CommentChange;\n    if (spec.reuse) {\n      record = spec.reuse.record;\n      change = spec.reuse.change;\n    } else if (spec.action === \"create\") {\n      record = Object.freeze({ id: commentId, rowId: spec.rowId, columnId: spec.columnId, text: text as string, ...(userNow ? { author: userNow } : {}), createdAt: ts, updatedAt: ts, version: 1, writeId, resolved: false });\n      change = Object.freeze({ kind: \"upsert\" as const, comment: record, baseVersion: 0 });\n    } else if (spec.action === \"delete\") {\n      record = base as CellComment;\n      change = Object.freeze({ kind: \"delete\" as const, id: commentId, rowId: record.rowId, columnId: record.columnId, version: baseVersion + 1, writeId, baseVersion });\n    } else {\n      const source = base as CellComment;\n      const next: CellComment = { ...source, updatedAt: ts, version: baseVersion + 1, writeId };\n      if (spec.action === \"update\") next.text = text as string;\n      else if (spec.action === \"resolve\") {\n        next.resolved = true;\n        if (userNow) next.resolvedBy = userNow;\n        else delete next.resolvedBy;\n        next.resolvedAt = ts;\n      } else {\n        next.resolved = false;\n        delete next.resolvedBy;\n        delete next.resolvedAt;\n      }\n      record = Object.freeze(next);\n      change = Object.freeze({ kind: \"upsert\" as const, comment: record, baseVersion });\n    }\n\n    // the draft base against the confirmed record: a mismatch is a stale conflict, never an overwrite\n    if (spec.base && base && !spec.reuse && (spec.base.version !== base.version || spec.base.writeId !== base.writeId)) {\n      const stale: Conflict = {\n        id: commentId,\n        rowId: record.rowId,\n        columnId: record.columnId,\n        action: spec.action,\n        reason: \"stale\",\n        writeId,\n        baseVersion,\n        baseWriteId: base.writeId,\n        change,\n        record,\n        thrown: false,\n        text: spec.action === \"update\" ? text : undefined,\n        shownVersion: base.version,\n        discardOnly: false,\n      };\n      core.conflicts.set(commentId, stale);\n      if (text !== undefined && spec.action === \"update\") {\n        putDraft(core, { key: editDraftKey(commentId), kind: \"edit\", commentId, rowId: record.rowId, columnId: record.columnId, text, baseVersion: spec.base.version, baseWriteId: spec.base.writeId });\n      }\n      store.bumpDrafts();\n      return rejectBeforeWrite(spec.action, \"stale\", change);\n    }\n\n    const applied = dispatch({ type: \"localWrite\", action: spec.action, change, record, baseWriteId: base?.writeId, now: ts });\n    if (!applied.ok) return rejectBeforeWrite(spec.action, \"limit\", change);\n    if (spec.action === \"create\") discardDraft(core, newDraftKey(spec.rowId, spec.columnId));\n    else if (spec.action === \"update\") discardDraft(core, editDraftKey(commentId));\n\n    const settled = settleWrite(spec.action, commentId, writeId, change, base);\n    return { ok: true, settled };\n  }\n\n  function settleWrite(action: CommentAction, id: string, writeId: string, change: CommentChange, prev: CellComment | undefined): Promise<void> {\n    const o = optionsOf();\n    const settle = (outcome: AckOutcome): void => {\n      dispatch({ type: \"ack\", id, writeId, outcome, now: now() });\n    };\n    if (!o.onCommentSave) {\n      settle({ kind: \"void\", server: false });\n      return Promise.resolve();\n    }\n    let result: unknown;\n    try {\n      result = o.onCommentSave({ action, change, prev });\n    } catch (error) {\n      settle({ kind: \"throw\", error });\n      return Promise.resolve();\n    }\n    if (!isThenable(result)) {\n      settle(parseSaveAnswer(result, refreshBounds()));\n      return Promise.resolve();\n    }\n    return (result as Promise<unknown>).then(\n      (value) => settle(parseSaveAnswer(value, refreshBounds())),\n      (error: unknown) => settle({ kind: \"throw\", error }),\n    );\n  }\n\n  // --- observer ---------------------------------------------------------------------------------\n\n  const observeDataChange: CommentEngine[\"observeDataChange\"] = (next, change, ctx) => {\n    if (disposed) return;\n    if (change.source === \"id-swap\") {\n      const rowIndex = new Map<unknown, number>();\n      next.forEach((row, i) => rowIndex.set(row, i));\n      const map = new Map<string, string>();\n      for (const op of change.ops) {\n        if (op.type !== \"update\") continue;\n        const index = rowIndex.get(op.row);\n        if (index === undefined) continue;\n        const newId = ctx.getRowId(op.row, index);\n        if (newId !== op.rowId) map.set(op.rowId, newId);\n      }\n      if (map.size === 0) return;\n      for (const [oldId, newId] of map) if (busyRows.delete(oldId)) busyRows.add(newId);\n      fetcher.remapRows(map);\n      const open = store.ui.getState().open;\n      dispatch({ type: \"idSwap\", map });\n      if (open && map.has(open.rowId)) store.ui.setState({ open: { ...open, rowId: map.get(open.rowId) as string } });\n      return;\n    }\n    const deleted: string[] = [];\n    for (const op of change.ops) {\n      if (op.type === \"insert\") {\n        if (grid?.saveStatus(op.rowId) === \"saving\" && busyRows.size < MAX_BUSY_ROWS) busyRows.add(op.rowId);\n      } else if (op.type === \"delete\") {\n        busyRows.delete(op.rowId);\n        if (core.index.has(op.rowId)) deleted.push(op.rowId);\n      }\n    }\n    if (deleted.length === 0) return;\n    const comments: CellComment[] = [];\n    for (const rowId of deleted) {\n      const columns = core.index.get(rowId);\n      if (!columns) continue;\n      for (const [columnId] of columns) for (const entry of cellComments(core, rowId, columnId)) comments.push(entry.comment);\n    }\n    if (comments.length === 0) return;\n    const handler = optionsOf().onOrphanedComments;\n    if (handler) {\n      const ctxOut: OrphanedCommentsCtx = { comments, rowIds: deleted, source: change.source };\n      callSafely(() => handler(ctxOut));\n    }\n  };\n\n  const engine: CommentEngine = {\n    store,\n    attachGrid(adapter) {\n      grid = adapter;\n      return () => {\n        if (grid === adapter) grid = null;\n      };\n    },\n    bounds: () => bounds,\n    applyRemote(changes) {\n      const b = refreshBounds();\n      const list = Array.isArray(changes) ? changes : [];\n      const batch = list.slice(0, MAX_REMOTE_BATCH);\n      const valid: { index: number; change: CommentChange }[] = [];\n      const invalid: number[] = [];\n      batch.forEach((raw, index) => {\n        const change = validateChange(raw, b);\n        if (change) valid.push({ index, change });\n        else invalid.push(index);\n      });\n      if (invalid.length > 0) warnOnce(\"remote-invalid\", `${invalid.length} remote change(s) were dropped (invalid)`);\n      const result = dispatch({ type: \"remote\", changes: valid, invalid, truncated: Math.max(0, list.length - batch.length), now: now() });\n      return result.verdict as ApplyRemoteVerdict;\n    },\n    getComments() {\n      return confirmedSnapshot(core).slice(0, bounds.maxComments);\n    },\n    removeComments(rowIds) {\n      const list = rowIds.slice(0, MAX_REMOTE_BATCH);\n      const open = store.ui.getState().open;\n      const result = dispatch({ type: \"remove\", rowIds: list, now: now() });\n      if (open && list.includes(open.rowId)) store.close();\n      return result.removed ?? 0;\n    },\n    refetch(rowIds) {\n      fetcher.refetch(rowIds ? rowIds.slice(0, MAX_REMOTE_BATCH) : null);\n    },\n    syncProp(next) {\n      refreshBounds();\n      dispatch({ type: \"propChange\", next, now: now() });\n      if (core.dropped > 0) warnOnce(\"prop-dropped\", `${core.dropped} record(s) of the comments prop were dropped (invalid or over a bound)`);\n    },\n    create: (input) => execute({ action: \"create\", rowId: input.rowId, columnId: input.columnId, text: input.text }),\n    edit: (id, text, base) => {\n      const c = core.confirmed.get(id);\n      return c ? execute({ action: \"update\", id, rowId: c.rowId, columnId: c.columnId, text, base }) : Promise.resolve(rejectBeforeWrite(\"update\", \"invalid\"));\n    },\n    remove: (id, base) => {\n      const c = core.confirmed.get(id);\n      return c ? execute({ action: \"delete\", id, rowId: c.rowId, columnId: c.columnId, base }) : Promise.resolve(rejectBeforeWrite(\"delete\", \"invalid\"));\n    },\n    setResolved: (id, resolved, base) => {\n      const c = core.confirmed.get(id);\n      return c ? execute({ action: resolved ? \"resolve\" : \"reopen\", id, rowId: c.rowId, columnId: c.columnId, base }) : Promise.resolve(rejectBeforeWrite(resolved ? \"resolve\" : \"reopen\", \"invalid\"));\n    },\n    retry(id, text) {\n      const conflict = core.conflicts.get(id);\n      if (!conflict) return Promise.resolve({ ok: false as const, reason: \"invalid\" as const });\n      const unchanged = conflict.text === undefined || text === undefined || text === conflict.text;\n      discardConflict(core, id);\n      store.bumpDrafts();\n      if (conflict.thrown && unchanged) {\n        const spec: WriteSpec = { action: conflict.action, id: conflict.action === \"create\" ? undefined : id, rowId: conflict.rowId, columnId: conflict.columnId, reuse: conflict };\n        return execute(spec);\n      }\n      return execute({\n        action: conflict.action,\n        id: conflict.action === \"create\" ? undefined : id,\n        rowId: conflict.rowId,\n        columnId: conflict.columnId,\n        text: text ?? conflict.text,\n        base: conflict.action === \"create\" ? undefined : { version: conflict.baseVersion, writeId: conflict.baseWriteId },\n      });\n    },\n    saveMine(id, text) {\n      const conflict = core.conflicts.get(id);\n      if (!conflict) return Promise.resolve({ ok: false as const, reason: \"invalid\" as const });\n      discardConflict(core, id);\n      store.bumpDrafts();\n      const base = core.confirmed.get(id);\n      return execute({\n        action: conflict.action,\n        id: conflict.action === \"create\" ? undefined : id,\n        rowId: conflict.rowId,\n        columnId: conflict.columnId,\n        text,\n        forceBase: conflict.shownVersion ?? base?.version,\n      });\n    },\n    discard(id) {\n      const conflict = core.conflicts.get(id);\n      discardConflict(core, id);\n      if (conflict) {\n        discardDraft(core, conflict.action === \"create\" ? newDraftKey(conflict.rowId, conflict.columnId) : editDraftKey(id));\n      }\n      store.bumpDrafts();\n    },\n    setDraft(draft) {\n      putDraft(core, { ...draft, key: draft.key ?? (draft.kind === \"new\" ? newDraftKey(draft.rowId, draft.columnId) : editDraftKey(draft.commentId as string)) });\n      store.bumpDrafts();\n    },\n    discardDraft(key) {\n      discardDraft(core, key);\n      store.bumpDrafts();\n    },\n    isRowBusy: isBusy,\n    fetchState: (rowId) => fetcher.fetchState(rowId),\n    retryFetch: (rowId) => fetcher.retryFetch(rowId),\n    observeDataChange,\n    kickFetch: () => fetcher.schedule(),\n    noteRowsRendered(rowIds) {\n      store.setVisibleRowIds(rowIds);\n    },\n    currentUser: userState,\n    labels: () => resolveCommentsLabels(grid?.gridLabels(), optionsOf().labels),\n    seed: (records) => {\n      if (!config.controlled) applySeed(records);\n    },\n    isDisposed: () => disposed,\n    openComments: (ref, by = \"pointer\") => grid?.open(ref, by) ?? false,\n    start() {\n      disposed = false;\n      startExpire();\n      store.onVisibleChange = fetcher.onVisibleChange;\n      fetcher.schedule();\n    },\n    dispose() {\n      disposed = true;\n      fetcher.dispose();\n      if (expireTimer !== null) clearInterval(expireTimer);\n      expireTimer = null;\n      for (const controller of gateControllers.values()) controller.abort();\n      gateControllers.clear();\n      store.onVisibleChange = null;\n    },\n  };\n  return engine;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-engine.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comments-overlay.tsx",
      "content": "\"use client\";\n\nimport { memo, useLayoutEffect, useMemo, type ComponentType, type CSSProperties, type ReactNode } from \"react\";\nimport { useStore } from \"zustand\";\nimport { useShallow } from \"zustand/react/shallow\";\nimport { useDataGridVisibleColumns, type OverlayPluginCtx } from \"@/registry/default/components/data-grid/data-grid\";\nimport { GRID_LAYER, dataIndexAt, hasAnyPin, rowIdAtViewRow, useDataGridSelector } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { cellComments } from \"./comment-state\";\nimport type { CommentEngine } from \"./comment-engine\";\nimport type { UseDataGridCommentsOptions } from \"./types\";\n\nexport const MAX_MARKERS = 2048;\n\ntype Marker = { key: string; rowId: string; columnId: string; viewRow: number; col: number; unresolved: boolean };\n\ntype MarkerProps = {\n  marker: Marker;\n  windowStart: number;\n  colOffset: number;\n  pinStyle: CSSProperties | undefined;\n  onOpen: (rowId: string, columnId: string) => void;\n};\n\nconst CommentMarker = memo(function CommentMarker({ marker, windowStart, colOffset, pinStyle, onOpen }: MarkerProps) {\n  return (\n    <div\n      data-grid-comment-marker-cell=\"\"\n      data-pinned={pinStyle ? \"\" : undefined}\n      className=\"pointer-events-none\"\n      style={{\n        // out of flow when unpinned, so a marker change never re-lays out the rows canvas\n        position: \"absolute\",\n        inset: 0,\n        gridColumnStart: marker.col + colOffset,\n        gridColumnEnd: marker.col + colOffset + 1,\n        gridRowStart: marker.viewRow - windowStart + 1,\n        gridRowEnd: marker.viewRow - windowStart + 2,\n        // one step above the active cell it marks, so a pinned cell still covers an unpinned marker\n        zIndex: (pinStyle ? GRID_LAYER.activePinnedCell : GRID_LAYER.activeCell) + 1,\n        ...(pinStyle ? { inset: undefined, ...pinStyle } : {}),\n      }}\n    >\n      <span\n        aria-hidden=\"true\"\n        data-grid-comment-marker=\"\"\n        data-unresolved={marker.unresolved ? \"\" : undefined}\n        className=\"pointer-events-auto absolute end-[var(--data-grid-comment-marker-inset,0px)] top-0 block size-2 cursor-pointer pointer-coarse:size-6\"\n        onClick={(event) => {\n          event.stopPropagation();\n          onOpen(marker.rowId, marker.columnId);\n        }}\n        onPointerDown={(event) => event.stopPropagation()}\n        onDoubleClick={(event) => event.stopPropagation()}\n      >\n        <span\n          className={`pointer-events-none absolute end-[var(--data-grid-comment-marker-inset,0px)] top-0 block size-2 ${\n            marker.unresolved\n              ? \"bg-primary [clip-path:polygon(0_0,100%_0,100%_100%)] rtl:[clip-path:polygon(0_0,100%_0,0_100%)] forced-colors:bg-[Highlight]\"\n              : \"rounded-full border border-primary forced-colors:border-[CanvasText]\"\n          }`}\n        />\n      </span>\n    </div>\n  );\n});\n\n/** Walks the rendered rows once; only rows with comments read their cells. `revision` keys the memo on the mutable add-on state. */\nfunction computeMarkers(\n  core: CommentEngine[\"store\"][\"core\"],\n  rowIds: readonly (string | undefined)[],\n  columnIndex: ReadonlyMap<string, number>,\n  hideResolved: boolean,\n  resolveEnabled: boolean,\n  firstViewRow: number,\n  revision: number,\n): Marker[] {\n  const list: Marker[] = [];\n  if (revision < 0) return list;\n  for (let i = 0; i < rowIds.length && list.length < MAX_MARKERS; i += 1) {\n    const rowId = rowIds[i];\n    if (rowId === undefined) continue;\n    const columns = core.index.get(rowId);\n    if (!columns) continue;\n    for (const columnId of columns.keys()) {\n      const col = columnIndex.get(columnId);\n      if (col === undefined) continue;\n      const entries = cellComments(core, rowId, columnId);\n      if (entries.length === 0) continue;\n      const unresolved = !resolveEnabled || entries.some((e) => !e.comment.resolved);\n      if (!unresolved && hideResolved) continue;\n      list.push({ key: `${rowId}\\u0001${columnId}`, rowId, columnId, viewRow: firstViewRow + i, col, unresolved });\n      if (list.length >= MAX_MARKERS) break;\n    }\n  }\n  return list;\n}\n\n/** The Overlay component of the plugin, closed over the engine. */\nexport function createCommentsOverlay(engine: CommentEngine, getOptions: () => UseDataGridCommentsOptions): ComponentType<OverlayPluginCtx> {\n  function CommentsOverlay(ctx: OverlayPluginCtx): ReactNode {\n    const { windowStart, clampRowStart, clampRowEnd, colOffset, pinTrack, splitRectByPinZones } = ctx;\n    const revision = useStore(engine.store.ui, (s) => s.revision);\n    const visibleColumns = useDataGridVisibleColumns();\n    const rowIds = useDataGridSelector<unknown, readonly (string | undefined)[]>(\n      useShallow((s) => {\n        const ids: (string | undefined)[] = [];\n        for (let viewRow = clampRowStart; viewRow < clampRowEnd; viewRow += 1) ids.push(dataIndexAt(s, viewRow) === undefined ? undefined : rowIdAtViewRow(s, viewRow));\n        return ids;\n      }),\n    );\n    useLayoutEffect(() => {\n      engine.noteRowsRendered(rowIds.filter((id): id is string => id !== undefined));\n    }, [rowIds]);\n\n    const hideResolved = getOptions().hideResolved === true;\n    const resolveEnabled = getOptions().enableResolve !== false;\n    const columnIndex = useMemo(() => new Map(visibleColumns.map((c, i) => [c.id, i])), [visibleColumns]);\n\n    const markers = useMemo(\n      () => computeMarkers(engine.store.core, rowIds, columnIndex, hideResolved, resolveEnabled, clampRowStart, revision),\n      [rowIds, columnIndex, hideResolved, resolveEnabled, clampRowStart, revision],\n    );\n\n    const onOpen = useMemo(() => (rowId: string, columnId: string) => void engine.openComments({ rowId, columnId }, \"pointer\"), []);\n\n    return (\n      <>\n        {markers.map((marker) => {\n          const segments = hasAnyPin(pinTrack) ? splitRectByPinZones({ x: marker.col, y: marker.viewRow, width: 1, height: 1 }, pinTrack) : [{ rect: { x: marker.col, y: marker.viewRow, width: 1, height: 1 }, pinStyle: undefined }];\n          const segment = segments[0];\n          if (!segment) return null;\n          return (\n            <CommentMarker\n              key={marker.key}\n              marker={marker}\n              windowStart={windowStart}\n              colOffset={colOffset}\n              pinStyle={\"pinStyle\" in segment ? segment.pinStyle : undefined}\n              onOpen={onOpen}\n            />\n          );\n        })}\n      </>\n    );\n  }\n  return CommentsOverlay;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comments-overlay.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comments-mount.tsx",
      "content": "\"use client\";\r\n\r\nimport { useEffect, useState, type ComponentType, type ReactNode } from \"react\";\r\nimport { createPortal } from \"react-dom\";\r\nimport { useStore } from \"zustand\";\r\nimport { useDataGridActiveCell, useDataGridApi, useDataGridKeymap, useDataGridReadOnly, type DataGridApi } from \"@/registry/default/components/data-grid/data-grid\";\r\nimport { GRID_ATTR, isDev, rowIdAtViewRow, useDataGridContainer } from \"@/registry/default/components/data-grid/data-grid-sdk\";\r\nimport { CommentPopoverHost } from \"./comment-popover\";\r\nimport { findOwnCell, viewRowOfRowId } from \"./own-cell\";\r\nimport { cellComments } from \"./comment-state\";\r\nimport type { CommentEngine, GridAdapter } from \"./comment-engine\";\r\nimport type { UseDataGridCommentsOptions } from \"./types\";\r\n\r\nconst ANNOUNCE_DEBOUNCE_MS = 250;\r\nconst OPEN_WAIT_FRAMES = 10;\r\n\r\nfunction humanizeChord(binding: string | undefined): string {\r\n  if (!binding) return \"\";\r\n  return binding\r\n    .split(\"+\")\r\n    .map((part) => (part.length > 1 ? part.charAt(0).toUpperCase() + part.slice(1) : part.toUpperCase()))\r\n    .join(\"+\");\r\n}\r\n\r\n/** Empties the live region before each message so a repeated text is read again. */\r\nfunction createSpeaker(setText: (text: string) => void) {\r\n  let timer: ReturnType<typeof setTimeout> | null = null;\r\n  return {\r\n    say(message: string): void {\r\n      setText(\"\");\r\n      if (timer !== null) clearTimeout(timer);\r\n      timer = setTimeout(() => setText(message), 30);\r\n    },\r\n    dispose(): void {\r\n      if (timer !== null) clearTimeout(timer);\r\n    },\r\n  };\r\n}\r\n\r\nfunction Announcer({ engine, getOptions }: { engine: CommentEngine; getOptions: () => UseDataGridCommentsOptions }): ReactNode {\r\n  const api = useDataGridApi();\r\n  const scrollRef = useDataGridContainer();\r\n  const activeCell = useDataGridActiveCell();\r\n  const keymap = useDataGridKeymap();\r\n  const announcement = useStore(engine.store.ui, (s) => s.announcement);\r\n  const revision = useStore(engine.store.ui, (s) => s.revision);\r\n  const [text, setText] = useState(\"\");\r\n  const [mounted, setMounted] = useState(false);\r\n  const [speaker] = useState(() => createSpeaker(setText));\r\n  const [last] = useState(() => ({ key: \"\" }));\r\n  const chord = humanizeChord(keymap[\"openComments\"]?.[0]);\r\n\r\n  useEffect(() => setMounted(true), []);\r\n  useEffect(() => () => speaker.dispose(), [speaker]);\r\n\r\n  useEffect(() => {\r\n    if (announcement.nonce > 0 && announcement.text) speaker.say(announcement.text);\r\n  }, [announcement, speaker]);\r\n\r\n  useEffect(() => {\r\n    if (!activeCell) return;\r\n    const timer = setTimeout(() => {\r\n      const scroll = scrollRef.current;\r\n      const focus = document.activeElement;\r\n      const inside = focus !== null && ((scroll?.contains(focus) ?? false) || focus.closest(`[${GRID_ATTR.commentsPopup}]`) !== null);\r\n      if (!inside) return;\r\n      const state = api.store.getState();\r\n      const rowId = rowIdAtViewRow(state, activeCell.row);\r\n      const columnId = state.visibleColumns[activeCell.col]?.id;\r\n      if (rowId === undefined || columnId === undefined) return;\r\n      const entries = cellComments(engine.store.core, rowId, columnId);\r\n      const options = getOptions();\r\n      const hidden = options.hideResolved === true && options.enableResolve !== false && entries.every((e) => e.comment.resolved);\r\n      if (entries.length === 0 || hidden) {\r\n        last.key = \"\";\r\n        return;\r\n      }\r\n      const key = `${rowId}\\u0001${columnId}`;\r\n      if (last.key === key) return;\r\n      last.key = key;\r\n      const labels = engine.labels();\r\n      if (options.enableResolve === false) speaker.say(labels.announceCount(entries.length, chord));\r\n      else speaker.say(labels.announce(entries.length, entries.filter((e) => !e.comment.resolved).length, chord));\r\n    }, ANNOUNCE_DEBOUNCE_MS);\r\n    return () => clearTimeout(timer);\r\n  }, [activeCell, revision, api, engine, scrollRef, getOptions, speaker, last, chord]);\r\n\r\n  if (!mounted || typeof document === \"undefined\") return null;\r\n  return createPortal(\r\n    <div role=\"status\" aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\" data-grid-comments-announcer=\"\">\r\n      {text}\r\n    </div>,\r\n    document.body,\r\n  );\r\n}\r\n\r\nfunction findCell(scroll: HTMLElement | null, viewRow: number, columnId: string): boolean {\r\n  return findOwnCell(scroll, viewRow, columnId) !== null;\r\n}\r\n\r\nfunction waitForCell(engine: CommentEngine, scroll: HTMLElement | null, viewRow: number, ref: { rowId: string; columnId: string }, by: \"keyboard\" | \"pointer\" | \"menu\", frame: number): void {\r\n  if (engine.isDisposed()) return;\r\n  if (findCell(scroll, viewRow, ref.columnId)) {\r\n    engine.store.open(ref, by);\r\n    return;\r\n  }\r\n  if (frame >= OPEN_WAIT_FRAMES) {\r\n    if (isDev()) console.warn(\"[data-grid-comments] openComments dropped: the cell did not render within 10 frames\");\r\n    return;\r\n  }\r\n  requestAnimationFrame(() => waitForCell(engine, scroll, viewRow, ref, by, frame + 1));\r\n}\r\n\r\n/** Scrolls to the cell, makes it active, and opens the popover once the cell renders. */\r\nfunction openCell(\r\n  engine: CommentEngine,\r\n  api: DataGridApi<unknown>,\r\n  scroll: HTMLElement | null,\r\n  ref: { rowId: string; columnId: string },\r\n  by: \"keyboard\" | \"pointer\" | \"menu\",\r\n): boolean {\r\n  const state = api.store.getState();\r\n  if (!state.visibleColumns.some((c) => c.id === ref.columnId)) return false;\r\n  const viewRow = viewRowOfRowId(state, ref.rowId);\r\n  if (viewRow < 0) return false;\r\n  api.scrollTo(ref);\r\n  api.actions.selectCell(ref);\r\n  waitForCell(engine, scroll, viewRow, ref, by, 0);\r\n  return true;\r\n}\r\n\r\nfunction assignReadOnly(state: { readOnly: boolean }, readOnly: boolean): void {\r\n  state.readOnly = readOnly;\r\n}\r\n\r\n/** The plugin's Mount component: grid adapter, save-status watcher, announcer, popover host. */\r\nexport function createCommentsMount(engine: CommentEngine, getOptions: () => UseDataGridCommentsOptions): ComponentType {\r\n  function CommentsMount(): ReactNode {\r\n    const api = useDataGridApi();\r\n    const scrollRef = useDataGridContainer();\r\n    const readOnly = useDataGridReadOnly();\r\n    const [gridState] = useState(() => ({ readOnly: false }));\r\n\r\n    useEffect(() => {\r\n      assignReadOnly(gridState, readOnly);\r\n    }, [gridState, readOnly]);\r\n\r\n    useEffect(() => {\r\n      const adapter: GridAdapter = {\r\n        readOnly: () => gridState.readOnly,\r\n        saveStatus: (rowId) => api.store.getState().saveStatus.get(rowId),\r\n        open: (ref, by) => openCell(engine, api, scrollRef.current, ref, by),\r\n        gridLabels: () => {\r\n          const { locale, labels } = api.store.getState();\r\n          return { locale, comments: labels.comments };\r\n        },\r\n      };\r\n      return engine.attachGrid(adapter);\r\n    }, [api, scrollRef, gridState]);\r\n\r\n    useEffect(() => {\r\n      let previous = api.store.getState().saveStatus;\r\n      return api.store.subscribe((s) => {\r\n        if (s.saveStatus === previous) return;\r\n        previous = s.saveStatus;\r\n        engine.kickFetch();\r\n      });\r\n    }, [api]);\r\n\r\n    return (\r\n      <>\r\n        <CommentPopoverHost engine={engine} getOptions={getOptions} />\r\n        <Announcer engine={engine} getOptions={getOptions} />\r\n      </>\r\n    );\r\n  }\r\n  return CommentsMount;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comments-mount.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/comment-popover.tsx",
      "content": "\"use client\";\n\nimport { Popover as PopoverPrimitive } from \"@base-ui/react/popover\";\nimport { useCallback, useEffect, useMemo, useState, type KeyboardEvent, type ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { useStore } from \"zustand\";\nimport { Button } from \"@/components/ui/button\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { useDataGridApi, useDataGridReadOnly } from \"@/registry/default/components/data-grid/data-grid\";\nimport { GRID_ATTR, isComposingKey, rowIdAtViewRow, toSafeText, useDataGridContainer } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { findOwnCell, viewRowOfRowId } from \"./own-cell\";\nimport { cellComments, editDraftKey, newDraftKey } from \"./comment-state\";\nimport { authorLabelName, defaultCanModify } from \"./default-gate\";\nimport type { CommentEngine, WriteResult } from \"./comment-engine\";\nimport type { DataGridCommentsLabels } from \"./labels\";\nimport type { CellComment, UseDataGridCommentsOptions } from \"./types\";\n\nconst FALLBACK_COLOR = \"var(--color-primary)\";\n\nfunction safeColor(color: string | undefined): string {\n  if (!color) return FALLBACK_COLOR;\n  if (typeof CSS === \"undefined\" || typeof CSS.supports !== \"function\") return color;\n  return CSS.supports(\"color\", color) ? color : FALLBACK_COLOR;\n}\n\nfunction focusableIn(root: HTMLElement): HTMLElement[] {\n  return Array.from(root.querySelectorAll<HTMLElement>(\"button, textarea, input, [href], [tabindex]:not([tabindex='-1'])\")).filter(\n    (el) => el.getAttribute(\"aria-disabled\") !== \"true\" && !(el as HTMLButtonElement).disabled,\n  );\n}\n\ntype Locate = () => HTMLElement | null;\ntype Holder<T> = { current: T };\n\nfunction setHolder<T>(holder: Holder<T>, value: T): void {\n  holder.current = value;\n}\n\n/** The cell's rect, or the last known one while the cell is out of the rendered rows. */\nfunction rectOf(cell: HTMLElement | null, last: Holder<DOMRect | null>): DOMRect {\n  if (cell) last.current = cell.getBoundingClientRect();\n  return last.current ?? new DOMRect();\n}\n\n/** A mutable holder that is not a React ref: popup and field elements are read by event handlers and Base UI callbacks, never during render. */\nfunction useHolder<T>(initial: T): Holder<T> {\n  return useState(() => ({ current: initial }))[0];\n}\n\n/** Finds the rendered cell element of `{ rowId, columnId }`; the view row is cached and re-resolved when the store moved the row. */\nfunction createCellAnchor(locate: Locate, getScroll: () => HTMLElement | null, last: Holder<DOMRect | null>) {\n  return {\n    get contextElement() {\n      return getScroll() ?? undefined;\n    },\n    getBoundingClientRect: () => rectOf(locate(), last),\n  };\n}\n\nfunction useLocateCell(rowId: string, columnId: string): Locate {\n  const api = useDataGridApi();\n  const scrollRef = useDataGridContainer();\n  const viewRowCache = useHolder(-1);\n  return useCallback(() => {\n    const scroll = scrollRef.current;\n    if (!scroll) return null;\n    const state = api.store.getState();\n    let viewRow = viewRowCache.current;\n    if (viewRow < 0 || rowIdAtViewRow(state, viewRow) !== rowId) {\n      viewRow = viewRowOfRowId(state, rowId);\n      setHolder(viewRowCache, viewRow);\n    }\n    if (viewRow < 0) return null;\n    return findOwnCell(scroll, viewRow, columnId);\n  }, [api, scrollRef, rowId, columnId, viewRowCache]);\n}\n\n/** The active row stays mounted off-window, so a mounted cell is not enough: it must also overlap the scrollport. */\nfunction isCellInView(cell: HTMLElement | null, scroll: HTMLElement | null): boolean {\n  if (!cell) return false;\n  if (!scroll) return true;\n  const c = cell.getBoundingClientRect();\n  const v = scroll.getBoundingClientRect();\n  return c.bottom > v.top && c.top < v.bottom && c.right > v.left && c.left < v.right;\n}\n\ntype HostProps = { engine: CommentEngine; getOptions: () => UseDataGridCommentsOptions };\n\n/** Mounts the popover for the open target. */\nexport function CommentPopoverHost({ engine, getOptions }: HostProps): ReactNode {\n  const open = useStore(engine.store.ui, (s) => s.open);\n  if (!open || typeof document === \"undefined\") return null;\n  // portaled to the body: Base UI leaves an aria-owns span where it renders, and inside role=\"grid\" that span fails the required-children rule\n  return createPortal(<OpenPopover key={open.nonce} engine={engine} getOptions={getOptions} rowId={open.rowId} columnId={open.columnId} />, document.body);\n}\n\nfunction OpenPopover({ engine, getOptions, rowId, columnId }: HostProps & { rowId: string; columnId: string }): ReactNode {\n  const api = useDataGridApi();\n  const scrollRef = useDataGridContainer();\n  const locate = useLocateCell(rowId, columnId);\n  const getScroll = useCallback(() => scrollRef.current, [scrollRef]);\n  const popupEl = useHolder<HTMLDivElement | null>(null);\n  const composerEl = useHolder<HTMLTextAreaElement | null>(null);\n  const escapeFn = useHolder<(() => boolean) | null>(null);\n  const lastRect = useHolder<DOMRect | null>(null);\n  const options = getOptions();\n  useStore(api.store, (s) => s.labels);\n  useStore(api.store, (s) => s.locale);\n  const labels = engine.labels();\n\n  // a function anchor: Base UI builds the virtual element outside render, where it reads the scroll element\n  const anchor = useCallback(() => createCellAnchor(locate, getScroll, lastRect), [locate, getScroll, lastRect]);\n\n  const closeWithFocusGrid = useCallback(\n    (reason: \"scroll-out\" | \"tab\") => {\n      const popup = popupEl.current;\n      const hadFocus = popup !== null && popup.contains(document.activeElement);\n      engine.store.close();\n      if (!hadFocus) return;\n      if (reason === \"tab\") api.focus();\n      else scrollRef.current?.focus({ preventScroll: true });\n    },\n    [api, engine, scrollRef, popupEl],\n  );\n\n  useEffect(() => {\n    const scroll = scrollRef.current;\n    let frame = 0;\n    const check = (): void => {\n      frame = 0;\n      if (!isCellInView(locate(), scroll)) closeWithFocusGrid(\"scroll-out\");\n    };\n    const schedule = (): void => {\n      if (frame === 0) frame = requestAnimationFrame(check);\n    };\n    scroll?.addEventListener(\"scroll\", schedule, { passive: true });\n    const unsubscribe = api.store.subscribe(schedule);\n    schedule();\n    return () => {\n      scroll?.removeEventListener(\"scroll\", schedule);\n      unsubscribe();\n      if (frame !== 0) cancelAnimationFrame(frame);\n    };\n  }, [api, closeWithFocusGrid, locate, scrollRef]);\n\n  const columnTitle = useMemo(() => {\n    const column = api.store.getState().visibleColumns.find((c) => c.id === columnId);\n    if (!column) return columnId;\n    return column.headerText ?? (typeof column.header === \"string\" ? column.header : column.id);\n  }, [api, columnId]);\n  const [cellText, setCellText] = useState(\"\");\n  useEffect(() => {\n    setCellText((locate()?.textContent ?? \"\").trim().slice(0, 60));\n  }, [locate]);\n\n  return (\n    <PopoverPrimitive.Root\n      open\n      modal={false}\n      onOpenChange={(next, details) => {\n        if (next) return;\n        if (details.reason === \"escape-key\" && escapeFn.current?.()) {\n          details.cancel();\n          return;\n        }\n        engine.store.close();\n      }}\n    >\n      <PopoverPrimitive.Portal>\n        <PopoverPrimitive.Positioner anchor={anchor} side=\"bottom\" align=\"start\" sideOffset={4} className=\"isolate z-50\">\n          <PopoverPrimitive.Popup\n            ref={popupEl}\n            tabIndex={-1}\n            aria-label={labels.popover(columnTitle, cellText)}\n            {...{ [GRID_ATTR.commentsPopup]: \"\", [GRID_ATTR.keepFocus]: \"\" }}\n            initialFocus={() => (cellComments(engine.store.core, rowId, columnId).length === 0 ? (composerEl.current ?? popupEl.current) : popupEl.current)}\n            finalFocus={() => {\n              const active = document.activeElement;\n              const free = !active || active === document.body || popupEl.current?.contains(active) === true;\n              if (free) api.focus();\n              return false;\n            }}\n            onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {\n              if (event.key !== \"Tab\" || isComposingKey(event)) return;\n              const popup = popupEl.current;\n              if (!popup) return;\n              const items = focusableIn(popup);\n              const first = items[0];\n              const last = items[items.length - 1];\n              const active = document.activeElement;\n              if ((event.shiftKey && (active === first || active === popup)) || (!event.shiftKey && active === last)) closeWithFocusGrid(\"tab\");\n            }}\n            className={cn(\n              \"z-50 flex max-h-96 w-80 origin-(--transform-origin) flex-col gap-2.5 overflow-y-auto rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n              options.className,\n            )}\n          >\n            <PopoverBody engine={engine} getOptions={getOptions} rowId={rowId} columnId={columnId} labels={labels} composerEl={composerEl} escapeFn={escapeFn} />\n          </PopoverPrimitive.Popup>\n        </PopoverPrimitive.Positioner>\n      </PopoverPrimitive.Portal>\n    </PopoverPrimitive.Root>\n  );\n}\n\ntype BodyProps = {\n  engine: CommentEngine;\n  getOptions: () => UseDataGridCommentsOptions;\n  rowId: string;\n  columnId: string;\n  labels: DataGridCommentsLabels;\n  composerEl: Holder<HTMLTextAreaElement | null>;\n  escapeFn: Holder<(() => boolean) | null>;\n};\n\nfunction noticeFor(result: WriteResult, labels: DataGridCommentsLabels): string {\n  if (result.ok) return \"\";\n  switch (result.reason) {\n    case \"forbidden\":\n      return labels.refused;\n    case \"row-busy\":\n      return labels.rowBusyHint;\n    case \"read-only\":\n      return labels.readOnlyHint;\n    case \"pending\":\n      return \"\";\n    default:\n      return labels.failed;\n  }\n}\n\nfunction formatTime(ts: number, locale: string): string {\n  try {\n    return new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"short\" }).format(new Date(ts));\n  } catch {\n    return new Date(ts).toISOString();\n  }\n}\n\n/** The add-on state is mutable; both revisions are inputs here so the compiler re-reads it when either moves. */\nfunction readBody(engine: CommentEngine, getOptions: () => UseDataGridCommentsOptions, rowId: string, columnId: string, revision: number, draftRevision: number) {\n  return {\n    options: getOptions(),\n    user: engine.currentUser(),\n    entries: cellComments(engine.store.core, rowId, columnId),\n    fetchState: engine.fetchState(rowId),\n    busy: engine.isRowBusy(rowId),\n    stamp: revision + draftRevision,\n  };\n}\n\nfunction readDraft(core: CommentEngine[\"store\"][\"core\"], key: string, draftRevision: number) {\n  return draftRevision < 0 ? undefined : core.drafts.get(key);\n}\n\nfunction findComposeConflict(core: CommentEngine[\"store\"][\"core\"], rowId: string, columnId: string, draftRevision: number) {\n  if (draftRevision < 0) return undefined;\n  return Array.from(core.conflicts.values()).find((c) => c.rowId === rowId && c.columnId === columnId && (c.action === \"create\" || !core.confirmed.has(c.id)));\n}\n\nfunction PopoverBody({ engine, getOptions, rowId, columnId, labels, composerEl, escapeFn }: BodyProps): ReactNode {\n  const revision = useStore(engine.store.ui, (s) => s.revision);\n  const draftRevision = useStore(engine.store.ui, (s) => s.draftRevision);\n  const core = engine.store.core;\n  const gridReadOnly = useDataGridReadOnly();\n  const { options, user, entries, fetchState, busy } = readBody(engine, getOptions, rowId, columnId, revision, draftRevision);\n  const writable = user.kind !== \"invalid\" && options.readOnly !== true && (!gridReadOnly || options.allowWhenReadOnly === true);\n  const currentUser = user.kind === \"user\" ? user.user : undefined;\n  const resolveEnabled = options.enableResolve !== false;\n  const [confirmId, setConfirmId] = useState<string | null>(null);\n  const [notice, setNotice] = useState(\"\");\n  const composeKey = newDraftKey(rowId, columnId);\n  const composeDraft = readDraft(core, composeKey, draftRevision);\n  const composeConflict = findComposeConflict(core, rowId, columnId, draftRevision);\n  const rootEl = useHolder<HTMLDivElement | null>(null);\n  const focusedInside = useHolder(false);\n\n  useEffect(() => {\n    setHolder(escapeFn, () => {\n      if (confirmId === null) return false;\n      setConfirmId(null);\n      return true;\n    });\n    return () => setHolder(escapeFn, null);\n  }, [confirmId, escapeFn]);\n\n  useEffect(() => {\n    const popup = rootEl.current?.closest<HTMLElement>(`[${GRID_ATTR.commentsPopup}]`) ?? null;\n    if (confirmId !== null) rootEl.current?.querySelector<HTMLElement>(\"[data-comment-confirm]\")?.focus();\n    else if (focusedInside.current && (!document.activeElement || document.activeElement === document.body)) popup?.focus();\n  }, [confirmId, rootEl, focusedInside]);\n\n  useEffect(() => {\n    if (!focusedInside.current) return;\n    if (document.activeElement && document.activeElement !== document.body) return;\n    rootEl.current?.closest<HTMLElement>(`[${GRID_ATTR.commentsPopup}]`)?.focus();\n  });\n\n  const run = async (promise: Promise<WriteResult>): Promise<void> => {\n    const result = await promise;\n    setNotice(noticeFor(result, labels));\n  };\n\n  const submitCompose = (): void => {\n    const text = composeDraft?.text ?? \"\";\n    if (!text.trim()) return;\n    void run(engine.create({ rowId, columnId, text })).then(() => composerEl.current?.focus());\n  };\n\n  const hasCustomGate = (name: \"canEdit\" | \"canDelete\"): boolean => options[name] !== undefined;\n  const canShowEdit = (c: CellComment): boolean => writable && options.enableEdit !== false && (hasCustomGate(\"canEdit\") || defaultCanModify(c, currentUser));\n  const canShowDelete = (c: CellComment): boolean => writable && options.enableDelete !== false && (hasCustomGate(\"canDelete\") || defaultCanModify(c, currentUser));\n  const max = engine.bounds().maxTextLength;\n  const anySaving = entries.some((e) => e.saving);\n\n  return (\n    <div\n      ref={rootEl}\n      className=\"flex flex-col gap-2\"\n      aria-busy={anySaving || undefined}\n      onFocusCapture={() => setHolder(focusedInside, true)}\n    >\n      {fetchState === \"loading\" || fetchState === \"idle\" ? (\n        <p role=\"status\" aria-live=\"polite\" className=\"text-muted-foreground\">\n          {labels.loading}\n        </p>\n      ) : null}\n      {fetchState === \"failed\" ? (\n        <div role=\"alert\" className=\"flex items-center justify-between gap-2\">\n          <span>{labels.loadFailed}</span>\n          <Button type=\"button\" size=\"xs\" variant=\"outline\" onClick={() => engine.retryFetch(rowId)}>\n            {labels.retry}\n          </Button>\n        </div>\n      ) : null}\n      {entries.length === 0 && fetchState === \"ready\" ? <p className=\"text-muted-foreground\">{labels.noComments}</p> : null}\n      {entries.length > 0 ? (\n        <ul role=\"list\" aria-label={labels.commentList} className=\"flex flex-col gap-2\">\n          {entries.map(({ comment, saving }, index) => {\n            const time = formatTime(comment.createdAt, labels.locale);\n            const name = authorLabelName(comment.author, labels.unknownAuthor);\n            const editDraft = core.drafts.get(editDraftKey(comment.id));\n            const conflict = core.conflicts.get(comment.id);\n            const disabled = saving;\n            return (\n              <li key={comment.id} className=\"flex flex-col gap-1.5\">\n                {index > 0 ? <Separator /> : null}\n                <div className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n                  {comment.author ? (\n                    <>\n                      <span aria-hidden=\"true\" className=\"size-2 shrink-0 rounded-full\" style={{ backgroundColor: safeColor(comment.author.color) }} />\n                      <bdi className=\"font-medium text-foreground\">{name}</bdi>\n                    </>\n                  ) : null}\n                  <time dateTime={new Date(comment.createdAt).toISOString()}>{time}</time>\n                  {resolveEnabled && comment.resolved ? <span>{labels.resolved}</span> : null}\n                  {saving ? <span role=\"status\">{labels.saving}</span> : null}\n                </div>\n                {editDraft ? (\n                  <EditBox\n                    engine={engine}\n                    comment={comment}\n                    text={editDraft.text}\n                    base={{ version: editDraft.baseVersion, writeId: editDraft.baseWriteId }}\n                    labels={labels}\n                    max={max}\n                    disabled={disabled}\n                    onResult={(result) => setNotice(noticeFor(result, labels))}\n                  />\n                ) : (\n                  <p className=\"text-sm\">\n                    <bdi className=\"whitespace-pre-wrap [overflow-wrap:anywhere]\">{toSafeText(comment.text)}</bdi>\n                  </p>\n                )}\n                {conflict ? <ConflictBox engine={engine} conflictId={comment.id} labels={labels} onResult={(result) => setNotice(noticeFor(result, labels))} /> : null}\n                {!editDraft ? (\n                  <div className=\"flex flex-wrap gap-1\">\n                    {canShowEdit(comment) ? (\n                      <Button\n                        type=\"button\"\n                        size=\"xs\"\n                        variant=\"ghost\"\n                        aria-disabled={disabled || undefined}\n                        aria-label={labels.edit(name, time)}\n                        onClick={() => {\n                          if (disabled) return;\n                          engine.setDraft({ kind: \"edit\", commentId: comment.id, rowId, columnId, text: comment.text, baseVersion: comment.version, baseWriteId: comment.writeId });\n                        }}\n                      >\n                        {labels.editAction}\n                      </Button>\n                    ) : null}\n                    {canShowDelete(comment) ? (\n                      confirmId === comment.id ? (\n                        <>\n                          <Button\n                            type=\"button\"\n                            size=\"xs\"\n                            variant=\"destructive\"\n                            data-comment-confirm=\"\"\n                            aria-disabled={disabled || undefined}\n                            aria-label={labels.confirmRemove(name, time)}\n                            onClick={() => {\n                              if (disabled) return;\n                              setConfirmId(null);\n                              void run(engine.remove(comment.id, { version: comment.version, writeId: comment.writeId }));\n                            }}\n                          >\n                            {labels.confirmDeleteAction}\n                          </Button>\n                          <Button type=\"button\" size=\"xs\" variant=\"ghost\" onClick={() => setConfirmId(null)}>\n                            {labels.cancel}\n                          </Button>\n                        </>\n                      ) : (\n                        <Button type=\"button\" size=\"xs\" variant=\"ghost\" aria-disabled={disabled || undefined} aria-label={labels.remove(name, time)} onClick={() => !disabled && setConfirmId(comment.id)}>\n                          {labels.deleteAction}\n                        </Button>\n                      )\n                    ) : null}\n                    {writable && resolveEnabled ? (\n                      <Button\n                        type=\"button\"\n                        size=\"xs\"\n                        variant=\"ghost\"\n                        aria-disabled={disabled || undefined}\n                        aria-label={comment.resolved ? labels.reopen(name, time) : labels.resolve(name, time)}\n                        onClick={() => !disabled && void run(engine.setResolved(comment.id, !comment.resolved, { version: comment.version, writeId: comment.writeId }))}\n                      >\n                        {comment.resolved ? labels.reopenAction : labels.resolveAction}\n                      </Button>\n                    ) : null}\n                  </div>\n                ) : null}\n              </li>\n            );\n          })}\n        </ul>\n      ) : null}\n      {notice ? (\n        <p role=\"alert\" className=\"text-destructive\">\n          {notice}\n        </p>\n      ) : null}\n      {composeConflict ? <ConflictBox engine={engine} conflictId={composeConflict.id} labels={labels} onResult={(result) => setNotice(noticeFor(result, labels))} /> : null}\n      {fetchState === \"ready\" ? (\n        writable && !busy ? (\n          <div className=\"flex flex-col gap-1.5\">\n            <Textarea\n              ref={composerEl}\n              aria-label={labels.composer}\n              placeholder={labels.composerPlaceholder}\n              maxLength={max}\n              value={composeDraft?.text ?? \"\"}\n              className=\"min-h-16\"\n              onChange={(event) => engine.setDraft({ kind: \"new\", rowId, columnId, text: event.target.value, baseVersion: 0, baseWriteId: undefined })}\n              onKeyDown={(event) => {\n                if (event.key === \"Enter\" && (event.ctrlKey || event.metaKey) && !isComposingKey(event)) {\n                  event.preventDefault();\n                  submitCompose();\n                }\n              }}\n            />\n            <div className=\"flex items-center justify-between gap-2\">\n              <span className=\"text-xs text-muted-foreground\">{(composeDraft?.text.length ?? 0) > max * 0.8 ? labels.counter(composeDraft?.text.length ?? 0, max) : \"\"}</span>\n              <Button type=\"button\" size=\"sm\" onClick={submitCompose}>\n                {labels.submit}\n              </Button>\n            </div>\n          </div>\n        ) : (\n          <p className=\"text-muted-foreground\">{busy ? labels.rowBusyHint : labels.readOnlyHint}</p>\n        )\n      ) : null}\n    </div>\n  );\n}\n\nfunction EditBox({\n  engine,\n  comment,\n  text,\n  base,\n  labels,\n  max,\n  disabled,\n  onResult,\n}: {\n  engine: CommentEngine;\n  comment: CellComment;\n  text: string;\n  base: { version: number; writeId: string | undefined };\n  labels: DataGridCommentsLabels;\n  max: number;\n  disabled: boolean;\n  onResult: (result: WriteResult) => void;\n}): ReactNode {\n  useStore(engine.store.ui, (s) => s.draftRevision);\n  const submit = (): void => {\n    if (disabled || !text.trim()) return;\n    void engine.edit(comment.id, text, base).then(onResult);\n  };\n  return (\n    <div className=\"flex flex-col gap-1.5\">\n      <Textarea\n        autoFocus\n        aria-label={labels.editComposer}\n        maxLength={max}\n        value={text}\n        onChange={(event) => engine.setDraft({ kind: \"edit\", commentId: comment.id, rowId: comment.rowId, columnId: comment.columnId, text: event.target.value, baseVersion: base.version, baseWriteId: base.writeId })}\n        onKeyDown={(event) => {\n          if (event.key === \"Enter\" && (event.ctrlKey || event.metaKey) && !isComposingKey(event)) {\n            event.preventDefault();\n            submit();\n          }\n        }}\n      />\n      <div className=\"flex gap-1\">\n        <Button type=\"button\" size=\"xs\" aria-disabled={disabled || undefined} onClick={submit}>\n          {labels.save}\n        </Button>\n        <Button type=\"button\" size=\"xs\" variant=\"ghost\" onClick={() => engine.discardDraft(editDraftKey(comment.id))}>\n          {labels.cancel}\n        </Button>\n      </div>\n    </div>\n  );\n}\n\nfunction ConflictBox({ engine, conflictId, labels, onResult }: { engine: CommentEngine; conflictId: string; labels: DataGridCommentsLabels; onResult: (result: WriteResult) => void }): ReactNode {\n  const revision = useStore(engine.store.ui, (s) => s.draftRevision);\n  const conflict = revision < 0 ? undefined : engine.store.core.conflicts.get(conflictId);\n  if (!conflict) return null;\n  const gone = conflict.action !== \"create\" && !engine.store.core.confirmed.has(conflict.id);\n  const draftKey = conflict.action === \"create\" || gone ? newDraftKey(conflict.rowId, conflict.columnId) : editDraftKey(conflict.id);\n  const draftText = engine.store.core.drafts.get(draftKey)?.text ?? conflict.text;\n  const message = conflict.reason === \"stale\" ? labels.changedByOther : conflict.reason === \"forbidden\" ? labels.refused : labels.failed;\n  return (\n    <div role=\"alert\" className=\"flex flex-col gap-1.5 text-destructive\">\n      <span>{conflict.message ?? message}</span>\n      <div className=\"flex flex-wrap gap-1\">\n        {conflict.reason === \"stale\" && !conflict.discardOnly && !gone && conflict.text !== undefined ? (\n          <Button type=\"button\" size=\"xs\" variant=\"outline\" onClick={() => void engine.saveMine(conflict.id, draftText ?? \"\").then(onResult)}>\n            {labels.saveMine}\n          </Button>\n        ) : null}\n        {conflict.thrown || conflict.reason === \"error\" ? (\n          <Button type=\"button\" size=\"xs\" variant=\"outline\" onClick={() => void engine.retry(conflict.id, draftText).then(onResult)}>\n            {labels.retry}\n          </Button>\n        ) : null}\n        <Button type=\"button\" size=\"xs\" variant=\"ghost\" onClick={() => engine.discard(conflict.id)}>\n          {labels.discard}\n        </Button>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/comment-popover.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-comments/menu-items.ts",
      "content": "import type { CommentEngine } from \"./comment-engine\";\nimport type { CommentMenuItem, CommentMenuItemsResolver, CommentMenuSeparator } from \"./types\";\n\nconst COMMENTS_ITEM_ID = \"comments\";\n\ntype MenuCtx = { rowId: string; columnId: string };\n\n/** The separator and the \"Comments…\" item. The popover opens on the next frame, after the menu has closed and returned focus. */\nexport function commentMenuItems(engine: CommentEngine, ctx: MenuCtx): [CommentMenuSeparator, CommentMenuItem] {\n  return [\n    { id: \"sep-comments\", separator: true },\n    {\n      id: COMMENTS_ITEM_ID,\n      label: engine.labels().menuItem,\n      onClick: () => {\n        requestAnimationFrame(() => {\n          if (engine.isDisposed()) return;\n          engine.openComments({ rowId: ctx.rowId, columnId: ctx.columnId }, \"menu\");\n        });\n      },\n    },\n  ];\n}\n\n/** The manual path for a menu that does not read plugin items; it adds nothing when the plugin's item is already there. */\nexport function createMenuItemsResolver(engine: CommentEngine): CommentMenuItemsResolver {\n  return function getCommentMenuItems<TItem extends { id: string }>(\n    ctx: { rowId: string; columnId: string; viewRowIndex: number },\n    defaults: TItem[],\n  ): (TItem | CommentMenuItem | CommentMenuSeparator)[] {\n    if (defaults.some((item) => item.id === COMMENTS_ITEM_ID)) return defaults;\n    return [...defaults, ...commentMenuItems(engine, ctx)];\n  };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-comments/menu-items.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
