1
//! Apply a [`DocumentOperation`] to a [`Dom`] tree - the helper for apps
2
//! WITHOUT their own document model (Path 2).
3
//!
4
//! The applier operates on azul's NATIVE node tree (`azul_core::dom::Dom` -
5
//! what a layout callback returns, what `reconstruct_dom_subtree` hands
6
//! back), not on markup. Operations are STRUCTURAL: subtrees move wholesale
7
//! (`<b>…</b>` inside a split paragraph survives intact, a `<ul>` splits
8
//! between `<li>`s, a table row inserts like any other subtree); the ONLY
9
//! thing ever cut is a text child, at a char boundary, when a
10
//! [`NodePosition`] points inside it.
11
//!
12
//! Azul records structural intent (`DocumentChangeset`); the app applies it
13
//! to ITS model and regenerates the DOM - the `StyledDom` is never mutated.
14
//! An app holding a `Dom` calls [`apply_document_operation`], then
15
//! `CallbackInfo::mark_document_edit_applied_with_inverse(changeset.id,
16
//! applied.inverse)` (the commit handshake), then returns
17
//! `Update::RefreshDom`.
18
//!
19
//! Every successful apply returns the INVERSE operation - tree-shaped undo
20
//! for free (undoing re-RECORDS the inverse through the same
21
//! record→apply→ack loop; it never mutates either).
22
//!
23
//! **Fragment semantics**: `content: Dom` payloads are DocumentFragment-like
24
//! - the fragment's ROOT is ignored, its CHILDREN are the inserted nodes.
25
//! This closes the inverse algebra for multi-child operations
26
//! (`RemoveChildren [s, e)` ⇄ `InsertChildren` of the removed fragment).
27

            
28
use azul_core::dom::{Dom, NodeType};
29
use azul_css::{impl_result, impl_result_inner};
30

            
31
use crate::managers::changeset::{
32
    DocOpInsertChildren, DocOpMergeNodes, DocOpRemoveChildren, DocOpReplaceChildren,
33
    DocOpSplitNode, DocumentChangeset, DocumentOperation, NodePosition,
34
};
35

            
36
/// The outcome of a successful apply.
37
#[repr(C)]
38
#[derive(Debug, Clone)]
39
pub struct AppliedEdit {
40
    /// Where the caret/anchor should land (passed through from the changeset
41
    /// - already expressed re-render-stably).
42
    pub resume: crate::managers::changeset::EditResumePoint,
43
    /// The operation that undoes this one. `DomNodeId` fields are advisory
44
    /// (they refer to the generation the ORIGINAL changeset was recorded
45
    /// against); the structural payload (positions, ranges, fragments) is
46
    /// what the undo path re-records.
47
    pub inverse: DocumentOperation,
48
    /// The resume point to re-record [`inverse`] WITH.
49
    ///
50
    /// Index resolution is asymmetric - a split targets
51
    /// `resume.node_path.last() - 1` while a merge keeps
52
    /// `resume.node_path.last()` - so replaying the inverse with the
53
    /// ORIGINAL resume point lands one node off and edits the wrong pair.
54
    /// An application undoing an edit must not have to know that: this is
55
    /// the resume point that makes `inverse` apply to exactly the nodes the
56
    /// forward operation touched.
57
    pub inverse_resume: crate::managers::changeset::EditResumePoint,
58
}
59

            
60
/// Why an apply failed. Failures leave the tree UNCHANGED.
61
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62
#[repr(C)]
63
pub enum DocumentEditError {
64
    /// `host_path` did not resolve to a node in the tree.
65
    HostNotFound,
66
    /// An index/range in the operation does not exist under the host.
67
    TargetNotFound,
68
    /// The operation kind cannot be applied (reserved). (Previously carried a
69
    /// `&'static str` detail; dropped for ABI - the variant is still unused.)
70
    Unsupported,
71
}
72

            
73
/// Wrap subtrees in a fragment `Dom` (root ignored by the applier).
74
#[must_use]
75
8
pub fn fragment(children: Vec<Dom>) -> Dom {
76
8
    let mut f = Dom::create_div();
77
23
    for c in children {
78
15
        f.add_child(c);
79
15
    }
80
8
    f
81
8
}
82

            
83
/// Apply a structural changeset to the `Dom` the app holds.
84
///
85
/// * `root` - the app's document tree (e.g. from its own builder or `reconstruct_dom_subtree`).
86
/// * `host_path` - child-index path from `root` to the node whose CHILD LIST the operation edits
87
///   (`[]` = `root` itself). For Split/Merge this is the PARENT of the split/merged nodes.
88
/// * `changeset` - as delivered by `CallbackInfo::get_document_edit_clone`.
89
///
90
/// Index resolution for Split/Merge uses the changeset's OWN resume point
91
/// (recorded by the same engine that computes it, so the two cannot drift):
92
/// a split targets `resume.node_path.last() - 1` (the resume names the NEW
93
/// second node), a merge keeps `resume.node_path.last()`.
94
///
95
/// # Errors
96
///
97
/// Returns a [`DocumentEditError`] (tree unchanged) on unresolvable paths,
98
/// missing targets, or record-only operation kinds.
99
89
pub fn apply_document_operation(
100
89
    root: &mut Dom,
101
89
    host_path: &[u32],
102
89
    changeset: &DocumentChangeset,
103
89
) -> Result<AppliedEdit, DocumentEditError> {
104
89
    let host = resolve_path_mut(root, host_path).ok_or(DocumentEditError::HostNotFound)?;
105
88
    let resume_index = changeset
106
88
        .resume
107
88
        .node_path
108
88
        .as_ref()
109
88
        .last()
110
88
        .copied()
111
88
        .unwrap_or(0);
112

            
113
    // The index the inverse must address, in the units ITS OWN arm reads
114
    // (split reads `last - 1`, merge reads `last`), so the caller can replay
115
    // the inverse verbatim.
116
88
    let mut inverse_resume_last = resume_index;
117
88
    let inverse = match &changeset.operation {
118
47
        DocumentOperation::SplitNode(split) => {
119
47
            let node_index = resume_index.saturating_sub(1) as usize;
120
            // Inverse is a MERGE of (node_index, node_index + 1); merge reads
121
            // the index directly.
122
47
            inverse_resume_last = node_index as u32;
123
47
            apply_split(host, node_index, split)?
124
        }
125
34
        DocumentOperation::MergeNodes(merge) => {
126
34
            let first_index = resume_index as usize;
127
            // Inverse is a SPLIT of `first_index`; split reads `last - 1`.
128
34
            inverse_resume_last = first_index as u32 + 1;
129
34
            apply_merge(host, first_index, merge)?
130
        }
131
1
        DocumentOperation::InsertChildren(insert) => apply_insert(host, insert),
132
1
        DocumentOperation::RemoveChildren(remove) => apply_remove(host, remove)?,
133
2
        DocumentOperation::ReplaceChildren(replace) => apply_replace(host, replace)?,
134
2
        DocumentOperation::WrapRange(wrap) => apply_wrap(host, wrap)?,
135
1
        DocumentOperation::UnwrapRange(unwrap) => apply_unwrap(host, unwrap)?,
136
    };
137

            
138
    // Direct `children` mutation desyncs `estimated_total_children` (the
139
    // CompactDom conversion asserts on it); re-sync the WHOLE tree — counts
140
    // bubble up through every ancestor of the edited node.
141
87
    root.fixup_children_estimated();
142

            
143
87
    let mut inverse_resume = changeset.resume.clone();
144
    {
145
87
        let mut path = inverse_resume.node_path.as_ref().to_vec();
146
87
        match path.last_mut() {
147
87
            Some(last) => *last = inverse_resume_last,
148
            None => path.push(inverse_resume_last),
149
        }
150
87
        inverse_resume.node_path = path.into();
151
    }
152

            
153
87
    Ok(AppliedEdit {
154
87
        resume: changeset.resume.clone(),
155
87
        inverse,
156
87
        inverse_resume,
157
87
    })
158
89
}
159

            
160
/// Walk a child-index path down the tree.
161
89
fn resolve_path_mut<'a>(root: &'a mut Dom, path: &[u32]) -> Option<&'a mut Dom> {
162
89
    let mut node = root;
