Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

35.4 KB
Raw Blame
/**
 * The one place this system touches real Lexical (and, via `propagate`, Loro).
 * `Doc` implements both `DocReader` (reads to plan) and `DocWriter` (atomic
 * edits), resolving every `NodeRef` through the durable id ↔ node-key map and
 * delegating the actual mutations to the existing `ai-toolkit` `$`-helpers. A
 * minted ref IS the inserted node's id — `assignRef` stamps it on directly — so
 * later reads/edits in the same run resolve it with no extra mapping.
 */

import { $createCodeNode } from '@lexical/code';
import { $createLinkNode, $isLinkNode, type LinkNode } from '@lexical/link';
import {
  $createListItemNode,
  $createListNode,
  $isListItemNode,
  $isListNode,
  type ListType,
} from '@lexical/list';
import { $createMarkNode, $isMarkNode } from '@lexical/mark';
import {
  $createHeadingNode,
  $createQuoteNode,
  type HeadingTagType,
} from '@lexical/rich-text';
import {
  $createTableCellNode,
  $createTableRowNode,
  $isTableCellNode,
  $isTableNode,
  $isTableRowNode,
  TableCellHeaderStates,
  type TableNode,
} from '@lexical/table';
import { $createAgentSessionMentionNode } from '@macro-inc/lexical-core/nodes/AgentSessionMentionNode';
import { $createBookingLinkMentionNode } from '@macro-inc/lexical-core/nodes/BookingLinkMentionNode';
import { $createContactMentionNode } from '@macro-inc/lexical-core/nodes/ContactMentionNode';
import {
  $createDateMentionNode,
  $isDateMentionNode,
} from '@macro-inc/lexical-core/nodes/DateMentionNode';
import { $createDocumentCardNode } from '@macro-inc/lexical-core/nodes/DocumentCardNode';
import { $createDocumentMentionNode } from '@macro-inc/lexical-core/nodes/DocumentMentionNode';
import { $createEquationNode } from '@macro-inc/lexical-core/nodes/EquationNode';
import { $createGroupMentionNode } from '@macro-inc/lexical-core/nodes/GroupMentionNode';
import { $createHorizontalRuleNode } from '@macro-inc/lexical-core/nodes/HorizontalRuleNode';
import { $createHtmlRenderNode } from '@macro-inc/lexical-core/nodes/HtmlRenderNode';
import {
  $createImageNode,
  ImageNode,
} from '@macro-inc/lexical-core/nodes/ImageNode';
import { $createPullRequestMentionNode } from '@macro-inc/lexical-core/nodes/PullRequestMentionNode';
import { $createTagMentionNode } from '@macro-inc/lexical-core/nodes/TagMentionNode';
import { $createUserMentionNode } from '@macro-inc/lexical-core/nodes/UserMentionNode';
import {
  $createVideoNode,
  VideoNode,
} from '@macro-inc/lexical-core/nodes/VideoNode';
import {
  $getId,
  $setId,
  $updateAllNodeIds,
} from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
import {
  $createLineBreakNode,
  $createParagraphNode,
  $createTextNode,
  $findMatchingParent,
  $getRoot,
  $isElementNode,
  $isTextNode,
  type ElementNode,
  type LexicalNode,
} from 'lexical';
import { match } from 'ts-pattern';
import * as blocks from '../ai-toolkit/blocks';
import * as databases from '../ai-toolkit/databases';
import * as inline from '../ai-toolkit/inline';
import * as lists from '../ai-toolkit/lists';
import * as locate from '../ai-toolkit/locate';
import * as modify from '../ai-toolkit/modify';
import type { LexicalSession } from '../ai-toolkit/session';
import * as tables from '../ai-toolkit/tables';
import type {
  DatabaseQueryView,
  DocumentOp,
  Format,
  ListKind,
  NodeRef,
  NodeSpec,
  Offset,
  Position,
  Scope,
} from '../editor';
import { EditError } from '../editor';
import type { DocReader, DocWriter, Match } from './interfaces';
import { assertSubstringMatched } from './substring-miss';

const FORMAT_BIT: Record<
  Format,
  'bold' | 'italic' | 'underline' | 'strikethrough' | 'code'
> = {
  bold: 'bold',
  italic: 'italic',
  underline: 'underline',
  strike: 'strikethrough',
  code: 'code',
};

export class Doc implements DocReader, DocWriter {
  constructor(
    private readonly session: LexicalSession,
    /** Push the new state out (snapshot to mirror to Loro). Noop in unit tests. */
    private readonly propagate: () => void = () => {}
  ) {}

  /** A ref IS the node's id (we stamp it on at insert), so resolution is identity. */
  public resolveRef(node: NodeRef): NodeRef {
    return node;
  }

