Modern Apps git

← Modern-Apps.git

office: tree CRDT merges element attributes (LWW per element, keeps text) + O(children) render via parent index; remove dead codecs/DocumentCrdt

Commit
fcc05ea59b6610dcbad5c6a0dcb26b2584ff070a
Author
Vayun Mathur <[email protected]>
When
2026-07-06 21:34 UTC (5 months ago)
Parents
01d6474

Diff

office/src/main/java/com/vayunmathur/office/util/DocumentCrdt.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/DocumentCrdt.kt b/office/src/main/java/com/vayunmathur/office/util/DocumentCrdt.ktdeleted file mode 100644index 59d51976b7..0000000000--- a/office/src/main/java/com/vayunmathur/office/util/DocumentCrdt.kt+++ /dev/null@@ -1,186 +0,0 @@-package com.vayunmathur.office.util--import kotlinx.serialization.Serializable--/**- * A convergent, operation-based sequence CRDT used to merge concurrent edits to a document without- * a central authority and without last-writer-wins clobbering.- *- * The document is represented as an ordered sequence of opaque **lines** (we split the serialized- * flat-ODF at tag boundaries, so each element/paragraph is roughly one line — see [OfficeCrdtCodec]).- * Each line is an RGA element with a globally-unique id `(lamport, device)` and an `origin` (the id- * of the element it was inserted after). Deletions are tombstones. Merging is:- *   - **element set union** by id (idempotent),- *   - **deletion is monotonic** (a tombstone, once set, stays — delete wins),- *   - **ordering** via RGA linearization (children of the same origin ordered by id descending),- * which is commutative and associative, so all replicas that have seen the same ops converge to the- * same sequence regardless of arrival order.- *- * Editing is snapshot-driven: [update] diffs the CRDT's current rendered lines against a new set of- * lines (LCS) and emits the insert/delete ops needed, mutating the state. Concurrent edits to the- * *same* line are preserved as two lines (no data loss) rather than one silently winning.- */-class DocumentCrdt(-    val device: String,-    var clock: Long = 0,-    private val elements: LinkedHashMap<String, CrdtElement> = LinkedHashMap(),-) {-    @Serializable-    data class CrdtElement(-        val lamport: Long,-        val device: String,-        val originLamport: Long, // -1 => head-        val originDevice: String, // "" => head-        var content: String,-        var deleted: Boolean = false,-    )--    @Serializable-    data class State(val device: String, val clock: Long, val elements: List<CrdtElement>)--    private fun key(lamport: Long, dev: String) = "$lamport:$dev"--    fun toState(): State = State(device, clock, elements.values.map { it.copy() })--    /** Merges a batch of remote ops (elements) into this replica. Commutative + idempotent. */-    fun apply(ops: List<CrdtElement>) {-        for (op in ops) {-            clock = maxOf(clock, op.lamport)-            val k = key(op.lamport, op.device)-            val cur = elements[k]-            if (cur == null) {-                elements[k] = op.copy()-            } else {-                // Same element id: deletion is monotonic; content is immutable per id in our diff-                // model (edits are delete+insert), so we only ever need to OR the tombstone.-                if (op.deleted) cur.deleted = true-            }-        }-    }--    /** RGA linearization of all elements (including tombstones), in convergent order. */-    private fun linearize(): List<CrdtElement> {-        val children = HashMap<String, MutableList<CrdtElement>>()-        for (e in elements.values) {-            val ok = if (e.originLamport < 0) HEAD else key(e.originLamport, e.originDevice)-            children.getOrPut(ok) { mutableListOf() }.add(e)-        }-        // Concurrent inserts after the same origin: higher id first (RGA tie-break) — deterministic.-        val cmp = compareByDescending<CrdtElement> { it.lamport }.thenByDescending { it.device }-        for (l in children.values) l.sortWith(cmp)-        val result = ArrayList<CrdtElement>(elements.size)-        // Iterative pre-order DFS to avoid deep recursion on large documents.-        val stack = ArrayDeque<CrdtElement>()-        children[HEAD]?.asReversed()?.forEach { stack.addLast(it) }-        while (stack.isNotEmpty()) {-            val e = stack.removeLast()-            result.add(e)-            children[key(e.lamport, e.device)]?.asReversed()?.forEach { stack.addLast(it) }-        }-        return result-    }--    /** The current merged document as an ordered list of live (non-deleted) lines. */-    fun render(): List<String> = linearize().filter { !it.deleted }.map { it.content }--    /**-     * Diffs the current rendered lines against [newLines] and produces the ops that transform one-     * into the other, applying them to this replica. Returns the ops to broadcast (may be empty).-     */-    fun update(newLines: List<String>): List<CrdtElement> {-        val live = linearize().filter { !it.deleted }-        val oldLines = live.map { it.content }-        val n = oldLines.size-        val m = newLines.size--        // Trim the common prefix/suffix so the (expensive) LCS runs only over the changed middle.-        // This makes a typical single-character edit O(1)-ish instead of O(n*m).-        var pre = 0-        while (pre < n && pre < m && oldLines[pre] == newLines[pre]) pre++-        var suf = 0-        while (suf < (n - pre) && suf < (m - pre) && oldLines[n - 1 - suf] == newLines[m - 1 - suf]) suf++--        val oldMid = oldLines.subList(pre, n - suf)-        val newMid = newLines.subList(pre, m - suf)-        val a = oldMid.size-        val b = newMid.size--        // LCS over the middle only.-        val dp = Array(a + 1) { IntArray(b + 1) }-        for (i in a - 1 downTo 0) {-            for (j in b - 1 downTo 0) {-                dp[i][j] = if (oldMid[i] == newMid[j]) dp[i + 1][j + 1] + 1-                else maxOf(dp[i + 1][j], dp[i][j + 1])-            }-        }-        val newMidToOldMid = HashMap<Int, Int>()-        run {-            var i = 0; var j = 0-            while (i < a && j < b) {-                when {-                    oldMid[i] == newMid[j] -> { newMidToOldMid[j] = i; i++; j++ }-                    dp[i + 1][j] >= dp[i][j + 1] -> i++-                    else -> j++-                }-            }-        }-        val matchedOldMid = newMidToOldMid.values.toHashSet()--        val ops = ArrayList<CrdtElement>()-        // Deletions: middle old lines not matched become tombstones (prefix/suffix are untouched).-        for (idx in oldMid.indices) {-            if (idx !in matchedOldMid) {-                val e = live[pre + idx]-                if (!e.deleted) {-                    e.deleted = true-                    ops.add(e.copy())-                }-            }-        }-        // Insertions: walk the new middle; inserts chain after the running "left" element, which-        // starts at the last prefix element (or head).-        var leftLamport = if (pre > 0) live[pre - 1].lamport else -1L-        var leftDevice = if (pre > 0) live[pre - 1].device else ""-        for (nj in newMid.indices) {-            val oIdx = newMidToOldMid[nj]-            if (oIdx != null) {-                val e = live[pre + oIdx]-                leftLamport = e.lamport; leftDevice = e.device-            } else {-                clock++-                val e = CrdtElement(-                    lamport = clock, device = device,-                    originLamport = if (leftLamport < 0) -1 else leftLamport,-                    originDevice = leftDevice,-                    content = newMid[nj],-                )-                elements[key(clock, device)] = e-                ops.add(e.copy())-                leftLamport = clock; leftDevice = device-            }-        }-        return ops-    }--    companion object {-        private const val HEAD = "HEAD"--        fun fromState(state: State): DocumentCrdt {-            val map = LinkedHashMap<String, CrdtElement>()-            for (e in state.elements) map["${e.lamport}:${e.device}"] = e.copy()-            return DocumentCrdt(state.device, state.clock, map)-        }-    }-}--/**- * Splits/joins the serialized flat-ODF document into CRDT "lines". The serializer emits the whole- * document with essentially no newlines, so we split at adjacent-tag boundaries (`><`), which puts- * each element/paragraph on its own line. Joining is exact and lossless (we only ever split at- * boundaries we introduced), so non-conflicting concurrent edits recombine into valid flat-ODF.- */-object OfficeCrdtCodec {-    private const val SEP = "\u0001"-    fun toLines(flatOdf: String): List<String> = flatOdf.replace("><", ">$SEP<").split(SEP)-    fun fromLines(lines: List<String>): String = lines.joinToString("")-}
office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt b/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.ktindex 2da0dfe953..6b1b90cbe6 100644--- a/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt+++ b/office/src/main/java/com/vayunmathur/office/util/DocumentTreeCrdt.kt@@ -4,15 +4,14 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json  /**- * A hierarchical (tree) CRDT over a flat-ODF XML document. Unlike the flat sequence CRDT, every- * character/element is a **node with a parent**, so deleting an element deletes its whole subtree —- * including characters a peer inserted into it concurrently. This eliminates the "stranded text"- * edge of char-merging serialized markup while still merging text within a node at character level.+ * A hierarchical (tree) CRDT over a flat-ODF XML document. Every character/element is a **node with a+ * parent**, so deleting an element deletes its whole subtree — including characters a peer inserted+ * into it concurrently. Text within a node merges at character level (RGA among sibling char nodes),+ * and an element's **attributes merge by last-writer-wins** (elements keep identity across attribute+ * edits, so concurrent formatting changes never drop the element or its text).  *- * Model: each node has an id `lamport:device`, a `parent` id, a `left` sibling id (RGA order), a- * [kind] ("e" element, "s" self-closing element, "c" character, "r" raw/opaque run) and a [payload]- * (the open tag, the char, or the raw text). Rendering is a DFS that skips deleted nodes and never- * descends into a deleted element, so a deletion cascades automatically.+ * Node kinds: "e" element (has children; [payload] is the open tag, [name] the tag name), "s" opaque+ * leaf (self-closing element / `<?xml?>` / comment / doctype), "c" character, "r" raw run (base64).  */ class DocumentTreeCrdt(private val device: String) { @@ -21,40 +20,54 @@ class DocumentTreeCrdt(private val device: String) {         val id: String,         val parent: String,         val left: String,-        val kind: String,        // "e" | "s" | "c" | "r"-        val payload: String,+        val kind: String,+        var payload: String,         var deleted: Boolean = false,         val lamport: Long,         val dev: String,+        val name: String = "",      // element tag name (kind "e"); used for identity across attr edits+        var attrLamport: Long = 0,  // LWW clock for attribute (payload) updates on elements+        var attrDev: String = "",   // device of the last attribute write (LWW tie-break)     )      @Serializable     data class State(val device: String, val clock: Long, val nodes: List<Node>)      private val nodes = LinkedHashMap<String, Node>()+    private val childrenByParent = HashMap<String, MutableList<Node>>() // parent id -> children (incl. tombstones)     private var clock = 0L     private val json = Json { ignoreUnknownKeys = true }      fun toState(): State = State(device, clock, nodes.values.map { it.copy() }) -    fun loadState(json: String) {-        val s = runCatching { this.json.decodeFromString<State>(json) }.getOrNull() ?: return-        nodes.clear(); s.nodes.forEach { nodes[it.id] = it.copy() }; clock = s.clock+    fun loadState(jsonStr: String) {+        val s = runCatching { json.decodeFromString<State>(jsonStr) }.getOrNull() ?: return+        nodes.clear(); childrenByParent.clear()+        for (n in s.nodes) { val c = n.copy(); nodes[c.id] = c; childrenByParent.getOrPut(c.parent) { ArrayList() }.add(c) }+        clock = s.clock     }      fun serialize(): String = json.encodeToString(toState()) -    /** Merges a batch of remote node ops. Commutative + idempotent; deletion is monotonic. */+    private fun index(node: Node) { childrenByParent.getOrPut(node.parent) { ArrayList() }.add(node) }++    /** Merges a batch of remote node ops. Commutative + idempotent; deletion + attrs are monotonic. */     fun apply(ops: List<Node>) {         for (op in ops) {-            clock = maxOf(clock, op.lamport)+            clock = maxOf(clock, maxOf(op.lamport, op.attrLamport))             val cur = nodes[op.id]-            if (cur == null) nodes[op.id] = op.copy()-            else if (op.deleted) cur.deleted = true+            if (cur == null) { val c = op.copy(); nodes[c.id] = c; index(c) }+            else {+                if (op.deleted) cur.deleted = true+                // Attribute LWW: the write with the higher lamport wins (device breaks ties).+                if (op.kind == "e" && (op.attrLamport > cur.attrLamport ||+                        (op.attrLamport == cur.attrLamport && op.attrDev > cur.attrDev))) {+                    cur.payload = op.payload; cur.attrLamport = op.attrLamport; cur.attrDev = op.attrDev+                }+            }         }     } -    /** Renders the current merged document back to flat XML. */     fun render(): String {         val sb = StringBuilder()         renderChildren("", sb)@@ -66,19 +79,19 @@ class DocumentTreeCrdt(private val device: String) {             if (node.deleted) continue // skip deleted node + its subtree (never descend)             when (node.kind) {                 "e" -> { sb.append(node.payload); renderChildren(node.id, sb); sb.append(closeTagOf(node.payload)) }-                else -> sb.append(node.payload) // "s", "c", "r"+                else -> sb.append(node.payload)             }         }     } -    /** RGA order of a parent's children, INCLUDING tombstones (needed to chain `left` links). */+    /** RGA order of a parent's children (incl. tombstones, needed to chain `left`). O(children). */     private fun orderedChildren(parent: String): List<Node> {+        val kids = childrenByParent[parent] ?: return emptyList()         val byLeft = HashMap<String, MutableList<Node>>()-        for (n in nodes.values) if (n.parent == parent) byLeft.getOrPut(n.left) { mutableListOf() }.add(n)-        if (byLeft.isEmpty()) return emptyList()+        for (n in kids) byLeft.getOrPut(n.left) { mutableListOf() }.add(n)         val cmp = compareByDescending<Node> { it.lamport }.thenByDescending { it.dev }         for (l in byLeft.values) l.sortWith(cmp)-        val result = ArrayList<Node>()+        val result = ArrayList<Node>(kids.size)         val stack = ArrayDeque<Node>()         byLeft[""]?.asReversed()?.forEach { stack.addLast(it) }         while (stack.isNotEmpty()) {@@ -91,7 +104,6 @@ class DocumentTreeCrdt(private val device: String) {      // --- Reconcile the current tree toward a new flat-XML state, producing ops --- -    /** Diffs [xml] against the current tree, mutating this replica and returning ops to broadcast. */     fun update(xml: String): List<Node> {         val ops = ArrayList<Node>()         diffChildren("", parse(xml).children, ops)@@ -101,18 +113,17 @@ class DocumentTreeCrdt(private val device: String) {     private fun newId(): String { clock += 1; return "$clock:$device" }      private fun keyOfDesired(d: Desired): String = when (d) {-        is Desired.El -> (if (d.selfClosing) "s:" else "e:") + d.tag+        is Desired.El -> if (d.selfClosing) "s:" + d.tag else "e:" + nameOf(d.tag)         is Desired.Text -> (if (d.raw) "r:" else "c:") + d.text     } -    private fun keyOfNode(n: Node): String = n.kind + ":" + n.payload+    private fun keyOfNode(n: Node): String = if (n.kind == "e") "e:" + n.name else n.kind + ":" + n.payload      private fun diffChildren(parent: String, desired: List<Desired>, ops: MutableList<Node>) {-        val current = orderedChildren(parent).filter { !it.deleted }+        val current = (childrenByParent[parent]?.let { orderedChildren(parent) } ?: emptyList()).filter { !it.deleted }         val keyC = current.map { keyOfNode(it) }         val keyD = desired.map { keyOfDesired(it) } -        // Common prefix / suffix are matched directly (keeps typing O(changed), not O(n^2)).         var pre = 0         while (pre < current.size && pre < desired.size && keyC[pre] == keyD[pre]) pre++         var suf = 0@@ -121,22 +132,27 @@ class DocumentTreeCrdt(private val device: String) {          var prevId = ""         fun reuse(node: Node, d: Desired) {-            if (d is Desired.El && node.kind == "e") diffChildren(node.id, d.children, ops)+            if (d is Desired.El && node.kind == "e") {+                if (node.payload != d.tag) { // attributes changed → LWW update, identity kept+                    node.payload = d.tag; node.attrLamport = ++clock; node.attrDev = device+                    ops.add(node.copy())+                }+                if (!d.selfClosing) diffChildren(node.id, d.children, ops)+            }             prevId = node.id         }         fun insert(d: Desired) {             val id = newId()             val kind = when (d) { is Desired.El -> if (d.selfClosing) "s" else "e"; is Desired.Text -> if (d.raw) "r" else "c" }             val payload = when (d) { is Desired.El -> d.tag; is Desired.Text -> d.text }-            val node = Node(id, parent, prevId, kind, payload, false, clock, device)-            nodes[id] = node; ops.add(node.copy())+            val name = if (d is Desired.El && !d.selfClosing) nameOf(d.tag) else ""+            val node = Node(id, parent, prevId, kind, payload, false, clock, device, name, if (kind == "e") clock else 0, if (kind == "e") device else "")+            nodes[id] = node; index(node); ops.add(node.copy())             if (d is Desired.El && !d.selfClosing) diffChildren(id, d.children, ops)             prevId = id         } -        // prefix         for (i in 0 until pre) reuse(current[i], desired[i])-        // middle via LCS         val midC = current.subList(pre, current.size - suf)         val midD = desired.subList(pre, desired.size - suf)         val pairs = lcs(midD.map { keyOfDesired(it) }, midC.map { keyOfNode(it) })@@ -149,19 +165,10 @@ class DocumentTreeCrdt(private val device: String) {                 reuse(midC[ci], midD[di])             } else insert(midD[di])         }-        for (ci in midC.indices) if (ci !in matchedC) tombstone(midC[ci], ops)-        // suffix+        for (ci in midC.indices) if (ci !in matchedC && !midC[ci].deleted) { midC[ci].deleted = true; ops.add(midC[ci].copy(deleted = true)) }         for (i in 0 until suf) reuse(current[current.size - suf + i], desired[desired.size - suf + i])     } -    private fun tombstone(node: Node, ops: MutableList<Node>) {-        if (node.deleted) return-        node.deleted = true-        ops.add(node.copy(deleted = true))-        // Children cascade at render time; no need to tombstone them individually.-    }--    /** Longest common subsequence of two key lists → matched (indexInA, indexInB) pairs, in order. */     private fun lcs(a: List<String>, b: List<String>): List<Pair<Int, Int>> {         val n = a.size; val m = b.size         if (n == 0 || m == 0) return emptyList()@@ -208,7 +215,6 @@ class DocumentTreeCrdt(private val device: String) {                 val tag = xml.substring(i, minOf(j + 1, n))                 when {                     tag.startsWith("</") -> { if (stack.size > 1) stack.removeLast(); if (tag.startsWith("</office:binary-data")) inBinary = false }-                    // XML declaration, processing instructions, comments, doctype: opaque leaves (no close tag).                     tag.startsWith("<?") || tag.startsWith("<!") -> stack.last().children.add(Desired.El(tag, true))                     tag.endsWith("/>") -> stack.last().children.add(Desired.El(tag, true))                     else -> {@@ -228,10 +234,11 @@ class DocumentTreeCrdt(private val device: String) {         return root     } -    private fun closeTagOf(openTag: String): String {-        // "<name att...>" -> "</name>"+    private fun nameOf(tag: String): String {         var k = 1-        while (k < openTag.length && openTag[k] != ' ' && openTag[k] != '>' && openTag[k] != '\t' && openTag[k] != '\n') k++-        return "</" + openTag.substring(1, k) + ">"+        while (k < tag.length && tag[k] != ' ' && tag[k] != '>' && tag[k] != '/' && tag[k] != '\t' && tag[k] != '\n') k+++        return tag.substring(1, k)     }++    private fun closeTagOf(openTag: String): String = "</" + nameOf(openTag) + ">" }
office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt b/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.ktdeleted file mode 100644index c994c18931..0000000000--- a/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt+++ /dev/null@@ -1,61 +0,0 @@-package com.vayunmathur.office.util--/**- * Universal character-level projection of a **flat ODF XML** document: text content between tags- * becomes individual character cells (char-merged by [DocumentCrdt]), while tags stay whole cells and- * `office:binary-data` content (base64 images) stays a single opaque cell (never char-split).- *- * This lets *any* document — including ones with images, tables, shapes, notes — merge concurrent- * edits to the same text region at character granularity, while non-text structure merges at element- * granularity. Rebuild simply concatenates the cells back into the original XML, so a clean (no- * concurrent structural conflict) merge always reproduces valid XML.- */-object FlatXmlCharCodec {-    private const val SEP = '\u0002'--    fun toCells(xml: String): List<String> {-        val cells = ArrayList<String>(xml.length)-        val n = xml.length-        var i = 0-        var inBinary = false-        while (i < n) {-            if (xml[i] == '<') {-                // Scan to the closing '>', skipping any '>' inside quoted attribute values.-                var j = i + 1-                var quote = '\u0000'-                while (j < n) {-                    val c = xml[j]-                    when {-                        quote != '\u0000' -> if (c == quote) quote = '\u0000'-                        c == '"' || c == '\'' -> quote = c-                        c == '>' -> break-                    }-                    j++-                }-                val tag = xml.substring(i, minOf(j + 1, n))-                cells.add("t$SEP$tag")-                when {-                    tag.startsWith("<office:binary-data") -> inBinary = !tag.endsWith("/>")-                    tag.startsWith("</office:binary-data") -> inBinary = false-                }-                i = j + 1-            } else {-                val end = xml.indexOf('<', i).let { if (it < 0) n else it }-                val text = xml.substring(i, end)-                if (inBinary) cells.add("b$SEP$text") // base64 blob stays a single opaque cell-                else for (c in text) cells.add("c$SEP$c")-                i = end-            }-        }-        return cells-    }--    fun fromCells(cells: List<String>): String {-        val sb = StringBuilder()-        for (cell in cells) {-            val sep = cell.indexOf(SEP)-            if (sep >= 0) sb.append(cell.substring(sep + 1))-        }-        return sb.toString()-    }-}
office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt b/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.ktdeleted file mode 100644index e6649a46be..0000000000--- a/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt+++ /dev/null@@ -1,123 +0,0 @@-package com.vayunmathur.office.util--import androidx.compose.ui.text.style.TextAlign-import com.vayunmathur.library.ui.odf.OdfCell-import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfRow-import com.vayunmathur.library.ui.odf.OdfSheet-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json--/**- * Projects an [OdfDocument.Spreadsheet] to/from a flat list of cells so [DocumentCrdt] merges cell- * *text* at character granularity (two people editing the same cell converge without clobbering).- *- * Layout per sheet: the characters of each cell, a `C` terminator carrying the cell's non-text- * attributes (formula/style), an `R` terminator per row, and an `S` terminator per sheet carrying the- * sheet's layout. Only spreadsheets whose content the codec can fully represent are eligible (see- * [isEligible]); anything richer (images, merged cells, borders, floating objects) uses the lossless- * line-level codec.- */-object SheetDocCodec {-    private const val SEP = '\u0002'-    private val json = Json { ignoreUnknownKeys = true }--    @Serializable-    data class CellMeta(-        val formula: String? = null, val valueType: String? = null,-        val bold: Boolean = false, val italic: Boolean = false,-        val textColor: Long? = null, val bg: Long? = null, val align: String? = null,-    )--    @Serializable-    data class SheetMeta(-        val name: String,-        val colWidths: List<Float?> = emptyList(),-        val rowHeights: List<Float?> = emptyList(),-        val freezeRows: Int = 0, val freezeCols: Int = 0,-        val hidden: Boolean = false, val tabColor: Long? = null,-    )--    fun isEligible(doc: OdfDocument): Boolean {-        if (doc !is OdfDocument.Spreadsheet) return false-        if (doc.images.isNotEmpty() || doc.namedRanges.isNotEmpty() || doc.validations.isNotEmpty()) return false-        for (sheet in doc.sheets) {-            if (sheet.floating.isNotEmpty()) return false-            for (row in sheet.rows) for (c in row.cells) {-                if (c.borders != null || c.isCovered || c.spannedColumns != 1 || c.rowSpan != 1) return false-            }-        }-        return true-    }--    fun toCells(doc: OdfDocument.Spreadsheet): List<String> {-        val cells = ArrayList<String>()-        for (sheet in doc.sheets) {-            for (row in sheet.rows) {-                for (cell in row.cells) {-                    for (ch in cell.text) cells.add("c$SEP$ch")-                    cells.add("C$SEP${json.encodeToString(cellMeta(cell))}")-                }-                cells.add("R$SEP")-            }-            cells.add("S$SEP${json.encodeToString(sheetMeta(sheet))}")-        }-        return cells-    }--    fun fromCells(cells: List<String>, base: OdfDocument.Spreadsheet): OdfDocument.Spreadsheet {-        val sheets = ArrayList<OdfSheet>()-        var rows = ArrayList<OdfRow>()-        var rowCells = ArrayList<OdfCell>()-        val text = StringBuilder()-        for (cell in cells) {-            val sep = cell.indexOf(SEP)-            if (sep < 0) continue-            val kind = cell.substring(0, sep)-            val value = cell.substring(sep + 1)-            when (kind) {-                "c" -> text.append(value)-                "C" -> {-                    val m = runCatching { json.decodeFromString<CellMeta>(value) }.getOrNull() ?: CellMeta()-                    rowCells.add(OdfCell(-                        text = text.toString(), formula = m.formula, valueType = m.valueType,-                        bold = m.bold, italic = m.italic, textColor = m.textColor, backgroundColor = m.bg,-                        alignment = parseAlign(m.align),-                    ))-                    text.clear()-                }-                "R" -> { rows.add(OdfRow(rowCells)); rowCells = ArrayList() }-                "S" -> {-                    val m = runCatching { json.decodeFromString<SheetMeta>(value) }.getOrNull() ?: SheetMeta("Sheet")-                    sheets.add(OdfSheet(-                        name = m.name, rows = rows, columnWidths = m.colWidths, rowHeights = m.rowHeights,-                        freezeRows = m.freezeRows, freezeCols = m.freezeCols, hidden = m.hidden, tabColor = m.tabColor,-                    ))-                    rows = ArrayList()-                }-            }-        }-        if (sheets.isEmpty()) sheets.add(OdfSheet("Sheet 1", listOf(OdfRow(listOf(OdfCell(text = ""))))))-        return base.copy(sheets = sheets)-    }--    private fun cellMeta(c: OdfCell) = CellMeta(-        formula = c.formula, valueType = c.valueType, bold = c.bold, italic = c.italic,-        textColor = c.textColor, bg = c.backgroundColor, align = c.alignment?.let { alignName(it) },-    )--    private fun sheetMeta(s: OdfSheet) = SheetMeta(-        name = s.name, colWidths = s.columnWidths, rowHeights = s.rowHeights,-        freezeRows = s.freezeRows, freezeCols = s.freezeCols, hidden = s.hidden, tabColor = s.tabColor,-    )--    private fun alignName(a: TextAlign): String = when (a) {-        TextAlign.Start -> "start"; TextAlign.End -> "end"; TextAlign.Center -> "center"-        TextAlign.Justify -> "justify"; TextAlign.Left -> "left"; TextAlign.Right -> "right"; else -> "start"-    }--    private fun parseAlign(s: String?): TextAlign? = when (s) {-        "start" -> TextAlign.Start; "end" -> TextAlign.End; "center" -> TextAlign.Center-        "justify" -> TextAlign.Justify; "left" -> TextAlign.Left; "right" -> TextAlign.Right; else -> null-    }-}
office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt b/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.ktdeleted file mode 100644index ff417b7871..0000000000--- a/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt+++ /dev/null@@ -1,130 +0,0 @@-package com.vayunmathur.office.util--import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfFrame-import com.vayunmathur.library.ui.odf.OdfParagraph-import com.vayunmathur.library.ui.odf.OdfSlide-import com.vayunmathur.library.ui.odf.OdfSlideElement-import com.vayunmathur.library.ui.odf.OdfSpan-import com.vayunmathur.library.ui.odf.ParagraphStyle-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json--/**- * Projects an [OdfDocument.Presentation] to/from a flat cell list so [DocumentCrdt] merges slide- * text-box text at character granularity. Eligible only for presentations whose elements are all- * text frames (no images/charts/shapes, no slide notes/background image); richer decks use the- * lossless line-level codec.- *- * Layout: per slide, per frame, per paragraph → the paragraph's characters (each carrying its span- * style), a `P` terminator (paragraph style), an `E` terminator per frame (geometry/fill), and a `D`- * terminator per slide (name/background/transition).- */-object SlideDocCodec {-    private const val SEP = '\u0002'-    private const val CSEP = '\u0003'-    private val json = Json { ignoreUnknownKeys = true }--    @Serializable-    data class SpanStyle(val b: Boolean = false, val i: Boolean = false, val u: Boolean = false, val sz: Float? = null, val col: Long? = null)--    @Serializable-    data class FrameMeta(val x: Float, val y: Float, val w: Float, val h: Float, val fill: Long? = null, val stroke: Long? = null, val strokeW: Float? = null)--    @Serializable-    data class SlideMeta(val name: String, val bg: Long? = null, val transitionType: String? = null, val transitionSpeed: String? = null, val masterName: String? = null)--    fun isEligible(doc: OdfDocument): Boolean {-        if (doc !is OdfDocument.Presentation) return false-        if (doc.images.isNotEmpty()) return false-        for (slide in doc.slides) {-            if (slide.backgroundImagePath != null || slide.notes.isNotEmpty()) return false-            for (el in slide.elements) {-                val f = (el as? OdfSlideElement.Frame)?.frame ?: return false-                if (f.image != null || f.chart != null) return false-            }-        }-        return true-    }--    fun toCells(doc: OdfDocument.Presentation): List<String> {-        val cells = ArrayList<String>()-        for (slide in doc.slides) {-            for (el in slide.elements) {-                val f = (el as OdfSlideElement.Frame).frame-                for (para in f.paragraphs) {-                    for (span in para.spans) {-                        val key = json.encodeToString(spanStyle(span))-                        for (ch in span.text) cells.add("c$SEP$key$CSEP$ch")-                    }-                    cells.add("P$SEP${para.style.name}")-                }-                cells.add("E$SEP${json.encodeToString(frameMeta(f))}")-            }-            cells.add("D$SEP${json.encodeToString(slideMeta(slide))}")-        }-        return cells-    }--    fun fromCells(cells: List<String>, base: OdfDocument.Presentation): OdfDocument.Presentation {-        val slides = ArrayList<OdfSlide>()-        var elements = ArrayList<OdfSlideElement>()-        var paras = ArrayList<OdfParagraph>()-        var spans = ArrayList<OdfSpan>()-        var curKey: String? = null-        val text = StringBuilder()--        fun flushSpan() {-            if (curKey != null && text.isNotEmpty()) {-                val s = runCatching { json.decodeFromString<SpanStyle>(curKey!!) }.getOrNull() ?: SpanStyle()-                spans.add(OdfSpan(text = text.toString(), bold = s.b, italic = s.i, underline = s.u, fontSize = s.sz, color = s.col))-            }-            text.clear()-        }-        fun flushPara(styleName: String) {-            flushSpan()-            val style = runCatching { ParagraphStyle.valueOf(styleName) }.getOrNull() ?: ParagraphStyle.BODY-            paras.add(OdfParagraph(spans = if (spans.isEmpty()) listOf(OdfSpan("")) else spans, style = style))-            spans = ArrayList(); curKey = null-        }--        for (cell in cells) {-            val sep = cell.indexOf(SEP)-            if (sep < 0) continue-            val kind = cell.substring(0, sep)-            val value = cell.substring(sep + 1)-            when (kind) {-                "c" -> {-                    val cs = value.indexOf(CSEP)-                    if (cs < 0) continue-                    val key = value.substring(0, cs); val ch = value.substring(cs + 1)-                    if (key != curKey) { flushSpan(); curKey = key }-                    text.append(ch)-                }-                "P" -> flushPara(value)-                "E" -> {-                    val m = runCatching { json.decodeFromString<FrameMeta>(value) }.getOrNull() ?: FrameMeta(0f, 0f, 100f, 40f)-                    elements.add(OdfSlideElement.Frame(OdfFrame(-                        x = m.x, y = m.y, width = m.w, height = m.h, paragraphs = paras,-                        fillColor = m.fill, strokeColor = m.stroke, strokeWidth = m.strokeW,-                    )))-                    paras = ArrayList()-                }-                "D" -> {-                    val m = runCatching { json.decodeFromString<SlideMeta>(value) }.getOrNull() ?: SlideMeta("Slide")-                    slides.add(OdfSlide(-                        name = m.name, elements = elements, backgroundColor = m.bg,-                        transitionType = m.transitionType, transitionSpeed = m.transitionSpeed, masterName = m.masterName,-                    ))-                    elements = ArrayList()-                }-            }-        }-        if (slides.isEmpty()) slides.add(OdfSlide("Slide 1"))-        return base.copy(slides = slides)-    }--    private fun spanStyle(s: OdfSpan) = SpanStyle(b = s.bold, i = s.italic, u = s.underline, sz = s.fontSize, col = s.color)-    private fun frameMeta(f: OdfFrame) = FrameMeta(f.x, f.y, f.width, f.height, f.fillColor, f.strokeColor, f.strokeWidth)-    private fun slideMeta(s: OdfSlide) = SlideMeta(s.name, s.backgroundColor, s.transitionType, s.transitionSpeed, s.masterName)-}
office/src/main/java/com/vayunmathur/office/util/TextDocCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/TextDocCodec.kt b/office/src/main/java/com/vayunmathur/office/util/TextDocCodec.ktdeleted file mode 100644index 2fc8896d2b..0000000000--- a/office/src/main/java/com/vayunmathur/office/util/TextDocCodec.kt+++ /dev/null@@ -1,166 +0,0 @@-package com.vayunmathur.office.util--import androidx.compose.ui.text.style.TextAlign-import com.vayunmathur.library.ui.odf.ListType-import com.vayunmathur.library.ui.odf.OdfContentBlock-import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfParagraph-import com.vayunmathur.library.ui.odf.OdfSpan-import com.vayunmathur.library.ui.odf.ParagraphStyle-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json--/**- * Projects a paragraph-only [OdfDocument.TextDocument] to/from a flat list of **character cells** so- * it can be merged by [DocumentCrdt] at *character* granularity (conflict-free, Yjs-style) rather- * than at line/element granularity.- *- * Each cell is `"<styleJson>\u0002<char>"`. A paragraph's characters each carry their span's inline- * style; each paragraph is terminated by a newline cell whose style carries the paragraph's layout.- * Rebuilding groups consecutive equal-style chars into spans and splits paragraphs on newline cells,- * so the result is always a valid document (we never merge serialized XML).- *- * Only plain paragraph content is representable here (see [isEligible]); documents with tables,- * images, footnotes, headers/footers, comments, bookmarks, fields, page setup, etc. fall back to the- * lossless line-level XML CRDT so nothing is dropped.- */-object TextDocCodec {-    private const val SEP = '\u0002'-    private val json = Json { ignoreUnknownKeys = true }--    @Serializable-    data class CellStyle(-        // Inline (character) style.-        val b: Boolean = false,-        val i: Boolean = false,-        val u: Boolean = false,-        val st: Boolean = false,-        val sz: Float? = null,-        val col: Long? = null,-        val href: String? = null,-        val ff: String? = null,   // font family-        val bg: Long? = null,     // highlight / background color-        val sup: Boolean = false, // superscript-        val sub: Boolean = false, // subscript-        // Paragraph layout (only on newline cells).-        val pstyle: String? = null,-        val al: String? = null,   // alignment-        val ml: Float = 0f,       // left margin (indent)-        val ti: Float = 0f,       // first-line indent-        val ll: Int = 0,          // list level-        val lt: String? = null,   // list type-        val chk: Boolean = false, // checkbox checked-        val lh: Float? = null,    // line-height percent-        val pbg: Long? = null,    // paragraph background color-    )--    /**-     * True only if the document is representable as plain paragraphs with no content the codec can't-     * carry — so switching to char-level never loses data. Anything richer uses the line-level codec.-     */-    fun isEligible(doc: OdfDocument): Boolean {-        if (doc !is OdfDocument.TextDocument) return false-        if (doc.footnotes.isNotEmpty() || doc.headerParagraphs.isNotEmpty() || doc.footerParagraphs.isNotEmpty() ||-            doc.bookmarks.isNotEmpty() || doc.changes.isNotEmpty() || doc.pageSetup != null-        ) return false-        for (block in doc.content) {-            val para = (block as? OdfContentBlock.Paragraph)?.paragraph ?: return false-            for (s in para.spans) if (s.annotation != null || s.field != null || s.refName != null) return false-        }-        return true-    }--    private fun spanStyle(s: OdfSpan) = CellStyle(-        b = s.bold, i = s.italic, u = s.underline, st = s.strikethrough,-        sz = s.fontSize, col = s.color, href = s.href, ff = s.fontFamily, bg = s.backgroundColor,-        sup = s.superscript, sub = s.subscript,-    )--    private fun paraStyle(p: OdfParagraph) = CellStyle(-        pstyle = p.style.name, al = p.alignment?.let { alignName(it) }, ml = p.marginLeft, ti = p.textIndent,-        ll = p.listLevel, lt = p.listType.name, chk = p.listChecked, lh = p.lineHeightPercent, pbg = p.backgroundColor,-    )--    fun toCells(doc: OdfDocument.TextDocument): List<String> {-        val cells = ArrayList<String>()-        for (block in doc.content) {-            val para = (block as? OdfContentBlock.Paragraph)?.paragraph ?: continue-            for (span in para.spans) {-                val key = json.encodeToString(spanStyle(span))-                for (ch in span.text) cells.add("$key$SEP$ch")-            }-            cells.add("${json.encodeToString(paraStyle(para))}$SEP\n")-        }-        return cells-    }--    /** Rebuilds a document from merged cells, copying non-content fields from [base]. */-    fun fromCells(cells: List<String>, base: OdfDocument.TextDocument): OdfDocument.TextDocument {-        val blocks = ArrayList<OdfContentBlock>()-        var spans = ArrayList<OdfSpan>()-        var curKey: String? = null-        var curText = StringBuilder()--        fun flushSpan() {-            if (curKey != null && curText.isNotEmpty()) {-                val cs = runCatching { json.decodeFromString<CellStyle>(curKey!!) }.getOrNull() ?: CellStyle()-                spans.add(-                    OdfSpan(-                        text = curText.toString(), bold = cs.b, italic = cs.i, underline = cs.u,-                        strikethrough = cs.st, fontSize = cs.sz, color = cs.col, href = cs.href,-                        fontFamily = cs.ff, backgroundColor = cs.bg, superscript = cs.sup, subscript = cs.sub,-                    )-                )-            }-            curText = StringBuilder()-        }--        fun flushPara(newlineKey: String?) {-            flushSpan()-            val cs = newlineKey?.let { runCatching { json.decodeFromString<CellStyle>(it) }.getOrNull() }-            val style = cs?.pstyle?.let { runCatching { ParagraphStyle.valueOf(it) }.getOrNull() } ?: ParagraphStyle.BODY-            val listType = cs?.lt?.let { runCatching { ListType.valueOf(it) }.getOrNull() } ?: ListType.BULLET-            blocks.add(OdfContentBlock.Paragraph(OdfParagraph(-                spans = if (spans.isEmpty()) listOf(OdfSpan("")) else spans,-                style = style,-                alignment = parseAlign(cs?.al),-                marginLeft = cs?.ml ?: 0f,-                textIndent = cs?.ti ?: 0f,-                listLevel = cs?.ll ?: 0,-                listType = listType,-                listChecked = cs?.chk ?: false,-                lineHeightPercent = cs?.lh,-                backgroundColor = cs?.pbg,-            )))-            spans = ArrayList()-            curKey = null-        }--        for (cell in cells) {-            val sep = cell.indexOf(SEP)-            if (sep < 0) continue-            val key = cell.substring(0, sep)-            val value = cell.substring(sep + 1)-            if (value == "\n") {-                flushPara(key)-            } else {-                if (key != curKey) { flushSpan(); curKey = key }-                curText.append(value)-            }-        }-        // Trailing text with no final newline cell => final paragraph.-        if (curText.isNotEmpty() || spans.isNotEmpty()) flushPara(null)-        if (blocks.isEmpty()) blocks.add(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("")))))-        return base.copy(content = blocks)-    }--    private fun alignName(a: TextAlign): String = when (a) {-        TextAlign.Start -> "start"; TextAlign.End -> "end"; TextAlign.Center -> "center"-        TextAlign.Justify -> "justify"; TextAlign.Left -> "left"; TextAlign.Right -> "right"; else -> "start"-    }--    private fun parseAlign(s: String?): TextAlign? = when (s) {-        "start" -> TextAlign.Start; "end" -> TextAlign.End; "center" -> TextAlign.Center-        "justify" -> TextAlign.Justify; "left" -> TextAlign.Left; "right" -> TextAlign.Right; else -> null-    }-}
office/src/test/java/com/vayunmathur/office/util/DocumentCrdtTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/DocumentCrdtTest.kt b/office/src/test/java/com/vayunmathur/office/util/DocumentCrdtTest.ktdeleted file mode 100644index 65ec039c4d..0000000000--- a/office/src/test/java/com/vayunmathur/office/util/DocumentCrdtTest.kt+++ /dev/null@@ -1,133 +0,0 @@-package com.vayunmathur.office.util--import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class DocumentCrdtTest {--    private fun basePair(base: List<String>): Pair<DocumentCrdt, DocumentCrdt> {-        val a = DocumentCrdt("A")-        val ops = a.update(base)-        val b = DocumentCrdt("B")-        b.apply(ops)-        assertEquals(a.render(), b.render())-        return a to b-    }--    @Test-    fun update_from_empty_renders_input() {-        val a = DocumentCrdt("A")-        a.update(listOf("l1", "l2", "l3"))-        assertEquals(listOf("l1", "l2", "l3"), a.render())-    }--    @Test-    fun idempotent_apply() {-        val a = DocumentCrdt("A")-        val ops = a.update(listOf("x", "y"))-        val b = DocumentCrdt("B")-        b.apply(ops)-        b.apply(ops) // applying twice must not duplicate-        assertEquals(listOf("x", "y"), b.render())-    }--    @Test-    fun concurrent_edits_to_different_lines_merge() {-        val (a, b) = basePair(listOf("a", "b", "c"))-        // A edits line "a" -> "a2"; B edits line "c" -> "c2" (edit = delete + insert).-        val opsA = a.update(listOf("a2", "b", "c"))-        val opsB = b.update(listOf("a", "b", "c2"))-        a.apply(opsB)-        b.apply(opsA)-        // Both replicas converge and both edits survive.-        assertEquals(a.render(), b.render())-        assertTrue(a.render().contains("a2"))-        assertTrue(a.render().contains("c2"))-        assertTrue(a.render().contains("b"))-    }--    @Test-    fun concurrent_inserts_at_same_position_both_survive_and_converge() {-        val (a, b) = basePair(listOf("start", "end"))-        val opsA = a.update(listOf("start", "A-line", "end"))-        val opsB = b.update(listOf("start", "B-line", "end"))-        a.apply(opsB)-        b.apply(opsA)-        assertEquals(a.render(), b.render()) // deterministic order on both sides-        assertTrue(a.render().containsAll(listOf("start", "end", "A-line", "B-line")))-    }--    @Test-    fun apply_order_independent() {-        val a = DocumentCrdt("A")-        val op1 = a.update(listOf("1"))-        val op2 = a.update(listOf("1", "2"))-        val op3 = a.update(listOf("1", "2", "3"))-        val b = DocumentCrdt("B")-        // Apply in a scrambled order.-        b.apply(op3); b.apply(op1); b.apply(op2)-        assertEquals(a.render(), b.render())-    }--    @Test-    fun concurrent_delete_and_insert_converge() {-        val (a, b) = basePair(listOf("keep", "drop"))-        val opsA = a.update(listOf("keep")) // A deletes "drop"-        val opsB = b.update(listOf("keep", "drop", "new")) // B adds "new"-        a.apply(opsB)-        b.apply(opsA)-        assertEquals(a.render(), b.render())-        assertTrue(a.render().contains("keep"))-        assertTrue(a.render().contains("new"))-        assertTrue(!a.render().contains("drop")) // delete wins-    }--    @Test-    fun state_roundtrip_preserves_render() {-        val a = DocumentCrdt("A")-        a.update(listOf("p", "q", "r"))-        val restored = DocumentCrdt.fromState(a.toState())-        assertEquals(a.render(), restored.render())-        // Continues to work after restore.-        restored.update(listOf("p", "q", "r", "s"))-        assertEquals(listOf("p", "q", "r", "s"), restored.render())-    }--    @Test-    fun single_edit_in_large_doc_is_minimal() {-        val a = DocumentCrdt("A")-        val base = (1..1000).map { "line$it" }-        a.update(base)-        val edited = base.toMutableList().also { it[500] = "line500-edited" }-        val ops = a.update(edited)-        // Only the changed line: one tombstone + one insert (prefix/suffix trimmed).-        assertEquals(2, ops.size)-        assertEquals(edited, a.render())-    }--    @Test-    fun codec_roundtrips_flat_odf() {-        val xml = "<office:document><body><text:p>Hello</text:p><text:p/></body></office:document>"-        val lines = OfficeCrdtCodec.toLines(xml)-        assertTrue(lines.size > 1) // actually split into element lines-        assertEquals(xml, OfficeCrdtCodec.fromLines(lines))-    }--    @Test-    fun codec_merge_preserves_valid_join() {-        val xml = "<r><a/><b/><c/></r>"-        val a = DocumentCrdt("A")-        val baseOps = a.update(OfficeCrdtCodec.toLines(xml))-        val b = DocumentCrdt("B")-        b.apply(baseOps)-        // A inserts <x/> after <a/>, B inserts <y/> after <b/>-        val opsA = a.update(OfficeCrdtCodec.toLines("<r><a/><x/><b/><c/></r>"))-        val opsB = b.update(OfficeCrdtCodec.toLines("<r><a/><b/><y/><c/></r>"))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = OfficeCrdtCodec.fromLines(a.render())-        assertTrue(merged.contains("<x/>"))-        assertTrue(merged.contains("<y/>"))-    }-}
office/src/test/java/com/vayunmathur/office/util/DocumentTreeCrdtTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/DocumentTreeCrdtTest.kt b/office/src/test/java/com/vayunmathur/office/util/DocumentTreeCrdtTest.ktindex 658a30a168..9bde196caa 100644--- a/office/src/test/java/com/vayunmathur/office/util/DocumentTreeCrdtTest.kt+++ b/office/src/test/java/com/vayunmathur/office/util/DocumentTreeCrdtTest.kt@@ -34,6 +34,29 @@ class DocumentTreeCrdtTest {         assertEquals(1, Regex("<office:document ").findAll(r).count())     } +    @Test+    fun concurrent_attribute_edit_and_text_edit_both_preserved() {+        val (a, b) = replicas("<t><p a=\"1\">Hello</p></t>")+        val opsA = a.update("<t><p a=\"2\">Hello</p></t>")       // A changes the attribute+        val opsB = b.update("<t><p a=\"1\">Hello World</p></t>") // B edits the text+        a.apply(opsB); b.apply(opsA)+        assertEquals(a.render(), b.render())+        val r = a.render()+        assertTrue("text edit kept", r.contains("Hello World"))+        assertTrue("attr change kept", r.contains("<p a=\"2\">"))+        assertEquals("element not duplicated", 1, Regex("<p").findAll(r).count())+    }++    @Test+    fun concurrent_conflicting_attr_edits_converge() {+        val (a, b) = replicas("<t><p x=\"0\">z</p></t>")+        val opsA = a.update("<t><p x=\"A\">z</p></t>")+        val opsB = b.update("<t><p x=\"B\">z</p></t>")+        a.apply(opsB); b.apply(opsA)+        assertEquals("deterministic LWW winner on both replicas", a.render(), b.render())+        assertEquals(1, Regex("<p").findAll(a.render()).count())+    }+     @Test     fun roundtrip_render_equals_input() {         val a = DocumentTreeCrdt("A")
office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.ktdeleted file mode 100644index 972ec843b8..0000000000--- a/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt+++ /dev/null@@ -1,66 +0,0 @@-package com.vayunmathur.office.util--import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class FlatXmlCharCodecTest {--    @Test-    fun roundtrip_is_exact() {-        val xml = """<office:document office:mimetype="x"><office:body><text:p>Hello &amp; world</text:p><draw:frame svg:width="1>2"/></office:body></office:document>"""-        assertEquals(xml, FlatXmlCharCodec.fromCells(FlatXmlCharCodec.toCells(xml)))-    }--    @Test-    fun tag_with_gt_in_attribute_stays_one_cell() {-        val xml = """<a b="x>y">t</a>"""-        val cells = FlatXmlCharCodec.toCells(xml)-        // The opening tag (with the '>' inside the quoted attribute) must be a single tag cell.-        assertTrue(cells.any { it == "t\u0002<a b=\"x>y\">" })-        assertEquals(xml, FlatXmlCharCodec.fromCells(cells))-    }--    @Test-    fun binary_data_is_one_opaque_cell_not_char_split() {-        val b64 = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=" // stand-in for a large image blob-        val xml = "<draw:image><office:binary-data>$b64</office:binary-data></draw:image>"-        val cells = FlatXmlCharCodec.toCells(xml)-        assertTrue("base64 kept whole", cells.any { it == "b\u0002$b64" })-        assertTrue("not char-split", cells.none { it == "c\u0002Q" && b64.startsWith("Q") && cells.count { c -> c.startsWith("c\u0002") } > 5 })-        assertEquals(xml, FlatXmlCharCodec.fromCells(cells))-    }--    @Test-    fun concurrent_edits_same_text_run_merge_char_level() {-        val base = "<office:text><text:p>Hello</text:p></office:text>"-        val a = DocumentCrdt("A"); val baseOps = a.update(FlatXmlCharCodec.toCells(base))-        val b = DocumentCrdt("B"); b.apply(baseOps)-        val opsA = a.update(FlatXmlCharCodec.toCells("<office:text><text:p>Hello World</text:p></office:text>"))-        val opsB = b.update(FlatXmlCharCodec.toCells("<office:text><text:p>Hi Hello</text:p></office:text>"))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = FlatXmlCharCodec.fromCells(a.render())-        assertTrue("has A's edit", merged.contains("World"))-        assertTrue("has B's edit", merged.contains("Hi"))-        // Tags stay intact and balanced (one paragraph, valid structure).-        assertEquals(1, Regex("<text:p>").findAll(merged).count())-        assertEquals(1, Regex("</text:p>").findAll(merged).count())-    }--    @Test-    fun concurrent_structural_inserts_stay_wellformed() {-        val base = "<office:text><text:p>one</text:p></office:text>"-        val a = DocumentCrdt("A"); val baseOps = a.update(FlatXmlCharCodec.toCells(base))-        val b = DocumentCrdt("B"); b.apply(baseOps)-        val opsA = a.update(FlatXmlCharCodec.toCells("<office:text><text:p>one</text:p><text:p>A-para</text:p></office:text>"))-        val opsB = b.update(FlatXmlCharCodec.toCells("<office:text><text:p>one</text:p><text:p>B-para</text:p></office:text>"))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = FlatXmlCharCodec.fromCells(a.render())-        assertTrue(merged.contains("A-para")); assertTrue(merged.contains("B-para")); assertTrue(merged.contains("one"))-        // Every <text:p> is matched by a </text:p> (no interleaved/stranded tags).-        assertEquals(Regex("<text:p>").findAll(merged).count(), Regex("</text:p>").findAll(merged).count())-        assertEquals(3, Regex("<text:p>").findAll(merged).count())-    }-}
office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.ktindex 14c3797bd3..5c57fbf28d 100644--- a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt@@ -4,10 +4,6 @@ import com.vayunmathur.e2ee.E2ee import com.vayunmathur.e2ee.E2eeKeyStore import com.vayunmathur.e2ee.Pqc import com.vayunmathur.e2ee.PqcIdentity-import com.vayunmathur.library.ui.odf.OdfContentBlock-import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfParagraph-import com.vayunmathur.library.ui.odf.OdfSpan import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json import org.junit.Assert.assertArrayEquals@@ -47,14 +43,6 @@ class OfficeSharingE2ETest {      private fun memberBytes(docId: String, m: OfficeMember) = "$docId|${m.id}|${m.role}".encodeToByteArray() -    private fun textDoc(vararg paras: String) = OdfDocument.TextDocument(-        title = "E2E",-        content = paras.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) }-    )--    private fun paraTexts(doc: OdfDocument.TextDocument) =-        doc.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text } }-     @Test     fun owner_shares_editor_reconstructs_document_and_viewer_is_rejected() = runBlocking {         val relay = Relay()@@ -66,11 +54,11 @@ class OfficeSharingE2ETest {          val docId = "doc-1"         val docKey = E2ee.newContentKey()-        val ownerDoc = textDoc("Shared heading", "A paragraph of content")+        val ownerXml = "<office:text><text:p>Shared heading</text:p><text:p>A paragraph of content</text:p></office:text>"          // ---- Owner: push signed op + owner-signed roster + invite -----        val crdtO = DocumentCrdt(ownerId)-        val opsJson = json.encodeToString(crdtO.update(TextDocCodec.toCells(ownerDoc)))+        val crdtO = DocumentTreeCrdt(ownerId)+        val opsJson = json.encodeToString(crdtO.update(ownerXml))         val signedOp = SignedOp(ownerId, Base64.encode(owner.sign(opsJson.encodeToByteArray())), opsJson)         relay.append(docId, Base64.encode(E2ee.aesEncrypt(docKey, json.encodeToString(signedOp).encodeToByteArray()))) @@ -78,7 +66,7 @@ class OfficeSharingE2ETest {             val sm = SignedMember(m, Base64.encode(owner.sign(memberBytes(docId, m))))             relay.append("members:$docId", Base64.encode(E2ee.aesEncrypt(docKey, json.encodeToString(sm).encodeToByteArray())))         }-        val invite = OfficeSync.Invite(docId, Base64.encode(docKey), ownerDoc.title, charMode = true, role = OfficeRoles.EDITOR, ownerKey = Base64.encode(owner.publicBundle))+        val invite = OfficeSync.Invite(docId, Base64.encode(docKey), "E2E", charMode = true, role = OfficeRoles.EDITOR, ownerKey = Base64.encode(owner.publicBundle))         relay.append("inbox:$editorId", Base64.encode(Pqc.encryptTo(editor.publicBundle, json.encodeToString(invite).encodeToByteArray())))          // ---- Editor: open the shared document ----@@ -99,20 +87,19 @@ class OfficeSharingE2ETest {         assertEquals(OfficeRoles.OWNER, roleById[ownerId])          // ops: verify author signature + editor/owner role, then apply-        val crdtR = DocumentCrdt(editorId)+        val crdtR = DocumentTreeCrdt(editorId)         for (blob in relay.pull(docId)) {             val so = json.decodeFromString<SignedOp>(E2ee.aesDecrypt(recDocKey, Base64.decode(blob)).decodeToString())             val authorKey = relay.directory[so.author] ?: continue             val sigOk = Pqc.verify(authorKey, so.ops.encodeToByteArray(), Base64.decode(so.sig))             val roleOk = OfficeRoles.canEdit(roleById[so.author] ?: OfficeRoles.VIEWER)-            if (sigOk && roleOk) crdtR.apply(json.decodeFromString(so.ops))+            if (sigOk && roleOk) crdtR.apply(json.decodeFromString<List<DocumentTreeCrdt.Node>>(so.ops))         }-        val rebuilt = TextDocCodec.fromCells(crdtR.render(), OdfDocument.TextDocument(inv.title, emptyList()))-        assertEquals(paraTexts(ownerDoc), paraTexts(rebuilt)) // reconstructed identically+        assertEquals(ownerXml, crdtR.render()) // reconstructed identically          // ---- Negative: a viewer's forged op is rejected ----         roleById[editorId] = OfficeRoles.VIEWER-        val forgedOps = DocumentCrdt(editorId).update(TextDocCodec.toCells(textDoc("malicious edit")))+        val forgedOps = DocumentTreeCrdt(editorId).update("<office:text><text:p>malicious edit</text:p></office:text>")         val forgedJson = json.encodeToString(forgedOps)         val forged = SignedOp(editorId, Base64.encode(editor.sign(forgedJson.encodeToByteArray())), forgedJson)         val sigOk = Pqc.verify(relay.directory[editorId]!!, forged.ops.encodeToByteArray(), Base64.decode(forged.sig))
office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.ktdeleted file mode 100644index ec6b74a7ec..0000000000--- a/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt+++ /dev/null@@ -1,75 +0,0 @@-package com.vayunmathur.office.util--import com.vayunmathur.library.ui.odf.OdfCell-import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfRow-import com.vayunmathur.library.ui.odf.OdfSheet-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class SheetDocCodecTest {--    private fun sheet(vararg rows: List<String>) = OdfDocument.Spreadsheet(-        title = "s",-        sheets = listOf(OdfSheet("Sheet 1", rows.map { r -> OdfRow(r.map { OdfCell(text = it) }) }))-    )--    private fun cellTexts(doc: OdfDocument.Spreadsheet) = doc.sheets[0].rows.map { row -> row.cells.map { it.text } }--    @Test-    fun roundtrip_preserves_cells_and_style() {-        val doc = OdfDocument.Spreadsheet(-            title = "s",-            sheets = listOf(OdfSheet("Data", listOf(-                OdfRow(listOf(OdfCell(text = "Name", bold = true), OdfCell(text = "Total", formula = "=SUM(A1:A2)", valueType = "float"))),-                OdfRow(listOf(OdfCell(text = "x"), OdfCell(text = "5")))-            )))-        )-        val rebuilt = SheetDocCodec.fromCells(SheetDocCodec.toCells(doc), doc)-        assertEquals(cellTexts(doc), cellTexts(rebuilt))-        assertEquals("Data", rebuilt.sheets[0].name)-        assertTrue(rebuilt.sheets[0].rows[0].cells[0].bold)-        assertEquals("=SUM(A1:A2)", rebuilt.sheets[0].rows[0].cells[1].formula)-    }--    @Test-    fun concurrent_edits_same_cell_merge_char_level() {-        val base = sheet(listOf("Hello"))-        val a = DocumentCrdt("A"); val baseOps = a.update(SheetDocCodec.toCells(base))-        val b = DocumentCrdt("B"); b.apply(baseOps)-        val opsA = a.update(SheetDocCodec.toCells(sheet(listOf("Hello World")))) // append " World"-        val opsB = b.update(SheetDocCodec.toCells(sheet(listOf("Hi Hello"))))    // prepend "Hi "-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = SheetDocCodec.fromCells(a.render(), base)-        val text = merged.sheets[0].rows[0].cells[0].text-        assertTrue("has A's edit", text.contains("World"))-        assertTrue("has B's edit", text.contains("Hi"))-        assertEquals("still one row", 1, merged.sheets[0].rows.size)-        assertEquals("still one cell (no duplication)", 1, merged.sheets[0].rows[0].cells.size)-    }--    @Test-    fun concurrent_new_rows_merge() {-        val base = sheet(listOf("r1"))-        val a = DocumentCrdt("A"); val baseOps = a.update(SheetDocCodec.toCells(base))-        val b = DocumentCrdt("B"); b.apply(baseOps)-        val opsA = a.update(SheetDocCodec.toCells(sheet(listOf("r1"), listOf("from-A"))))-        val opsB = b.update(SheetDocCodec.toCells(sheet(listOf("r1"), listOf("from-B"))))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = SheetDocCodec.fromCells(a.render(), base)-        val allText = merged.sheets[0].rows.flatMap { it.cells }.joinToString("|") { it.text }-        assertTrue(allText.contains("from-A"))-        assertTrue(allText.contains("from-B"))-        assertTrue(allText.contains("r1"))-    }--    @Test-    fun ineligible_when_merged_cells_or_images() {-        assertTrue(SheetDocCodec.isEligible(sheet(listOf("a"))))-        val merged = OdfDocument.Spreadsheet(title = "s", sheets = listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell(text = "a", spannedColumns = 2)))))))-        assertTrue(!SheetDocCodec.isEligible(merged))-    }-}
office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.ktdeleted file mode 100644index 9540e73e1d..0000000000--- a/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt+++ /dev/null@@ -1,64 +0,0 @@-package com.vayunmathur.office.util--import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfFrame-import com.vayunmathur.library.ui.odf.OdfParagraph-import com.vayunmathur.library.ui.odf.OdfSlide-import com.vayunmathur.library.ui.odf.OdfSlideElement-import com.vayunmathur.library.ui.odf.OdfSpan-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class SlideDocCodecTest {--    private fun frame(text: String) = OdfSlideElement.Frame(-        OdfFrame(x = 0f, y = 0f, width = 100f, height = 40f, paragraphs = listOf(OdfParagraph(listOf(OdfSpan(text)))))-    )--    private fun deck(vararg frameTexts: String) = OdfDocument.Presentation(-        title = "p", slides = listOf(OdfSlide("Slide 1", elements = frameTexts.map { frame(it) }))-    )--    private fun frameTexts(doc: OdfDocument.Presentation) =-        doc.slides[0].elements.map { (it as OdfSlideElement.Frame).frame.paragraphs.joinToString("") { p -> p.spans.joinToString("") { s -> s.text } } }--    @Test-    fun roundtrip_preserves_frames_and_bold() {-        val doc = OdfDocument.Presentation(title = "p", slides = listOf(OdfSlide("Intro", elements = listOf(-            OdfSlideElement.Frame(OdfFrame(10f, 20f, 300f, 80f, listOf(OdfParagraph(listOf(OdfSpan("Title", bold = true)))))),-            frame("Body text")-        ))))-        val rebuilt = SlideDocCodec.fromCells(SlideDocCodec.toCells(doc), doc)-        assertEquals(frameTexts(doc), frameTexts(rebuilt))-        assertEquals("Intro", rebuilt.slides[0].name)-        val firstFrame = (rebuilt.slides[0].elements[0] as OdfSlideElement.Frame).frame-        assertEquals(10f, firstFrame.x)-        assertTrue(firstFrame.paragraphs[0].spans[0].bold)-    }--    @Test-    fun concurrent_edits_same_textbox_merge_char_level() {-        val base = deck("Hello")-        val a = DocumentCrdt("A"); val baseOps = a.update(SlideDocCodec.toCells(base))-        val b = DocumentCrdt("B"); b.apply(baseOps)-        val opsA = a.update(SlideDocCodec.toCells(deck("Hello World")))-        val opsB = b.update(SlideDocCodec.toCells(deck("Hi Hello")))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = SlideDocCodec.fromCells(a.render(), base)-        val text = frameTexts(merged)[0]-        assertTrue("has A's edit", text.contains("World"))-        assertTrue("has B's edit", text.contains("Hi"))-        assertEquals("still one text box (no duplication)", 1, merged.slides[0].elements.size)-    }--    @Test-    fun ineligible_when_slide_has_image_frame() {-        assertTrue(SlideDocCodec.isEligible(deck("a")))-        val withImage = OdfDocument.Presentation(title = "p", slides = listOf(OdfSlide("S", elements = listOf(-            OdfSlideElement.Frame(OdfFrame(0f, 0f, 10f, 10f, emptyList(), image = com.vayunmathur.library.ui.odf.OdfImage(path = "x", imageData = ByteArray(0))))-        ))))-        assertTrue(!SlideDocCodec.isEligible(withImage))-    }-}
office/src/test/java/com/vayunmathur/office/util/TextDocCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/TextDocCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/TextDocCodecTest.ktdeleted file mode 100644index 773cd38e0f..0000000000--- a/office/src/test/java/com/vayunmathur/office/util/TextDocCodecTest.kt+++ /dev/null@@ -1,108 +0,0 @@-package com.vayunmathur.office.util--import com.vayunmathur.library.ui.odf.OdfContentBlock-import com.vayunmathur.library.ui.odf.OdfDocument-import com.vayunmathur.library.ui.odf.OdfParagraph-import com.vayunmathur.library.ui.odf.OdfSpan-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class TextDocCodecTest {--    private fun textDoc(vararg paras: String) = OdfDocument.TextDocument(-        title = "t",-        content = paras.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) }-    )--    private fun paraTexts(doc: OdfDocument.TextDocument): List<String> =-        doc.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text } }--    @Test-    fun roundtrip_preserves_full_formatting() {-        val doc = OdfDocument.TextDocument(-            title = "t",-            content = listOf(-                OdfContentBlock.Paragraph(OdfParagraph(-                    spans = listOf(OdfSpan("styled", italic = true, fontFamily = "Times", backgroundColor = 0xFFFFFF00L, color = 0xFF0000FFL)),-                    alignment = androidx.compose.ui.text.style.TextAlign.Center,-                    marginLeft = 24f, textIndent = 12f,-                    style = com.vayunmathur.library.ui.odf.ParagraphStyle.LIST_ITEM,-                    listLevel = 2, listType = com.vayunmathur.library.ui.odf.ListType.NUMBERED, listChecked = true,-                ))-            )-        )-        val p = (TextDocCodec.fromCells(TextDocCodec.toCells(doc), doc).content[0] as OdfContentBlock.Paragraph).paragraph-        assertEquals(androidx.compose.ui.text.style.TextAlign.Center, p.alignment)-        assertEquals(24f, p.marginLeft)-        assertEquals(12f, p.textIndent)-        assertEquals(2, p.listLevel)-        assertEquals(com.vayunmathur.library.ui.odf.ListType.NUMBERED, p.listType)-        assertTrue(p.listChecked)-        val s = p.spans.first()-        assertTrue(s.italic); assertEquals("Times", s.fontFamily)-        assertEquals(0xFFFFFF00L, s.backgroundColor); assertEquals(0xFF0000FFL, s.color)-    }--    @Test-    fun ineligible_when_special_content_present() {-        // A doc with a footnote must NOT be char-level (would drop the footnote) — use line-level.-        val withFootnote = textDoc("body").copy(-            footnotes = listOf(com.vayunmathur.library.ui.odf.OdfFootnote(citation = "1", body = emptyList()))-        )-        assertTrue(!TextDocCodec.isEligible(withFootnote))-        assertTrue(TextDocCodec.isEligible(textDoc("plain")))-    }--    @Test-    fun roundtrip_preserves_paragraphs_and_bold() {-        val doc = OdfDocument.TextDocument(-            title = "t",-            content = listOf(-                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("Hello ", bold = true), OdfSpan("world")))),-                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("second"))))-            )-        )-        val rebuilt = TextDocCodec.fromCells(TextDocCodec.toCells(doc), doc)-        assertEquals(listOf("Hello world", "second"), paraTexts(rebuilt))-        val firstSpans = (rebuilt.content[0] as OdfContentBlock.Paragraph).paragraph.spans-        assertTrue(firstSpans.first { it.text.startsWith("Hello") }.bold)-        assertTrue(!firstSpans.first { it.text == "world" }.bold)-    }--    @Test-    fun concurrent_edits_same_paragraph_merge_without_duplication() {-        val base = textDoc("Hello World")-        val a = DocumentCrdt("A")-        val baseOps = a.update(TextDocCodec.toCells(base))-        val b = DocumentCrdt("B")-        b.apply(baseOps)-        // A inserts "Brave " mid-paragraph; B appends "!" — both within the SAME paragraph.-        val opsA = a.update(TextDocCodec.toCells(textDoc("Hello Brave World")))-        val opsB = b.update(TextDocCodec.toCells(textDoc("Hello World!")))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = TextDocCodec.fromCells(a.render(), base)-        val text = paraTexts(merged).joinToString("\u0000")-        assertTrue("has A's edit", text.contains("Brave"))-        assertTrue("has B's edit", text.contains("!"))-        assertEquals("still a single paragraph (char-level merge, no duplication)", 1, merged.content.size)-    }--    @Test-    fun concurrent_new_paragraphs_merge() {-        val base = textDoc("intro")-        val a = DocumentCrdt("A")-        val baseOps = a.update(TextDocCodec.toCells(base))-        val b = DocumentCrdt("B")-        b.apply(baseOps)-        val opsA = a.update(TextDocCodec.toCells(textDoc("intro", "from-A")))-        val opsB = b.update(TextDocCodec.toCells(textDoc("intro", "from-B")))-        a.apply(opsB); b.apply(opsA)-        assertEquals(a.render(), b.render())-        val merged = paraTexts(TextDocCodec.fromCells(a.render(), base))-        assertTrue(merged.contains("from-A"))-        assertTrue(merged.contains("from-B"))-        assertTrue(merged.contains("intro"))-    }-}