163
89
    for &idx in path {
164
1
        node = node.children.as_mut().get_mut(idx as usize)?;
165
    }
166
88
    Some(node)
167
89
}
168

            
169
/// Take a node's children out as a plain Vec (write back with `.into()`).
170
168
fn take_children(node: &mut Dom) -> Vec<Dom> {
171
168
    core::mem::take(&mut node.children).into_library_owned_vec()
172
168
}
173

            
174
/// Split the text of a text-node `Dom` at `byte` (char-boundary clamped),
175
/// truncating the node to the head and returning the tail as a new node.
176
37
fn split_text_dom(node: &mut Dom, byte: usize) -> Dom {
177
37
    let (head, tail) = match node.root.get_node_type() {
178
37
        NodeType::Text(t) => {
179
37
            let s = t.as_str();
180
37
            let cut = byte.min(s.len());
181
37
            let cut = (0..=cut)
182
37
                .rev()
183
38
                .find(|&c| s.is_char_boundary(c))
184
37
                .unwrap_or(0);
185
37
            (s[..cut].to_string(), s[cut..].to_string())
186
        }
187
        _ => return Dom::create_text_do_not_use_without_block_level_wrapper(""),
188
    };
189
37
    *node = Dom::create_text_do_not_use_without_block_level_wrapper(head);
190
37
    Dom::create_text_do_not_use_without_block_level_wrapper(tail)
191
37
}
192

            
193
/// Split `host.children[node_index]` at the structural position: children
194
/// BEFORE the position stay, children AFTER move to a new sibling of the
195
/// SAME node shape (the `NodeData` is cloned - a `<ul>` splits into two
196
/// `<ul>`s, an `<h1>` into two `<h1>`s; tag conversion is an editing policy
197
/// for the RECORDER, not the tree algebra). A text child AT the position is
198
/// cut at its byte. Inverse: the merge at the same seam.
199
47
fn apply_split(
200
47
    host: &mut Dom,
201
47
    node_index: usize,
202
47
    split: &DocOpSplitNode,
203
47
) -> Result<DocumentOperation, DocumentEditError> {
204
47
    let mut host_children = take_children(host);
205
47
    if node_index >= host_children.len() {
206
        host.children = host_children.into();
207
        return Err(DocumentEditError::TargetNotFound);
208
47
    }
209

            
210
47
    let node = &mut host_children[node_index];
211
47
    let mut node_children = take_children(node);
212
47
    let child_index = (split.at.child_index as usize).min(node_children.len());
213

            
214
    let mut second_children: Vec<Dom>;
215
47
    match split.at.text_byte.into_option() {
216
35
        Some(byte)
217
35
            if child_index < node_children.len()
218
                && matches!(
219
35
                    node_children[child_index].root.get_node_type(),
220
                    NodeType::Text(_)
221
35
                ) =>
222
35
        {
223
35
            // Cut the boundary TEXT child; everything after it moves.
224
35
            let tail_text = split_text_dom(&mut node_children[child_index], byte as usize);
225
35
            second_children = vec![tail_text];
226
35
            second_children.extend(node_children.drain(child_index + 1..));
227
35
        }
228
12
        _ => {
229
12
            // Pure structural boundary: children[child_index..] move wholesale.
230
12
            second_children = node_children.drain(child_index..).collect();
231
12
        }
232
    }
233
47
    node.children = node_children.into();
234

            
235
    // The second node clones the first's SHAPE (same NodeData: type, classes,
236
    // attributes) and takes the moved children.
237
47
    let mut second = Dom {
238
47
        root: node.root.clone(),
239
47
        children: Vec::<Dom>::new().into(),
240
47
        css: Vec::new().into(),
241
47
        estimated_total_children: 0,
242
47
    };
243
96
    for c in second_children {
244
49
        second.add_child(c);
245
49
    }
246
47
    host_children.insert(node_index + 1, second);
247
47
    host.children = host_children.into();
248

            
249
47
    Ok(DocumentOperation::MergeNodes(DocOpMergeNodes {
250
47
        first: split.node,
251
47
        second: split.node,
252
47
        join: split.at,
253
47
    }))
254
47
}
255

            
256
/// Merge `host.children[first_index + 1]` into `host.children[first_index]`:
257
/// the second node's children are appended WHOLESALE; two text nodes meeting
258
/// at the seam coalesce iff the join position carries a byte (the recorder
259
/// says the seam is text|text). Inverse: the split at the seam.
260
34
fn apply_merge(
261
34
    host: &mut Dom,
262
34
    first_index: usize,
263
34
    merge: &DocOpMergeNodes,
264
34
) -> Result<DocumentOperation, DocumentEditError> {
265
34
    let mut host_children = take_children(host);
266
34
    if first_index + 1 >= host_children.len() {
267
1
        host.children = host_children.into();
268
1
        return Err(DocumentEditError::TargetNotFound);
269
33
    }
270

            
271
33
    let second = host_children.remove(first_index + 1);
272
33
    let first = &mut host_children[first_index];
273
33
    let mut first_children = take_children(first);
274
33
    let second_children = second.children.into_library_owned_vec();
275

            
276
33
    let mut iter = second_children.into_iter();
277
33
    if merge.join.text_byte.into_option().is_some() {
278
        // The recorder marked the seam text|text: coalesce the two nodes so
279
        // a later split at the join byte round-trips.
280
32
        if let Some(second_first) = iter.next() {
281
32
            let coalesced = match (
282
32
                first_children.last().map(|n| n.root.get_node_type()),
283
32
                second_first.root.get_node_type(),
284
            ) {
285
32
                (Some(NodeType::Text(a)), NodeType::Text(b)) => {
286
32
                    Some(format!("{}{}", a.as_str(), b.as_str()))
287
                }
288
                _ => None,
289
            };
290
32
            match coalesced {
291
32
                Some(joined) => {
292
32
                    *first_children.last_mut().unwrap() =
293
32
                        Dom::create_text_do_not_use_without_block_level_wrapper(joined);
294
32
                }
295
                None => first_children.push(second_first),
296
            }
297
        }
298
1
    }
299
33
    first_children.extend(iter);
300
33
    first.children = first_children.into();
301
33
    host.children = host_children.into();
302

            
303
33
    Ok(DocumentOperation::SplitNode(DocOpSplitNode {
304
33
        node: merge.first,
305
33
        at: merge.join,
306
33
    }))
307
34
}
308

            
309
/// Insert the fragment's children under `host` at `insert.index`.
310
/// Inverse: remove of exactly that range.
311
1
fn apply_insert(host: &mut Dom, insert: &DocOpInsertChildren) -> DocumentOperation {
312
1
    let mut host_children = take_children(host);
313
1
    let index = (insert.index as usize).min(host_children.len());
314
1
    let new_children = insert.content.children.as_ref().to_vec();
315
1
    let count = new_children.len();
316
2
    for (offset, child) in new_children.into_iter().enumerate() {
317
2
        host_children.insert(index + offset, child);
318
2
    }
319
1
    host.children = host_children.into();
320
1
    DocumentOperation::RemoveChildren(DocOpRemoveChildren {
321
1
        parent: insert.parent,
322
1
        start: u32::try_from(index).unwrap_or(u32::MAX),
323
1
        end: u32::try_from(index + count).unwrap_or(u32::MAX),
324
1
    })
325
1
}
326

            
327
/// Remove `host.children[start..end)`. Inverse: insert of the removed
328
/// fragment at `start`.
329
1
fn apply_remove(
330
1
    host: &mut Dom,
331
1
    remove: &DocOpRemoveChildren,
332
1
) -> Result<DocumentOperation, DocumentEditError> {
333
1
    let mut host_children = take_children(host);
334
1
    let start = remove.start as usize;
335
1
    let end = remove.end as usize;
336
1
    if start > end || end > host_children.len() {
337
        host.children = host_children.into();
338
        return Err(DocumentEditError::TargetNotFound);
339
1
    }
340
1
    let removed: Vec<Dom> = host_children.drain(start..end).collect();
341
1
    host.children = host_children.into();
342
1
    Ok(DocumentOperation::InsertChildren(DocOpInsertChildren {
343
1
        parent: remove.parent,
344
1
        index: remove.start,
345
1
        content: fragment(removed),
346
1
    }))
347
1
}
348

            
349
/// Replace `host.children[start..end)` with the fragment's children.
350
/// Inverse: the replace that puts the old range back.
351
2
fn apply_replace(
352
2
    host: &mut Dom,
353
2
    replace: &DocOpReplaceChildren,
354
2
) -> Result<DocumentOperation, DocumentEditError> {
355
2
    let mut host_children = take_children(host);
356
2
    let start = replace.start as usize;
357
2
    let end = replace.end as usize;
358
2
    if start > end || end > host_children.len() {
359
        host.children = host_children.into();
360
        return Err(DocumentEditError::TargetNotFound);
361
2
    }
362
2
    let new_children = replace.content.children.as_ref().to_vec();
363
2
    let count = new_children.len();
364
2
    let removed: Vec<Dom> = host_children.splice(start..end, new_children).collect();
365
2
    host.children = host_children.into();
366
2
    Ok(DocumentOperation::ReplaceChildren(DocOpReplaceChildren {
367
2
        parent: replace.parent,
368
2
        start: replace.start,
369
2
        end: u32::try_from(start + count).unwrap_or(u32::MAX),
370
2
        content: fragment(removed),
371
2
    }))
372
2
}
373

            
374
/// Wrap `host.children` between `start` and `end` in the wrapper element:
375
/// boundary TEXT children are cut at the range edges; everything covered
376
/// moves INTO a new wrapper node inserted at the range start. Inverse: the
377
/// unwrap at that position.
378
///
379
/// NOTE the host resolution difference: for wrap/unwrap `host_path` names
380
/// the node whose CONTENT the range covers (the edit happens inside it),
381
/// while split/merge name the PARENT (the edit adds/removes a sibling).
382
2
fn apply_wrap(
383
2
    host: &mut Dom,
384
2
    wrap: &crate::managers::changeset::DocOpWrapRange,
385
2
) -> Result<DocumentOperation, DocumentEditError> {
386
2
    let mut children = take_children(host);
387
2
    let len = children.len();
388

            
389
    // END boundary first (so start-side splits don't shift its index):
390
    // a byte inside a text child cuts it — the head stays IN the range,
391
    // the tail is re-inserted after it, outside.
392
2
    let mut end_exclusive = (wrap.end.child_index as usize).min(len);
393
2
    if let Some(byte) = wrap.end.text_byte.into_option() {
394
1
        if end_exclusive < children.len()
395
            && matches!(
396
1
                children[end_exclusive].root.get_node_type(),
397
                NodeType::Text(_)
398
            )
399
1
        {
400
1
            let tail = split_text_dom(&mut children[end_exclusive], byte as usize);
401
1
            children.insert(end_exclusive + 1, tail);
402
1
            end_exclusive += 1; // the head (now cut) is covered
403
1
        }
404
1
    }
405

            
406
    // START boundary: a byte inside a text child cuts it — the head stays
407
    // OUTSIDE, the tail begins the range (everything after shifts by one).
408
2
    let mut start_index = (wrap.start.child_index as usize).min(children.len());
409
2
    if let Some(byte) = wrap.start.text_byte.into_option() {
410
1
        if start_index < children.len()
411
            && matches!(
412
1
                children[start_index].root.get_node_type(),
413
                NodeType::Text(_)
414
            )
415
1
        {
416
1
            let tail = split_text_dom(&mut children[start_index], byte as usize);
417
1
            children.insert(start_index + 1, tail);
418
1
            start_index += 1;
419
1
            end_exclusive += 1;
420
1
        }
421
1
    }
422

            
423
2
    if start_index > end_exclusive || end_exclusive > children.len() {
424
        host.children = children.into();
425
        return Err(DocumentEditError::TargetNotFound);
426
2
    }
427

            
428
2
    let covered: Vec<Dom> = children.drain(start_index..end_exclusive).collect();
429
2
    let mut wrapper = Dom {
430
2
        root: wrap.wrapper.root.clone(),
431
2
        children: Vec::<Dom>::new().into(),
432
2
        css: Vec::new().into(),
433
2
        estimated_total_children: 0,
434
2
    };
435
5
    for c in covered {
436
3
        wrapper.add_child(c);
437
3
    }
438
2
    children.insert(start_index, wrapper);
439
2
    host.children = children.into();
440

            
441
2
    Ok(DocumentOperation::UnwrapRange(
442
2
        crate::managers::changeset::DocOpUnwrapRange {
443
2
            node: wrap.node,
444
2
            at: NodePosition::before_child(u32::try_from(start_index).unwrap_or(u32::MAX)),
445
2
        },
446
2
    ))
447
2
}
448

            
449
/// Remove the wrapper child at `at`, splicing its children into its place;
450
/// text meeting at either seam coalesces (so wrap → unwrap round-trips to
451
/// the original tree). Inverse: the wrap that re-covers the spliced range.
452
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose splice + both-seam coalesce +
453
                                 // exact inverse
