test-diff.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import ist from "ist"
  2. import {doc, p, em, strong, h1, h2} from "prosemirror-test-builder"
  3. import {Node} from "prosemirror-model"
  4. import {Span, Change, ChangeSet} from "prosemirror-changeset"
  5. const {computeDiff} = ChangeSet
  6. describe("computeDiff", () => {
  7. function test(doc1: Node, doc2: Node, ...ranges: number[][]) {
  8. let diff = computeDiff(doc1.content, doc2.content,
  9. new Change(0, doc1.content.size, 0, doc2.content.size,
  10. [new Span(doc1.content.size, 0)],
  11. [new Span(doc2.content.size, 0)]))
  12. ist(JSON.stringify(diff.map(r => [r.fromA, r.toA, r.fromB, r.toB])), JSON.stringify(ranges))
  13. }
  14. it("returns an empty diff for identical documents", () =>
  15. test(doc(p("foo"), p("bar")), doc(p("foo"), p("bar"))))
  16. it("finds single-letter changes", () =>
  17. test(doc(p("foo"), p("bar")), doc(p("foa"), p("bar")),
  18. [3, 4, 3, 4]))
  19. it("finds simple structure changes", () =>
  20. test(doc(p("foo"), p("bar")), doc(p("foobar")),
  21. [4, 6, 4, 4]))
  22. it("finds multiple changes", () =>
  23. test(doc(p("foo"), p("---bar")), doc(p("fgo"), p("---bur")),
  24. [2, 4, 2, 4], [10, 11, 10, 11]))
  25. it("ignores single-letter unchanged parts", () =>
  26. test(doc(p("abcdef")), doc(p("axydzf")), [2, 6, 2, 6]))
  27. it("ignores matching substrings in longer diffs", () =>
  28. test(doc(p("One two three")), doc(p("One"), p("And another long paragraph that has wo and ee in it")),
  29. [4, 14, 4, 57]))
  30. it("finds deletions", () =>
  31. test(doc(p("abc"), p("def")), doc(p("ac"), p("d")),
  32. [2, 3, 2, 2], [7, 9, 6, 6]))
  33. it("ignores marks", () =>
  34. test(doc(p("abc")), doc(p(em("a"), strong("bc")))))
  35. it("ignores marks in diffing", () =>
  36. test(doc(p("abcdefghi")), doc(p(em("x"), strong("bc"), "defgh", em("y"))),
  37. [1, 2, 1, 2], [9, 10, 9, 10]))
  38. it("ignores attributes", () =>
  39. test(doc(h1("x")), doc(h2("x"))))
  40. it("finds huge deletions", () => {
  41. let xs = "x".repeat(200), bs = "b".repeat(20)
  42. test(doc(p("a" + bs + "c")), doc(p("a" + xs + bs + xs + "c")),
  43. [2, 2, 2, 202], [22, 22, 222, 422])
  44. })
  45. it("finds huge insertions", () => {
  46. let xs = "x".repeat(200), bs = "b".repeat(20)
  47. test(doc(p("a" + xs + bs + xs + "c")), doc(p("a" + bs + "c")),
  48. [2, 202, 2, 2], [222, 422, 22, 22])
  49. })
  50. it("can handle ambiguous diffs", () =>
  51. test(doc(p("abcbcd")), doc(p("abcd")), [4, 6, 4, 4]))
  52. })