  /** See DocReader.blockRef. Falls back to the input when nothing resolves, so a
   *  planning read can never throw where the apply would report a clean error. */
  public blockRef(node: NodeRef): NodeRef {
    try {
      return this.session.editor.getEditorState().read(() => {
        const block = locate.$blockById(this.session, node as string);
        return ($getId(block) as NodeRef | undefined) ?? node;
      });
    } catch {
      return node;
    }
  }

  public apply(op: DocumentOp): void {
    match(op)
      .with({ kind: 'insertText' }, (e) =>
        this.insertText(e.node, e.at, e.text)
      )
      .with({ kind: 'removeText' }, (e) => this.removeText(e.node, e.at, e.len))
      .with({ kind: 'setText' }, (e) => this.setText(e.node, e.text))
      .with({ kind: 'setEquation' }, (e) => this.setEquation(e.node, e.tex))
      .with({ kind: 'appendText' }, (e) => this.appendText(e.node, e.text))
      .with({ kind: 'prependText' }, (e) => this.prependText(e.node, e.text))
      .with({ kind: 'insertTextAfterInline' }, (e) =>
        this.insertTextAfterInline(e.inline, e.text, e.ref)
      )
      .with({ kind: 'replaceText' }, (e) =>
        this.replaceText(e.node, e.find, e.to, e.scope)
      )
      .with({ kind: 'formatText' }, (e) =>
        this.formatText(e.node, e.match, e.format, e.on, e.scope)
      )
      .with({ kind: 'clearFormat' }, (e) =>
        this.clearFormat(e.node, e.match, e.scope)
      )
      .with({ kind: 'markText' }, (e) =>
        this.markText(e.node, e.match, e.on, e.scope)
      )
      .with({ kind: 'linkText' }, (e) =>
        this.linkText(e.node, e.match, e.url, e.scope)
      )
      .with({ kind: 'formatNode' }, (e) =>
        this.formatNode(e.node, e.format, e.on)
      )
      .with({ kind: 'clearNodeFormat' }, (e) => this.clearNodeFormat(e.node))
      .with({ kind: 'setBlockType' }, (e) =>
        this.setBlockType(e.node, e.block, {
          level: e.level,
          language: e.language,
        })
      )
      .with({ kind: 'setListType' }, (e) => this.setListType(e.nodes, e.list))
      .with({ kind: 'appendListItem' }, (e) =>
        this.appendListItem(e.ref, e.node, e.text, e.checked)
      )
      .with({ kind: 'prependListItem' }, (e) =>
        this.prependListItem(e.ref, e.node, e.text, e.checked)
      )
      .with({ kind: 'setChecked' }, (e) => this.setChecked(e.node, e.checked))
      .with({ kind: 'setIndent' }, (e) => this.setIndent(e.node, e.indent))
      .with({ kind: 'insertNode' }, (e) => this.insertNode(e.ref, e.spec, e.at))
      .with({ kind: 'insertInline' }, (e) =>
        this.insertInline(e.ref, e.node, e.at, e.spec)
      )
      .with({ kind: 'moveNode' }, (e) => this.moveNode(e.node, e.at))
      .with({ kind: 'removeNode' }, (e) => this.removeNode(e.node))
      .with({ kind: 'mergeBlocks' }, (e) =>
        this.mergeBlocks(e.nodes, e.separator)
      )
      .with({ kind: 'insertListItemAfter' }, (e) =>
        this.insertListItemAfter(e.ref, e.node, e.text, e.list)
      )
      .with({ kind: 'insertListItemBefore' }, (e) =>
        this.insertListItemBefore(e.ref, e.node, e.text, e.list)
      )
      .with({ kind: 'removeListItem' }, (e) => this.removeListItem(e.node))
      .with({ kind: 'setCell' }, (e) =>
        this.setCell(e.table, e.row, e.col, e.text)
      )
      .with({ kind: 'addRow' }, (e) => this.addRow(e.table, e.at))
      .with({ kind: 'addColumn' }, (e) => this.addColumn(e.table, e.at))
      .with({ kind: 'removeRow' }, (e) => this.removeRow(e.table, e.row))
      .with({ kind: 'removeColumn' }, (e) => this.removeColumn(e.table, e.col))
      .with({ kind: 'setImageAlt' }, (e) => this.setImageAlt(e.node, e.alt))
      .with({ kind: 'setImageUrl' }, (e) => this.setImageUrl(e.node, e.url))
      .with({ kind: 'setVideoUrl' }, (e) => this.setVideoUrl(e.node, e.url))
      .with({ kind: 'setVideoControls' }, (e) =>
        this.setVideoControls(e.node, e.controls)
      )
      .with({ kind: 'setDate' }, (e) =>
        this.setDate(e.node, e.date, e.displayFormat)
      )
      .with({ kind: 'setDatabaseQueryView' }, (e) =>
        this.setDatabaseQueryView(e.node, e.view)
      )
      .with({ kind: 'setDatabaseLocation' }, (e) =>
        this.setDatabaseLocation(e.node, e.tableId, e.viewId)
      )
      .exhaustive();
  }