454
1
fn apply_unwrap(
455
1
    host: &mut Dom,
456
1
    unwrap: &crate::managers::changeset::DocOpUnwrapRange,
457
1
) -> Result<DocumentOperation, DocumentEditError> {
458
1
    let mut children = take_children(host);
459
1
    let index = unwrap.at.child_index as usize;
460
1
    if index >= children.len() || matches!(children[index].root.get_node_type(), NodeType::Text(_))
461
    {
462
        host.children = children.into();
463
        return Err(DocumentEditError::TargetNotFound);
464
1
    }
465

            
466
1
    let wrapper = children.remove(index);
467
1
    let wrapper_shape = Dom {
468
1
        root: wrapper.root.clone(),
469
1
        children: Vec::<Dom>::new().into(),
470
1
        css: Vec::new().into(),
471
1
        estimated_total_children: 0,
472
1
    };
473
1
    let mut spliced: Vec<Dom> = wrapper.children.into_library_owned_vec();
474

            
475
    // Inverse range start: coalescing with a preceding text node moves the
476
    // start INTO it (at its pre-join byte length).
477
1
    let mut start = NodePosition::before_child(u32::try_from(index).unwrap_or(u32::MAX));
478
1
    if index > 0 {
479
1
        let coalesce_left = matches!(
480
            (
481
1
                children.get(index - 1).map(|c| c.root.get_node_type()),
482
1
                spliced.first().map(|c| c.root.get_node_type()),
483
            ),
484
            (Some(NodeType::Text(_)), Some(NodeType::Text(_)))
485
        );
486
1
        if coalesce_left {
487
1
            let first_spliced = spliced.remove(0);
488
1
            let (prev_len, joined) = match (
489
1
                children[index - 1].root.get_node_type(),
490
1
                first_spliced.root.get_node_type(),
491
            ) {
492
1
                (NodeType::Text(a), NodeType::Text(b)) => (
493
1
                    u32::try_from(a.as_str().len()).unwrap_or(u32::MAX),
494
1
                    format!("{}{}", a.as_str(), b.as_str()),
495
1
                ),
496
                _ => unreachable!("checked above"),
497
            };
498
1
            children[index - 1] = Dom::create_text_do_not_use_without_block_level_wrapper(joined);
499
1
            start =
500
1
                NodePosition::in_text_child(u32::try_from(index - 1).unwrap_or(u32::MAX), prev_len);
501
        }
502
    }
503

            
504
    // Splice the (remaining) children in.
505
1
    let spliced_count = spliced.len();
506
1
    let insert_at = index;
507
1
    for (offset, c) in spliced.into_iter().enumerate() {
508
        children.insert(insert_at + offset, c);
509
    }
510

            
511
    // The child that HOLDS the range end: the last spliced child, or — when
512
    // everything was absorbed into the left text node — that joined node.
513
1
    let (end_holder, mut end) = if spliced_count > 0 {
514
        let last = insert_at + spliced_count - 1;
515
        (
516
            Some(last),
517
            NodePosition::before_child(u32::try_from(last + 1).unwrap_or(u32::MAX)),
518
        )
519
1
    } else if start.text_byte.into_option().is_some() {
520
1
        let holder = index - 1;
521
1
        let byte = match children[holder].root.get_node_type() {
522
1
            NodeType::Text(t) => u32::try_from(t.as_str().len()).unwrap_or(u32::MAX),
523
            _ => 0,
524
        };
525
1
        (
526
1
            Some(holder),
527
1
            NodePosition::in_text_child(u32::try_from(holder).unwrap_or(u32::MAX), byte),
528
1
        )
529
    } else {
530
        // Empty wrapper removed: nothing to coalesce, range is empty.
531
        (
532
            None,
533
            NodePosition::before_child(u32::try_from(index).unwrap_or(u32::MAX)),
534
        )
535
    };
536

            
537
    // Right seam: the end-holder may coalesce with its follower (both text).
538
    // The inverse's end byte is the holder's length BEFORE the join — the
539
    // exact seam the original wrap cut.
540
1
    if let Some(holder) = end_holder {
541
1
        if holder + 1 < children.len() {
542
1
            let both_text = matches!(
543
                (
544
1
                    children[holder].root.get_node_type(),
545
1
                    children[holder + 1].root.get_node_type(),
546
                ),
547
                (NodeType::Text(_), NodeType::Text(_))
548
            );
549
1
            if both_text {
550
1
                let following = children.remove(holder + 1);
551
1
                let (seam_byte, joined) = match (
552
1
                    children[holder].root.get_node_type(),
553
1
                    following.root.get_node_type(),
554
                ) {
555
1
                    (NodeType::Text(a), NodeType::Text(b)) => (
556
1
                        u32::try_from(a.as_str().len()).unwrap_or(u32::MAX),
557
1
                        format!("{}{}", a.as_str(), b.as_str()),
558
1
                    ),
559
                    _ => unreachable!("checked above"),
560
                };
561
1
                children[holder] = Dom::create_text_do_not_use_without_block_level_wrapper(joined);
562
1
                end = NodePosition::in_text_child(
563
1
                    u32::try_from(holder).unwrap_or(u32::MAX),
564
1
                    seam_byte,
565
1
                );
566
            }
567
        }
568
    }
569

            
570
1
    host.children = children.into();
571
1
    Ok(DocumentOperation::WrapRange(
572
1
        crate::managers::changeset::DocOpWrapRange {
573
1
            node: unwrap.node,
574
1
            start,
575
1
            end,
576
1
            wrapper: wrapper_shape,
577
1
        },
578
1
    ))
579
1
}
580

            
581
/// Split a tree along a SPINE - the fragmentainer-flow cut.
582
///
583
/// `path` names, level by level, the child at which the document continues in
584
/// the NEXT fragmentainer (page/section). At every spine level the node's
585
/// shape (`NodeData`) is duplicated: children BEFORE the path index stay in
586
/// the head, the path child itself splits recursively, children AFTER move to
587
/// the tail. A `<section><ul>…` cut inside the `<ul>` yields two sections
588
/// each holding a `<ul>` - exactly how CSS fragmentation clones box chains
589
/// across fragmentainers (and how Word continues a list across a section
590
/// break).
591
///
592
/// An empty `path` puts EVERYTHING in the tail (cut before the root's
593
/// content); a path index past the child count puts the whole level in the
594
/// head. Counts are re-synced on both results.
595
#[must_use]
596
5
pub fn split_dom_at_path(dom: &Dom, path: &[u32]) -> (Dom, Dom) {
597
14
    fn shape_of(node: &Dom) -> Dom {
598
14
        Dom {
599
14
            root: node.root.clone(),
600
14
            children: Vec::new().into(),
601
14
            css: node.css.clone(),
602
14
            estimated_total_children: 0,
603
14
        }
604
14
    }
605
7
    fn rec(node: &Dom, path: &[u32]) -> (Dom, Dom) {
606
7
        let mut head = shape_of(node);
607
7
        let mut tail = shape_of(node);
608
7
        let Some((&idx, rest)) = path.split_first() else {
609
1
            tail.children = node.children.clone();
610
1
            return (head, tail);
611
        };
612
6
        let children = node.children.as_ref();
613
6
        let idx = idx as usize;
614
6
        let mut head_children: Vec<Dom> = children[..idx.min(children.len())].to_vec();
615
6
        let mut tail_children: Vec<Dom> = Vec::new();
616
6
        if idx < children.len() {
617
5
            if rest.is_empty() {
618
3
                // The cut lands BEFORE this child: it belongs to the tail.
619
3
                tail_children.push(children[idx].clone());
620
3
            } else {
621
2
                let (h, t) = rec(&children[idx], rest);
622
2
                head_children.push(h);
623
2
                tail_children.push(t);
624
2
            }
625
5
            tail_children.extend(children[idx + 1..].iter().cloned());
626
1
        }
627
6
        head.children = head_children.into();
628
6
        tail.children = tail_children.into();
629
6
        (head, tail)
630
7
    }
631
5
    let (mut head, mut tail) = rec(dom, path);
632
5
    head.fixup_children_estimated();
633
5
    tail.fixup_children_estimated();
634
5
    (head, tail)
635
5
}
636

            
637
#[cfg(test)]
638
mod tests {
639
    use azul_core::{
640
        dom::{DomId, DomNodeId},
641
        styled_dom::NodeHierarchyItemId,
642
        task::{Instant, SystemTick},
643
    };
644

            
645
    use super::*;
646
    use crate::managers::changeset::EditResumePoint;
647

            
648
37
    fn any_node() -> DomNodeId {
649
37
        DomNodeId {
650
37
            dom: DomId { inner: 0 },
651
37
            node: NodeHierarchyItemId::from_crate_internal(None),
652
37
        }
653
37
    }
654

            
655
19
    fn resume(node_index: u32, position: NodePosition) -> EditResumePoint {
656
19
        EditResumePoint {
657
19
            anchor_key: 1,
658
19
            node_path: vec![node_index].into(),
659
19
            position,
660
19
        }
661
19
    }
662

            
663
19
    fn changeset(op: DocumentOperation, r: EditResumePoint) -> DocumentChangeset {
664
19
        DocumentChangeset::new(any_node(), op, r, Instant::Tick(SystemTick::new(0)))
665
19
    }
666

            
667
25
    fn p(text: &str) -> Dom {
668
25
        let mut p = Dom::create_p();
669
25
        p.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
670
25
            text,
671
        ));
