diff --git a/shared/editor/lib/prosemirror-recreate-transform/applyOperation.test.ts b/shared/editor/lib/prosemirror-recreate-transform/applyOperation.test.ts new file mode 100644 index 0000000000..d3f3256f75 --- /dev/null +++ b/shared/editor/lib/prosemirror-recreate-transform/applyOperation.test.ts @@ -0,0 +1,56 @@ +import { applyPatch } from "@shared/utils/rfc6902"; +import { clone } from "@shared/utils/rfc6902/util"; +import { applyOperation } from "./applyOperation"; +import type { JSONObject } from "./types"; + +const doc = (): JSONObject => ({ + type: "doc", + content: [ + { + type: "paragraph", + attrs: { id: "a" }, + content: [{ type: "text", text: "first" }], + }, + { + type: "paragraph", + attrs: { id: "b" }, + content: [{ type: "text", text: "second" }], + }, + ], +}); + +describe("applyOperation", () => { + it.each([ + { op: "replace", path: "/content/0/content/0/text", value: "changed" }, + { op: "replace", path: "/content/1/attrs/id", value: "c" }, + { op: "add", path: "/content/1", value: { type: "paragraph" } }, + { op: "add", path: "/content/-", value: { type: "paragraph" } }, + { op: "remove", path: "/content/0" }, + { op: "move", from: "/content/0", path: "/content/1" }, + ] as const)("should match applyPatch for $op $path", (operation) => { + const original = doc(); + const expected = clone(original); + applyPatch(expected, [operation]); + + const result = applyOperation(original, operation); + + expect(result).toEqual(expected); + expect(original).toEqual(doc()); + }); + + it("should share the values that are not on the path", () => { + const original = doc(); + + const result = applyOperation(original, { + op: "replace", + path: "/content/0/content/0/text", + value: "changed", + }); + + const [first, second] = result.content as JSONObject[]; + const [originalFirst, originalSecond] = original.content as JSONObject[]; + expect(first).not.toBe(originalFirst); + expect(first.attrs).toBe(originalFirst.attrs); + expect(second).toBe(originalSecond); + }); +}); diff --git a/shared/editor/lib/prosemirror-recreate-transform/applyOperation.ts b/shared/editor/lib/prosemirror-recreate-transform/applyOperation.ts new file mode 100644 index 0000000000..e255a5849a --- /dev/null +++ b/shared/editor/lib/prosemirror-recreate-transform/applyOperation.ts @@ -0,0 +1,54 @@ +import type { Operation } from "@shared/utils/rfc6902"; +import { applyPatch } from "@shared/utils/rfc6902"; +import { Pointer } from "@shared/utils/rfc6902/pointer"; +import { clone, hasOwn } from "@shared/utils/rfc6902/util"; +import type { JSONObject, JSONValue } from "./types"; + +/** Keys that the JSON pointer evaluation skips, see `Pointer.evaluate`. */ +const skippedKeys = new Set(["__proto__", "constructor", "prototype"]); + +/** + * Applies a JSON patch operation without changing the given value. Only the + * containers on the path of the operation are copied, all other values are + * shared with the original. + * + * @param value the value to apply the operation to. + * @param operation the operation to apply. + * @returns the patched value. + */ +export function applyOperation( + value: JSONObject, + operation: Operation +): JSONObject { + const tokens = Pointer.fromJSON(operation.path).tokens; + + // Operations with a "from" path change a second location, so copy all. + if ("from" in operation || tokens.some((token) => skippedKeys.has(token))) { + const result = clone(value); + applyPatch(result, [operation]); + return result; + } + + const result = { ...value }; + let parent: JSONValue = result; + + // The last token is the key that the operation changes in its parent. + for (let i = 1; i < tokens.length - 1; i++) { + const key = tokens[i]; + if (typeof parent !== "object" || !hasOwn(parent, key)) { + break; + } + + const container = parent as Record; + const child = container[key]; + if (child === null || typeof child !== "object") { + break; + } + + container[key] = Array.isArray(child) ? [...child] : { ...child }; + parent = container[key]; + } + + applyPatch(result, [operation]); + return result; +} diff --git a/shared/editor/lib/prosemirror-recreate-transform/copy.ts b/shared/editor/lib/prosemirror-recreate-transform/copy.ts deleted file mode 100644 index f17b880c76..0000000000 --- a/shared/editor/lib/prosemirror-recreate-transform/copy.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function copy(value: T): T { - return JSON.parse(JSON.stringify(value)); -} diff --git a/shared/editor/lib/prosemirror-recreate-transform/recreateTransform.ts b/shared/editor/lib/prosemirror-recreate-transform/recreateTransform.ts index 5953e7d2ae..635db7e75d 100644 --- a/shared/editor/lib/prosemirror-recreate-transform/recreateTransform.ts +++ b/shared/editor/lib/prosemirror-recreate-transform/recreateTransform.ts @@ -3,8 +3,8 @@ import { diffWordsWithSpace, diffChars } from "diff"; import type { Node, Schema } from "prosemirror-model"; import { Transform } from "prosemirror-transform"; import type { Operation, ReplaceOperation } from "@shared/utils/rfc6902"; -import { applyPatch, createPatch } from "@shared/utils/rfc6902"; -import { copy } from "./copy"; +import { createPatch } from "@shared/utils/rfc6902"; +import { applyOperation } from "./applyOperation"; import { getFromPath } from "./getFromPath"; import { getReplaceStep } from "./getReplaceStep"; import { removeMarks } from "./removeMarks"; @@ -110,14 +110,14 @@ export class RecreateTransform { ops.push(op); let toDoc; - const afterStepJSON = copy(this.currentJSON); // working document receiving patches + let afterStepJSON = this.currentJSON; // working document receiving patches const pathParts = op.path.split("/"); // collect operations until we receive a valid document: // apply ops-patches until a valid prosemirror document is retrieved, // then try to create a transformation step or retry with next operation while (!toDoc) { - applyPatch(afterStepJSON, [op]); + afterStepJSON = applyOperation(afterStepJSON, op); try { toDoc = this.schema.nodeFromJSON(afterStepJSON); @@ -247,10 +247,8 @@ export class RecreateTransform { // We find the position number of the first character in the string const op1 = { ...op, value: "xx" }; const op2 = { ...op, value: "yy" }; - const afterOP1JSON = copy(this.currentJSON); - const afterOP2JSON = copy(this.currentJSON); - applyPatch(afterOP1JSON, [op1]); - applyPatch(afterOP2JSON, [op2]); + const afterOP1JSON = applyOperation(this.currentJSON, op1); + const afterOP2JSON = applyOperation(this.currentJSON, op2); const op1Doc = this.schema.nodeFromJSON(afterOP1JSON); const op2Doc = this.schema.nodeFromJSON(afterOP2JSON); diff --git a/shared/utils/rfc6902/diff.ts b/shared/utils/rfc6902/diff.ts index 633adc519a..4993bd7552 100644 --- a/shared/utils/rfc6902/diff.ts +++ b/shared/utils/rfc6902/diff.ts @@ -1,6 +1,5 @@ -import { isEqual } from "es-toolkit/compat"; import type { Pointer } from "./pointer"; -import { hasOwn, objectType } from "./util"; +import { hasOwn, isJSONEqual, objectType } from "./util"; /** * All diff* functions should return a list of operations, often empty. @@ -255,7 +254,7 @@ export function diffArrays( while ( start < input_length && start < output_length && - isEqual(input[start], output[start]) + isJSONEqual(input[start], output[start]) ) { start++; } @@ -264,7 +263,7 @@ export function diffArrays( let input_end = input_length; let output_end = output_length; while (input_end > start && output_end > start) { - if (isEqual(input[input_end - 1], output[output_end - 1])) { + if (isJSONEqual(input[input_end - 1], output[output_end - 1])) { input_end--; output_end--; } else { @@ -310,7 +309,7 @@ export function diffArrays( cost: memo[i][j - 1].cost + 1, }; } else { - if (isEqual(input[inputIdx], output[outputIdx])) { + if (isJSONEqual(input[inputIdx], output[outputIdx])) { memoized = memo[i - 1][j - 1]; } else { const remove_prev = memo[i - 1][j]; diff --git a/shared/utils/rfc6902/util.test.ts b/shared/utils/rfc6902/util.test.ts new file mode 100644 index 0000000000..b64d6d7e7b --- /dev/null +++ b/shared/utils/rfc6902/util.test.ts @@ -0,0 +1,39 @@ +import { isJSONEqual } from "./util"; + +describe("isJSONEqual", () => { + it("should compare primitives", () => { + expect(isJSONEqual("a", "a")).toBe(true); + expect(isJSONEqual(1, 1)).toBe(true); + expect(isJSONEqual(Number.NaN, Number.NaN)).toBe(true); + expect(isJSONEqual(null, null)).toBe(true); + expect(isJSONEqual("1", 1)).toBe(false); + expect(isJSONEqual(null, undefined)).toBe(false); + expect(isJSONEqual(null, {})).toBe(false); + }); + + it("should compare arrays", () => { + expect(isJSONEqual([1, [2, 3]], [1, [2, 3]])).toBe(true); + expect(isJSONEqual([1, 2], [2, 1])).toBe(false); + expect(isJSONEqual([1], [1, 2])).toBe(false); + expect(isJSONEqual([], {})).toBe(false); + expect(isJSONEqual({}, [])).toBe(false); + }); + + it("should compare objects regardless of key order", () => { + expect(isJSONEqual({ a: 1, b: { c: [1] } }, { b: { c: [1] }, a: 1 })).toBe( + true + ); + expect(isJSONEqual({ a: 1 }, { a: 2 })).toBe(false); + expect(isJSONEqual({ a: 1 }, { a: 1, b: 2 })).toBe(false); + expect(isJSONEqual({ a: undefined }, { b: undefined })).toBe(false); + }); + + it("should compare objects with a null prototype", () => { + const attrs = (level: number) => + Object.assign(Object.create(null) as Record, { level }); + + expect(isJSONEqual(attrs(1), attrs(1))).toBe(true); + expect(isJSONEqual(attrs(1), { level: 1 })).toBe(true); + expect(isJSONEqual(attrs(1), attrs(2))).toBe(false); + }); +}); diff --git a/shared/utils/rfc6902/util.ts b/shared/utils/rfc6902/util.ts index 9624f60f69..c4f08331f7 100644 --- a/shared/utils/rfc6902/util.ts +++ b/shared/utils/rfc6902/util.ts @@ -27,6 +27,54 @@ function isNonPrimitive(value: unknown): value is object { * @returns copy of source where every Array and Object have been recursively * reconstructed from their constituent elements. */ +/** + * Compares two JSON values for deep equality. This is faster than a generic + * deep equality check as it only handles the types that JSON can hold. Objects + * with a null prototype, such as ProseMirror attrs, are supported. + * + * @param a the first value. + * @param b the second value. + * @returns true if the values are deeply equal. + */ +export function isJSONEqual(a: unknown, b: unknown): boolean { + if (a === b) { + return true; + } + if (!isNonPrimitive(a) || !isNonPrimitive(b)) { + // NaN is equal to itself, as with isEqual. + return a !== a && b !== b; + } + + if (Array.isArray(a) || Array.isArray(b)) { + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!isJSONEqual(a[i], b[i])) { + return false; + } + } + return true; + } + + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) { + return false; + } + for (const key of keys) { + if ( + !hasOwn(b, key) || + !isJSONEqual( + (a as Record)[key], + (b as Record)[key] + ) + ) { + return false; + } + } + return true; +} + export function clone(source: T): T { if (!isNonPrimitive(source)) { // short-circuiting is faster than a single return