  private read<T>(fn: () => T): T {
    return this.session.editor.getEditorState().read(fn);
  }

  /** One discrete update; partial work is discarded on throw, errors surface as
   *  EditError, and the edit propagates to the live doc immediately so changes
   *  (and typing) stream in as they happen. */
  private tx(fn: () => void): void {
    const before = this.session.editor.getEditorState();
    try {
      this.session.editor.update(fn, { discrete: true });
    } catch (e) {
      this.session.editor.setEditorState(before);
      this.session.editor.update(() => $updateAllNodeIds(this.session.ids), {
        discrete: true,
      });
      if (!(e instanceof Error)) throw new Error(String(e));
      if (!(e instanceof EditError)) throw new EditError(e.message);
      throw e;
    }
    this.propagate();
  }

  private block(node: NodeRef): ElementNode {
    return locate.$blockById(this.session, node);
  }

  /** Text writers need a content block, not a table/list container. Reject
   * ambiguous container ids instead of choosing one of their descendants. */
  private textBlock(id: NodeRef): ElementNode {
    const block = this.block(id);
    if (
      $isTableNode(block) ||
      $isTableRowNode(block) ||
      $isTableCellNode(block) ||
      $isListNode(block) ||
      block.getType() === 'root'
    ) {
      throw new EditError(
        `id "${id}" is a ${block.getType()} container — target a paragraph or list item id; use setCell to replace a table cell.`
      );
    }
    return block;
  }

  /** Resolve a table by id, rejecting non-table ids. `setCell`/cell resolution
   *  otherwise walk up to the enclosing table, so a <tr>/<td> id "works" but
   *  reindexes row/col against the table — silently clobbering the wrong cell
   *  (e.g. the header). Require the table id so that mistake is a loud error. */
  private requireTable(id: NodeRef): TableNode {
    const node = locate.$byId(this.session, id);
    if ($isTableNode(node)) return node;
    const what = $isTableRowNode(node)
      ? 'a <tr>'
      : $isTableCellNode(node)
        ? 'a <td>'
        : `a <${node.getType()}>`;
    throw new EditError(
      `id "${id}" is ${what}, not a table — pass the table id with the cell's row/column (both shown in the XML).`
    );
  }

  public textLength(node: NodeRef): number {
    return this.read(
      () => locate.$byId(this.session, node).getTextContent().length
    );
  }

  public locate(id: string, match: string, scope?: Scope): Match[] {
    return this.read(() => locate.$locate(this.block(id), match, scope));
  }

  public cellNode(table: string, row: number, col: number): NodeRef {
    return this.read(() => {
      const cell = this.cell(table, row, col);
      const content = cell.getChildren().find($isElementNode) ?? cell;
      const cid = $getId(content as LexicalNode);
      if (!cid)
        throw new EditError(`cell [${row}, ${col}] has no addressable content`);
      return cid;
    });
  }

  private cell(tableRef: string, row: number, col: number) {
    const table = this.requireTable(tableRef);
    const cell = table
      .getChildren()
      .filter($isTableRowNode)
      [row]?.getChildren()
      .filter($isTableCellNode)[col];
    if (!cell) throw new EditError(`no cell at [${row}, ${col}]`);
    return cell;
  }

  private insertText(node: NodeRef, at: Offset, text: string): void {
    this.tx(() => {
      const target = locate.$byId(this.session, node);
      if ($isTextNode(target)) {
        const c = target.getTextContent();
        target.setTextContent(c.slice(0, at) + text + c.slice(at));
      } else {
        insertTextAt(this.textBlock(node), at, text);
      }
    });
  }

  private removeText(node: NodeRef, at: Offset, len: number): void {
    this.tx(() => removeTextAt(this.block(node), at, len));
  }

  /**
   * Set text content.
   *
   * Given a BLOCK id this replaces the block's contents, which is what the name
   * promises. Given an inline text-run id it sets THAT RUN and leaves its
   * siblings alone — matching `appendText`, `replace`, `bold` and friends, all of
   * which already act on the run they are handed.
   *
   * Widening a run id to its block was the single largest remaining source of
   * coder retries. `$setText` keeps only the block's FIRST text child and deletes
   * the rest, so a coder rewriting several runs in one paragraph destroyed its own
   * remaining targets with the first call:
   *
   *   editor.setText('n9qP6lV-', '…')   -> ok
   *   editor.setText('eNt8jsxy', 'him') -> error: No node with id "eNt8jsxy"
   *   editor.setText('rYT9Q8LF', '. …') -> error: No node with id "rYT9Q8LF"
   *   CHANGED — removed eNt8jsxy, rYT9Q8LF, IoUm7NTJ, …
   *
   * It could even remove the node it was given, when that run was not the first
   * child. Addressing runs individually is both what the call reads as and the
   * only way a multi-run rewrite can work.
   */
  private setText(node: NodeRef, text: string): void {
    this.tx(() => {
      const target = locate.$byId(this.session, node as string);
      if ($isTextNode(target)) {
        if (text.length === 0) target.remove();
        else target.setTextContent(text);
        return;
      }
      blocks.$setText(this.textBlock(node), text);
    });
  }

  private appendText(node: NodeRef, text: string): void {
    this.tx(() => inline.$appendText(this.textBlock(node), text));
  }

  private prependText(node: NodeRef, text: string): void {
    this.tx(() => inline.$prependText(this.textBlock(node), text));
  }

  private insertTextAfterInline(
    inlineRef: NodeRef,
    text: string,
    ref?: string
  ): void {
    this.tx(() => {
      const node = locate.$byId(this.session, inlineRef);
      const tn = $createTextNode(text);
      node.insertAfter(tn);
      if (ref !== undefined) this.assignRef(ref, tn);
    });
  }

  /** A miss on any substring-targeted op used to apply nothing and report
   *  success. Every one of these now raises instead — see ./substring-miss.ts. */
  private assertMatched(
    count: number,
    block: ElementNode,
    node: NodeRef,
    operation: string,
    needle: string
  ): void {
    assertSubstringMatched(
      count,
      block,
      typeof node === 'string' ? node : block.getType(),
      operation,
      needle
    );
  }

  private replaceText(
    node: NodeRef,
    find: string,
    to: string,
    scope: Scope
  ): void {
    this.tx(() => {
      const block = this.block(node);
      const count = inline.$replaceString(block, find, to, scope);
      this.assertMatched(count, block, node, 'replace', find);
    });
  }

  private formatText(
    node: NodeRef,
    match: string,
    format: Format,
    on: boolean,
    scope: Scope
  ): void {
    this.tx(() => {
      const block = this.block(node);
      const count = on
        ? inline.$formatTextInBlock(block, match, format, scope)
        : inline.$clearFormat(block, match, format, scope);
      this.assertMatched(count, block, node, `${format}`, match);
    });
  }

  private clearFormat(
    node: NodeRef,
    match: string | undefined,
    scope: Scope
  ): void {
    this.tx(() => {
      const block = this.block(node);
      if (match === undefined) {
        inline.$stripFormat(block);
        return;
      }
      const count = inline.$clearFormat(block, match, undefined, scope);
      this.assertMatched(count, block, node, 'clearFormat', match);
    });
  }

  private markText(
    node: NodeRef,
    match: string,
    on: boolean,
    scope: Scope
  ): void {
    this.tx(() => {
      const block = this.block(node);
      const count = on
        ? inline.$wrapInBlock(block, match, $createMarkNode, scope)
        : inline.$unwrapFromBlock(block, match, $isMarkNode, scope);
      this.assertMatched(count, block, node, 'mark', match);
    });
  }

  private linkText(
    node: NodeRef,
    match: string,
    url: string | null,
    scope: Scope
  ): void {
    this.tx(() => {
      const block = this.block(node);
      const count =
        url !== null
          ? inline.$wrapInBlock(
              block,
              match,
              () => $createLinkNode(url),
              scope,
              // Retarget an anchor the text is already inside rather than
              // nesting a second one within it.
              { is: $isLinkNode, update: (n) => (n as LinkNode).setURL(url) }
            )
          : inline.$unwrapFromBlock(block, match, $isLinkNode, scope);
      this.assertMatched(count, block, node, 'link', match);
    });
  }

  private formatNode(node: NodeRef, format: Format, on: boolean): void {
    this.tx(() => {
      const tn = locate.$textById(this.session, node);
      const bit = FORMAT_BIT[format];
      if (tn.hasFormat(bit) !== on) tn.toggleFormat(bit);
    });
  }

  private clearNodeFormat(node: NodeRef): void {
    this.tx(() => locate.$textById(this.session, node).setFormat(0));
  }

  private setEquation(node: NodeRef, tex: string): void {
    this.tx(() =>
      modify.$modifyNode(this.session, node, { op: 'equation', tex })
    );
  }

  // yes it'session a bit of a gross type but it'session for AI and prefers it flat
  private setBlockType(
    node: NodeRef,
    block: 'paragraph' | 'heading' | 'quote' | 'code',
    opts: { level?: number; language?: string }
  ): void {
    const data: blocks.BlockData =
      block === 'heading'
        ? { type: 'heading', level: opts.level ?? 1 }
        : block === 'code'
          ? { type: 'code', language: opts.language }
          : { type: block };
    this.tx(() => {
      this.textBlock(node);
      modify.$modifyNode(this.session, node, {
        op: 'blockType',
        block: data,
      });
    });
  }

  private setListType(nodes: NodeRef[], list: ListKind): void {
    this.tx(() => {
      const resolved = nodes.map((n) => locate.$byId(this.session, n));
      const first = resolved[0];
      // Already a list (addressed by its <ul>/<ol> id) or an item in one →
      // retype in place. $toggleList only WRAPS plain blocks into a new list;
      // handed an existing list it mangles structure or no-ops, so reserve it
      // for genuine non-list blocks (e.g. paragraphs being turned into a list).
      if (first && ($isListNode(first) || $isListItemNode(first)))
        lists.$setListType(first, list, this.session);
      else lists.$toggleList(resolved, list);
    });
  }

  private setChecked(node: NodeRef, checked: boolean): void {
    this.tx(() =>
      modify.$modifyNode(this.session, node, {
        op: 'checked',
        checked,
      })
    );
  }

  private setIndent(node: NodeRef, indent: number | 'in' | 'out'): void {
    this.tx(() =>
      modify.$modifyNode(this.session, node, { op: 'indent', indent })
    );
  }

  private appendListItem(
    ref: string,
    node: NodeRef,
    text: string,
    checked?: boolean
  ): void {
    this.tx(() => {
      const list = locate.$byId(this.session, node);
      if (!$isListNode(list)) throw new EditError(`{${node}} is not a list`);
      const li = $createListItemNode(checked ?? listItemChecked(list));
      if (text) li.append($createTextNode(text));
      list.append(li);
      this.assignRef(ref, li);
    });
  }

  private prependListItem(
    ref: string,
    node: NodeRef,
    text: string,
    checked?: boolean
  ): void {
    this.tx(() => {
      const list = locate.$byId(this.session, node);
      if (!$isListNode(list)) throw new EditError(`{${node}} is not a list`);
      const li = $createListItemNode(checked ?? listItemChecked(list));
      if (text) li.append($createTextNode(text));
      const first = list.getFirstChild();
      if (first) first.insertBefore(li);
      else list.append(li);
      this.assignRef(ref, li);
    });
  }

  private insertNode(ref: string, spec: NodeSpec, at: Position): void {
    this.tx(() => {
      // `insertNode` is for block specs; inline specs go through `insertInline`.
      if ('inline' in spec)
        throw new EditError('insertNode requires a block spec');
      let node: LexicalNode = buildNode(spec);
      // Most blocks are ElementNodes or block decorators (divider/image/video).
      // A few block specs build a structurally-inline decorator (equation) — wrap
      // it in a paragraph so it stands as its own block.
      if (node.isInline()) {
        const p = $createParagraphNode();
        p.append(node);
        node = p;
      }
      this.place(node, at);
      this.assignRef(ref, node);
    });
  }

  private insertInline(
    ref: string,
    node: NodeRef,
    at: Offset,
    spec: NodeSpec
  ): void {
    this.tx(() => {
      const block = this.textBlock(node);
      const inline = buildNode(spec);
      insertInlineAt(block, at, inline);
      this.assignRef(ref, inline);
    });
  }

  private moveNode(node: NodeRef, at: Position): void {
    this.tx(() => {
      const block = this.anchor(node);
      block.remove();
      this.place(block, at);
    });
  }

  private removeNode(node: NodeRef): void {
    this.tx(() => locate.$byId(this.session, node).remove());
  }

  private mergeBlocks(nodes: NodeRef[], separator: string): void {
    this.tx(() =>
      blocks.$mergeBlocks(
        nodes.map((n) => locate.$byId(this.session, n)),
        separator
      )
    );
  }

  private insertListItemAfter(
    ref: string,
    node: NodeRef,
    text: string,
    list: ListKind
  ): void {
    this.tx(() => this.insertListItem(ref, node, text, list, 'after'));
  }

  private insertListItemBefore(
    ref: string,
    node: NodeRef,
    text: string,
    list: ListKind
  ): void {
    this.tx(() => this.insertListItem(ref, node, text, list, 'before'));
  }