672
25
        p
673
25
    }
674

            
675
18
    fn el(tag: &str) -> Dom {
676
18
        Dom::create_node(azul_core::xml::tag_to_node_type(tag))
677
18
    }
678

            
679
6
    fn li(text: &str) -> Dom {
680
6
        let mut li = el("li");
681
6
        li.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
682
6
            text,
683
        ));
684
6
        li
685
6
    }
686

            
687
71
    fn collect_text(node: &Dom, out: &mut String) {
688
71
        if let NodeType::Text(t) = node.root.get_node_type() {
689
36
            out.push_str(t.as_str());
690
36
        }
691
71
        for c in node.children.as_ref() {
692
37
            collect_text(c, out);
693
37
        }
694
71
    }
695

            
696
    /// Flattened text of each direct child of the host (assertion helper -
697
    /// the OPERATIONS never flatten anything).
698
17
    fn texts(host: &Dom) -> Vec<String> {
699
17
        host.children
700
17
            .as_ref()
701
17
            .iter()
702
33
            .map(|c| {
703
33
                let mut t = String::new();
704
33
                collect_text(c, &mut t);
705
33
                t
706
33
            })
707
17
            .collect()
708
17
    }
709

            
710
    #[test]
711
1
    fn split_p_mid_text_at_start_and_at_end() {
712
3
        for (byte, first, second) in [
713
1
            (5, "hello", " world"),
714
1
            (0, "", "hello world"),
715
1
            (11, "hello world", ""),
716
        ] {
717
3
            let mut host = Dom::create_div();
718
3
            host.add_child(p("hello world"));
719
3
            let cs = changeset(
720
3
                DocumentOperation::SplitNode(DocOpSplitNode {
721
3
                    node: any_node(),
722
3
                    at: NodePosition::in_text_child(0, byte),
723
3
                }),
724
3
                resume(1, NodePosition::before_child(0)),
725
            );
726
3
            let applied = apply_document_operation(&mut host, &[], &cs).expect("split");
727
3
            assert_eq!(
728
3
                texts(&host),
729
3
                vec![first.to_string(), second.to_string()],
730
                "byte {byte}"
731
            );
732
3
            assert!(matches!(applied.inverse, DocumentOperation::MergeNodes(_)));
733
        }
734
1
    }
735

            
736
    #[test]
737
1
    fn split_preserves_nested_element_subtrees_wholesale() {
738
        // <p>["ab", <b>bold</b>, "cd"]</p> split at the BOUNDARY before <b>:
739
        // the <b> subtree must move to the second half INTACT — nothing is
740
        // flattened, re-parsed, or byte-walked.
741
1
        let mut host = Dom::create_div();
742
1
        let mut para = Dom::create_p();
743
1
        para.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
744
            "ab",
745
        ));
746
1
        let mut b = el("b");
747
1
        b.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
748
            "bold",
749
        ));
750
1
        para.add_child(b);
751
1
        para.add_child(Dom::create_text_do_not_use_without_block_level_wrapper(
752
            "cd",
753
        ));
754
1
        host.add_child(para);
755

            
756
1
        let cs = changeset(
757
1
            DocumentOperation::SplitNode(DocOpSplitNode {
758
1
                node: any_node(),
759
1
                at: NodePosition::before_child(1), // between "ab" and <b>
760
1
            }),
761
1
            resume(1, NodePosition::before_child(0)),
762
        );
763
1
        apply_document_operation(&mut host, &[], &cs).expect("split");
764

            
765
1
        assert_eq!(texts(&host), vec!["ab".to_string(), "boldcd".to_string()]);
