diff --git a/server/models/helpers/ProseMirrorHelper.test.ts b/server/models/helpers/ProseMirrorHelper.test.ts index 2aa114fdff..da7e3499f1 100644 --- a/server/models/helpers/ProseMirrorHelper.test.ts +++ b/server/models/helpers/ProseMirrorHelper.test.ts @@ -1753,6 +1753,220 @@ describe("ProsemirrorHelper", () => { ).toThrow(/not found/); }); + it("suggests the closest text when anchorText is not found", () => { + const docState = buildDocState([ + { + type: "paragraph", + content: [ + { type: "text", text: "Copy all 6 scripts to " }, + { + type: "text", + marks: [{ type: "code_inline" }], + text: "api-documentation/tools/", + }, + ], + }, + ]); + + expect(() => + ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "Copy all 7 scripts to `api-documentation/tools/`", + commentId: "comment-1", + userId: "user-1", + }) + ).toThrow( + 'the closest text is "Copy all 6 scripts to api-documentation/tools/"' + ); + }); + + it("does not suggest unrelated text when anchorText is not found", () => { + const docState = buildDocState([ + { + type: "paragraph", + content: [{ type: "text", text: "Copy all 6 scripts to tools" }], + }, + ]); + + expect(() => + ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "totally unrelated sentence here", + commentId: "comment-1", + userId: "user-1", + }) + ).toThrow(/^anchorText was not found in the document$/); + }); + + it("does not suggest text when anchorText is very long", () => { + const text = "lorem ipsum dolor sit amet ".repeat(50); + const docState = buildDocState([ + { + type: "paragraph", + content: [{ type: "text", text }], + }, + ]); + + expect(() => + ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: `${text}and more`, + commentId: "comment-1", + userId: "user-1", + }) + ).toThrow(/^anchorText was not found in the document$/); + }); + + describe("with markdown formatted anchorText", () => { + // Callers commonly read a document as markdown and then anchor using a + // substring of it, which does not exist verbatim in the plain text. + const steps = [ + { + type: "heading", + attrs: { level: 2 }, + content: [{ type: "text", text: "Implementation steps" }], + }, + { + type: "paragraph", + content: [ + { type: "text", text: "Remove " }, + { + type: "text", + marks: [{ type: "code_inline" }], + text: "--tools-dir", + }, + { type: "text", text: " arguments from the scripts" }, + ], + }, + ]; + + it("matches text containing inline code", () => { + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState: buildDocState(steps), + anchorText: "Remove `--tools-dir` arguments from the scripts", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe( + "Remove --tools-dir arguments from the scripts" + ); + }); + + it("matches text containing emphasis", () => { + const docState = buildDocState([ + { + type: "paragraph", + content: [ + { type: "text", text: "the " }, + { type: "text", marks: [{ type: "strong" }], text: "brown" }, + { type: "text", text: " fox" }, + ], + }, + ]); + + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "the **brown** fox", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe("the brown fox"); + }); + + it("matches text containing a link", () => { + const docState = buildDocState([ + { + type: "paragraph", + content: [ + { type: "text", text: "see " }, + { + type: "text", + marks: [{ type: "link", attrs: { href: "https://acme.com" } }], + text: "the docs", + }, + { type: "text", text: " for details" }, + ], + }, + ]); + + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "see [the docs](https://acme.com) for details", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe( + "see the docs for details" + ); + }); + + it("matches text including a heading marker", () => { + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState: buildDocState(steps), + anchorText: "## Implementation steps", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe("Implementation steps"); + }); + + it("matches text including a list marker", () => { + const docState = buildDocState([ + { + type: "bullet_list", + content: [ + { + type: "list_item", + content: [ + { + type: "paragraph", + content: [{ type: "text", text: "first item" }], + }, + ], + }, + ], + }, + ]); + + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "- first item", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe("first item"); + }); + + it("matches text that is wrapped over several lines", () => { + const docState = buildDocState([ + { + type: "paragraph", + content: [{ type: "text", text: "The quick brown fox jumps" }], + }, + ]); + + const result = ProsemirrorHelper.applyCommentMarkByText({ + docState, + anchorText: "The quick\n brown fox", + commentId: "comment-1", + userId: "user-1", + }); + + const marks = getCommentMarks(result!.state); + expect(marks.map((m) => m.text).join("")).toBe("The quick brown fox"); + }); + }); + describe("with anchorPrefix and anchorSuffix", () => { const fox = [ { diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index 1c3d4e7081..0514edcd71 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -1,6 +1,7 @@ import emojiRegex from "emoji-regex"; import type { JSDOM } from "jsdom"; import { chunk, isMatch } from "es-toolkit/compat"; +import ukkonen from "ukkonen"; import { EditorState, type Plugin } from "prosemirror-state"; import { DecorationSet, @@ -1222,6 +1223,9 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { * text equals `prefix` and immediately following text equals `suffix` is * used. Empty or omitted prefix/suffix imposes no constraint on that side. * + * Callers commonly take the text from the document's markdown, so when + * there is no match the text is converted from markdown and matched again. + * * @param params.docState The current Yjs document state. * @param params.anchorText The plain text substring to anchor the comment to. * @param params.commentId The comment identifier. @@ -1249,13 +1253,21 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { const yjsDoc = new Y.Doc(); Y.applyUpdate(yjsDoc, docState); const doc = Node.fromJSON(schema, yDocToProsemirrorJSON(yjsDoc, "default")); - const range = ProsemirrorHelper.findTextRange(doc, anchorText, { - prefix, - suffix, - }); + const text = ProsemirrorHelper.markdownToPlainText(anchorText); + const range = + ProsemirrorHelper.findTextRange(doc, anchorText, { prefix, suffix }) ?? + ProsemirrorHelper.findTextRange(doc, text, { + prefix: prefix && ProsemirrorHelper.markdownToPlainText(prefix), + suffix: suffix && ProsemirrorHelper.markdownToPlainText(suffix), + }); if (!range) { - throw ValidationError("anchorText was not found in the document"); + const closest = ProsemirrorHelper.findClosestText(doc, text); + throw ValidationError( + closest + ? `anchorText was not found in the document, the closest text is ${JSON.stringify(closest)}` + : "anchorText was not found in the document" + ); } try { @@ -1524,4 +1536,51 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { return { from, to }; } + + /** + * Converts markdown text to the plain text it represents, preserving any + * surrounding whitespace, which markdown parsing would otherwise discard. + */ + private static markdownToPlainText(text: string): string { + const leading = text.slice(0, text.length - text.trimStart().length); + const trailing = text.slice(text.trimEnd().length); + const doc = parser.parse(text.trim()); + + return doc + ? leading + textBetween(doc, 0, doc.content.size) + trailing + : text; + } + + /** + * Returns the block of the document's plain text that most closely + * resembles `needle`, or null if none resembles it closely enough. Used to + * point callers at a usable anchor when their text cannot be resolved. + */ + private static findClosestText(doc: Node, needle: string): string | null { + // Text this long is unlikely to be a single block, and comparing it is + // not worth the cost. + if (!needle.length || needle.length > 1000) { + return null; + } + + // At most half of the text may differ for a block to be a suggestion. + let limit = Math.floor(needle.length / 2); + let closest: string | null = null; + + for (const block of textBetween(doc, 0, doc.content.size).split("\n")) { + // Two strings differ by at least the difference in their lengths, so + // most blocks can be discarded without comparing them. + if (Math.abs(block.length - needle.length) > limit) { + continue; + } + + const distance = ukkonen(needle, block, limit + 1); + if (distance <= limit) { + limit = distance; + closest = block; + } + } + + return closest; + } }