  private removeListItem(node: NodeRef): void {
    this.tx(() => {
      const li = locate.$byId(this.session, node);
      if (!$isListItemNode(li))
        throw new EditError(`{${node}} is not a list item`);
      li.remove();
    });
  }

  /** Insert a new list item adjacent to an existing one. When `list` matches the
   *  surrounding list it lands as a plain sibling; when it differs, the new item
   *  is wrapped in a sublist of that kind (a numbered list inside a bullet list,
   *  etc.) — Lexical nests via a ListItemNode that holds the child ListNode. */
  private insertListItem(
    ref: string,
    node: NodeRef,
    text: string,
    list: ListKind,
    where: 'after' | 'before'
  ): void {
    const target = locate.$byId(this.session, node);
    if (!$isListItemNode(target))
      throw new EditError(`{${node}} is not a list item`);
    const newLi = $createListItemNode(list === 'check' ? false : undefined);
    newLi.append($createTextNode(text));

    const parent = target.getParent();
    const sameKind =
      $isListNode(parent) && parent.getListType() === (list as ListType);
    if (sameKind) {
      if (where === 'after') target.insertAfter(newLi);
      else target.insertBefore(newLi);
    } else {
      const sublist = $createListNode(list as ListType);
      sublist.append(newLi);
      const host = $createListItemNode();
      host.append(sublist);
      if (where === 'after') target.insertAfter(host);
      else target.insertBefore(host);
    }
    this.assignRef(ref, newLi);
  }

  private setCell(
    table: NodeRef,
    row: number,
    col: number,
    text: string
  ): void {
    this.tx(() => tables.$setCell(this.requireTable(table), row, col, text));
  }

  private addRow(table: NodeRef, at?: number): void {
    this.tx(() => {
      const t = resolveTable(locate.$byId(this.session, table));
      const rows = t.getChildren().filter($isTableRowNode);
      const cols = rows[0]?.getChildren().filter($isTableCellNode).length ?? 1;
      const row = $createTableRowNode();
      for (let c = 0; c < cols; c++) row.append(emptyCell(false));
      if (at == null || at >= rows.length) t.append(row);
      else rows[at]!.insertBefore(row);
    });
  }

  private addColumn(table: NodeRef, at?: number): void {
    this.tx(() => {
      const t = resolveTable(locate.$byId(this.session, table));
      t.getChildren()
        .filter($isTableRowNode)
        .forEach((row, ri) => {
          const cells = row.getChildren().filter($isTableCellNode);
          const cell = emptyCell(ri === 0);
          if (at == null || at >= cells.length) row.append(cell);
          else cells[at]!.insertBefore(cell);
        });
    });
  }

  private removeRow(table: NodeRef, row: number): void {
    this.tx(() => {
      const t = resolveTable(locate.$byId(this.session, table));
      t.getChildren().filter($isTableRowNode)[row]?.remove();
    });
  }

  private removeColumn(table: NodeRef, col: number): void {
    this.tx(() => {
      const t = resolveTable(locate.$byId(this.session, table));
      for (const row of t.getChildren().filter($isTableRowNode)) {
        row.getChildren().filter($isTableCellNode)[col]?.remove();
      }
    });
  }

  private setImageAlt(node: NodeRef, alt: string): void {
    this.tx(() => {
      const n = locate.$byId(this.session, node);
      if (!(n instanceof ImageNode))
        throw new EditError(`{${node}} is not an image`);
      n.setAlt(alt);
    });
  }

  private setImageUrl(node: NodeRef, url: string): void {
    this.tx(() => {
      const n = locate.$byId(this.session, node);
      if (!(n instanceof ImageNode))
        throw new EditError(`{${node}} is not an image`);
      n.setUrl(url);
    });
  }

  private setVideoUrl(node: NodeRef, url: string): void {
    this.tx(() => {
      const n = locate.$byId(this.session, node);
      if (!(n instanceof VideoNode))
        throw new EditError(`{${node}} is not a video`);
      n.setUrl(url);
    });
  }

  private setVideoControls(node: NodeRef, controls: boolean): void {
    this.tx(() => {
      const n = locate.$byId(this.session, node);
      if (!(n instanceof VideoNode))
        throw new EditError(`{${node}} is not a video`);
      n.setControls(controls);
    });
  }

  private setDate(node: NodeRef, date: string, displayFormat?: string): void {
    this.tx(() => {
      const n = locate.$byId(this.session, node);
      if (!$isDateMentionNode(n))
        throw new EditError(`{${node}} is not a date mention`);
      n.setDate(date);
      n.setDisplayFormat(displayFormat ?? date);
    });
  }