766
        // The second half's first child is the <b> ELEMENT with its own text
767
        // child — subtree preserved.
768
1
        let second = &host.children.as_ref()[1];
769
1
        let b2 = &second.children.as_ref()[0];
770
1
        assert_eq!(b2.children.as_ref().len(), 1);
771
1
        let mut t = String::new();
772
1
        collect_text(b2, &mut t);
773
1
        assert_eq!(t, "bold");
774
1
    }
775

            
776
    #[test]
777
1
    fn split_ul_between_list_items_is_pure_structure() {
778
        // A <ul> with 3 <li> splits between items 1 and 2 — no text involved,
779
        // both halves keep the SAME node shape (ul → ul, never a tag swap).
780
1
        let mut host = Dom::create_div();
781
1
        let mut ul = el("ul");
782
1
        ul.add_child(li("one"));
783
1
        ul.add_child(li("two"));
784
1
        ul.add_child(li("three"));
785
1
        host.add_child(ul);
786

            
787
1
        let cs = changeset(
788
1
            DocumentOperation::SplitNode(DocOpSplitNode {
789
1
                node: any_node(),
790
1
                at: NodePosition::before_child(1),
791
1
            }),
792
1
            resume(1, NodePosition::before_child(0)),
793
        );
794
1
        apply_document_operation(&mut host, &[], &cs).expect("split ul");
795

            
796
1
        let kids = host.children.as_ref();
797
1
        assert_eq!(kids.len(), 2);
798
1
        assert_eq!(kids[0].children.as_ref().len(), 1, "first ul keeps [one]");
799
1
        assert_eq!(
800
1
            kids[1].children.as_ref().len(),
801
            2,
802
            "second ul takes [two, three]"
803
        );
804
1
        assert_eq!(
805
1
            core::mem::discriminant(kids[0].root.get_node_type()),
806
1
            core::mem::discriminant(kids[1].root.get_node_type()),
807
            "the second node clones the first's shape"
808
        );
809
1
    }
810

            
811
    #[test]
812
1
    fn split_never_cuts_inside_a_multibyte_char() {
813
1
        let mut host = Dom::create_div();
814
1
        host.add_child(p("aä!")); // ä = bytes 1..3
815
1
        let cs = changeset(
816
1
            DocumentOperation::SplitNode(DocOpSplitNode {
817
1
                node: any_node(),
818
1
                at: NodePosition::in_text_child(0, 2), // INSIDE ä
819
1
            }),
820
1
            resume(1, NodePosition::before_child(0)),
821
        );
822
1
        apply_document_operation(&mut host, &[], &cs).expect("split");
823
1
        assert_eq!(texts(&host), vec!["a".to_string(), "ä!".to_string()]);
824
1
    }
825

            
826
    #[test]
827
1
    fn merge_appends_wholesale_and_coalesces_text_only_at_a_text_seam() {
828
1
        let mut host = Dom::create_div();
829
1
        host.add_child(p("hello"));
830
1
        host.add_child(p(" world"));
831
1
        let cs = changeset(
832
1
            DocumentOperation::MergeNodes(DocOpMergeNodes {
833
1
                first: any_node(),
834
1
                second: any_node(),
835
1
                join: NodePosition::in_text_child(0, 5),
836
1
            }),
837
1
            resume(0, NodePosition::in_text_child(0, 5)),
838
        );
839
1
        let applied = apply_document_operation(&mut host, &[], &cs).expect("merge");
840
1
        assert_eq!(texts(&host), vec!["hello world".to_string()]);
841
1
        assert_eq!(
842
1
            host.children.as_ref()[0].children.as_ref().len(),
843
            1,
844
            "text seam coalesced into ONE text child"
845
        );
846
1
        match applied.inverse {
847
1
            DocumentOperation::SplitNode(s) => {
848
1
                assert_eq!(s.at, NodePosition::in_text_child(0, 5));
849
            }
850
            other => panic!("inverse must be the split at the seam, got {other:?}"),
851
        }
852

            
853
        // A pure structural merge (ul + ul) coalesces NOTHING.
854
1
        let mut host = Dom::create_div();
855
1
        let mut ul1 = el("ul");
856
1
        ul1.add_child(li("one"));
857
1
        let mut ul2 = el("ul");
858
1
        ul2.add_child(li("two"));
859
1
        host.add_child(ul1);
860
1
        host.add_child(ul2);
861
1
        let cs = changeset(
862
1
            DocumentOperation::MergeNodes(DocOpMergeNodes {
863
1
                first: any_node(),
864
1
                second: any_node(),
865
1
                join: NodePosition::before_child(1),
866
1
            }),
867
1
            resume(0, NodePosition::before_child(1)),
868
        );
869
1
        apply_document_operation(&mut host, &[], &cs).expect("merge uls");
870
1
        assert_eq!(host.children.as_ref().len(), 1);
871
1
        assert_eq!(host.children.as_ref()[0].children.as_ref().len(), 2);
872
1
    }
