diff --git a/AGENTS.md b/AGENTS.md index f0dffee0a6..5c6a6c439b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -153,6 +153,7 @@ yarn sequelize migration:create --name=add-field-to-table - Handle connection state changes gracefully. - For bulk deletions that drive authorization or WebSocket processing, load affected models in the transaction and delete each with request context so downstream processors receive the expected per-item events. - Do not persist viewer-specific unfurls in shared document mentions; only store unfurls that map to a stable mention type. +- Editor plugins that repair the document (assigning missing IDs, fixing invalid structure) must use `RepairPlugin` from `shared/editor/plugins/RepairPlugin.ts`. Other plugins that change the document in `appendTransaction` must only respond to local changes, guard with `isLocalDocChange` from `shared/editor/lib/multiplayer.ts`. Otherwise every connected client writes the change in response to remote edits and is attributed as an editor. ## Documentation diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts index cd288cebca..4416b0db43 100644 --- a/server/commands/documentCreator.ts +++ b/server/commands/documentCreator.ts @@ -217,9 +217,11 @@ export default async function documentCreator( const contentWithReplacements = content ? content : text - ? ProsemirrorHelper.assignMentionActors( - ProsemirrorHelper.toProsemirror(text), - user.id + ? ProsemirrorHelper.assignMissingIds( + ProsemirrorHelper.assignMentionActors( + ProsemirrorHelper.toProsemirror(text), + user.id + ) ).toJSON() : template ? ProsemirrorHelper.replaceTemplateVariables( diff --git a/server/commands/documentUpdater.test.ts b/server/commands/documentUpdater.test.ts index c7feb44f51..cb74596c16 100644 --- a/server/commands/documentUpdater.test.ts +++ b/server/commands/documentUpdater.test.ts @@ -738,6 +738,7 @@ describe("documentUpdater", () => { listItem("Third item"), ], }, + { type: "paragraph" }, ], }); }); @@ -823,6 +824,7 @@ describe("documentUpdater", () => { listItem("gamma"), ], }, + { type: "paragraph" }, ], }); }); @@ -936,6 +938,7 @@ describe("documentUpdater", () => { listItem("gamma", [commentMark]), ], }, + { type: "paragraph" }, ], }); }); @@ -980,6 +983,7 @@ describe("documentUpdater", () => { type: "bullet_list", content: [listItem("beta"), listItem("gamma", [commentMark])], }, + { type: "paragraph" }, ], }); }); @@ -1032,6 +1036,7 @@ describe("documentUpdater", () => { "bullet_list", "ordered_list", "bullet_list", + "paragraph", ]); expect(document.text).toContain("alpha"); expect(document.text).toContain("beta EDITED"); @@ -1066,6 +1071,7 @@ describe("documentUpdater", () => { listItem("three"), ], }, + { type: "paragraph" }, ], }); }); @@ -1099,6 +1105,7 @@ describe("documentUpdater", () => { attrs: { listStyle: "number" }, content: [listItem("numeric")], }, + { type: "paragraph" }, ], }); }); @@ -1142,6 +1149,7 @@ describe("documentUpdater", () => { listItem("beta"), ], }, + { type: "paragraph" }, ], }); }); @@ -2148,7 +2156,8 @@ describe("documentUpdater", () => { ); const content = result.content!.content!; - expect(content).toHaveLength(1); + expect(content).toHaveLength(2); + expect(content[1].type).toBe("paragraph"); expect(content[0]).toMatchObject({ type: "code_block", content: [ @@ -2177,7 +2186,8 @@ describe("documentUpdater", () => { ); const content = result.content!.content!; - expect(content).toHaveLength(1); + expect(content).toHaveLength(2); + expect(content[1].type).toBe("paragraph"); expect(content[0]).toMatchObject({ type: "code_block", content: [ @@ -2328,4 +2338,78 @@ describe("documentUpdater", () => { expect(result.text).toContain("other"); }); }); + + describe("block ids", () => { + const paragraph = (text: string) => ({ + type: "paragraph", + content: [{ type: "text", text }], + }); + const listId = randomUUID(); + const toggleId = randomUUID(); + const content: ProsemirrorData = { + type: "doc", + content: [ + { + type: "checkbox_list", + attrs: { id: listId }, + content: ["one", "two"].map((text) => ({ + type: "checkbox_item", + attrs: { checked: false }, + content: [paragraph(text)], + })), + }, + { + type: "container_toggle", + attrs: { id: toggleId }, + content: [paragraph("Title"), paragraph("Body")], + }, + ], + }; + + const blockIds = (document: Document) => + (document.content?.content ?? []) + .filter((node) => node.type !== "paragraph") + .map((node) => node.attrs?.id); + + it("assigns ids and a trailing paragraph to markdown written through the API", async () => { + const user = await buildUser(); + const document = await buildDocument({ teamId: user.teamId }); + + const result = await withAPIContext(user, (ctx) => + documentUpdater(ctx, { + document, + text: "- [ ] one\n\n+++ Title\nBody\n+++", + }) + ); + + const [checklist, toggle] = blockIds(result); + expect(checklist).toEqual(expect.any(String)); + expect(toggle).toEqual(expect.any(String)); + expect(result.content?.content?.at(-1)?.type).toBe("paragraph"); + expect(result.text.trim().endsWith("+++")).toBe(true); + }); + + it.each([ + ["checkbox list", "two", "three"], + ["toggle block", "Body", "Changed body"], + ])("keeps the id of a patched %s", async (_name, findText, replacement) => { + const user = await buildUser(); + const document = await buildDocument({ + teamId: user.teamId, + content, + }); + + const result = await withAPIContext(user, (ctx) => + documentUpdater(ctx, { + document, + text: replacement, + editMode: TextEditMode.Patch, + findText, + }) + ); + + expect(result.text).toContain(replacement); + expect(blockIds(result)).toEqual([listId, toggleId]); + }); + }); }); diff --git a/server/models/helpers/DocumentHelper.tsx b/server/models/helpers/DocumentHelper.tsx index 4f47fd3baf..5a50ccd383 100644 --- a/server/models/helpers/DocumentHelper.tsx +++ b/server/models/helpers/DocumentHelper.tsx @@ -9,6 +9,7 @@ import { } from "@shared/editor/lib/ChangesetHelper"; import { HeadingSlugger } from "@shared/editor/lib/headingToSlug"; import textBetween from "@shared/editor/lib/textBetween"; +import { withTrailingNode } from "@shared/editor/lib/trailingNode"; import type { NavigationNode, ProsemirrorData } from "@shared/types"; import { DocumentPreference, IconType, TextEditMode } from "@shared/types"; import { determineIconType } from "@shared/utils/icon"; @@ -672,10 +673,14 @@ export class DocumentHelper { if (actorId) { doc = ProsemirrorHelper.assignMentionActors(doc, actorId, previousDoc); } - - document.content = doc.toJSON(); + doc = ProsemirrorHelper.assignMissingIds(doc); document.text = serializer.serialize(doc); + // Match the editor's normalized form, so open editors do not write their + // own repairs back in response to this change. + doc = withTrailingNode(doc); + document.content = doc.toJSON(); + if (document.state) { const ydoc = new Y.Doc(); Y.applyUpdate(ydoc, document.state); diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index 48b9aaebca..df5178fae0 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import emojiRegex from "emoji-regex"; import type { JSDOM } from "jsdom"; @@ -182,6 +183,23 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { return Node.fromJSON(schema, data); } + /** + * Assigns a new id to every node that has an empty id attribute, such as + * checkbox lists and toggle blocks parsed from Markdown. + * + * @param doc the document. + * @returns the document with missing ids assigned. + */ + static assignMissingIds(doc: Node) { + const tr = new Transform(doc); + doc.descendants((node, pos) => { + if (node.type.spec.attrs?.id && !node.attrs.id) { + tr.setNodeAttribute(pos, "id", randomUUID()); + } + }); + return tr.doc; + } + /** * Attributes new mentions to the writer, preserving the original actor of * mentions retained from an earlier document, including Markdown round trips. diff --git a/shared/editor/lib/multiplayer.ts b/shared/editor/lib/multiplayer.ts index a12f3257e1..f694089f9e 100644 --- a/shared/editor/lib/multiplayer.ts +++ b/shared/editor/lib/multiplayer.ts @@ -55,6 +55,19 @@ export function isRemoteTransaction( return getOperations(state)?.isRemoteTransaction(tr) ?? false; } +/** + * Checks if a transaction changed the document locally. Plugins that repair + * the document must only respond to local changes, otherwise every connected + * client writes the repair and is attributed as an editor. + * + * @param tr The Prosemirror transaction + * @param state The editor state + * @returns true if the transaction changed the document and is not remote + */ +export function isLocalDocChange(tr: Transaction, state: EditorState): boolean { + return tr.docChanged && !isRemoteTransaction(tr, state); +} + /** * Stops the collaborative undo manager from capturing further changes, if * the multiplayer extension is mounted in the editor. diff --git a/shared/editor/nodes/CheckboxList.ts b/shared/editor/nodes/CheckboxList.ts index 20c5f737bb..95b97d5b74 100644 --- a/shared/editor/nodes/CheckboxList.ts +++ b/shared/editor/nodes/CheckboxList.ts @@ -4,7 +4,7 @@ import type { Schema, Node as ProsemirrorNode, } from "prosemirror-model"; -import { Plugin, PluginKey } from "prosemirror-state"; +import { Plugin } from "prosemirror-state"; import { v4 as generateUuid } from "uuid"; import toggleList from "../commands/toggleList"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; @@ -12,8 +12,7 @@ import { checkboxListInputRule, listWrappingInputRule, } from "../lib/listInputRule"; -import { findBlockNodes } from "../queries/findChildren"; -import { isInlineTransaction } from "../queries/isInlineTransaction"; +import { RepairPlugin } from "../plugins/RepairPlugin"; import { CheckboxListView } from "./CheckboxListView"; import Node from "./Node"; @@ -42,44 +41,14 @@ export default class CheckboxList extends Node { const userIdentifier = this.editor.props.userId; // Plugin to auto-assign IDs to checkbox lists - const assignIdsPluginKey = new PluginKey("checkboxListIds"); - const assignIdsPlugin = new Plugin({ - key: assignIdsPluginKey, - state: { - // Whether any document change has been applied since load - init: () => false, - apply: (tr, hasChanged) => hasChanged || tr.docChanged, - }, - appendTransaction: (txs, oldSt, newSt) => { - if (!txs.some((t) => t.docChanged)) { - return null; - } - - // Lists loaded without ids are repaired on the first edit. After that - // only structural edits can introduce a list without an id. - const isFirstChange = !assignIdsPluginKey.getState(oldSt); - const hasStructuralChange = txs.some( - (t) => - t.docChanged && - !isInlineTransaction(t, (node) => node.type.name === this.name) - ); - if (!isFirstChange && !hasStructuralChange) { - return null; - } - - const checkboxLists = findBlockNodes(newSt.doc, true).filter( - (b) => b.node.type.name === this.name && !b.node.attrs.id - ); - - if (checkboxLists.length === 0) { - return null; - } - - let modifyTx = newSt.tr; - checkboxLists.forEach((listBlock) => { - modifyTx.setNodeAttribute(listBlock.pos, "id", generateUuid()); + const assignIdsPlugin = new RepairPlugin({ + needsRepair: (node) => node.type.name === this.name && !node.attrs.id, + repair: (state, lists) => { + const tr = state.tr; + lists.forEach(({ pos }) => { + tr.setNodeAttribute(pos, "id", generateUuid()); }); - return modifyTx; + return tr; }, }); diff --git a/shared/editor/nodes/Mention.test.ts b/shared/editor/nodes/Mention.test.ts index 5fe713f91b..e8183034bc 100644 --- a/shared/editor/nodes/Mention.test.ts +++ b/shared/editor/nodes/Mention.test.ts @@ -1,5 +1,7 @@ +import type { EditorState } from "prosemirror-state"; import { MentionType } from "../../types"; -import { schema, serializer } from "../../test/editor"; +import { createEditorState, schema, serializer } from "../../test/editor"; +import Mention from "./Mention"; const id = "0c440212-8b40-49fa-8a64-2548d6b60d59"; const modelId = "c85a0d80-3a89-4b25-a0cd-e7fc83f0d226"; @@ -161,3 +163,86 @@ describe("Mention serialization", () => { }); }); }); + +describe("Mention ids", () => { + const mention = (mentionId: string | null) => + schema.nodes.mention.create({ + id: mentionId, + modelId, + type: MentionType.User, + label: "Name", + }); + + const ids = (state: EditorState) => { + const result: string[] = []; + state.doc.descendants((node) => { + if (node.type.name === "mention") { + result.push(node.attrs.id); + } + }); + return result; + }; + + it("gives a pasted duplicate a new id and keeps the original", () => { + const state = createEditorState( + schema.nodes.doc.create(null, [ + schema.nodes.paragraph.create(null, [mention(id)]), + schema.nodes.paragraph.create(), + ]), + new Mention().plugins + ); + + const typed = state.apply(state.tr.insertText("x", 4)); + const pasted = typed.apply(typed.tr.insert(4, mention(id))); + + const [original, copy] = ids(pasted); + expect(original).toBe(id); + expect(copy).toEqual(expect.any(String)); + expect(copy).not.toBe(id); + }); + + it("keeps the original id when a duplicate is pasted as the first change", () => { + const state = createEditorState( + schema.nodes.doc.create(null, [ + schema.nodes.paragraph.create(null, [mention(id)]), + schema.nodes.paragraph.create(), + ]), + new Mention().plugins + ); + + const pasted = state.apply(state.tr.insert(4, mention(id))); + + const [original, copy] = ids(pasted); + expect(original).toBe(id); + expect(copy).toEqual(expect.any(String)); + expect(copy).not.toBe(id); + }); + + it("gives the later of two loaded duplicates a new id", () => { + const state = createEditorState( + schema.nodes.doc.create(null, [ + schema.nodes.paragraph.create(null, [mention(id)]), + schema.nodes.paragraph.create(null, [mention(id)]), + schema.nodes.paragraph.create(), + ]), + new Mention().plugins + ); + + const newState = state.apply(state.tr.insertText("x", 7)); + + const [first, second] = ids(newState); + expect(first).toBe(id); + expect(second).not.toBe(id); + }); + + it("assigns an id to a mention without one", () => { + const state = createEditorState( + schema.nodes.doc.create(null, [schema.nodes.paragraph.create()]), + new Mention().plugins + ); + + const newState = state.apply(state.tr.insert(1, mention(null))); + + expect(ids(newState)[0]).toEqual(expect.any(String)); + }); +}); diff --git a/shared/editor/nodes/Mention.tsx b/shared/editor/nodes/Mention.tsx index 6dd481fe0f..c369e820f1 100644 --- a/shared/editor/nodes/Mention.tsx +++ b/shared/editor/nodes/Mention.tsx @@ -8,7 +8,7 @@ import type { Schema, } from "prosemirror-model"; import type { Command } from "prosemirror-state"; -import { NodeSelection, Plugin, TextSelection } from "prosemirror-state"; +import { NodeSelection, TextSelection } from "prosemirror-state"; import type { Primitive } from "utility-types"; import { v4 as uuidv4 } from "uuid"; import env from "../../env"; @@ -31,8 +31,9 @@ import { transformListToMentions } from "../lib/mention"; import { findParentNodeClosestToPos } from "../queries/findParentNode"; import { isInList } from "../queries/isInList"; import { isList } from "../queries/isList"; +import { RepairPlugin } from "../plugins/RepairPlugin"; import mentionRule from "../rules/mention"; -import type { ComponentProps } from "../types"; +import type { ComponentProps, NodeWithPos } from "../types"; import Node from "./Node"; /** @@ -243,31 +244,32 @@ export default class Mention extends Node { get plugins() { return [ - // Ensure mentions have unique IDs - new Plugin({ - appendTransaction: (_transactions, _oldState, newState) => { - const tr = newState.tr; - const existingIds = new Set(); - let modified = false; - - tr.doc.descendants((node, pos) => { - let nodeId = node.attrs.id; - if ( - node.type.name === this.name && - (!nodeId || existingIds.has(nodeId)) - ) { - nodeId = uuidv4(); - modified = true; - tr.setNodeAttribute(pos, "id", nodeId); + // Ensure mentions have unique IDs. Unchanged mentions keep their id, so + // a pasted copy is given a new id rather than the original. + new RepairPlugin({ + needsRepair: (node) => node.type.name === this.name, + repair: (state, mentions) => { + const changed = mentions.filter((mention) => mention.changed); + const changedPositions = new Set(changed.map(({ pos }) => pos)); + const ordered: NodeWithPos[] = []; + state.doc.descendants((node, pos) => { + if (node.type.name === this.name && !changedPositions.has(pos)) { + ordered.push({ node, pos }); } - existingIds.add(nodeId); }); + ordered.push(...changed); - if (modified) { - return tr; - } - - return null; + const seen = new Set(); + const tr = state.tr; + ordered.forEach(({ node, pos }) => { + const { id } = node.attrs; + if (id && !seen.has(id)) { + seen.add(id); + return; + } + tr.setNodeAttribute(pos, "id", uuidv4()); + }); + return tr.docChanged ? tr : null; }, }), ]; diff --git a/shared/editor/nodes/ToggleBlock.ts b/shared/editor/nodes/ToggleBlock.ts index 7338c1f814..97c6d76033 100644 --- a/shared/editor/nodes/ToggleBlock.ts +++ b/shared/editor/nodes/ToggleBlock.ts @@ -12,7 +12,7 @@ import type { Command, EditorState, Transaction } from "prosemirror-state"; import { Plugin, PluginKey, TextSelection } from "prosemirror-state"; import { findWrapping } from "prosemirror-transform"; import { Decoration, DecorationSet } from "prosemirror-view"; -import { v4 } from "uuid"; +import { v4 as generateUuid } from "uuid"; import { LRUCache } from "../../utils/LRUCache"; import { deleteSelectionPreservingBody, @@ -46,6 +46,7 @@ import { isToggleBlock, getToggleBlockDepth } from "../queries/toggleBlock"; import Node from "./Node"; import { ToggleBlockView } from "./ToggleBlockView"; import { isRemoteTransaction } from "../lib/multiplayer"; +import { RepairPlugin } from "../plugins/RepairPlugin"; export enum Action { INIT, @@ -73,7 +74,7 @@ export const toggleFoldPluginKey = new PluginKey("toggleFold"); /** Plugin key for toggle block fold/unfold events. */ export const toggleEventPluginKey = new PluginKey("toggleBlockEvent"); -const toggleIdPluginKey = new PluginKey("toggleBlockIds"); +const toggleAutoFoldPluginKey = new PluginKey("toggleBlockAutoFold"); /** Build the localStorage key used to persist a toggle block's fold state. */ export const toggleStorageKey = (id: string) => `toggle:${id}`; @@ -119,9 +120,23 @@ export default class ToggleBlock extends Node { } get plugins() { - // Assign IDs and auto-fold empty + // Assign IDs and default to unfolded in this browser + const idPlugin = new RepairPlugin({ + needsRepair: (node) => node.type.name === this.name && !node.attrs.id, + repair: (state, blocks) => { + const tr = state.tr; + blocks.forEach(({ pos }) => { + const id = generateUuid(); + tr.setNodeAttribute(pos, "id", id); + foldStateCache.set(id, { fold: false }); + }); + return tr; + }, + }); + + // Auto-fold empty const plugin = new Plugin({ - key: toggleIdPluginKey, + key: toggleAutoFoldPluginKey, state: { // Whether any document change has been applied since load init: () => false, @@ -132,9 +147,9 @@ export default class ToggleBlock extends Node { return null; } - // Blocks loaded without ids are repaired on the first edit. After - // that only structural edits can add toggle blocks or empty bodies. - const isFirstChange = !toggleIdPluginKey.getState(oldState); + // Only structural edits can add toggle blocks or empty bodies after + // the first change. + const isFirstChange = !toggleAutoFoldPluginKey.getState(oldState); if ( !isFirstChange && !transactions.some((tr) => this.isStructuralChange(tr, newState)) @@ -142,50 +157,25 @@ export default class ToggleBlock extends Node { return null; } - // Single pass to find all toggle blocks - const toggleBlocks = findBlockNodes(newState.doc, true).filter( - (b) => b.node.type.name === this.name - ); - - if (toggleBlocks.length === 0) { + const pluginState = toggleFoldPluginKey.getState(newState); + if (!pluginState) { return null; } - let tr: Transaction | null = null; + const emptyBodyBlock = findBlockNodes(newState.doc, true).find( + (b) => + b.node.type.name === this.name && + b.node.childCount === 1 && + b.node.attrs.id && + !pluginState.foldedIds.has(b.node.attrs.id) + ); - // Assign IDs to blocks that need them and default to unfolded in this browser - const blocksNeedingIds = toggleBlocks.filter((b) => !b.node.attrs.id); - if (blocksNeedingIds.length > 0) { - tr = newState.tr; - blocksNeedingIds.forEach((block) => { - const id = v4(); - tr!.setNodeAttribute(block.pos, "id", id); - foldStateCache.set(id, { fold: false }); - }); - } - - // Auto-fold toggle blocks with empty bodies, only if no structural - // changes were made (positions would be invalid) - if (!tr) { - const pluginState = toggleFoldPluginKey.getState(newState); - if (pluginState) { - const emptyBodyBlock = toggleBlocks.find( - (b) => - b.node.childCount === 1 && - b.node.attrs.id && - !pluginState.foldedIds.has(b.node.attrs.id) - ); - - if (emptyBodyBlock) { - return newState.tr.setMeta(toggleFoldPluginKey, { - type: Action.FOLD, - at: emptyBodyBlock.pos, - }); - } - } - } - - return tr; + return emptyBodyBlock + ? newState.tr.setMeta(toggleFoldPluginKey, { + type: Action.FOLD, + at: emptyBodyBlock.pos, + }) + : null; }, }); @@ -330,6 +320,7 @@ export default class ToggleBlock extends Node { }); return [ + idPlugin, plugin, foldPlugin, eventPlugin, @@ -436,7 +427,7 @@ export default class ToggleBlock extends Node { if ($from.parent.type === state.schema.nodes.heading) { const $fr_ = TextSelection.near($from, 1).$from; const $to_ = TextSelection.near(findCutAfterHeading($from), -1).$to; - const id = v4(); + const id = generateUuid(); const range = $fr_.blockRange($to_), wrapping = range && findWrapping(range, type, { id }); if (!wrapping) { @@ -449,7 +440,7 @@ export default class ToggleBlock extends Node { } // if para if ($from.parent.type === state.schema.nodes.paragraph) { - const id = v4(); + const id = generateUuid(); const range = $from.blockRange($to), wrapping = range && findWrapping(range, type, { id }); if (!wrapping) { diff --git a/shared/editor/plugins/FixTablesPlugin.test.ts b/shared/editor/plugins/FixTablesPlugin.test.ts index 87e47a7f08..105a362c90 100644 --- a/shared/editor/plugins/FixTablesPlugin.test.ts +++ b/shared/editor/plugins/FixTablesPlugin.test.ts @@ -8,7 +8,12 @@ import { th, tr, } from "@shared/test/editor"; +import { Plugin } from "prosemirror-state"; import { TableMap } from "prosemirror-tables"; +import { + multiplayerPluginKey, + type MultiplayerOperations, +} from "../lib/multiplayer"; import { FixTablesPlugin } from "./FixTablesPlugin"; describe("FixTablesPlugin", () => { @@ -350,4 +355,58 @@ describe("FixTablesPlugin", () => { expect(newTable.child(1).child(1).type.name).toBe("td"); }); }); + + describe("collaboration", () => { + const multiplayer: MultiplayerOperations = { + isRemoteTransaction: (transaction) => !!transaction.getMeta("remote"), + stopCapturing: () => {}, + }; + const facade = new Plugin({ key: multiplayerPluginKey, multiplayer }); + const brokenTable = () => + doc(table([tr([th("H1"), th("H2")]), tr([th("R1"), th("Wrong")])])); + + it("should not repair tables in response to remote changes", () => { + const state = createEditorState(brokenTable(), [ + facade, + new FixTablesPlugin(), + ]); + + const newState = state.apply( + state.tr.insertText("x", 5).setMeta("remote", true) + ); + + expect(newState.doc.firstChild!.child(1).child(1).type.name).toBe("th"); + }); + + it("should repair tables on the first local change after a remote change", () => { + const state = createEditorState(brokenTable(), [ + facade, + new FixTablesPlugin(), + ]); + + const remoteState = state.apply( + state.tr.insertText("x", 5).setMeta("remote", true) + ); + const newState = remoteState.apply(remoteState.tr.insertText("y", 5)); + + expect(newState.doc.firstChild!.child(1).child(1).type.name).toBe("td"); + }); + + it("should repair tables received after an earlier local change", () => { + const state = createEditorState(doc(p("Intro")), [ + facade, + new FixTablesPlugin(), + ]); + + const localState = state.apply(state.tr.insertText("x", 1)); + const remoteState = localState.apply( + localState.tr + .insert(localState.doc.content.size, brokenTable().content) + .setMeta("remote", true) + ); + const newState = remoteState.apply(remoteState.tr.insertText("y", 1)); + + expect(newState.doc.child(1).child(1).child(1).type.name).toBe("td"); + }); + }); }); diff --git a/shared/editor/plugins/FixTablesPlugin.ts b/shared/editor/plugins/FixTablesPlugin.ts index fa45825b62..5afd481e09 100644 --- a/shared/editor/plugins/FixTablesPlugin.ts +++ b/shared/editor/plugins/FixTablesPlugin.ts @@ -1,9 +1,8 @@ import type { Node } from "prosemirror-model"; import type { EditorState, Transaction } from "prosemirror-state"; -import { Plugin } from "prosemirror-state"; import { TableMap } from "prosemirror-tables"; -import { changedDescendants } from "../lib/changedDescendants"; import { isValidCellSpan } from "../lib/table"; +import { RepairPlugin } from "./RepairPlugin"; /** * A ProseMirror plugin that fixes various ways that tables can end up in an incorrect state: @@ -12,94 +11,81 @@ import { isValidCellSpan } from "../lib/table"; * - Header cells should only exist in the first row or column * - Cells should span at least one row and column */ -export class FixTablesPlugin extends Plugin { +export class FixTablesPlugin extends RepairPlugin { constructor() { super({ - state: { - // Whether any document change has been applied since load - init: () => false, - apply: (tr, hasChanged) => hasChanged || tr.docChanged, - }, - appendTransaction: (_transactions, oldState, state) => { - if (oldState.doc === state.doc) { - return undefined; + needsRepair: (node, pos, state) => { + if (node.type.spec.tableRole !== "table") { + return false; } - const tr = state.tr; - const check = (node: Node, pos: number) => { - if (node.type.spec.tableRole === "table") { - this.fixTable(state, node, pos, tr); - } - }; - - // Tables loaded in a bad state are repaired on the first edit. After - // that only changed tables are checked. - if (!this.getState(oldState)) { - state.doc.descendants(check); - } else { - changedDescendants(oldState.doc, state.doc, 0, check); - } - return tr.docChanged ? tr : undefined; + fixTable(state, node, pos, tr); + return tr.docChanged; + }, + repair: (state, tables) => { + const tr = state.tr; + tables.forEach(({ node, pos }) => fixTable(state, node, pos, tr)); + return tr.docChanged ? tr : null; }, - }); - } - - private fixTable( - state: EditorState, - table: Node, - pos: number, - tr: Transaction - ) { - const map = TableMap.get(table); - - // If the table has only one column, remove the colwidth attribute on all cells - if (map.width === 1) { - const cells = map.cellsInRect({ - left: 0, - top: 0, - right: 1, - bottom: map.height, - }); - cells.forEach((offset) => { - const cellPos = pos + 1 + offset; - const node = state.doc.nodeAt(cellPos); - if (node?.attrs.colwidth) { - tr.setNodeMarkup(cellPos, undefined, { - ...node?.attrs, - colwidth: null, - }); - } - }); - } - - // If the table has header cells that are not in the first row or column - // then convert them to regular cells - const cellPositions = map.cellsInRect({ - left: 1, - top: 1, - right: map.width, - bottom: map.height, - }); - - for (let i = 0; i < cellPositions.length; i++) { - const cellPos = cellPositions[i]; - const cell = table.nodeAt(cellPos); - if (cell && cell.type === state.schema.nodes.th) { - tr.setNodeMarkup(cellPos + pos + 1, state.schema.nodes.td, cell.attrs); - } - } - - // Cells with an invalid span are left out of the table map, so reset them - // to a single row and column. - table.forEach((row, rowOffset) => { - row.forEach((cell, cellOffset) => { - const cellPos = pos + 1 + rowOffset + 1 + cellOffset; - for (const name of ["colspan", "rowspan"]) { - if (!isValidCellSpan(cell.attrs[name])) { - tr.setNodeAttribute(cellPos, name, 1); - } - } - }); }); } } + +function fixTable( + state: EditorState, + table: Node, + pos: number, + tr: Transaction +) { + const map = TableMap.get(table); + + // If the table has only one column, remove the colwidth attribute on all cells + if (map.width === 1) { + const cells = map.cellsInRect({ + left: 0, + top: 0, + right: 1, + bottom: map.height, + }); + cells.forEach((offset) => { + const cellPos = pos + 1 + offset; + const node = state.doc.nodeAt(cellPos); + if (node?.attrs.colwidth) { + tr.setNodeMarkup(cellPos, undefined, { + ...node?.attrs, + colwidth: null, + }); + } + }); + } + + // If the table has header cells that are not in the first row or column + // then convert them to regular cells + const cellPositions = map.cellsInRect({ + left: 1, + top: 1, + right: map.width, + bottom: map.height, + }); + + for (let i = 0; i < cellPositions.length; i++) { + const cellPos = cellPositions[i]; + const cell = table.nodeAt(cellPos); + if (cell && cell.type === state.schema.nodes.th) { + tr.setNodeMarkup(cellPos + pos + 1, state.schema.nodes.td, cell.attrs); + } + } + + // Cells with an invalid span are left out of the table map, so reset them + // to a single row and column. + table.forEach((row, rowOffset) => { + row.forEach((cell, cellOffset) => { + const cellPos = pos + 1 + rowOffset + 1 + cellOffset; + for (const name of ["colspan", "rowspan"]) { + if (!isValidCellSpan(cell.attrs[name])) { + tr.setNodeAttribute(cellPos, name, 1); + } + } + }); + }); +} diff --git a/shared/editor/plugins/RepairPlugin.test.ts b/shared/editor/plugins/RepairPlugin.test.ts new file mode 100644 index 0000000000..2a4cfb4899 --- /dev/null +++ b/shared/editor/plugins/RepairPlugin.test.ts @@ -0,0 +1,99 @@ +import { createEditorState, doc, heading, p } from "@shared/test/editor"; +import type { EditorState } from "prosemirror-state"; +import { Plugin } from "prosemirror-state"; +import { + multiplayerPluginKey, + type MultiplayerOperations, +} from "../lib/multiplayer"; +import { RepairPlugin } from "./RepairPlugin"; + +describe("RepairPlugin", () => { + const multiplayer: MultiplayerOperations = { + isRemoteTransaction: (transaction) => !!transaction.getMeta("remote"), + stopCapturing: () => {}, + }; + const facade = new Plugin({ key: multiplayerPluginKey, multiplayer }); + + // Treats level one headings as needing repair to level two. + const buildPlugin = () => { + const needsRepair = vi.fn( + (node) => node.type.name === "heading" && node.attrs.level === 1 + ); + const plugin = new RepairPlugin({ + needsRepair, + repair: (state, nodes) => { + const tr = state.tr; + nodes.forEach(({ pos }) => tr.setNodeAttribute(pos, "level", 2)); + return tr; + }, + }); + return { plugin, needsRepair }; + }; + + const levels = (state: EditorState) => { + const result: number[] = []; + state.doc.descendants((node) => { + if (node.type.name === "heading") { + result.push(node.attrs.level); + } + }); + return result; + }; + + const insertRemote = (state: EditorState) => + state.apply( + state.tr + .insert(state.doc.content.size, heading("Remote", 1)) + .setMeta("remote", true) + ); + + it("repairs loaded content on the first local change", () => { + const { plugin } = buildPlugin(); + const state = createEditorState(doc([heading("Loaded", 1), p("Text")]), [ + facade, + plugin, + ]); + + const newState = state.apply(state.tr.insertText("x", 10)); + + expect(levels(newState)).toEqual([2]); + }); + + it("does not repair in response to a remote change", () => { + const { plugin } = buildPlugin(); + const state = createEditorState(doc(p("Text")), [facade, plugin]); + + const newState = insertRemote(state); + + expect(levels(newState)).toEqual([1]); + }); + + it("repairs received content on the next local change", () => { + const { plugin } = buildPlugin(); + const state = createEditorState(doc(p("Text")), [facade, plugin]); + + const localState = state.apply(state.tr.insertText("x", 1)); + const remoteState = insertRemote(localState); + const newState = remoteState.apply(remoteState.tr.insertText("y", 1)); + + expect(levels(newState)).toEqual([2]); + }); + + it("only checks changed nodes when no repair is pending", () => { + const { plugin, needsRepair } = buildPlugin(); + const state = createEditorState( + doc([p("One"), p("Two"), p("Three"), p("Four")]), + [facade, plugin] + ); + + const localState = state.apply(state.tr.insertText("x", 1)); + const remoteState = localState.apply( + localState.tr.insertText("z", 7).setMeta("remote", true) + ); + needsRepair.mockClear(); + remoteState.apply(remoteState.tr.insertText("y", 1)); + + // The changed paragraph and its text, not the whole document. + expect(needsRepair.mock.calls.length).toBeLessThanOrEqual(2); + }); +}); diff --git a/shared/editor/plugins/RepairPlugin.ts b/shared/editor/plugins/RepairPlugin.ts new file mode 100644 index 0000000000..e86690f0fa --- /dev/null +++ b/shared/editor/plugins/RepairPlugin.ts @@ -0,0 +1,95 @@ +import type { Node } from "prosemirror-model"; +import type { EditorState, Transaction } from "prosemirror-state"; +import { Plugin } from "prosemirror-state"; +import { changedDescendants } from "../lib/changedDescendants"; +import { isLocalDocChange, isRemoteTransaction } from "../lib/multiplayer"; +import type { NodeWithPos } from "../types"; + +export interface RepairNode extends NodeWithPos { + /** Whether the node was changed by the local transactions being repaired. */ + changed: boolean; +} + +export interface RepairSpec { + /** + * Whether the node must be repaired. Called for changed nodes, and for every + * node when content that needs repair may exist. Must not have side effects. + * + * @param node The node to check. + * @param pos The position of the node. + * @param state The editor state. + * @returns true if the node must be repaired. + */ + needsRepair: (node: Node, pos: number, state: EditorState) => boolean; + + /** + * Repair the given nodes. + * + * @param state The editor state. + * @param nodes The nodes that need repair, in document order. + * @returns a transaction with the repairs, or null if nothing changed. + */ + repair: (state: EditorState, nodes: RepairNode[]) => Transaction | null; +} + +/** + * A plugin that repairs nodes in the document, such as by assigning missing + * ids or fixing invalid structure. Repairs are only made in response to local + * changes, otherwise every connected client writes the same repair and is + * attributed as an editor. Content that needs repair, whether loaded or + * received from a remote change, is repaired on the next local change. + */ +export class RepairPlugin extends Plugin { + constructor({ needsRepair, repair }: RepairSpec) { + const findChanged = (oldState: EditorState, state: EditorState) => { + const nodes: RepairNode[] = []; + changedDescendants(oldState.doc, state.doc, 0, (node, pos) => { + if (needsRepair(node, pos, state)) { + nodes.push({ node, pos, changed: true }); + } + }); + return nodes; + }; + + const findAll = (oldState: EditorState, state: EditorState) => { + const changed = new Set( + findChanged(oldState, state).map(({ pos }) => pos) + ); + const nodes: RepairNode[] = []; + state.doc.descendants((node, pos) => { + if (needsRepair(node, pos, state)) { + nodes.push({ node, pos, changed: changed.has(pos) }); + } + }); + return nodes; + }; + + super({ + state: { + // Whether content that needs repair may exist outside of the nodes + // changed locally, documents can be loaded in any state. + init: () => true, + apply: (tr, isPending, oldState, newState) => { + if (!tr.docChanged) { + return isPending; + } + if (!isRemoteTransaction(tr, newState)) { + return false; + } + return isPending || findChanged(oldState, newState).length > 0; + }, + }, + appendTransaction: (transactions, oldState, newState) => { + if (!transactions.some((tr) => isLocalDocChange(tr, newState))) { + return null; + } + + const nodes = this.getState(oldState) + ? findAll(oldState, newState) + : findChanged(oldState, newState); + + return nodes.length > 0 ? repair(newState, nodes) : null; + }, + }); + } +} diff --git a/shared/editor/plugins/TableLayoutPlugin.ts b/shared/editor/plugins/TableLayoutPlugin.ts index ee688acec0..021c508ce9 100644 --- a/shared/editor/plugins/TableLayoutPlugin.ts +++ b/shared/editor/plugins/TableLayoutPlugin.ts @@ -3,6 +3,7 @@ import type { EditorState, Transaction } from "prosemirror-state"; import { Plugin } from "prosemirror-state"; import { TableMap } from "prosemirror-tables"; import { changedDescendants } from "../lib/changedDescendants"; +import { isLocalDocChange } from "../lib/multiplayer"; /** * A ProseMirror plugin that watches for changes to the "layout" attribute on tables @@ -29,7 +30,7 @@ export class TableLayoutPlugin extends Plugin { if (!oldState) { // Initial state - check all tables newState.doc.descendants(check); - } else if (oldState.doc !== newState.doc) { + } else if (transactions.some((tr) => isLocalDocChange(tr, newState))) { // Document changed - check only changed tables changedDescendants(oldState.doc, newState.doc, 0, check); }