  private setDatabaseQueryView(node: NodeRef, view: DatabaseQueryView): void {
    this.tx(() =>
      databases.$setQueryView(locate.$byId(this.session, node), node, view)
    );
  }

  private setDatabaseLocation(
    node: NodeRef,
    tableId: string,
    viewId?: string
  ): void {
    this.tx(() =>
      databases.$setLocation(
        locate.$byId(this.session, node),
        node,
        tableId,
        viewId
      )
    );
  }

  /** Resolve an insert anchor to a sibling node. Climbs past inline nodes (so a
   *  text id resolves to its block) but stops at the first block-level node —
   *  including a decorator block like a divider/image/video. `$blockById` can't
   *  be used here: it only accepts ElementNodes, so an `<hr>` anchor would skip
   *  past to the root and `root.insertAfter` throws. */
  private anchor(id: NodeRef): LexicalNode {
    let node = locate.$byId(this.session, id);
    while (node.isInline() && node.getParent()) {
      node = node.getParent() as LexicalNode;
    }
    return node;
  }

  private place(node: LexicalNode, at: Position): void {
    // Node-level insertion (not the ElementNode-typed $-helpers) so decorator
    // blocks — divider/image/video/equation — place correctly too.
    if ('after' in at) this.anchor(at.after).insertAfter(node);
    else if ('before' in at) this.anchor(at.before).insertBefore(node);
    else if ('appendToRoot' in at) $getRoot().append(node);
    else {
      const first = $getRoot().getFirstChild();
      if (first) first.insertBefore(node);
      else $getRoot().append(node);
    }
  }

  /** Stamp the ref onto the node as its real id (refs ARE ids), then id the rest
   *  of the inserted subtree so later reads/edits resolve. */
  private assignRef(ref: string, node: LexicalNode): void {
    $setId(node, ref);
    $updateAllNodeIds(this.session.ids);
  }
}

/** A check-list item carries an (unchecked) checkbox; other list kinds don't. */
function listItemChecked(list: LexicalNode): boolean | undefined {
  return $isListNode(list) && list.getListType() === 'check'
    ? false
    : undefined;
}

function resolveTable(node: LexicalNode): TableNode {
  const t = $findMatchingParent(node, $isTableNode);
  if (!$isTableNode(t)) throw new EditError('no enclosing table');
  return t;
}

function emptyCell(header: boolean) {
  const cell = $createTableCellNode(
    header ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS
  );
  cell.append($createParagraphNode());
  return cell;
}

/** Insert plain `text` at char offset `at` within a block. Plain text inserted at
 *  the edge of a FORMATTED run goes into a fresh unformatted node (so appending
 *  after a bold word, or prepending before one, stays plain) rather than
 *  inheriting that run'session format. Past the end appends; empty block creates a new node. */
function insertTextAt(block: ElementNode, at: Offset, text: string): void {
  const texts = block.getAllTextNodes();
  if (texts.length === 0) {
    block.append($createTextNode(text));
    return;
  }
  const total = texts.reduce((n, t) => n + t.getTextContent().length, 0);
  // prepend boundary
  if (at <= 0) {
    const first = texts[0]!;
    if (first.getFormat() !== 0) first.insertBefore($createTextNode(text));
    else first.setTextContent(text + first.getTextContent());
    return;
  }
  // append boundary
  if (at >= total) {
    const last = texts[texts.length - 1]!;
    if (last.getFormat() !== 0) last.insertAfter($createTextNode(text));
    else last.setTextContent(last.getTextContent() + text);
    return;
  }
  // interior: splice into the run that contains the offset
  let remaining = at;
  for (const tn of texts) {
    const content = tn.getTextContent();
    if (remaining <= content.length) {
      tn.setTextContent(
        content.slice(0, remaining) + text + content.slice(remaining)
      );
      return;
    }
    remaining -= content.length;
  }
}

/** Remove `len` chars starting at offset `at`, spanning text nodes as needed. */
function removeTextAt(block: ElementNode, at: Offset, len: number): void {
  let skip = at;
  let left = len;
  for (const tn of block.getAllTextNodes()) {
    if (left <= 0) break;
    const content = tn.getTextContent();
    if (skip >= content.length) {
      skip -= content.length;
      continue;
    }
    const start = skip;
    const end = Math.min(content.length, start + left);
    tn.setTextContent(content.slice(0, start) + content.slice(end));
    left -= end - start;
    skip = 0;
  }
}