873

            
874
    #[test]
875
1
    fn split_then_inverse_merge_is_identity() {
876
1
        let mut original = Dom::create_div();
877
1
        original.add_child(p("hello world"));
878
1
        original.add_child(p("tail"));
879
1
        let mut host = original.clone();
880

            
881
1
        let split_cs = changeset(
882
1
            DocumentOperation::SplitNode(DocOpSplitNode {
883
1
                node: any_node(),
884
1
                at: NodePosition::in_text_child(0, 5),
885
1
            }),
886
1
            resume(1, NodePosition::before_child(0)),
887
        );
888
1
        let applied = apply_document_operation(&mut host, &[], &split_cs).expect("split");
889

            
890
1
        let merge_cs = changeset(
891
1
            applied.inverse,
892
1
            resume(0, NodePosition::in_text_child(0, 5)),
893
        );
894
1
        apply_document_operation(&mut host, &[], &merge_cs).expect("inverse merge");
895

            
896
1
        assert_eq!(
897
1
            texts(&host),
898
1
            texts(&original),
899
            "inverse-of-apply restores the tree"
900
        );
901
1
    }
902

            
903
    #[test]
904
1
    fn insert_remove_replace_close_their_inverse_algebra() {
905
        // insertChild: a fragment of TWO subtrees (a p and a whole ul) lands
906
        // at index 1; the inverse removes exactly that range.
907
1
        let mut host = Dom::create_div();
908
1
        host.add_child(p("one"));
909
1
        host.add_child(p("four"));
910

            
911
1
        let mut ul = el("ul");
912
1
        ul.add_child(li("x"));
913
1
        let cs = changeset(
914
1
            DocumentOperation::InsertChildren(DocOpInsertChildren {
915
1
                parent: any_node(),
916
1
                index: 1,
917
1
                content: fragment(vec![p("two"), ul]),
918
1
            }),
919
1
            resume(1, NodePosition::before_child(1)),
920
        );
921
1
        let inserted = apply_document_operation(&mut host, &[], &cs).expect("insert");
922
1
        assert_eq!(
923
1
            texts(&host),
924
1
            ["one", "two", "x", "four"].map(String::from).to_vec()
925
        );
926
1
        let DocumentOperation::RemoveChildren(ref rm) = inserted.inverse else {
927
            panic!("insert inverse must be a remove");
928
        };
929
1
        assert_eq!((rm.start, rm.end), (1, 3));
930

            
931
        // removeChild: applying the inverse removes both; ITS inverse
932
        // re-inserts the same fragment.
933
1
        let rm_cs = changeset(
934
1
            inserted.inverse.clone(),
935
1
            resume(1, NodePosition::before_child(1)),
936
        );
937
1
        let removed = apply_document_operation(&mut host, &[], &rm_cs).expect("remove");
938
1
        assert_eq!(texts(&host), vec!["one".to_string(), "four".to_string()]);
939
1
        let DocumentOperation::InsertChildren(ref ins) = removed.inverse else {
940
            panic!("remove inverse must be an insert");
941
        };
942
1
        assert_eq!(ins.index, 1);
943
1
        assert_eq!(
944
1
            ins.content.children.as_ref().len(),
945
            2,
946
            "removed fragment captured"
947
        );
948

            
949
        // replaceChild: swap [0..1) for two nodes; inverse restores.
950
1
        let mut host2 = Dom::create_div();
951
1
        host2.add_child(p("old"));
952
1
        let rep_cs = changeset(
953
1
            DocumentOperation::ReplaceChildren(DocOpReplaceChildren {
954
1
                parent: any_node(),
955
1
                start: 0,
956
1
                end: 1,
957
1
                content: fragment(vec![p("new1"), p("new2")]),
958
1
            }),
959
1
            resume(0, NodePosition::before_child(0)),
960
        );
961
1
        let replaced = apply_document_operation(&mut host2, &[], &rep_cs).expect("replace");
962
1
        assert_eq!(texts(&host2), vec!["new1".to_string(), "new2".to_string()]);
963
1
        let inv_cs = changeset(replaced.inverse, resume(0, NodePosition::before_child(0)));
964
1
        apply_document_operation(&mut host2, &[], &inv_cs).expect("inverse replace");
965
1
        assert_eq!(texts(&host2), vec!["old".to_string()]);
966
1
    }
967

            
968
    #[test]
969
1
    fn wrap_mid_text_range_cuts_boundaries_and_unwrap_round_trips() {
970
        // Bold "world" inside <p>"hello world extra"</p>: both boundaries cut
971
        // the SAME text child; the wrapper takes exactly the covered bytes.
972
1
        let mut host = p("hello world extra");
973
1
        let wrapper = el("b");
974
1
        let cs = changeset(
975
1
            DocumentOperation::WrapRange(crate::managers::changeset::DocOpWrapRange {
976
1
                node: any_node(),
977
1
                start: NodePosition::in_text_child(0, 6),
978
1
                end: NodePosition::in_text_child(0, 11),
979
1
                wrapper: wrapper.clone(),
980
1
            }),
981
1
            resume(0, NodePosition::before_child(0)),
982
        );
983
1
        let applied = apply_document_operation(&mut host, &[], &cs).expect("wrap");
984

            
985
        // Children now: ["hello ", <b>"world"</b>, " extra"].
986
1
        let kids = host.children.as_ref();
987
1
        assert_eq!(kids.len(), 3, "{:?}", texts(&host));
988
1
        assert_eq!(
989
1
            texts(&host),
990
1
            ["hello ", "world", " extra"].map(String::from).to_vec()
991
        );
992
1
        assert!(
993
            matches!(
994
1
                kids[1].root.get_node_type(),
995
                NodeType::B | NodeType::Div | NodeType::Strong
996
            ) || !matches!(kids[1].root.get_node_type(), NodeType::Text(_))
997
        );
998

            
999
        // Unwrap (the inverse) restores ONE coalesced text child.
1
        let DocumentOperation::UnwrapRange(ref uw) = applied.inverse else {
            panic!("wrap inverse must be an unwrap");
        };
1
        assert_eq!(uw.at.child_index, 1);
1
        let un_cs = changeset(applied.inverse, resume(0, NodePosition::before_child(0)));
1
        let unwrapped = apply_document_operation(&mut host, &[], &un_cs).expect("unwrap");
1
        assert_eq!(host.children.as_ref().len(), 1, "seams coalesced back");
1
        assert_eq!(texts(&host), vec!["hello world extra".to_string()]);
        // And the unwrap's inverse is the wrap over the same byte range.
1
        match unwrapped.inverse {
1
            DocumentOperation::WrapRange(w) => {
1
                assert_eq!(w.start, NodePosition::in_text_child(0, 6));
1
                assert_eq!(w.end, NodePosition::in_text_child(0, 11));
            }
            other => panic!("unwrap inverse must be the wrap, got {other:?}"),
        }
1
    }
    #[test]
