Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(revisions): diff rich text without htmldiff-js
Elian Doranbfe35a0a9a4b
diff --git a/apps/client/package.json b/apps/client/package.jsonindex f7b020867a..e943b650c0 100644--- a/apps/client/package.json+++ b/apps/client/package.json@@ -48,7 +48,6 @@"force-graph": "1.52.0","fullcalendar": "7.1.3","gridstack": "14.0.0",- "htmldiff-js": "1.0.5","i18next": "26.5.11","i18next-http-backend": "4.0.6","jquery": "4.0.0",diff --git a/apps/client/src/services/html_diff.spec.ts b/apps/client/src/services/html_diff.spec.tsnew file mode 100644index 0000000000..b55ef84a8d--- /dev/null+++ b/apps/client/src/services/html_diff.spec.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";++import { diffHtml } from "./html_diff";++describe("diffHtml", () => {+ it("returns identical content unchanged", () => {+ expect(diffHtml("<p>a b</p>", "<p>a b</p>")).toBe("<p>a b</p>");+ });++ it("marks a replaced, an inserted and a deleted word", () => {+ expect(diffHtml("<p>The quick brown fox</p>", "<p>The quick red fox</p>"))+ .toBe("<p>The quick <del class=\"diffmod\">brown</del><ins class=\"diffmod\">red</ins> fox</p>");+ expect(diffHtml("<p>one three</p>", "<p>one two three</p>"))+ .toBe("<p>one <ins class=\"diffins\">two </ins>three</p>");+ expect(diffHtml("<p>one two three</p>", "<p>one three</p>"))+ .toBe("<p>one <del class=\"diffdel\">two </del>three</p>");+ });++ it("keeps punctuation and entities out of the word they follow", () => {+ expect(diffHtml("<p>Hello, world.</p>", "<p>Hello, there.</p>"))+ .toBe("<p>Hello, <del class=\"diffmod\">world</del><ins class=\"diffmod\">there</ins>.</p>");+ expect(diffHtml("<p>Tom & Jerry</p>", "<p>Tom & Spike</p>"))+ .toBe("<p>Tom & <del class=\"diffmod\">Jerry</del><ins class=\"diffmod\">Spike</ins></p>");+ });++ it("ignores a changed attribute, but marks a changed image", () => {+ expect(diffHtml("<p><a href=\"1\">x</a></p>", "<p><a href=\"2\">x</a></p>"))+ .toBe("<p><a href=\"2\">x</a></p>");+ expect(diffHtml("<p><img src=\"a.png\"></p>", "<p><img src=\"b.png\"></p>"))+ .toBe("<p><del class=\"diffmod\"><img src=\"a.png\"></del><ins class=\"diffmod\"><img src=\"b.png\"></ins></p>");+ });++ it("marks the text of an added paragraph inside the paragraph's own markup", () => {+ expect(diffHtml("<p>a</p>", "<p>a</p><p>b</p>"))+ .toBe("<p>a</p><p><ins class=\"diffins\">b</ins></p>");+ expect(diffHtml("", "<p>x</p>")).toBe("<p><ins class=\"diffins\">x</ins></p>");+ });++ it("keeps the space a mark starts with visible", () => {+ expect(diffHtml("<p>a</p>", "<p>a b</p>")).toBe("<p>a<ins class=\"diffins\"> b</ins></p>");+ });++ it("keeps accented and non-Latin words whole", () => {+ expect(diffHtml("<p>Pijem čaj.</p>", "<p>Pijem čas.</p>"))+ .toBe("<p>Pijem <del class=\"diffmod\">čaj</del><ins class=\"diffmod\">čas</ins>.</p>");+ expect(diffHtml("<p>привет мир</p>", "<p>привет друг</p>"))+ .toBe("<p>привет <del class=\"diffmod\">мир</del><ins class=\"diffmod\">друг</ins></p>");+ });++ it("compares Chinese and Japanese text character by character", () => {+ expect(diffHtml("<p>我的笔记本</p>", "<p>我的电脑</p>"))+ .toBe("<p>我的<del class=\"diffmod\">笔记本</del><ins class=\"diffmod\">电脑</ins></p>");+ });++ it("shows a change of formatting as the new formatting, without marks", () => {+ expect(diffHtml("<p>foo bar</p>", "<p>foo <strong>bar</strong></p>"))+ .toBe("<p>foo <strong>bar</strong></p>");+ expect(diffHtml("<p>foo <strong>bar</strong></p>", "<p>foo bar</p>"))+ .toBe("<p>foo bar</p>");+ });+});diff --git a/apps/client/src/services/html_diff.ts b/apps/client/src/services/html_diff.tsnew file mode 100644index 0000000000..aec497ee65--- /dev/null+++ b/apps/client/src/services/html_diff.ts@@ -0,0 +1,186 @@+/**+ * Marks up the word-level difference between two HTML fragments: the new fragment, with each+ * deleted run of text in a `<del>` and each inserted one in an `<ins>`. A run that replaces another+ * gets the class `diffmod` on both marks, a plain insertion `diffins` and a plain deletion `diffdel`.+ *+ * It follows htmldiff (and its `htmldiff-js` port): the fragments are split into words, tags,+ * whitespace and punctuation, and aligned on the longest common run of those, then recursively on+ * the longest runs on either side of it. Aligning on long runs rather than on the shortest edit+ * keeps a reworded sentence readable, where a minimal diff would match every "a" and "the" in it.+ *+ * Tags are compared without their attributes, so a changed attribute alone is not marked; an+ * `<img>` counts as a word, attributes included, so a changed image is. A deleted formatting tag+ * (`<strong>`, `<em>`, …) is dropped from the output, which shows the formatting the new fragment+ * has.+ */+export function diffHtml(oldHtml: string, newHtml: string): string {+ if (oldHtml === newHtml) {+ return newHtml;+ }++ const oldTokens = tokenize(oldHtml);+ const newTokens = tokenize(newHtml);+ const matches = findMatchingRuns(oldTokens.map(toKey), newTokens.map(toKey));+ matches.push({ inOld: oldTokens.length, inNew: newTokens.length, size: 0 });++ const output: string[] = [];+ let positionInOld = 0;+ let positionInNew = 0;+ for (const match of matches) {+ const deleted = oldTokens.slice(positionInOld, match.inOld);+ const inserted = newTokens.slice(positionInNew, match.inNew);+ const isReplacement = deleted.length > 0 && inserted.length > 0;+ markRun(output, "del", isReplacement ? "diffmod" : "diffdel", deleted);+ markRun(output, "ins", isReplacement ? "diffmod" : "diffins", inserted);++ output.push(...newTokens.slice(match.inNew, match.inNew + match.size));+ positionInOld = match.inOld + match.size;+ positionInNew = match.inNew + match.size;+ }++ return output.join("");+}++/** A run of `size` tokens that starts at `inOld` in the old fragment and at `inNew` in the new one. */+interface Match {+ inOld: number;+ inNew: number;+ size: number;+}++/**+ * A tag, an entity, a run of whitespace, a word, or any other single character. Chinese and+ * Japanese characters are words of their own, since those scripts put no spaces between words.+ */+const TOKEN = /<[^>]*>?|&#?\w+;|\s+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[\p{L}\p{M}\p{N}_#@]+|./gsu;++/** The tags whose deletion changes only how the text looks. */+const FORMATTING_TAG = /^<\/?(strong|b|i|em|big|small|u|sub|sup|strike|s)[\s>/]/i;++/**+ * The longest run is first looked for in blocks of this many tokens and then of fewer, which+ * makes it cheaper to find in long fragments, whose single tokens repeat a lot.+ */+const MAX_BLOCK_SIZE = 4;++function tokenize(html: string) {+ return html.match(TOKEN) ?? [];+}++function isTag(token: string) {+ return token.startsWith("<") && !token.toLowerCase().startsWith("<img");+}++/** What a token is compared by: a tag without its attributes. */+function toKey(token: string) {+ if (!isTag(token)) {+ return token;+ }+ const name = /^<\/?[^\s>/]*/.exec(token)?.[0] ?? token;+ return name + (token.endsWith("/>") ? "/>" : ">");+}++/**+ * Wraps each run of text among `tokens` in `<mark class="cssClass">`, and leaves the tags between+ * them out of the marks, apart from the formatting tags of a deletion, which it drops.+ */+function markRun(output: string[], mark: "ins" | "del", cssClass: string, tokens: string[]) {+ let text: string[] = [];+ const flush = () => {+ if (text.length) {+ // A mark that starts with a space would show nothing where the space is.+ if (text[0] === " ") text[0] = " ";+ output.push(`<${mark} class="${cssClass}">${text.join("")}</${mark}>`);+ text = [];+ }+ };++ for (const token of tokens) {+ if (!isTag(token)) {+ text.push(token);+ continue;+ }++ flush();+ if (mark === "ins" || !FORMATTING_TAG.test(token)) {+ output.push(token);+ }+ }+ flush();+}++/** The runs the two fragments have in common, in order, found longest first. */+function findMatchingRuns(oldKeys: string[], newKeys: string[]) {+ const maxBlockSize = Math.min(MAX_BLOCK_SIZE, oldKeys.length, newKeys.length);+ const matches: Match[] = [];+ const ranges = [ { startInOld: 0, endInOld: oldKeys.length, startInNew: 0, endInNew: newKeys.length } ];++ for (let range = ranges.pop(); range; range = ranges.pop()) {+ const match = findLongestRun(oldKeys, newKeys, range, maxBlockSize);+ if (!match) continue;++ matches.push(match);+ if (range.startInOld < match.inOld && range.startInNew < match.inNew) {+ ranges.push({ ...range, endInOld: match.inOld, endInNew: match.inNew });+ }+ if (match.inOld + match.size < range.endInOld && match.inNew + match.size < range.endInNew) {+ ranges.push({ ...range, startInOld: match.inOld + match.size, startInNew: match.inNew + match.size });+ }+ }++ return matches.sort((a, b) => a.inOld - b.inOld);+}++interface Range {+ startInOld: number;+ endInOld: number;+ startInNew: number;+ endInNew: number;+}++function findLongestRun(oldKeys: string[], newKeys: string[], range: Range, maxBlockSize: number) {+ for (let blockSize = maxBlockSize; blockSize > 0; blockSize--) {+ const match = findLongestRunOfBlocks(oldKeys, newKeys, range, blockSize);+ if (match) return match;+ }+ return null;+}++/**+ * The longest run of consecutive common blocks of `blockSize` tokens, the earliest in the old+ * fragment and then in the new one among equally long runs.+ */+function findLongestRunOfBlocks(oldKeys: string[], newKeys: string[], range: Range, blockSize: number): Match | null {+ const blockKey = (keys: string[], end: number) => keys.slice(end - blockSize + 1, end + 1).join("\0");++ /** The positions in the new fragment at which each block ends. */+ const blockEndsInNew = new Map<string, number[]>();+ for (let index = range.startInNew + blockSize - 1; index < range.endInNew; index++) {+ const key = blockKey(newKeys, index);+ const ends = blockEndsInNew.get(key);+ if (ends) {+ ends.push(index);+ } else {+ blockEndsInNew.set(key, [ index ]);+ }+ }++ let best: Match | null = null;+ /** For each block end in the new fragment, the run of common blocks ending there. */+ let runLengths = new Map<number, number>();+ for (let indexInOld = range.startInOld + blockSize - 1; indexInOld < range.endInOld; indexInOld++) {+ const nextRunLengths = new Map<number, number>();+ for (const indexInNew of blockEndsInNew.get(blockKey(oldKeys, indexInOld)) ?? []) {+ const runLength = (runLengths.get(indexInNew - 1) ?? 0) + 1;+ nextRunLengths.set(indexInNew, runLength);++ const size = runLength + blockSize - 1;+ if (!best || size > best.size) {+ best = { inOld: indexInOld - size + 1, inNew: indexInNew - size + 1, size };+ }+ }+ runLengths = nextRunLengths;+ }++ return best;+}diff --git a/apps/client/src/types-lib.d.ts b/apps/client/src/types-lib.d.tsindex 7386254fe2..5f62103a5b 100644--- a/apps/client/src/types-lib.d.ts+++ b/apps/client/src/types-lib.d.ts@@ -1,12 +1,5 @@import type { HTMLAttributes } from "preact";-declare module "htmldiff-js" {- const HtmlDiff: {- execute(oldHtml: string, newHtml: string): string;- };- export default HtmlDiff;-}-// TODO: Use real @types/ but that one generates a lot of errors.declare module "draggabilly" {type DraggabillyEventData = {};diff --git a/apps/client/src/widgets/dialogs/revisions.css b/apps/client/src/widgets/dialogs/revisions.cssindex cb4c1c341a..7628aeed47 100644--- a/apps/client/src/widgets/dialogs/revisions.css+++ b/apps/client/src/widgets/dialogs/revisions.css@@ -219,7 +219,7 @@ body.desktop .revisions-dialog {padding: 0;}- /* HTML diff styles (htmldiff-js) */+ /* The `ins`/`del` marks of `diffHtml()` */.revision-diff-content {ins {text-decoration: none;diff --git a/apps/client/src/widgets/dialogs/revisions.spec.tsx b/apps/client/src/widgets/dialogs/revisions.spec.tsxindex 04acfe194b..5362a0f18e 100644--- a/apps/client/src/widgets/dialogs/revisions.spec.tsx+++ b/apps/client/src/widgets/dialogs/revisions.spec.tsx@@ -4,9 +4,9 @@* elements carrying metadata. Rendering the stored HTML on its own therefore shows less than the* note does, and in the case of a link preview shows nothing at all (#10707).*/-import HtmlDiff from "htmldiff-js";import { describe, expect, it, vi } from "vitest";+import { diffHtml } from "../../services/html_diff";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import { RevisionContentDiff, RevisionContentText, seedLinkPreviewTitles } from "./revisions";@@ -157,12 +157,12 @@ describe("seedLinkPreviewTitles", () => {const withPreview = seedLinkPreviewTitles(`<p>x</p><p>${mention}</p>`);const without = seedLinkPreviewTitles("<p>x</p>");- const added = HtmlDiff.execute(without, withPreview);- const removed = HtmlDiff.execute(withPreview, without);+ const added = diffHtml(without ?? "", withPreview ?? "");+ const removed = diffHtml(withPreview ?? "", without ?? "");expect(added).toContain("diffins");expect(removed).toContain("diffdel");- // Unseeded, htmldiff-js emits these two byte-identical: the empty element carries no word+ // Unseeded, `diffHtml()` emits these two byte-identical: the empty element carries no word// for it to compare, so neither direction produces a marker at all.expect(added).not.toBe(removed);});diff --git a/apps/client/src/widgets/dialogs/revisions.tsx b/apps/client/src/widgets/dialogs/revisions.tsxindex 2ab2a1b360..ce6c520f00 100644--- a/apps/client/src/widgets/dialogs/revisions.tsx+++ b/apps/client/src/widgets/dialogs/revisions.tsx@@ -6,7 +6,6 @@ import {import { dayjs, type RevisionItem, type RevisionPojo, safeHostname, safeLinkPreviewHref } from "@triliumnext/commons";import clsx from "clsx";import { diffWords } from "diff";-import HtmlDiff from "htmldiff-js";import { type CSSProperties, Fragment } from "preact";import { Dispatch, StateUpdater, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";@@ -14,6 +13,7 @@ import appContext from "../../components/app_context";import FNote from "../../entities/fnote";import dialog from "../../services/dialog";import froca from "../../services/froca";+import { diffHtml } from "../../services/html_diff";import { t } from "../../services/i18n";import { applyLinkEmbeds } from "../../services/link_embed";import open from "../../services/open";@@ -727,14 +727,17 @@ export function RevisionContentDiff({ noteContent, itemContent, itemType }: {);}- let diffHtml: string;+ let html: string;if (itemType === "text") {// Use proper HTML-aware diff for rich text content- diffHtml = HtmlDiff.execute(seedLinkPreviewTitles(noteContent), seedLinkPreviewTitles(itemContent));+ html = diffHtml(+ seedLinkPreviewTitles(noteContent) ?? "",+ seedLinkPreviewTitles(itemContent) ?? ""+ );} else {// Use word diff for code/mermaid (plain text)const diff = diffWords(noteContent ?? "", itemContent);- diffHtml = diff.map(part => {+ html = diff.map(part => {if (part.added) {return `<span class="revision-diff-added">${utils.escapeHtml(part.value)}</span>`;} else if (part.removed) {@@ -745,14 +748,14 @@ export function RevisionContentDiff({ noteContent, itemContent, itemType }: {}// Diff returned no results, meaning that they are identical.- if (!diffHtml) {+ if (!html) {return <NoItems className="revision-diff-content" icon="bx bx-copy" text={t("revisions.diff_identical")} />;}return <SanitizedHtmlcontainerRef={contentRef}className={clsx("revision-diff-content", itemType === "text" ? "ck-content" : "revision-diff-code")}- html={diffHtml}+ html={html}/>;}@@ -760,7 +763,7 @@ export function RevisionContentDiff({ noteContent, itemContent, itemType }: {* Fills every link preview with a real link carrying the title it displays, so that the differ can* see it and the reader gets something they recognise as a link.*- * htmldiff-js diffs words, and a link preview holds none: it is stored as an empty+ * `diffHtml()` diffs words, and a link preview holds none: it is stored as an empty* `<span class="link-mention">` / `<section class="link-embed">` carrying its metadata in data* attributes, which only the note view turns into a card. Left alone the differ emits the element* unmarked whether it was added or removed, so a revision that gained a link and one that lost itdiff --git a/apps/client/src/widgets/type_widgets/text/ai_diff.ts b/apps/client/src/widgets/type_widgets/text/ai_diff.tsindex 6beabb083b..54a5781f8d 100644--- a/apps/client/src/widgets/type_widgets/text/ai_diff.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.ts@@ -1,12 +1,13 @@import type { AiDiffResult } from "@triliumnext/ckeditor5";import { diffArrays } from "diff";-import HtmlDiff from "htmldiff-js";++import { diffHtml } from "../../../services/html_diff";/*** The "Changes" view of the AI assistant's review: the response marked up against the content it* would replace.*- * A word-level HTML diff — `htmldiff-js` on the two fragments, which is what the revisions dialog+ * A word-level HTML diff — `diffHtml()` on the two fragments, which is what the revisions dialog* shows — is the right tool only while both sides are recognisably the same text. It aligns on the* longest common runs of words, so a corrected typo or a tightened sentence comes out as a precise* mark on an otherwise readable paragraph. Give it a translation, or any rewrite that keeps the@@ -32,7 +33,7 @@ export default function diffAiResponse(oldHtml: string, newHtml: string): AiDiff// Nothing to align against, so the whole of whichever side exists is the change.if (!oldBlocks.length || !newBlocks.length) {- return { html: HtmlDiff.execute(oldHtml, newHtml), rewriteRatio: 1 };+ return { html: diffHtml(oldHtml, newHtml), rewriteRatio: 1 };}const chunks: string[] = [];@@ -249,12 +250,12 @@ function kindOf(block: Block): string {** Only what the blocks hold is diffed. The containers are rarely identical even when the block is* the same one — the captured selection may have none at all, and a rewrapped paragraph carries- * different attributes — and handing two markup streams to `htmldiff-js` is what makes it emit+ * different attributes — and handing two markup streams to `diffHtml()` is what makes it emit* tags that close in the wrong order, leaving the preview's parser to rebuild the result in* whatever shape it likes.*/function diffInside(before: Block, after: Block): string | null {- const diffed = HtmlDiff.execute(before.inner, after.inner);+ const diffed = diffHtml(before.inner, after.inner);return markedRatio(before, after, diffed) > INLINE_DIFF_CHURN_LIMIT ? null : wrap(after, diffed);}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 2e6fc4c705..22343d7a17 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -127,9 +127,10 @@ export interface AiDiffResult {/*** Renders an inline HTML diff between two HTML fragments, returning HTML in which insertions and- * deletions are marked with `<ins>`/`<del>` elements (the `htmldiff-js` output convention, the- * same mechanism Trilium's revision dialog uses). Returning an {@link AiDiffResult} instead of a- * bare string lets the renderer also say how much of the response it could not align.+ * deletions are marked with `<ins>`/`<del>` elements (the output convention of the client's+ * `diffHtml()`, the same mechanism Trilium's revision dialog uses). Returning an+ * {@link AiDiffResult} instead of a bare string lets the renderer also say how much of the+ * response it could not align.*/export type AiDiffFunction = (oldHtml: string, newHtml: string) => string | AiDiffResult;diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.cssindex 74df1b7bba..f3c4353513 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css@@ -194,9 +194,10 @@white-space: nowrap;}-/* The inline diff shown by the "Changes" view (htmldiff-js `ins`/`del` markup, the same- convention the revisions dialog styles). Colors are self-contained rather than borrowing the- client's Bootstrap variables, so the plugin package stays host-agnostic. */+/* The inline diff shown by the "Changes" view (`ins`/`del` markup from the client's+ `diffHtml()`, the same convention the revisions dialog styles). Colors are self-contained+ rather than borrowing the client's Bootstrap variables, so the plugin package stays+ host-agnostic. */.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins {text-decoration: none;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d828f81545..896212f819 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -288,9 +288,6 @@ importers:gridstack:specifier: 14.0.0version: 14.0.0- htmldiff-js:- specifier: 1.0.5- version: 1.0.5i18next:specifier: 26.5.11version: 26.5.11([email protected])@@ -7969,9 +7966,6 @@ packages:resolution: {integrity: sha512-lw/7YsdKiP3kk5PnR1INY17iJuzdAtJewxr14ozKJWbbR97znovZ0mh+WEMZ8rjc3lgTK+ID/htTjuyGKB52Kw==}hasBin: true- resolution: {integrity: sha512-rmow9353OK0elkub15Sbze8Nj7BYfduqoJJw4yEvHHjOcHeCazNPk0PoUbjE8SvxKgjymeRIFU/OnS8jtitRtA==}-resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}@@ -19961,8 +19955,6 @@ snapshots:dependencies:concat-stream: 1.6.2- [email protected]: {}-dependencies:domelementtype: 2.3.0