Precise DOM morphing
morphing typescript dom

Whitespace test

+68
+68
test/new/whitespace.browser.test.ts
··· 1 + import { test, expect } from "vitest" 2 + import { morph } from "../../src/morphlex" 3 + import { dom } from "./utils" 4 + 5 + test("whitespace is removed when target has no whitespace", () => { 6 + const from = dom(`<div><span>A</span> <span>B</span> <span>C</span></div>`) 7 + const to = dom(`<div><span>A</span><span>B</span><span>C</span></div>`) 8 + 9 + // Verify initial state 10 + expect(from.childNodes.length).toBe(5) // SPAN, TEXT, SPAN, TEXT, SPAN 11 + expect(to.childNodes.length).toBe(3) // SPAN, SPAN, SPAN 12 + 13 + morph(from, to) 14 + 15 + // After morph, from should have no whitespace like to 16 + expect(from.childNodes.length).toBe(3) 17 + expect(from.childNodes[0]?.nodeName).toBe("SPAN") 18 + expect(from.childNodes[1]?.nodeName).toBe("SPAN") 19 + expect(from.childNodes[2]?.nodeName).toBe("SPAN") 20 + }) 21 + 22 + test("whitespace is added when target has whitespace", () => { 23 + const from = dom(`<div><span>A</span><span>B</span><span>C</span></div>`) 24 + const to = dom(`<div><span>A</span> <span>B</span> <span>C</span></div>`) 25 + 26 + // Verify initial state 27 + expect(from.childNodes.length).toBe(3) // SPAN, SPAN, SPAN 28 + expect(to.childNodes.length).toBe(5) // SPAN, TEXT, SPAN, TEXT, SPAN 29 + 30 + morph(from, to) 31 + 32 + // After morph, from should have whitespace like to 33 + expect(from.childNodes.length).toBe(5) 34 + expect(from.childNodes[0]?.nodeName).toBe("SPAN") 35 + expect(from.childNodes[1]?.nodeType).toBe(3) // TEXT_NODE 36 + expect(from.childNodes[1]?.textContent).toBe(" ") 37 + expect(from.childNodes[2]?.nodeName).toBe("SPAN") 38 + expect(from.childNodes[3]?.nodeType).toBe(3) // TEXT_NODE 39 + expect(from.childNodes[3]?.textContent).toBe(" ") 40 + expect(from.childNodes[4]?.nodeName).toBe("SPAN") 41 + }) 42 + 43 + test("whitespace is reused when both have whitespace", () => { 44 + const from = dom(`<div><span>A</span> <span>B</span> <span>C</span></div>`) 45 + const to = dom(`<div><span>A</span> <span>B</span> <span>C</span></div>`) 46 + 47 + // Verify initial state 48 + expect(from.childNodes.length).toBe(5) 49 + expect(to.childNodes.length).toBe(5) 50 + 51 + // Capture the original text nodes from 'from' 52 + const originalTextNode1 = from.childNodes[1] 53 + const originalTextNode2 = from.childNodes[3] 54 + 55 + morph(from, to) 56 + 57 + // After morph, structure should be the same 58 + expect(from.childNodes.length).toBe(5) 59 + expect(from.childNodes[0]?.nodeName).toBe("SPAN") 60 + expect(from.childNodes[1]?.nodeType).toBe(3) 61 + expect(from.childNodes[2]?.nodeName).toBe("SPAN") 62 + expect(from.childNodes[3]?.nodeType).toBe(3) 63 + expect(from.childNodes[4]?.nodeName).toBe("SPAN") 64 + 65 + // The original text nodes should be reused 66 + expect(from.childNodes[1]).toBe(originalTextNode1) 67 + expect(from.childNodes[3]).toBe(originalTextNode2) 68 + })