1
    fn wrap_whole_elements_is_the_same_op_as_bolding_a_word() {
        // Wrap paragraphs 2..4 of a div in a <blockquote> — pure structure,
        // no text involved, subtrees move wholesale.
1
        let mut host = Dom::create_div();
4
        for t in ["one", "two", "three", "four"] {
4
            host.add_child(p(t));
4
        }
1
        let cs = changeset(
1
            DocumentOperation::WrapRange(crate::managers::changeset::DocOpWrapRange {
1
                node: any_node(),
1
                start: NodePosition::before_child(1),
1
                end: NodePosition::before_child(3),
1
                wrapper: el("blockquote"),
1
            }),
1
            resume(0, NodePosition::before_child(1)),
        );
1
        apply_document_operation(&mut host, &[], &cs).expect("wrap blocks");
1
        let kids = host.children.as_ref();
1
        assert_eq!(kids.len(), 3, "{:?}", texts(&host));
1
        assert_eq!(
1
            kids[1].children.as_ref().len(),
            2,
            "blockquote took [two, three]"
        );
1
        assert_eq!(
1
            texts(&host),
1
            ["one", "twothree", "four"].map(String::from).to_vec()
        );
1
    }
    #[test]
1
    fn failures_leave_the_tree_unchanged() {
1
        let mut original = Dom::create_div();
1
        original.add_child(p("only"));
1
        let mut host = original.clone();
1
        let cs = changeset(
1
            DocumentOperation::MergeNodes(DocOpMergeNodes {
1
                first: any_node(),
1
                second: any_node(),
1
                join: NodePosition::before_child(1),
1
            }),
1
            resume(0, NodePosition::before_child(1)),
        );
1
        assert_eq!(
1
            apply_document_operation(&mut host, &[], &cs).unwrap_err(),
            DocumentEditError::TargetNotFound
        );
1
        assert_eq!(texts(&host), texts(&original));
1
        let cs2 = changeset(
1
            DocumentOperation::RemoveChildren(DocOpRemoveChildren {
1
                parent: any_node(),
1
                start: 0,
1
                end: 1,
1
            }),
1
            resume(0, NodePosition::before_child(0)),
        );
1
        assert_eq!(
1
            apply_document_operation(&mut host, &[7, 7], &cs2).unwrap_err(),
            DocumentEditError::HostNotFound
        );
1
    }
    // ==================================================================
    // split_dom_at_path — the fragmentainer spine cut
    // ==================================================================
    #[test]
1
    fn spine_split_partitions_flat_children() {
1
        let doc = fragment(vec![p("a"), p("b"), p("c")]);
1
        let (head, tail) = split_dom_at_path(&doc, &[1]);
1
        assert_eq!(head.children.as_ref().len(), 1, "a stays");
1
        assert_eq!(tail.children.as_ref().len(), 2, "b + c flow on");
1
        assert_eq!(
            head.estimated_total_children,
1
            head.children.as_ref().len() + 1
        );
1
    }
    #[test]
1
    fn spine_split_clones_the_box_chain_at_depth() {
        // section > ul > li,li,li — cut before the third li: BOTH results
        // hold a section>ul chain (the CSS fragmentation box-chain clone).
1
        let mut ul = el("ul");
1
        ul.add_child(el("li"));
1
        ul.add_child(el("li"));
1
        ul.add_child(el("li"));
1
        let mut section = el("section");
1
        section.add_child(ul);
1
        let doc = fragment(vec![section]);
1
        let (head, tail) = split_dom_at_path(&doc, &[0, 0, 2]);
1
        let head_ul = &head.children.as_ref()[0].children.as_ref()[0];
1
        let tail_ul = &tail.children.as_ref()[0].children.as_ref()[0];
1
        assert_eq!(head_ul.children.as_ref().len(), 2);
1
        assert_eq!(tail_ul.children.as_ref().len(), 1);
1
        assert_eq!(
1
            head.children.as_ref()[0].root.get_node_type(),
1
            tail.children.as_ref()[0].root.get_node_type(),
            "the section shape duplicates across the cut"
        );
1
    }
    #[test]
1
    fn spine_split_edge_paths() {
1
        let doc = fragment(vec![p("a"), p("b")]);
        // Empty path: everything flows to the tail.
1
        let (h, t) = split_dom_at_path(&doc, &[]);
1
        assert_eq!(h.children.as_ref().len(), 0);
1
        assert_eq!(t.children.as_ref().len(), 2);
        // Past-the-end: everything stays in the head.
1
        let (h, t) = split_dom_at_path(&doc, &[9]);
1
        assert_eq!(h.children.as_ref().len(), 2);
1
        assert_eq!(t.children.as_ref().len(), 0);
1
    }
}
impl_result!(
    AppliedEdit,
    DocumentEditError,
    ResultAppliedEditDocumentEditError,
    copy = false,
    [Debug, Clone]
);
/// The two halves of [`split_dom_at_path`] as an ABI-crossable pair.
///
/// `head` = everything strictly BEFORE the addressed node (document order),
/// `tail` = the addressed node and everything after it. An empty/invalid
/// path yields the documented `split_dom_at_path` fallback in each half.
#[repr(C)]
#[derive(Debug)]
pub struct DomSplit {
    pub head: Dom,
    pub tail: Dom,
}
impl DomSplit {
    /// [`split_dom_at_path`] for API consumers (the tuple return does not
    /// cross the ABI): split `dom` at the root-to-node child-index `path` -
    /// the same paths [`crate::solver3::paged_layout::StructuralBreak`]
    /// carries and `PaginationSnapshot::break_path` hands out.
    #[must_use]
    pub fn at_path(dom: &Dom, path: azul_css::corety::U32Vec) -> Self {
        let (head, tail) = split_dom_at_path(dom, path.as_ref());
        Self { head, tail }
    }
}