/** Insert an inline node at char offset `at` within a block. */
function insertInlineAt(
  block: ElementNode,
  at: Offset,
  inline: LexicalNode
): void {
  let remaining = at;
  for (const tn of block.getAllTextNodes()) {
    const len = tn.getTextContent().length;
    if (remaining <= len) {
      if (remaining === 0) tn.insertBefore(inline);
      else if (remaining >= len) tn.insertAfter(inline);
      else {
        const [, tail] = tn.splitText(remaining);
        (tail ?? tn).insertBefore(inline);
      }
      return;
    }
    remaining -= len;
  }
  block.append(inline);
}

/** Turn a declarative spec into real Lexical nodes. */
export function buildNode(spec: NodeSpec): LexicalNode {
  return match(spec)
    .returnType<LexicalNode>()
    .with({ block: 'paragraph' }, (session) =>
      withText($createParagraphNode(), session.text)
    )
    .with({ block: 'heading' }, (session) =>
      withText(
        $createHeadingNode(`h${session.level}` as HeadingTagType),
        session.text
      )
    )
    .with({ block: 'quote' }, (session) =>
      withText($createQuoteNode(), session.text)
    )
    .with({ block: 'code' }, (session) =>
      withText($createCodeNode(session.language), session.text)
    )
    .with({ block: 'list' }, (session) => {
      const list = $createListNode(session.list as ListType);
      for (const item of session.items) {
        const li = $createListItemNode(
          session.list === 'check' ? false : undefined
        );
        li.append($createTextNode(item));
        list.append(li);
      }
      return list;
    })
    .with({ block: 'table' }, (session) => tables.$table(session.rows))
    .with({ block: 'divider' }, () => $createHorizontalRuleNode())
    .with({ block: 'document-card' }, (s) =>
      $createDocumentCardNode({
        documentId: s.documentId,
        documentName: s.documentName,
        blockName: s.blockName,
        blockParams: s.blockParams,
      })
    )
    .with({ block: 'html-render' }, (s) =>
      $createHtmlRenderNode({ html: s.html })
    )
    .with({ block: 'database-query' }, (s) =>
      databases.$createQueryBlock(s.query)
    )
    .with({ block: 'image' }, (session) =>
      $createImageNode({
        srcType: session.srcType,
        url: session.url,
        alt: session.alt,
        width: session.width,
        height: session.height,
      })
    )
    .with({ block: 'video' }, (session) =>
      $createVideoNode({
        srcType: session.srcType,
        url: session.url,
        controls: session.controls,
        width: session.width,
        height: session.height,
      })
    )
    .with({ block: 'equation' }, (session) =>
      $createEquationNode(session.tex, session.inline ?? false)
    )
    .with({ inline: 'linebreak' }, () => $createLineBreakNode())
    .with({ inline: 'database-query' }, (s) =>
      databases.$createInlineQuery(s.query)
    )
    .with({ inline: 'equation' }, (session) =>
      $createEquationNode(session.tex, true)
    )
    .with({ inline: 'date' }, (session) =>
      $createDateMentionNode({
        date: session.date,
        displayFormat: session.displayFormat ?? session.date,
      })
    )
    .with({ inline: 'mention' }, (session) =>
      match(session.mention)
        .with({ kind: 'user' }, (m) =>
          $createUserMentionNode({ userId: m.userId, email: m.email })
        )
        .with({ kind: 'contact' }, (m) =>
          $createContactMentionNode({
            contactId: m.contactId,
            name: m.name,
            emailOrDomain: m.emailOrDomain,
            isCompany: m.isCompany,
          })
        )
        .with({ kind: 'group' }, (m) =>
          $createGroupMentionNode({ groupAlias: m.groupAlias })
        )
        .with({ kind: 'document' }, (m) =>
          $createDocumentMentionNode({
            documentId: m.documentId,
            documentName: m.documentName,
            blockName: m.blockName,
            blockParams: m.blockParams,
          })
        )
        .with({ kind: 'agent_session' }, (m) =>
          $createAgentSessionMentionNode({
            id: m.id,
            label: m.label,
            expanded: m.expanded,
          })
        )
        .with({ kind: 'pr' }, (m) =>
          $createPullRequestMentionNode({ id: m.id, label: m.label })
        )
        .with({ kind: 'booking_link' }, (m) =>
          $createBookingLinkMentionNode({
            profileId: m.profileId,
            url: m.url,
            slug: m.slug,
            label: m.label,
          })
        )
        .with({ kind: 'tag' }, (m) =>
          $createTagMentionNode({
            optionId: m.optionId,
            propertyDefinitionId: m.propertyDefinitionId,
            scope: m.scope,
            name: m.name,
            color: m.color,
          })
        )
        .exhaustive()
    )
    .exhaustive();
}

function withText(block: ElementNode, text?: string): ElementNode {
  if (text) block.append($createTextNode(text));
  return block;
}