Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): table copy fidelity + draggable reorder handles (#2429)

Abrahama941f0a0f1dc
diff --git a/packages/app/src/editor/clipboard/serialize.test.ts b/packages/app/src/editor/clipboard/serialize.test.ts
index be35b111c..9a260b642 100644
--- a/packages/app/src/editor/clipboard/serialize.test.ts
+++ b/packages/app/src/editor/clipboard/serialize.test.ts
@@ -16,16 +16,22 @@
*/
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { sharedExtensions } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
+import { getSchema } from '@tiptap/core';
import type { Fragment } from '@tiptap/pm/model';
-import { Schema } from '@tiptap/pm/model';
+import { Fragment as PmFragment, type Node as PmNode, Schema } from '@tiptap/pm/model';
+import { EditorState, type TextSelection } from '@tiptap/pm/state';
+import { CellSelection, TableMap } from '@tiptap/pm/tables';
import type { EditorView } from '@tiptap/pm/view';
import {
createClipboardHtmlSerializer,
createClipboardTextSerializer,
findDescriptorRoot,
+ serializeCellSelectionAsText,
sliceToDocJson,
+ wrapAsTableFragment,
} from './serialize.ts';
// Minimal schema that lets us synthesise a `doc > paragraph > text` tree.
@@ -540,3 +546,218 @@ describe('sliceToDocJson — inline-first wrapping branch', () => {
expect(docJson.content?.[0]?.content?.[0]?.type).toBe('image');
});
});
+
+// Shared schema for the CellSelection tests below. Real table nodes from core's
+// shared extensions — `wrapAsTableFragment` and `serializeCellSelectionAsText`
+// both switch on `type === schema.nodes.table` / `tableRow`, so a hand-rolled
+// schema wouldn't exercise the type-identity checks.
+const tableSchema = getSchema(sharedExtensions);
+
+function tableCell(text: string, header = false): PmNode {
+ const cellType = header ? tableSchema.nodes.tableHeader : tableSchema.nodes.tableCell;
+ const p = tableSchema.nodes.paragraph.create(null, text ? [tableSchema.text(text)] : []);
+ return cellType.createChecked(null, p);
+}
+
+function tableRow(cells: PmNode[]): PmNode {
+ return tableSchema.nodes.tableRow.createChecked(null, cells);
+}
+
+function tableNode(rows: string[][]): PmNode {
+ return tableSchema.nodes.table.createChecked(
+ null,
+ rows.map((r, i) => tableRow(r.map((c) => tableCell(c, i === 0)))),
+ );
+}
+
+describe('wrapAsTableFragment — normalize CellSelection.content() shapes', () => {
+ // `CellSelection.content()` returns a different fragment shape depending on
+ // which cells are selected. The paste-side handler needs a top-level
+ // `<table>` element to recognize the payload as a table, so every input
+ // shape must round-trip through this normalizer as `Fragment<table>`.
+
+ test('Fragment<table> → passed through unchanged', () => {
+ const t = tableNode([
+ ['H1', 'H2'],
+ ['a', 'b'],
+ ]);
+ const input = PmFragment.from(t);
+ const out = wrapAsTableFragment(input, tableSchema);
+ expect(out.firstChild?.type).toBe(tableSchema.nodes.table);
+ expect(out.childCount).toBe(1);
+ // Same table node identity — nothing rebuilt when already wrapped.
+ expect(out.firstChild).toBe(t);
+ });
+
+ test('Fragment<tableRow> → wrapped in a table', () => {
+ // Cells within a single row's worth of selection yield a bare row.
+ const row = tableRow([tableCell('a'), tableCell('b')]);
+ const input = PmFragment.from(row);
+ const out = wrapAsTableFragment(input, tableSchema);
+ expect(out.firstChild?.type).toBe(tableSchema.nodes.table);
+ // Table has one row with two cells preserved.
+ const wrappedTable = out.firstChild;
+ expect(wrappedTable?.childCount).toBe(1);
+ const wrappedRow = wrappedTable?.child(0);
+ expect(wrappedRow?.type).toBe(tableSchema.nodes.tableRow);
+ expect(wrappedRow?.childCount).toBe(2);
+ expect(wrappedRow?.child(0).textContent).toBe('a');
+ expect(wrappedRow?.child(1).textContent).toBe('b');
+ });
+
+ test('Fragment<tableCell> → wrapped in row, then table', () => {
+ // A single-cell selection yields just the cell.
+ const cell = tableCell('lone');
+ const input = PmFragment.from(cell);
+ const out = wrapAsTableFragment(input, tableSchema);
+ expect(out.firstChild?.type).toBe(tableSchema.nodes.table);
+ const wrappedRow = out.firstChild?.child(0);
+ expect(wrappedRow?.type).toBe(tableSchema.nodes.tableRow);
+ expect(wrappedRow?.child(0).textContent).toBe('lone');
+ });
+
+ test('empty fragment → returned as-is (no throw, no synthesis)', () => {
+ const empty = PmFragment.empty;
+ expect(wrapAsTableFragment(empty, tableSchema)).toBe(empty);
+ });
+
+ test('non-table schema → fragment returned unchanged', () => {
+ // Defense against a hypothetical schema that lacks table nodes: the
+ // guard clause should bail without throwing so the caller falls through.
+ const plainSchema = new Schema({
+ nodes: {
+ doc: { content: 'block+' },
+ paragraph: { group: 'block', content: 'text*' },
+ text: {},
+ },
+ });
+ const p = plainSchema.node('paragraph', null, [plainSchema.text('hello')]);
+ const frag = PmFragment.from(p);
+ expect(wrapAsTableFragment(frag, plainSchema)).toBe(frag);
+ });
+});
+
+// Build a real CellSelection over an anchor→head cell range on a fresh doc.
+// `CellSelection` resolves anchor/head positions where `nodeAfter` is the
+// target cell and `node(-1)` is the table — i.e. the position immediately
+// before the cell within its row. `TableMap.positionAt(row, col, tableStart)`
+// returns exactly that.
+function tableStateWithSelection(
+ rows: string[][],
+ anchorCoords: [number, number],
+ headCoords: [number, number],
+) {
+ const t = tableNode(rows);
+ const doc = tableSchema.nodes.doc.create(null, t);
+ const state = EditorState.create({ schema: tableSchema, doc });
+ // Table is doc's first child, so it starts at position 0 (before the table
+ // node); position 1 is the first position inside the table (before the
+ // first row). `TableMap.positionAt` expects the "inside table" start.
+ const tableStart = 1;
+ const map = TableMap.get(t);
+ const anchorPos = map.positionAt(anchorCoords[0], anchorCoords[1], t) + tableStart;
+ const headPos = map.positionAt(headCoords[0], headCoords[1], t) + tableStart;
+ const $anchor = state.doc.resolve(anchorPos);
+ const $head = state.doc.resolve(headPos);
+ const selection = new CellSelection($anchor, $head);
+ const tr = state.tr.setSelection(selection as unknown as TextSelection);
+ return state.apply(tr);
+}
+
+describe('serializeCellSelectionAsText — spreadsheet clipboard convention', () => {
+ // Multi-cell copies must emit `\t`-separated cells and `\n`-separated rows
+ // for `text/plain`, matching what Excel / Sheets / Numbers exchange. The
+ // markdown pipeline can't serialize tableRow / tableCell fragments as
+ // top-level doc content, so without this branch the text collapses to
+ // concatenated cell strings and column boundaries disappear.
+
+ test('2×2 selection → two tab-separated rows joined with a newline', () => {
+ const state = tableStateWithSelection(
+ [
+ ['Col X', 'Col Y'],
+ ['Andrew', 'Sarah'],
+ ['Robert', 'Miles'],
+ ],
+ [1, 0], // anchor: Andrew
+ [2, 1], // head: Miles
+ );
+ const text = serializeCellSelectionAsText(state.selection as CellSelection);
+ expect(text).toBe('Andrew\tSarah\nRobert\tMiles');
+ });
+
+ test('single-row multi-cell selection → one tab-separated row, no newline', () => {
+ const state = tableStateWithSelection(
+ [
+ ['H1', 'H2', 'H3'],
+ ['a', 'b', 'c'],
+ ],
+ [1, 0],
+ [1, 2],
+ );
+ const text = serializeCellSelectionAsText(state.selection as CellSelection);
+ expect(text).toBe('a\tb\tc');
+ });
+
+ test('single-cell selection → cell text with no tabs, no newlines', () => {
+ const state = tableStateWithSelection(
+ [
+ ['H1', 'H2'],
+ ['a', 'b'],
+ ],
+ [1, 1],
+ [1, 1],
+ );
+ const text = serializeCellSelectionAsText(state.selection as CellSelection);
+ expect(text).toBe('b');
+ });
+
+ test('whole-column selection → cells joined by newlines, no tabs', () => {
+ const state = tableStateWithSelection(
+ [
+ ['H1', 'H2'],
+ ['a', 'b'],
+ ['c', 'd'],
+ ],
+ [0, 0],
+ [2, 0],
+ );
+ const text = serializeCellSelectionAsText(state.selection as CellSelection);
+ expect(text).toBe('H1\na\nc');
+ });
+});
+
+describe('createClipboardTextSerializer — CellSelection routing decision', () => {
+ // The `if (view.state.selection instanceof CellSelection)` branch is the
+ // core behavior fix for the multi-cell copy bug. The
+ // serializeCellSelectionAsText tests above cover the tab / newline
+ // formatting; this describes pins the ROUTING decision — a regression
+ // that removes the CellSelection guard would silently fall through to
+ // the markdown path and re-introduce the empty-copy bug.
+
+ test('CellSelection state → routes to spreadsheet text, skips markdown pipeline', () => {
+ const state = tableStateWithSelection(
+ [
+ ['H1', 'H2'],
+ ['a', 'b'],
+ ['c', 'd'],
+ ],
+ [1, 0],
+ [2, 1],
+ );
+ // If the routing decision breaks, this markdown mock is invoked and
+ // returns the sentinel. A passing test proves the CellSelection branch
+ // fired instead.
+ const md = fakeMdManager();
+ md.serialize = mock(() => 'MARKDOWN-PATH-FALLTHROUGH');
+ // biome-ignore lint/suspicious/noExplicitAny: fake md manager shape
+ const serializer = createClipboardTextSerializer({ mdManager: md as any });
+ // Real state carries the CellSelection; the slice arg is unused by
+ // the CellSelection branch but must be a valid Slice for the type.
+ const slice = state.selection.content();
+ const text = serializer(slice, {
+ state,
+ } as unknown as Parameters<ReturnType<typeof createClipboardTextSerializer>>[1]);
+ expect(text).toBe('a\tb\nc\td');
+ expect(md.serialize).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/editor/clipboard/serialize.ts b/packages/app/src/editor/clipboard/serialize.ts
index f6f883d9f..c8fc7597a 100644
--- a/packages/app/src/editor/clipboard/serialize.ts
+++ b/packages/app/src/editor/clipboard/serialize.ts
@@ -32,8 +32,9 @@
import type { MarkdownManager } from '@inkeep/open-knowledge-core';
import { markdownToHtml } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
-import type { Schema, Slice } from '@tiptap/pm/model';
+import type { Node, Schema, Slice } from '@tiptap/pm/model';
import { DOMSerializer, Fragment, Slice as SliceCtor } from '@tiptap/pm/model';
+import { CellSelection } from '@tiptap/pm/tables';
import type { EditorView } from '@tiptap/pm/view';
import {
type SerializeResult,
@@ -65,6 +66,32 @@ export interface ClipboardHtmlSerializerHandle {
*/
export function createClipboardTextSerializer(deps: WysiwygSerializerDeps) {
return (slice: Slice, view: EditorView): string => {
+ // CellSelection copies belong to the table clipboard convention, not
+ // to the markdown pipeline. `\t`-separated cells / `\n`-separated
+ // rows is what browsers and spreadsheets (Excel, Sheets, Numbers)
+ // exchange as `text/plain`; it also pastes cleanly into GitHub /
+ // Slack. The default markdown path serializes tableRow / tableCell
+ // fragments as top-level doc content, which the schema rejects, so
+ // the text collapses to the concatenated cell strings and paste-
+ // side loses column boundaries entirely.
+ //
+ // Wrapped in try/catch to match the file's documented error-path
+ // discipline (see header): text-serializer throw → fall through to
+ // markdown / PM textBetween. `forEachCell` and `resolve(pos).before()`
+ // are the throw surfaces here; both are low-probability but real
+ // (RangeError on a stale position after a race with a remote edit).
+ if (view.state.selection instanceof CellSelection) {
+ try {
+ return serializeCellSelectionAsText(view.state.selection);
+ } catch (err) {
+ logSerializeFail({
+ view: 'wysiwyg',
+ kind: 'text',
+ reason: `cellselection:${(err as Error)?.message ?? 'unknown'}`,
+ });
+ // Fall through to the markdown path below.
+ }
+ }
try {
return sliceToMarkdown(slice, view.state.schema, deps.mdManager);
} catch (err) {
@@ -78,6 +105,23 @@ export function createClipboardTextSerializer(deps: WysiwygSerializerDeps) {
};
}
+export function serializeCellSelectionAsText(selection: CellSelection): string {
+ const rows: string[][] = [];
+ let currentRowTop: number | null = null;
+ let currentRow: string[] = [];
+ selection.forEachCell((cell, pos) => {
+ const rowTop = selection.$anchorCell.doc.resolve(pos).before();
+ if (currentRowTop === null || rowTop !== currentRowTop) {
+ if (currentRow.length > 0) rows.push(currentRow);
+ currentRow = [];
+ currentRowTop = rowTop;
+ }
+ currentRow.push(cell.textContent);
+ });
+ if (currentRow.length > 0) rows.push(currentRow);
+ return rows.map((r) => r.join('\t')).join('\n');
+}
+
/**
* Build an object that matches PM's expected `clipboardSerializer` shape.
*
@@ -115,6 +159,38 @@ class MdastClipboardSerializer extends DOMSerializer {
target?: HTMLElement | DocumentFragment,
): HTMLElement | DocumentFragment {
const view = this.view;
+ // Table-cell selection escape hatch. The walker's containment guard
+ // (see `clipboard-walker.ts` `selectionPartiallyCoversTopLevelNode`)
+ // bails on any selection that only partially covers a top-level
+ // block — and a `CellSelection` is by definition inside the top-
+ // level `<table>`, so the walker always returns empty for it.
+ // Falling through to the markdown tier is worse: `sliceToDocJson`
+ // can't fit tableRow / tableCell fragments as top-level doc content,
+ // so markdown output is empty and the `text/html` clipboard payload
+ // collapses to `""`. Paste-side (any target — our own, GitHub,
+ // Sheets) then reads only `text/plain` and the entire multi-cell
+ // selection lands in one cell.
+ //
+ // For CellSelection, use the schema's default DOMSerializer directly
+ // on the fragment. The fragment already carries `table` + `tableRow`
+ // + `tableCell` structure from `CellSelection.content()`, so
+ // `serializeFragment` produces standard `<table><tr><td>...` HTML
+ // that every paste handler understands.
+ if (view && view.state.selection instanceof CellSelection) {
+ try {
+ const schema = fragment.firstChild?.type.schema ?? view.state.schema;
+ const defaultSerializer = DOMSerializer.fromSchema(schema);
+ const wrapped = wrapAsTableFragment(fragment, schema);
+ return defaultSerializer.serializeFragment(wrapped, { document }, target);
+ } catch (err) {
+ logSerializeFail({
+ view: 'wysiwyg',
+ kind: 'html',
+ reason: `cellselection:${(err as Error)?.message ?? 'unknown'}`,
+ });
+ // Fall through to the standard tiers below.
+ }
+ }
// Walker tier (primary). When a view is attached AND there's an active
// selection, capture whatever React rendered + whatever CSS resolved.
// A walker throw or empty result falls through to the markdown tier
@@ -363,6 +439,44 @@ export function sliceToDocJson(slice: Slice, schema: Schema): JSONContent {
return docNode.toJSON() as JSONContent;
}
+/**
+ * Ensure a fragment for a `CellSelection` is wrapped in a `<table>` node.
+ *
+ * `CellSelection.content()` returns different shapes depending on the
+ * selection:
+ * - Cells across multiple rows or spanning the whole row →
+ * `Fragment<table>` where the top-level child is the `table` node
+ * containing the selected `tableRow` children.
+ * - Cells within a single row → `Fragment<tableRow>` (cells wrapped in
+ * a row but NOT in a table).
+ * - A single cell → `Fragment<tableCell>` (bare cell).
+ *
+ * The default DOMSerializer needs the outer `<table>` element for the
+ * paste-side to recognize the shape as a table, so we normalize every
+ * incoming fragment to `Fragment<table>` before serializing. Uses the
+ * schema's node types so it works with any table-flavored schema
+ * (GFM tables, custom extensions).
+ */
+export function wrapAsTableFragment(fragment: Fragment, schema: Schema): Fragment {
+ const tableType = schema.nodes.table;
+ const rowType = schema.nodes.tableRow;
+ if (!tableType || !rowType) return fragment;
+ const first = fragment.firstChild;
+ if (!first) return fragment;
+ if (first.type === tableType) return fragment;
+ const rows: Node[] = [];
+ fragment.forEach((child) => {
+ if (child.type === rowType) {
+ rows.push(child);
+ } else {
+ const row = rowType.createAndFill(null, child);
+ if (row) rows.push(row);
+ }
+ });
+ const table = tableType.createAndFill(null, Fragment.fromArray(rows));
+ return table ? Fragment.from(table) : fragment;
+}
+
function parseHtmlToDocumentFragment(html: string): DocumentFragment {
const doc = new DOMParser().parseFromString(html, 'text/html');
const frag = document.createDocumentFragment();
diff --git a/packages/app/src/editor/table-controls/TableCellHandles.tsx b/packages/app/src/editor/table-controls/TableCellHandles.tsx
index 77b06de5c..e64a1bd49 100644
--- a/packages/app/src/editor/table-controls/TableCellHandles.tsx
+++ b/packages/app/src/editor/table-controls/TableCellHandles.tsx
@@ -65,14 +65,15 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { getFindReplaceState } from '../find-replace/tiptap-find-replace-extension';
+import { useTableDragReorder } from './useTableDragReorder';
type Axis = 'column' | 'row';
interface ActiveCell {
/** Top cell of the active column — anchor for the column handle. */
- columnAnchor: HTMLElement;
+ columnAnchor: HTMLTableCellElement;
/** Left cell of the active row — anchor for the row handle. */
- rowAnchor: HTMLElement;
+ rowAnchor: HTMLTableCellElement;
isFirstColumn: boolean;
isFirstRow: boolean;
}
@@ -195,11 +196,22 @@ function CellHandle({
items,
}: {
editor: Editor;
- anchor: HTMLElement;
+ anchor: HTMLTableCellElement;
axis: Axis;
items: MenuItem[];
}) {
const ref = useRef<HTMLDivElement>(null);
+ // Controlled Radix open state — the drag hook coordinates against it so
+ // a pending drag never flashes the menu open. The hook's pointerup calls
+ // onClickGesture when the gesture stayed under the drag threshold, and
+ // we translate that into `setOpen(true)`.
+ const [open, setOpen] = useState(false);
+ const drag = useTableDragReorder({
+ editor,
+ axis,
+ anchor,
+ onClickGesture: () => setOpen(true),
+ });
useEffect(() => {
const el = ref.current;
@@ -233,43 +245,75 @@ function CellHandle({
const HandleIcon = axis === 'column' ? Ellipsis : EllipsisVertical;
return (
- <div ref={ref} data-testid="table-cell-handle" className="absolute left-0 top-0 z-10 opacity-0">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="secondary"
- // The transparent `::before` (-inset-6px) expands the click target
- // to ~24px (WCAG 2.5.8) without enlarging the visible 12px pill.
- className={
- axis === 'column'
- ? 'h-3 w-7 rounded-full p-0 text-gray-700 dark:text-muted-foreground bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 hover:text-foreground dark:hover:bg-gray-600 dark:hover:text-gray-100 relative before:absolute before:-inset-[6px] before:content-[""]'
- : 'h-7 w-3 rounded-full p-0 text-gray-700 dark:text-muted-foreground bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 hover:text-foreground dark:hover:bg-gray-600 dark:hover:text-gray-100 relative before:absolute before:-inset-[6px] before:content-[""]'
- }
- aria-label={axis === 'column' ? 'Column options' : 'Row options'}
- >
- <HandleIcon className="size-3.5" aria-hidden />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align={axis === 'column' ? 'center' : 'start'}
- side={axis === 'column' ? 'bottom' : 'right'}
- // Override the shadcn default `w-(--radix-…-trigger-width)`: the trigger
- // is a tiny handle, so width-to-trigger collapses the menu and wraps
- // labels. Size to content instead, with a comfortable floor.
- className="w-auto min-w-44 whitespace-nowrap"
+ <>
+ <div
+ ref={ref}
+ data-testid="table-cell-handle"
+ className="absolute left-0 top-0 z-10 opacity-0"
+ >
+ <DropdownMenu
+ open={open}
+ onOpenChange={(next) => {
+ if (drag.shouldAllowOpen(next)) setOpen(next);
+ }}
>
- {items.map((item) => (
- <Fragment key={item.label}>
- {item.separatorBefore && <DropdownMenuSeparator />}
- <DropdownMenuItem onSelect={() => item.run(editor)}>
- <item.icon aria-hidden />
- {item.label}
- </DropdownMenuItem>
- </Fragment>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ onPointerDown={drag.onPointerDown}
+ // The transparent `::before` (-inset-6px) expands the click target
+ // to ~24px (WCAG 2.5.8) without enlarging the visible 12px pill.
+ // `cursor-grab` telegraphs the drag affordance; the drag hook
+ // swaps it for `grabbing` on the body during an active gesture.
+ className={
+ axis === 'column'
+ ? 'h-3 w-7 rounded-full p-0 text-gray-700 dark:text-muted-foreground bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 hover:text-foreground dark:hover:bg-gray-600 dark:hover:text-gray-100 relative cursor-grab before:absolute before:-inset-[6px] before:content-[""]'
+ : 'h-7 w-3 rounded-full p-0 text-gray-700 dark:text-muted-foreground bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 hover:text-foreground dark:hover:bg-gray-600 dark:hover:text-gray-100 relative cursor-grab before:absolute before:-inset-[6px] before:content-[""]'
+ }
+ aria-label={axis === 'column' ? 'Column options' : 'Row options'}
+ >
+ <HandleIcon className="size-3.5" aria-hidden />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align={axis === 'column' ? 'center' : 'start'}
+ side={axis === 'column' ? 'bottom' : 'right'}
+ // Override the shadcn default `w-(--radix-…-trigger-width)`: the trigger
+ // is a tiny handle, so width-to-trigger collapses the menu and wraps
+ // labels. Size to content instead, with a comfortable floor.
+ className="w-auto min-w-44 whitespace-nowrap"
+ >
+ {items.map((item) => (
+ <Fragment key={item.label}>
+ {item.separatorBefore && <DropdownMenuSeparator />}
+ <DropdownMenuItem onSelect={() => item.run(editor)}>
+ <item.icon aria-hidden />
+ {item.label}
+ </DropdownMenuItem>
+ </Fragment>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ {drag.indicator && (
+ // Fixed-position drop indicator. Escapes the transformed-ancestor
+ // trap that `strategy: 'absolute'` was chosen to avoid — we compute
+ // client coordinates directly from the table's DOMRect, so fixed
+ // positioning is correct here (unlike the handles, whose autoUpdate
+ // tracks scroll via floating-ui). The `pointerEvents: 'none'` keeps
+ // the indicator from intercepting the ongoing gesture.
+ <div
+ aria-hidden
+ className="pointer-events-none fixed z-50 bg-primary"
+ style={{
+ left: drag.indicator.rect.left,
+ top: drag.indicator.rect.top,
+ width: drag.indicator.rect.width,
+ height: drag.indicator.rect.height,
+ }}
+ />
+ )}
+ </>
);
}
diff --git a/packages/app/src/editor/table-controls/useTableDragReorder.test.ts b/packages/app/src/editor/table-controls/useTableDragReorder.test.ts
new file mode 100644
index 000000000..4ac772f96
--- /dev/null
+++ b/packages/app/src/editor/table-controls/useTableDragReorder.test.ts
@@ -0,0 +1,298 @@
+/**
+ * Unit tests for the pure PM-node transforms + coordinate mapping in
+ * useTableDragReorder. The hook's stateful gesture logic and DOM listener
+ * lifecycle are covered by the browser walkthrough in the PR verification;
+ * these tests pin the off-by-one arithmetic in the splice-based transforms
+ * and the drop-index derivation from pointer coordinates, both of which are
+ * exactly the kind of pure logic that regresses silently on a refactor.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { sharedExtensions } from '@inkeep/open-knowledge-core';
+import { getSchema } from '@tiptap/core';
+import type { Node as PmNode } from '@tiptap/pm/model';
+
+import { computeDragTarget, tableWithMovedColumn, tableWithMovedRow } from './useTableDragReorder';
+
+const schema = getSchema(sharedExtensions);
+
+function cell(text: string, header = false): PmNode {
+ const type = header ? schema.nodes.tableHeader : schema.nodes.tableCell;
+ return type.createChecked(null, schema.nodes.paragraph.create(null, schema.text(text)));
+}
+
+function row(cells: PmNode[]): PmNode {
+ return schema.nodes.tableRow.createChecked(null, cells);
+}
+
+/** Build a `rows × cols` table doc; row 0 uses tableHeader cells, the rest
+ * tableCell. The label is the cell text so assertions read directly. */
+function makeTable(labels: string[][]): PmNode {
+ return schema.nodes.table.createChecked(
+ null,
+ labels.map((r, i) => row(r.map((label) => cell(label, i === 0)))),
+ );
+}
+
+/** Row-by-row text snapshot for concise reorder assertions. */
+function tableTexts(table: PmNode): string[][] {
+ const rows: string[][] = [];
+ table.forEach((r) => {
+ const cells: string[] = [];
+ r.forEach((c) => {
+ cells.push(c.textContent);
+ });
+ rows.push(cells);
+ });
+ return rows;
+}
+
+/** Header/body kind per cell, so cell-type invariant tests read directly. */
+function tableCellKinds(table: PmNode): string[][] {
+ const rows: string[][] = [];
+ table.forEach((r) => {
+ const kinds: string[] = [];
+ r.forEach((c) => {
+ kinds.push(c.type.name === 'tableHeader' ? 'H' : 'C');
+ });
+ rows.push(kinds);
+ });
+ return rows;
+}
+
+describe('tableWithMovedRow', () => {
+ const t = makeTable([
+ ['H1', 'H2'], // row 0 — header
+ ['A1', 'A2'],
+ ['B1', 'B2'],
+ ['C1', 'C2'],
+ ]);
+
+ test('move down: from=1 to=3 → A lands between B and C (dest = to − 1)', () => {
+ // The critical off-by-one branch. Removing index 1 shifts C to index 2,
+ // so a target of 3 in the original list becomes 2 in the spliced list.
+ // A regression to `dest = to` would insert A after C instead of between.
+ const result = tableWithMovedRow(t, 1, 3);
+ expect(tableTexts(result)).toEqual([
+ ['H1', 'H2'],
+ ['B1', 'B2'],
+ ['A1', 'A2'],
+ ['C1', 'C2'],
+ ]);
+ });
+
+ test('move down to end: from=1 to=4 → A ends up last', () => {
+ const result = tableWithMovedRow(t, 1, 4);
+ expect(tableTexts(result)).toEqual([
+ ['H1', 'H2'],
+ ['B1', 'B2'],
+ ['C1', 'C2'],
+ ['A1', 'A2'],
+ ]);
+ });
+
+ test('move up: from=3 to=1 → C lands between H and A (dest = to)', () => {
+ // Sibling-symmetric with move-down. The `to > from` branch is skipped
+ // here so `dest` stays `to`. Regression to `dest = to - 1` would put
+ // C above the header — a header-invariant break in disguise.
+ const result = tableWithMovedRow(t, 3, 1);
+ expect(tableTexts(result)).toEqual([
+ ['H1', 'H2'],
+ ['C1', 'C2'],
+ ['A1', 'A2'],
+ ['B1', 'B2'],
+ ]);
+ });
+
+ test('cell node types travel with their row (movement preserves them)', () => {
+ // The transform is a pure splice — no cell-type mutation. But the
+ // header-invariant guards in commitReorder / computeDragTarget are what
+ // prevent a data row from LANDING at index 0 to begin with; this test
+ // pins that the pure splice really does move rows verbatim.
+ const result = tableWithMovedRow(t, 1, 3);
+ expect(tableCellKinds(result)).toEqual([
+ ['H', 'H'], // row 0 still header cells
+ ['C', 'C'],
+ ['C', 'C'],
+ ['C', 'C'],
+ ]);
+ });
+
+ test('table attrs and cell content preserved on move', () => {
+ // Table attrs / marks must survive a splice — the transform copies them
+ // through table.type.create(table.attrs, rows, table.marks).
+ const result = tableWithMovedRow(t, 1, 3);
+ expect(result.type.name).toBe('table');
+ expect(result.childCount).toBe(4);
+ });
+});
+
+describe('tableWithMovedColumn', () => {
+ const t = makeTable([
+ ['H1', 'H2', 'H3'],
+ ['A1', 'A2', 'A3'],
+ ['B1', 'B2', 'B3'],
+ ]);
+
+ test('move down: from=0 to=2 → col 0 lands between col 1 and col 2', () => {
+ const result = tableWithMovedColumn(t, 0, 2);
+ expect(tableTexts(result)).toEqual([
+ ['H2', 'H1', 'H3'],
+ ['A2', 'A1', 'A3'],
+ ['B2', 'B1', 'B3'],
+ ]);
+ });
+
+ test('move to end: from=0 to=3 → col 0 ends up last', () => {
+ const result = tableWithMovedColumn(t, 0, 3);
+ expect(tableTexts(result)).toEqual([
+ ['H2', 'H3', 'H1'],
+ ['A2', 'A3', 'A1'],
+ ['B2', 'B3', 'B1'],
+ ]);
+ });
+
+ test('move left: from=2 to=0 → col 2 lands at position 0', () => {
+ const result = tableWithMovedColumn(t, 2, 0);
+ expect(tableTexts(result)).toEqual([
+ ['H3', 'H1', 'H2'],
+ ['A3', 'A1', 'A2'],
+ ['B3', 'B1', 'B2'],
+ ]);
+ });
+
+ test('each row rebuilt with row attrs preserved', () => {
+ const result = tableWithMovedColumn(t, 0, 2);
+ expect(result.childCount).toBe(3);
+ result.forEach((r) => {
+ expect(r.type.name).toBe('tableRow');
+ expect(r.childCount).toBe(3);
+ });
+ });
+});
+
+describe('computeDragTarget — pointer → insertion index mapping', () => {
+ // Fake element shape covering everything computeDragTarget touches on the
+ // anchor: `closest('table')` for the containing table, then per-row and
+ // per-cell `getBoundingClientRect`. Keeps the test DOM-free (bun-test has
+ // no live DOM) while exercising the real code path.
+
+ interface Rect {
+ top: number;
+ right: number;
+ bottom: number;
+ left: number;
+ width: number;
+ height: number;
+ }
+
+ function rectOf(left: number, top: number, right: number, bottom: number): Rect {
+ return { left, top, right, bottom, width: right - left, height: bottom - top };
+ }
+
+ function fakeRow(rect: Rect, cellRects: Rect[]): HTMLTableRowElement {
+ return {
+ getBoundingClientRect: () => rect as DOMRect,
+ cells: cellRects.map((r) => ({
+ getBoundingClientRect: () => r as DOMRect,
+ })) as unknown as HTMLCollectionOf<HTMLTableCellElement>,
+ } as unknown as HTMLTableRowElement;
+ }
+
+ function fakeTable(tableRect: Rect, rows: HTMLTableRowElement[]): HTMLTableElement {
+ return {
+ getBoundingClientRect: () => tableRect as DOMRect,
+ rows: rows as unknown as HTMLCollectionOf<HTMLTableRowElement>,
+ } as unknown as HTMLTableElement;
+ }
+
+ function fakeAnchor(table: HTMLTableElement): HTMLTableCellElement {
+ return {
+ closest: (sel: string) => (sel === 'table' ? table : null),
+ } as unknown as HTMLTableCellElement;
+ }
+
+ /** Build a 3-row table with rows stacked vertically: header 0-20, row 1
+ * 20-40, row 2 40-60. Cell widths: 100 each, 2 columns. */
+ function threeRowTable() {
+ const tableRect = rectOf(0, 0, 200, 60);
+ const rows = [
+ fakeRow(rectOf(0, 0, 200, 20), [rectOf(0, 0, 100, 20), rectOf(100, 0, 200, 20)]),
+ fakeRow(rectOf(0, 20, 200, 40), [rectOf(0, 20, 100, 40), rectOf(100, 20, 200, 40)]),
+ fakeRow(rectOf(0, 40, 200, 60), [rectOf(0, 40, 100, 60), rectOf(100, 40, 200, 60)]),
+ ];
+ const table = fakeTable(tableRect, rows);
+ return fakeAnchor(table);
+ }
+
+ test('row axis: pointer above the header clamps to insertion index 1', () => {
+ // Without the header-invariant clamp this would return index 0, which
+ // would silently invert the markdown header on the next round-trip.
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'row', 100, -5);
+ expect(result?.index).toBe(1);
+ // Indicator y anchored to the bottom of the header row.
+ expect(result?.rect.top).toBe(20 - 1);
+ });
+
+ test('row axis: pointer in header row upper half clamps to index 1', () => {
+ // Regression pin: a raw split would return 0 here (upper half → insert-
+ // before-row-0). Clamp keeps it at 1.
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'row', 100, 5);
+ expect(result?.index).toBe(1);
+ });
+
+ test('row axis: pointer in header row lower half → index 1 (unclamped)', () => {
+ // Below the header midpoint is a natural "insert after header" → index 1.
+ // No clamp needed, but the result should still be 1.
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'row', 100, 15);
+ expect(result?.index).toBe(1);
+ });
+
+ test('row axis: pointer in row 1 lower half → index 2 (between row 1 and 2)', () => {
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'row', 100, 35);
+ expect(result?.index).toBe(2);
+ // Indicator at row 1's bottom edge.
+ expect(result?.rect.top).toBe(40 - 1);
+ });
+
+ test('row axis: pointer below the last row → index = rowCount', () => {
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'row', 100, 100);
+ expect(result?.index).toBe(3);
+ // Indicator at the last row's bottom edge.
+ expect(result?.rect.top).toBe(60 - 1);
+ });
+
+ test('column axis: pointer left of column 0 → index 0 (no clamp — columns have no header invariant)', () => {
+ // Symmetric to the row test, but columns lack the positional-header
+ // constraint (markdown has no header-column concept), so index 0 is a
+ // legitimate target here. Regression pin: someone applying the row
+ // clamp to columns would break this.
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'column', -10, 30);
+ expect(result?.index).toBe(0);
+ });
+
+ test('column axis: pointer in column 0 right half → index 1', () => {
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'column', 60, 30);
+ expect(result?.index).toBe(1);
+ // Indicator at column 0's right edge.
+ expect(result?.rect.left).toBe(100 - 1);
+ });
+
+ test('column axis: pointer beyond the last column → index = colCount', () => {
+ const anchor = threeRowTable();
+ const result = computeDragTarget(anchor, 'column', 300, 30);
+ expect(result?.index).toBe(2);
+ });
+
+ test('anchor with no containing table → null', () => {
+ const anchor = { closest: () => null } as unknown as HTMLTableCellElement;
+ expect(computeDragTarget(anchor, 'row', 0, 0)).toBeNull();
+ });
+});
diff --git a/packages/app/src/editor/table-controls/useTableDragReorder.tsx b/packages/app/src/editor/table-controls/useTableDragReorder.tsx
new file mode 100644
index 000000000..2f5f488d1
--- /dev/null
+++ b/packages/app/src/editor/table-controls/useTableDragReorder.tsx
@@ -0,0 +1,426 @@
+/**
+ * Drag-to-reorder gesture for the TableCellHandles ellipsis buttons.
+ *
+ * The handle is dual-gesture: a click opens its dropdown (insert / delete /
+ * toggle-header), a drag past a small threshold reorders the row / column.
+ * Distinguishing the two:
+ *
+ * 1. On pointerdown we set `pendingDragRef` and DON'T yet decide.
+ * 2. Radix DropdownMenuTrigger tries to open on the same pointerdown,
+ * but the CellHandle owns `open` state and forwards Radix's request
+ * through `handleOpenChange` — which refuses while `pendingDragRef`
+ * is set so the menu never flashes during a drag.
+ * 3. On pointermove past `DRAG_THRESHOLD_PX` we flip into drag mode and
+ * an insertion indicator tracks the pointer's nearest row / column
+ * boundary.
+ * 4. On pointerup: drag mode → commit the reorder transaction and swallow
+ * the click; otherwise → open the menu manually via `setOpen(true)`.
+ *
+ * The reorder is a single ProseMirror transaction that rebuilds the table
+ * with the moved row / column at the new index. This works for GFM tables
+ * (rectangular, no colspan / rowspan) — the same rectangularity assumption
+ * TableCellHandles' geometry logic already relies on.
+ *
+ * **Row 0 is the markdown header — positional, not per-cell.** The OK
+ * markdown pipeline treats row 0 as the header on every path
+ * (`packages/core/src/markdown/index.ts:595` on parse,
+ * `to-markdown-handlers.ts:896` on emit); the per-cell `tableHeader` /
+ * `tableCell` distinction is discarded during PM→mdast
+ * (`index.ts:1760-1765`). A row-splice that lands ANY data row at index 0
+ * (or drags the header row away) silently inverts the markdown header on
+ * the next round-trip. We enforce the invariant in two places: the row
+ * branch of `computeDragTarget` clamps target indices to `[1, rowCount]`
+ * so the drop indicator never suggests a position above / at the header,
+ * and `commitReorder` refuses to move a header-row source. Users who want
+ * to change the header row use the "Toggle header row" menu item, not a
+ * drag.
+ */
+
+import type { Node as PmNode, ResolvedPos } from '@tiptap/pm/model';
+import type { Transaction } from '@tiptap/pm/state';
+import type { Editor } from '@tiptap/react';
+import { type PointerEvent as ReactPointerEvent, useEffect, useRef, useState } from 'react';
+
+type Axis = 'row' | 'column';
+
+/** Cursor must move at least this many CSS pixels before the gesture flips
+ * from "candidate click" to "drag". A too-small threshold catches jitter on
+ * a mouse-down; a too-large one makes the drag feel unresponsive. 5px is
+ * the same threshold the Radix DnD primitives use. */
+const DRAG_THRESHOLD_PX = 5;
+
+/** Row 0 is the positional markdown header — see the file header. Any drag
+ * whose source OR target is index 0 would corrupt the header on round-trip.
+ * The clamp lives here instead of a magic number in the middle of the file. */
+const FIRST_MOVABLE_ROW_INDEX = 1;
+
+interface UseTableDragReorderOptions {
+ editor: Editor;
+ axis: Axis;
+ /** The active cell whose column / row this handle belongs to — the source
+ * of the drag. Used to resolve the source index + the containing table. */
+ anchor: HTMLTableCellElement;
+ /** Called on pointerup when the gesture stayed under the drag threshold
+ * (a click). The consumer opens its controlled Radix menu here since the
+ * hook refused Radix's own pointerdown open request. Kept in a ref so a
+ * fresh closure per render never staled the pointerup handler. */
+ onClickGesture: () => void;
+}
+
+interface DragTarget {
+ /** Insertion index. `0` = before row / column 0, `N` = after the last one. */
+ index: number;
+ /** Fixed-position bounding box for the drop indicator line. */
+ rect: { left: number; top: number; width: number; height: number };
+}
+
+export interface UseTableDragReorderResult {
+ /** Wire this onto the handle Button (or any ancestor that receives the
+ * pointerdown). Ignores non-primary buttons. */
+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
+ /** Consult this before letting Radix DropdownMenu open. Refuses opens
+ * while the pointer is a drag candidate so a pending drag never flashes
+ * the menu. */
+ shouldAllowOpen: (nextOpen: boolean) => boolean;
+ /** True while the pointer is past-threshold and reordering is live.
+ * Callers can gate visual state on it (e.g. cursor styling). */
+ isDragging: boolean;
+ /** Rendered indicator line for the imminent drop position — null unless
+ * dragging AND a valid target is under the pointer. Render into a
+ * fixed-position portal / absolutely-positioned host that doesn't move
+ * with editor scroll. */
+ indicator: DragTarget | null;
+}
+
+/**
+ * Attach to a CellHandle. Returns pointer handlers, an indicator descriptor,
+ * and hooks the caller uses to coordinate with a controlled Radix menu.
+ */
+export function useTableDragReorder({
+ editor,
+ axis,
+ anchor,
+ onClickGesture,
+}: UseTableDragReorderOptions): UseTableDragReorderResult {
+ // Ref rather than state — the pointerdown / move / up handlers all read
+ // and mutate it synchronously; setState would introduce render-cycle
+ // races (pointermove firing before pointerdown's state has committed).
+ const pendingDragRef = useRef<{
+ startX: number;
+ startY: number;
+ isDragging: boolean;
+ lastTarget: DragTarget | null;
+ } | null>(null);
+
+ // Held here so an unmount effect can abort mid-drag: CellHandle unmounts
+ // whenever `computeActiveCell` returns null — a realistic path via a
+ // concurrent CRDT edit that deletes the table, or a keystroke that moves
+ // the selection out. Without this, `document.body.style.cursor =
+ // 'grabbing'` stays set until page reload and `onUp` eventually fires
+ // `commitReorder` against a stale editor / anchor.
+ const controllerRef = useRef<AbortController | null>(null);
+
+ // Latest-ref pattern for the click callback so the pointerup handler
+ // (installed lazily inside onPointerDown) always calls the freshest
+ // version, without having to re-bind on every render.
+ const onClickGestureRef = useRef(onClickGesture);
+ useEffect(() => {
+ onClickGestureRef.current = onClickGesture;
+ }, [onClickGesture]);
+
+ useEffect(() => {
+ return () => {
+ controllerRef.current?.abort();
+ controllerRef.current = null;
+ pendingDragRef.current = null;
+ // Body style mutations from an active drag must be undone on unmount
+ // — the gesture's `onUp` handler is the normal reset path, but it
+ // never fires if the component unmounts first.
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ };
+ }, []);
+
+ const [isDragging, setIsDragging] = useState(false);
+ const [indicator, setIndicator] = useState<DragTarget | null>(null);
+
+ const shouldAllowOpen = (nextOpen: boolean): boolean => {
+ // Radix opens on pointerdown; refuse while the pointer is a drag
+ // candidate (or actively dragging). If the gesture turns out to be a
+ // click, the pointerup handler calls onClickGestureRef.current() explicitly.
+ if (nextOpen && pendingDragRef.current !== null) return false;
+ return true;
+ };
+
+ const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
+ // Left-button only. Right / middle / touch-hold shouldn't reorder.
+ if (event.button !== 0) return;
+
+ // Abort any lingering gesture from a previous pointerdown that never got
+ // its pointerup (browser bug, focus-stealing dev-tools, etc.). Idempotent
+ // when there's nothing to abort.
+ controllerRef.current?.abort();
+
+ pendingDragRef.current = {
+ startX: event.clientX,
+ startY: event.clientY,
+ isDragging: false,
+ lastTarget: null,
+ };
+
+ // AbortController for the gesture's document listeners. Lets `onUp`
+ // tear down every subscription with one `abort()` call instead of
+ // referencing itself for `removeEventListener` — the self-reference
+ // form trips React Compiler's missing-dep pass. Stored in
+ // `controllerRef` so the unmount effect can abort mid-gesture.
+ const controller = new AbortController();
+ controllerRef.current = controller;
+ const { signal } = controller;
+
+ const onMove = (moveEvent: PointerEvent): void => {
+ const drag = pendingDragRef.current;
+ if (!drag) return;
+
+ if (!drag.isDragging) {
+ const dx = moveEvent.clientX - drag.startX;
+ const dy = moveEvent.clientY - drag.startY;
+ if (Math.hypot(dx, dy) < DRAG_THRESHOLD_PX) return;
+ drag.isDragging = true;
+ setIsDragging(true);
+ document.body.style.cursor = 'grabbing';
+ // Text selection while dragging on a cell would fight the browser's
+ // caret drag behavior. Belt-and-suspenders in case the pointerdown
+ // originated on a text node.
+ document.body.style.userSelect = 'none';
+ }
+
+ const target = computeDragTarget(anchor, axis, moveEvent.clientX, moveEvent.clientY);
+ drag.lastTarget = target;
+ setIndicator(target);
+ };
+
+ const onUp = (): void => {
+ controller.abort();
+ // Only clear the shared ref if THIS controller still owns it — a
+ // subsequent pointerdown may have replaced it already, and clobbering
+ // that would leak the newer gesture's cleanup path.
+ if (controllerRef.current === controller) controllerRef.current = null;
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+
+ const drag = pendingDragRef.current;
+ pendingDragRef.current = null;
+ setIsDragging(false);
+ setIndicator(null);
+
+ if (!drag) return;
+ if (drag.isDragging && drag.lastTarget) {
+ commitReorder(editor, anchor, axis, drag.lastTarget.index);
+ } else if (!drag.isDragging) {
+ // Click gesture: open the menu manually since shouldAllowOpen
+ // refused Radix's pointerdown attempt.
+ onClickGestureRef.current();
+ }
+ };
+
+ document.addEventListener('pointermove', onMove, { signal });
+ document.addEventListener('pointerup', onUp, { signal });
+ // pointercancel fires when the OS interrupts the gesture (dev-tools
+ // stealing focus, alt-tab, PIP takeover). Same cleanup path.
+ document.addEventListener('pointercancel', onUp, { signal });
+ };
+
+ return { onPointerDown, shouldAllowOpen, isDragging, indicator };
+}
+
+/**
+ * Given the anchor cell + pointer position, decide which row / column
+ * boundary is closest and return an insertion index + the rect for the
+ * indicator line.
+ *
+ * For rows: iterate the table's `<tr>`s and check which one the pointer
+ * is over; split each row into upper half (insert before) and lower half
+ * (insert after). Above the first row → index 0; below the last → row
+ * count.
+ *
+ * For columns: same shape against row 0's `<td>`s (GFM tables are
+ * rectangular so row 0 has the same column count as every other row).
+ */
+export function computeDragTarget(
+ anchor: HTMLTableCellElement,
+ axis: Axis,
+ clientX: number,
+ clientY: number,
+): DragTarget | null {
+ const table = anchor.closest('table');
+ if (!table) return null;
+ const tableRect = table.getBoundingClientRect();
+
+ if (axis === 'row') {
+ const rows = Array.from(table.rows);
+ if (rows.length === 0) return null;
+ for (let i = 0; i < rows.length; i++) {
+ const rect = rows[i].getBoundingClientRect();
+ if (clientY < rect.top) {
+ // Above the first row → clamp to insert BELOW the header row. Above-
+ // header drops would corrupt the positional header (see file header).
+ return {
+ index: FIRST_MOVABLE_ROW_INDEX,
+ rect: horizontalLine(tableRect, rowBottomOr(rows, 0, rect.top)),
+ };
+ }
+ if (clientY <= rect.bottom) {
+ const midY = rect.top + rect.height / 2;
+ const insertAfter = clientY >= midY;
+ const rawIndex = insertAfter ? i + 1 : i;
+ const index = Math.max(FIRST_MOVABLE_ROW_INDEX, rawIndex);
+ // If the clamp bumped the index, anchor the indicator at the bottom
+ // of the header row so what the user sees matches what will happen.
+ const clamped = index !== rawIndex;
+ const y = clamped ? rowBottomOr(rows, 0, rect.top) : insertAfter ? rect.bottom : rect.top;
+ return { index, rect: horizontalLine(tableRect, y) };
+ }
+ }
+ const last = rows[rows.length - 1].getBoundingClientRect();
+ return { index: rows.length, rect: horizontalLine(tableRect, last.bottom) };
+ }
+
+ const referenceRow = table.rows[0];
+ if (!referenceRow) return null;
+ const cells = Array.from(referenceRow.cells);
+ if (cells.length === 0) return null;
+ for (let i = 0; i < cells.length; i++) {
+ const rect = cells[i].getBoundingClientRect();
+ if (clientX < rect.left) {
+ return { index: 0, rect: verticalLine(tableRect, rect.left) };
+ }
+ if (clientX <= rect.right) {
+ const midX = rect.left + rect.width / 2;
+ const insertAfter = clientX >= midX;
+ const x = insertAfter ? rect.right : rect.left;
+ return { index: insertAfter ? i + 1 : i, rect: verticalLine(tableRect, x) };
+ }
+ }
+ const last = cells[cells.length - 1].getBoundingClientRect();
+ return { index: cells.length, rect: verticalLine(tableRect, last.right) };
+}
+
+/** Bottom edge of `rows[index]` if it exists, else the given fallback. Keeps
+ * the row-branch clamp behavior sensible for a one-row table (no header
+ * boundary to draw a line at — fall back to the caller's own reference y). */
+function rowBottomOr(rows: HTMLTableRowElement[], index: number, fallbackY: number): number {
+ const row = rows[index];
+ return row ? row.getBoundingClientRect().bottom : fallbackY;
+}
+
+function horizontalLine(tableRect: DOMRect, y: number): DragTarget['rect'] {
+ return { left: tableRect.left, top: y - 1, width: tableRect.width, height: 2 };
+}
+
+function verticalLine(tableRect: DOMRect, x: number): DragTarget['rect'] {
+ return { left: x - 1, top: tableRect.top, width: 2, height: tableRect.height };
+}
+
+function commitReorder(
+ editor: Editor,
+ anchor: HTMLTableCellElement,
+ axis: Axis,
+ targetIndex: number,
+): void {
+ const sourceIndex = axis === 'row' ? rowIndexOf(anchor) : anchor.cellIndex;
+ if (sourceIndex < 0) return;
+ // Row 0 is the positional markdown header (see file header). Refuse header
+ // sources and above-header targets; computeDragTarget already clamps the
+ // indicator, but a defense-in-depth check here handles callers that could
+ // ever bypass the indicator.
+ if (axis === 'row') {
+ if (sourceIndex < FIRST_MOVABLE_ROW_INDEX) return;
+ if (targetIndex < FIRST_MOVABLE_ROW_INDEX) return;
+ }
+ // A move to the immediate before / after position is a no-op; skip
+ // dispatching so the doc's history doesn't accumulate empty transactions.
+ if (targetIndex === sourceIndex || targetIndex === sourceIndex + 1) return;
+
+ const { state, view } = editor;
+ const tablePos = findTablePos(state.selection.$from);
+ if (tablePos < 0) {
+ // Selection no longer inside a table (moved out mid-gesture, remote
+ // edit deleted the table, etc.). Warn to match the `nodeAt null` case
+ // below — otherwise a "drag didn't work" report is indistinguishable
+ // from the header-guard refusal or the adjacent no-op.
+ console.warn('[table-drag-reorder] no table found at selection depth');
+ return;
+ }
+ const table = state.doc.nodeAt(tablePos);
+ if (!table) {
+ // `findTablePos` returned a plausible position but the doc has no node
+ // there — a PM doc / selection inconsistency (concurrent edit landing
+ // between selection resolution and dispatch). Log so the "drag didn't
+ // work" report has telemetry; otherwise this is indistinguishable from
+ // an adjacent no-op drop.
+ console.warn('[table-drag-reorder] nodeAt returned null at tablePos', tablePos);
+ return;
+ }
+
+ const tr = state.tr;
+ const newTable =
+ axis === 'row'
+ ? tableWithMovedRow(table, sourceIndex, targetIndex)
+ : tableWithMovedColumn(table, sourceIndex, targetIndex);
+ applyTableReplacement(tr, tablePos, table, newTable);
+ view.dispatch(tr);
+}
+
+function rowIndexOf(cell: HTMLTableCellElement): number {
+ const tr = cell.parentElement;
+ const table = tr?.closest('table');
+ if (!table) return -1;
+ return Array.prototype.indexOf.call(table.rows, tr);
+}
+
+function findTablePos($from: ResolvedPos): number {
+ for (let depth = $from.depth; depth > 0; depth--) {
+ if ($from.node(depth).type.spec.tableRole === 'table') {
+ return $from.before(depth);
+ }
+ }
+ return -1;
+}
+
+export function tableWithMovedRow(table: PmNode, from: number, to: number): PmNode {
+ const rows: PmNode[] = [];
+ table.forEach((row) => {
+ rows.push(row);
+ });
+ const [moved] = rows.splice(from, 1);
+ // When moving DOWN, removing `from` shifts every subsequent index left by
+ // one, so a target of `to` in the original list becomes `to - 1` in the
+ // spliced list.
+ const dest = to > from ? to - 1 : to;
+ rows.splice(dest, 0, moved);
+ return table.type.create(table.attrs, rows, table.marks);
+}
+
+export function tableWithMovedColumn(table: PmNode, from: number, to: number): PmNode {
+ const dest = to > from ? to - 1 : to;
+ const newRows: PmNode[] = [];
+ table.forEach((row) => {
+ const cells: PmNode[] = [];
+ row.forEach((cell) => {
+ cells.push(cell);
+ });
+ const [moved] = cells.splice(from, 1);
+ cells.splice(dest, 0, moved);
+ newRows.push(row.type.create(row.attrs, cells, row.marks));
+ });
+ return table.type.create(table.attrs, newRows, table.marks);
+}
+
+function applyTableReplacement(
+ tr: Transaction,
+ tablePos: number,
+ oldTable: PmNode,
+ newTable: PmNode,
+): void {
+ tr.replaceRangeWith(tablePos, tablePos + oldTable.nodeSize, newTable);
+}
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index 8f9d95287..c014b1413 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index c18c086d5..8890f6739 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 864bc7245..b0a80fbd9 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -37,7 +37,6 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: string
return parts.join('\n');
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 592f0b956..e67f33b40 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 47f0d07e4..193e286b0 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index fb5ac8e8a..c7518d614 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 7a22e8016..f758cf737 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 2f082e6d0..78fdfeb02 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -76,8 +75,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 064fa0773..58a810193 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -165,7 +164,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -214,7 +212,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -233,7 +230,6 @@ function effectiveDirty(node: PmNode): boolean {
return node.attrs.sourceDirty || hasDirtyDescendant(node);
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -302,7 +298,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -552,7 +547,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -632,7 +626,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -911,7 +904,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1037,7 +1029,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(schema: Schema): {
nodeHandlers: FromProseMirrorOptions<string, string>['nodeHandlers'];
markHandlers: FromProseMirrorOptions<string, string>['markHandlers'];
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index f84967798..679c72ef7 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 153fdc1d8..79072375c 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import { normalizeUri } from 'micromark-util-sanitize-uri';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index a58f8c720..35d74b85e 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 7e4a9a48b..9864b3b60 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 5b9550e90..5d6db7aa8 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 4ac5731e7..248685cfe 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 240be90e6..50a193a16 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -467,8 +466,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 542204403..46cc6a074 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index fe73659e6..be97d4d62 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index e1161455b..1a2fb5d50 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index c5bfd2386..cd245c38c 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index 1b75ba564..a100cad76 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {