taino-edit-dom 0.5.3

contenteditable/DOM bridge for the taino-edit WYSIWYG editor (web-sys, wasm-bindgen, js-sys).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
//! [`EditorView`] — mount a document into a `contenteditable` element and
//! own the [`ViewDesc`] tree that mirrors it.
//!
//! v0.1 / Unit A: initial render only. Incremental diff/patch, selection
//! sync, `MutationObserver`, IME and clipboard land in subsequent units of
//! Phase 4.

use std::cell::Cell;

use taino_edit_core::{Command, DomSpec, Fragment, Node, Schema, Selection, Slice, Transform};
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{Document, Element};

use crate::decoration::Decoration;
use crate::desc::ViewDesc;
use crate::position_map::{doc_pos_to_dom, dom_to_doc_pos};

/// What a [`ViewPlugin`] asks the editor to do in response to a DOM event.
pub enum ViewAction {
    /// Replace the selection (e.g. a cell drag selecting a range).
    Select(Selection),
    /// Run an editing [`Command`] against the state (e.g. a column resize
    /// reusing `set_column_width`). The adapter applies it to its state.
    Command(Command),
}

/// A DOM-aware editor plugin: it reacts to raw browser events and
/// contributes [`Decoration`]s, with access to the live [`EditorView`] (its
/// document, schema and DOM-position primitives). Extensions whose
/// behaviour is purely structural use the schema/keymap surface in
/// `taino-edit-extensions`; those needing real pointer interaction
/// (table cell-drag-select, column resizing, …) implement this instead.
///
/// Adapters wire the editor's pointer/keyboard events to
/// [`EditorView::handle_view_event`] and refresh decorations through
/// [`EditorView::refresh_view_decorations`]; a plugin therefore stays
/// framework-agnostic.
pub trait ViewPlugin {
    /// Handle a raw DOM event. Return an action to apply, or `None` to pass.
    fn handle_event(&self, _view: &EditorView, _event: &web_sys::Event) -> Option<ViewAction> {
        None
    }

    /// Decorations to render for the current document and selection.
    fn decorations(&self, _view: &EditorView, _selection: Option<Selection>) -> Vec<Decoration> {
        Vec::new()
    }
}

/// The DOM-bound editor view.
pub struct EditorView {
    root: Element,
    schema: Schema,
    doc: Node,
    /// Descriptors mirroring `doc.content()` children. The document node
    /// itself is "transparent" — its children become the direct children of
    /// the root element.
    children: Vec<ViewDesc>,
    /// `true` while an IME composition is in progress — adapters wire
    /// `compositionstart`/`compositionend` to flip it. While set,
    /// [`read_dom_changes`](EditorView::read_dom_changes) returns `None` so
    /// transient intermediate-glyph states never trigger transactions.
    composing: Cell<bool>,
    /// Decorations currently applied on top of the rendered DOM.
    decorations: Vec<Decoration>,
    /// DOM-aware plugins consulted for event handling and decorations.
    plugins: Vec<Box<dyn ViewPlugin>>,
    /// The overlay layer for inline (range-level) decorations, created lazily
    /// as a *sibling* of `root`. Kept out of `root` so it never shifts the
    /// root's child indexing that selection mapping depends on.
    overlay: Option<Element>,
}

impl std::fmt::Debug for EditorView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EditorView")
            .field("doc", &self.doc)
            .field("children", &self.children)
            .field("decorations", &self.decorations)
            .field("plugins", &self.plugins.len())
            .finish_non_exhaustive()
    }
}

impl Drop for EditorView {
    fn drop(&mut self) {
        // The inline-decoration overlay is a sibling of `root`, so it would
        // otherwise outlive the view when the adapter removes the editor.
        if let Some(layer) = &self.overlay {
            if let Some(parent) = layer.parent_element() {
                let _ = parent.remove_child(layer);
            }
        }
    }
}

impl EditorView {
    /// Mount `doc` into `root`, marking the latter `contenteditable` and
    /// replacing any pre-existing children. Also sets `tabindex="0"` so the
    /// editor is reachable via the keyboard's Tab focus chain (a11y baseline);
    /// callers can change it later with [`set_tabindex`](EditorView::set_tabindex).
    pub fn mount(doc: Node, schema: Schema, root: Element) -> Self {
        let _ = root.set_attribute("contenteditable", "true");
        if !root.has_attribute("tabindex") {
            let _ = root.set_attribute("tabindex", "0");
        }
        let document = root
            .owner_document()
            .expect("root element has an owner Document");

        // Empty `root`.
        while let Some(child) = root.first_child() {
            if root.remove_child(&child).is_err() {
                break; // never spin if a child can't be removed
            }
        }

        let mut children = Vec::with_capacity(doc.child_count());
        for child in doc.content().iter() {
            let desc = render(child, &document);
            let _ = root.append_child(&desc.dom_node());
            children.push(desc);
        }

        EditorView {
            root,
            schema,
            doc,
            children,
            composing: Cell::new(false),
            decorations: Vec::new(),
            plugins: Vec::new(),
            overlay: None,
        }
    }

    /// Install the DOM-aware [`ViewPlugin`]s (replacing any existing set).
    pub fn set_view_plugins(&mut self, plugins: Vec<Box<dyn ViewPlugin>>) {
        self.plugins = plugins;
    }

    /// Offer a raw DOM event to each view plugin in turn; returns the first
    /// [`ViewAction`] a plugin produces (the adapter applies it to state).
    pub fn handle_view_event(&self, event: &web_sys::Event) -> Option<ViewAction> {
        for p in &self.plugins {
            if let Some(action) = p.handle_event(self, event) {
                return Some(action);
            }
        }
        None
    }

    /// Recompute decorations from every plugin for the given selection and
    /// apply them. Adapters call this after the state signal changes.
    pub fn refresh_view_decorations(&mut self, selection: Option<Selection>) {
        let decos: Vec<Decoration> = self
            .plugins
            .iter()
            .flat_map(|p| p.decorations(self, selection))
            .collect();
        self.set_decorations(decos);
    }

    /// Map a viewport point to the document position just before the
    /// innermost rendered node element under it (walking up from
    /// `elementFromPoint` to the nearest node in the view tree). Used by
    /// pointer-driven plugins (e.g. table cell drag-select). `None` if the
    /// point isn't over the editor.
    pub fn pos_at_point(&self, x: f32, y: f32) -> Option<usize> {
        let document = web_sys::window()?.document()?;
        let mut el = document.element_from_point(x, y)?;
        loop {
            if let Some(pos) = pos_before_element(&self.children, 0, &el) {
                return Some(pos);
            }
            let parent = el.parent_element()?;
            let same_root = parent.is_same_node(Some(self.root.as_ref()));
            if !same_root && !self.root.contains(Some(parent.as_ref())) {
                return None;
            }
            el = parent;
        }
    }

    /// The DOM element of the node that begins at document position `pos`
    /// (any depth — block or nested cell). Used by pointer plugins to read
    /// a cell's geometry (e.g. for column-resize hit-testing).
    pub fn node_dom_at(&self, pos: usize) -> Option<Element> {
        dom_element_at(&self.children, 0, pos).cloned()
    }

    /// Replace the set of decorations applied on top of the rendered DOM.
    /// Previous decorations are removed; new ones are applied. Decorations
    /// that target positions outside the current document are silently
    /// skipped.
    ///
    /// [`Node`](Decoration::Node) decorations toggle a CSS class on the target
    /// element; [`Inline`](Decoration::Inline) decorations are drawn as boxes
    /// in an overlay layer that is rebuilt wholesale on every call.
    pub fn set_decorations(&mut self, decorations: Vec<Decoration>) {
        // Node decorations: remove the previous class set, then add the new.
        for d in &self.decorations {
            if matches!(d, Decoration::Node { .. }) {
                apply_decoration(&self.children, d, false);
            }
        }
        for d in &decorations {
            if matches!(d, Decoration::Node { .. }) {
                apply_decoration(&self.children, d, true);
            }
        }
        self.decorations = decorations;
        // Inline decorations: create the overlay layer only when needed, then
        // (re)paint it from the current decoration set.
        let any_inline = self
            .decorations
            .iter()
            .any(|d| matches!(d, Decoration::Inline { .. }));
        let _ = self.ensure_overlay(any_inline);
        self.paint_inline_overlay();
    }

    /// The decorations currently applied.
    pub fn decorations(&self) -> &[Decoration] {
        &self.decorations
    }

    /// Recompute the inline-decoration overlay against the *current* layout.
    ///
    /// The boxes are positioned from live client rects, so they only stay
    /// aligned with the text while the layout is unchanged. Adapters wire this
    /// to `scroll` (capture) and `resize` so highlights track the text when
    /// the geometry shifts without a document edit. A no-op when there is no
    /// overlay (i.e. no inline decorations).
    pub fn reposition_inline_decorations(&self) {
        self.paint_inline_overlay();
    }

    /// Clear and redraw the overlay boxes for the current inline decorations.
    /// Each inline range becomes one box per client rect (so a range spanning
    /// lines draws several boxes), positioned over the text it covers. The
    /// overlay is a sibling of `root`, so this never alters the editable DOM —
    /// typing and the diff/patch read-back are unaffected.
    ///
    /// Takes `&self`: it mutates the overlay element + document DOM (both
    /// interior-mutable handles) but no view field, so `scroll`/`resize`
    /// handlers can call it through a shared reference.
    fn paint_inline_overlay(&self) {
        let Some(layer) = &self.overlay else {
            return;
        };
        layer.set_inner_html("");
        let Some(document) = self.root.owner_document() else {
            return;
        };
        // The overlay sits at its containing block's origin; its own client
        // rect gives that origin in viewport coordinates, so each box can be
        // placed relative to it regardless of the positioning context.
        let origin = layer.get_bounding_client_rect();
        for d in &self.decorations {
            let Decoration::Inline { from, to, class } = d else {
                continue;
            };
            let (Some((sn, so)), Some((en, eo))) = (
                doc_pos_to_dom(&self.root, &self.children, *from),
                doc_pos_to_dom(&self.root, &self.children, *to),
            ) else {
                continue;
            };
            let Ok(range) = document.create_range() else {
                continue;
            };
            if range.set_start(&sn, so).is_err() || range.set_end(&en, eo).is_err() {
                continue;
            }
            let Some(rects) = range.get_client_rects() else {
                continue;
            };
            for i in 0..rects.length() {
                let Some(r) = rects.get(i) else { continue };
                if r.width() <= 0.0 && r.height() <= 0.0 {
                    continue;
                }
                let Ok(box_el) = document.create_element("span") else {
                    continue;
                };
                let _ = box_el.set_attribute("class", class);
                let style = format!(
                    "position:absolute;left:{:.2}px;top:{:.2}px;width:{:.2}px;\
                     height:{:.2}px;pointer-events:none;",
                    r.left() - origin.left(),
                    r.top() - origin.top(),
                    r.width(),
                    r.height(),
                );
                let _ = box_el.set_attribute("style", &style);
                let _ = layer.append_child(&box_el);
            }
        }
    }

    /// The overlay layer, created as a sibling of `root` on first need. When
    /// `want` is false and no overlay exists yet, returns `None` (don't make
    /// one only to clear it). `None` too if `root` has no parent to host it.
    fn ensure_overlay(&mut self, want: bool) -> Option<Element> {
        if let Some(layer) = &self.overlay {
            return Some(layer.clone());
        }
        if !want {
            return None;
        }
        let parent = self.root.parent_element()?;
        let document = self.root.owner_document()?;
        let layer = document.create_element("div").ok()?;
        let _ = layer.set_attribute("class", "taino-deco-layer");
        let _ = layer.set_attribute(
            "style",
            "position:absolute;left:0;top:0;width:0;height:0;pointer-events:none;",
        );
        let _ = parent.append_child(&layer);
        self.overlay = Some(layer.clone());
        Some(layer)
    }

    /// Programmatically focus the editor.
    pub fn focus(&self) -> Result<(), JsValue> {
        let el: web_sys::HtmlElement = self.root.clone().dyn_into()?;
        el.focus()
    }

    /// Whether the editor is the document's active (focused) element.
    pub fn has_focus(&self) -> bool {
        let Some(document) = self.root.owner_document() else {
            return false;
        };
        let Some(active) = document.active_element() else {
            return false;
        };
        wasm_bindgen::JsValue::from(active) == wasm_bindgen::JsValue::from(&self.root)
    }

    /// Override the tab index. Pass `-1` to take the editor out of the Tab
    /// focus chain (mouse-only); `0` to put it back in normal flow.
    pub fn set_tabindex(&self, n: i32) {
        let _ = self.root.set_attribute("tabindex", &n.to_string());
    }

    /// Wire this from the host's `compositionstart` event handler.
    pub fn composition_start(&self) {
        self.composing.set(true);
    }

    /// Wire this from the host's `compositionend` event handler. The
    /// committed text is now stable in the DOM, so `read_dom_changes()`
    /// will once again report changes.
    pub fn composition_end(&self) {
        self.composing.set(false);
    }

    /// Whether an IME composition is in progress.
    pub fn is_composing(&self) -> bool {
        self.composing.get()
    }

    /// The mounted root element.
    pub fn root(&self) -> &Element {
        &self.root
    }

    /// The schema this view was mounted against.
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// The current document.
    pub fn doc(&self) -> &Node {
        &self.doc
    }

    /// The view descriptors mirroring the document's top-level children.
    pub fn children(&self) -> &[ViewDesc] {
        &self.children
    }

    /// Write the editor selection to the browser's `window.getSelection()`.
    ///
    /// Text selections map both endpoints; node selections collapse to the
    /// node's start/end positions; an all-selection covers the whole root.
    /// Returns `Err` if the underlying DOM call rejects (e.g. no window).
    pub fn set_selection(&self, sel: Selection) -> Result<(), JsValue> {
        let window = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?;
        let selection = window
            .get_selection()?
            .ok_or_else(|| JsValue::from_str("no Selection api"))?;

        let (anchor_pos, head_pos) = match sel {
            Selection::Text { anchor, head } => (anchor, head),
            Selection::Node { pos } => {
                let len = self.doc.node_at(pos).map(|n| n.node_size()).unwrap_or(0);
                (pos, pos + len)
            }
            Selection::Cell { anchor, head } => {
                // Render as a contiguous range covering both cells. A
                // browser Range can't paint a true rectangular cell
                // selection; the editor highlights cells via decorations.
                let lo = anchor.min(head);
                let hi = anchor.max(head);
                let hi_end = self
                    .doc
                    .node_at(hi)
                    .map(|n| hi + n.node_size())
                    .unwrap_or(hi);
                (lo, hi_end)
            }
            Selection::All => (0, self.doc.content().size()),
        };

        let (anchor_node, anchor_off) = doc_pos_to_dom(&self.root, &self.children, anchor_pos)
            .ok_or_else(|| JsValue::from_str("anchor out of range"))?;
        let (focus_node, focus_off) = doc_pos_to_dom(&self.root, &self.children, head_pos)
            .ok_or_else(|| JsValue::from_str("head out of range"))?;

        selection.remove_all_ranges()?;
        selection.set_base_and_extent(&anchor_node, anchor_off, &focus_node, focus_off)
    }

    /// Read the current browser selection and translate its endpoints back
    /// into a doc-level [`Selection::Text`]. `None` if the browser has no
    /// selection (or anchor/focus are outside the mounted root).
    pub fn read_selection(&self) -> Option<Selection> {
        let window = web_sys::window()?;
        let selection = window.get_selection().ok().flatten()?;
        let anchor_node = selection.anchor_node()?;
        let focus_node = selection.focus_node()?;
        let anchor = dom_to_doc_pos(
            &self.root,
            &self.children,
            &anchor_node,
            selection.anchor_offset(),
        )?;
        let head = dom_to_doc_pos(
            &self.root,
            &self.children,
            &focus_node,
            selection.focus_offset(),
        )?;
        Some(Selection::Text { anchor, head })
    }

    /// Detect a divergence between a text node's DOM contents and its
    /// document text (the typical effect of typing/IME), and produce a
    /// [`Transform`] that, when applied to the current doc, brings them back
    /// into sync. Returns `None` if every text run matches.
    ///
    /// v0.1 reports the first divergent text run. Adapters wire this up
    /// behind a `MutationObserver` so it runs on every browser-side edit.
    /// During an IME composition (see [`composition_start`]) it returns
    /// `None` so transient glyph states never produce transactions; the
    /// host commits the change from the `compositionend` handler after
    /// calling [`composition_end`].
    ///
    /// [`composition_start`]: EditorView::composition_start
    /// [`composition_end`]: EditorView::composition_end
    pub fn read_dom_changes(&self) -> Option<Transform> {
        if self.composing.get() {
            return None;
        }
        let mut found = None;
        collect_text_changes(&self.children, 0, &mut |desc, doc_pos| {
            if found.is_some() {
                return;
            }
            if let ViewDesc::Text { node, text, .. } = desc {
                let dom_data = text.data();
                let doc_text = node.text().unwrap_or("");
                if dom_data != doc_text {
                    if let Some((offset, old_len, new_part)) = find_diff(doc_text, &dom_data) {
                        found = Some((doc_pos + offset, old_len, new_part, node.clone()));
                    }
                }
            }
        });
        if let Some((pos, old_len, new_text, prev_text_node)) = found {
            let mut transform = Transform::new(self.doc.clone());
            let replacement = if new_text.is_empty() {
                Slice::empty()
            } else {
                let new_node = self
                    .schema
                    .text(&new_text, prev_text_node.marks().to_vec())
                    .ok()?;
                Slice::new(Fragment::from_node(new_node), 0, 0)
            };
            transform
                .replace(pos, pos + old_len, replacement, &self.schema)
                .ok()?;
            return Some(transform);
        }

        // No existing text run changed. Detect text the browser inserted into a
        // previously-empty textblock (no text descriptor exists to diff), e.g.
        // typing into the new paragraph created by pressing Enter.
        if let Some((pos, text)) = find_empty_block_text(&self.children, 0) {
            let new_node = self.schema.text(&text, vec![]).ok()?;
            let mut transform = Transform::new(self.doc.clone());
            transform
                .replace(
                    pos,
                    pos,
                    Slice::new(Fragment::from_node(new_node), 0, 0),
                    &self.schema,
                )
                .ok()?;
            return Some(transform);
        }
        None
    }

    /// The currently-selected document range (or, when the selection lies
    /// outside the mounted root, `None`).
    fn paste_range(&self) -> Option<(usize, usize)> {
        let sel = self.read_selection()?;
        Some(match sel {
            Selection::Text { anchor, head } => (anchor.min(head), anchor.max(head)),
            Selection::Node { pos } => {
                let len = self.doc.node_at(pos).map(|n| n.node_size()).unwrap_or(0);
                (pos, pos + len)
            }
            Selection::Cell { anchor, head } => {
                let lo = anchor.min(head);
                let hi = anchor.max(head);
                let hi_end = self
                    .doc
                    .node_at(hi)
                    .map(|n| hi + n.node_size())
                    .unwrap_or(hi);
                (lo, hi_end)
            }
            Selection::All => (0, self.doc.content().size()),
        })
    }

    /// Paste plain text at the current DOM selection, returning the
    /// resulting [`Transform`]. The text becomes a new text node with no
    /// marks; the prior selection is replaced (range or caret).
    pub fn paste_text(&self, text: &str) -> Option<Transform> {
        let (from, to) = self.paste_range()?;
        let mut transform = Transform::new(self.doc.clone());
        let slice = if text.is_empty() {
            Slice::empty()
        } else {
            let node = self.schema.text(text, vec![]).ok()?;
            Slice::new(Fragment::from_node(node), 0, 0)
        };
        transform.replace(from, to, slice, &self.schema).ok()?;
        Some(transform)
    }

    /// Paste HTML at the current DOM selection. The HTML is parsed through
    /// [`Schema::parse_html`] — which is already strict and depth-bounded,
    /// so untrusted clipboard content cannot inject schema-illegal
    /// structure — and the resulting blocks are spliced into the range.
    /// Returns `None` when parsing fails or the replacement would violate
    /// the schema for the destination.
    pub fn paste_html(&self, html: &str) -> Option<Transform> {
        let parsed = self.schema.parse_html(html).ok()?;
        let (from, to) = self.paste_range()?;
        let slice = Slice::new(parsed.content().clone(), 0, 0);
        let mut transform = Transform::new(self.doc.clone());
        transform.replace(from, to, slice, &self.schema).ok()?;
        Some(transform)
    }

    /// Paste Markdown at the current DOM selection. The text is parsed
    /// through [`taino_edit_core::markdown::parse_markdown`] and validated
    /// against the schema, so unknown constructs are dropped rather than
    /// breaking the doc. Adapters prefer this over `paste_text` when the
    /// clipboard advertises `text/markdown`.
    pub fn paste_markdown(&self, md: &str) -> Option<Transform> {
        let parsed = taino_edit_core::markdown::parse_markdown(&self.schema, md).ok()?;
        let (from, to) = self.paste_range()?;
        let slice = Slice::new(parsed.content().clone(), 0, 0);
        let mut transform = Transform::new(self.doc.clone());
        transform.replace(from, to, slice, &self.schema).ok()?;
        Some(transform)
    }

    /// Extract a [`Slice`] of the document between `from` and `to` — what
    /// adapters dispatch as the "dragged content" on `dragstart`. Returns
    /// `None` if the range is out of bounds.
    pub fn extract_slice(&self, from: usize, to: usize) -> Option<Slice> {
        self.doc.slice(from, to).ok()
    }

    /// Insert `slice` at document position `at`, producing the
    /// [`Transform`] that commits the drop. Returns `None` when the
    /// resulting doc would violate the schema (e.g. dropping a block into
    /// inline content).
    pub fn drop_slice(&self, slice: &Slice, at: usize) -> Option<Transform> {
        let mut transform = Transform::new(self.doc.clone());
        transform
            .replace(at, at, slice.clone(), &self.schema)
            .ok()?;
        Some(transform)
    }

    /// Reconcile the mounted DOM with `new_doc`, performing minimal
    /// mutations: identical subtrees are kept, text-only changes set
    /// `nodeValue` in place, same-type elements recurse, and only nodes that
    /// truly changed are removed/replaced/appended.
    pub fn update(&mut self, new_doc: Node) {
        let document = self
            .root
            .owner_document()
            .expect("root element has an owner Document");
        let new_kids: Vec<Node> = new_doc.content().iter().cloned().collect();
        let new_descs = patch_children(&document, &self.root, &self.children, &new_kids);
        self.children = new_descs;
        self.doc = new_doc;
    }
}

/// Build a `ViewDesc` for `node`, creating its DOM subtree along the way.
fn render(node: &Node, document: &Document) -> ViewDesc {
    if node.is_text() {
        return render_text(node, document);
    }

    let dom_el = match node.node_type().spec().to_dom {
        Some(f) => create_element(document, &f(node)),
        // Transparent / unrendered nodes still need *some* container so
        // editing inside them works; a `<span>` is the conservative default.
        None => document
            .create_element("span")
            .expect("create_element succeeds for `span`"),
    };

    let mut children = Vec::with_capacity(node.child_count());
    for child in node.content().iter() {
        let cd = render(child, document);
        let _ = dom_el.append_child(&cd.dom_node());
        children.push(cd);
    }

    // An empty textblock needs a trailing <br> to be focusable / typable.
    if children.is_empty() && is_textblock(node) {
        append_trailing_break(document, &dom_el);
    }

    ViewDesc::Element {
        node: node.clone(),
        dom: dom_el,
        children,
    }
}

/// Render a text node, wrapping it with the DOM elements declared by its
/// marks (innermost = the raw text node).
fn render_text(node: &Node, document: &Document) -> ViewDesc {
    let text_node = document.create_text_node(node.text().unwrap_or(""));
    let mut current: web_sys::Node = text_node.clone().into();
    let mut wrapper: Option<Element> = None;
    for mark in node.marks() {
        let Some(f) = mark.mark_type().spec().to_dom else {
            continue;
        };
        let el = create_element(document, &f(mark));
        let _ = el.append_child(&current);
        current = el.clone().into();
        wrapper = Some(el);
    }
    ViewDesc::Text {
        node: node.clone(),
        text: text_node,
        wrapper,
    }
}

/// Marker attribute on the synthetic trailing `<br>` we add to empty
/// textblocks so the caret can land in them (a bare `<p></p>` is zero-height
/// and unfocusable in `contenteditable`). Lets us find/remove only *our* break
/// and skip it when reading text back.
const TRAILING_BREAK_ATTR: &str = "data-taino-trailing-break";

/// A block node that holds *inline* content (paragraph, heading, code block,
/// …) — the nodes that need a trailing break when empty. Block *containers*
/// (doc, blockquote, list, list item, table cell) hold other blocks and must
/// **not** be treated as textblocks: doing so would (a) add stray breaks and
/// (b) make `reconcile_trailing_break` strip a nested block's break. We detect
/// inline content from the content expression (`inline*`, `text*`, …).
fn is_textblock(node: &Node) -> bool {
    node.node_type().is_block()
        && node
            .node_type()
            .spec()
            .content
            .as_deref()
            .is_some_and(|c| c.contains("inline") || c.contains("text"))
}

/// Append a synthetic trailing `<br>` to `el`.
fn append_trailing_break(document: &Document, el: &Element) {
    if let Ok(br) = document.create_element("br") {
        let _ = br.set_attribute(TRAILING_BREAK_ATTR, "");
        let _ = el.append_child(&br);
    }
}

/// Our trailing break among `el`'s **direct** children (never a descendant —
/// we must not touch a nested block's break).
fn direct_trailing_break(el: &Element) -> Option<Element> {
    let kids = el.child_nodes();
    for i in 0..kids.length() {
        if let Some(node) = kids.item(i) {
            if let Ok(e) = node.dyn_into::<Element>() {
                if e.has_attribute(TRAILING_BREAK_ATTR) {
                    return Some(e);
                }
            }
        }
    }
    None
}

/// Add our trailing break when `empty` and missing; remove it when not empty.
fn reconcile_trailing_break(document: &Document, el: &Element, empty: bool) {
    let existing = direct_trailing_break(el);
    match (empty, existing) {
        (true, None) => append_trailing_break(document, el),
        (false, Some(br)) => {
            if let Some(parent) = br.parent_node() {
                let _ = parent.remove_child(&br);
            }
        }
        _ => {}
    }
}

/// Concatenated data of `el`'s direct child *text* nodes (ignoring element
/// children such as the trailing `<br>`). Used to detect text the browser
/// inserted into a previously-empty textblock.
fn direct_text(el: &Element) -> String {
    let kids = el.child_nodes();
    let mut s = String::new();
    for i in 0..kids.length() {
        if let Some(n) = kids.item(i) {
            if n.node_type() == web_sys::Node::TEXT_NODE {
                if let Some(d) = n.text_content() {
                    s.push_str(&d);
                }
            }
        }
    }
    s
}

/// Find the first empty textblock whose DOM has gained text (the browser
/// inserting a character into a previously-empty block), returning the
/// document position just inside it and the typed text. Walks in document
/// order, mirroring [`collect_text_changes`]' position model.
fn find_empty_block_text(descs: &[ViewDesc], base: usize) -> Option<(usize, String)> {
    let mut pos = base;
    for d in descs {
        match d {
            ViewDesc::Text { node, .. } => pos += node.node_size(),
            ViewDesc::Element {
                node,
                dom,
                children,
            } => {
                let content_start = pos + 1;
                if children.is_empty() {
                    if is_textblock(node) {
                        let txt = direct_text(dom);
                        if !txt.is_empty() {
                            return Some((content_start, txt));
                        }
                    }
                } else if let Some(found) = find_empty_block_text(children, content_start) {
                    return Some(found);
                }
                pos += node.node_size();
            }
        }
    }
    None
}

/// Materialize a [`DomSpec`] into a `web_sys::Element` (tag + attrs).
fn create_element(document: &Document, spec: &DomSpec) -> Element {
    let el = document
        .create_element(spec.tag())
        .expect("create_element succeeds for spec tag");
    for (name, value) in spec.attrs() {
        let _ = el.set_attribute(name, value);
    }
    el
}

/// Walk descs in doc order, calling `visit` for each descriptor with its
/// absolute document position at the start of the descriptor's coverage.
fn collect_text_changes(
    descs: &[ViewDesc],
    base: usize,
    visit: &mut dyn FnMut(&ViewDesc, usize),
) -> usize {
    let mut pos = base;
    for d in descs {
        match d {
            ViewDesc::Text { node, .. } => {
                visit(d, pos);
                pos += node.node_size();
            }
            ViewDesc::Element { node, children, .. } => {
                collect_text_changes(children, pos + 1, visit);
                pos += node.node_size();
            }
        }
    }
    pos
}

// ---- decorations --------------------------------------------------------

fn apply_decoration(children: &[ViewDesc], deco: &Decoration, add: bool) {
    match deco {
        Decoration::Node { pos, class } => {
            if let Some(dom) = dom_element_at(children, 0, *pos) {
                let list = dom.class_list();
                if add {
                    let _ = list.add_1(class);
                } else {
                    let _ = list.remove_1(class);
                }
            }
        }
        // Inline decorations are drawn in the overlay layer, not by toggling
        // a class on document DOM — see `EditorView::render_inline_overlay`.
        Decoration::Inline { .. } => {}
    }
}

/// The document position directly before the node whose DOM element is
/// `target`, searched recursively. `None` if `target` isn't a node element
/// in the view tree.
fn pos_before_element(children: &[ViewDesc], base: usize, target: &Element) -> Option<usize> {
    let mut pos = base;
    for c in children {
        match c {
            ViewDesc::Text { node, .. } => {
                pos += node.node_size();
            }
            ViewDesc::Element {
                node,
                dom,
                children: kids,
            } => {
                if dom.is_same_node(Some(target.as_ref())) {
                    return Some(pos);
                }
                if let Some(p) = pos_before_element(kids, pos + 1, target) {
                    return Some(p);
                }
                pos += node.node_size();
            }
        }
    }
    None
}

/// The DOM element of the node that begins exactly at `target`, searched
/// recursively through element descriptors. `base` is the document position
/// just inside the parent of `children`. Returns the element for nested
/// nodes too (e.g. a table cell), not just top-level blocks.
fn dom_element_at(children: &[ViewDesc], base: usize, target: usize) -> Option<&Element> {
    let mut pos = base;
    for c in children {
        match c {
            ViewDesc::Text { node, .. } => {
                pos += node.node_size();
            }
            ViewDesc::Element {
                node,
                dom,
                children: kids,
            } => {
                if pos == target {
                    return Some(dom);
                }
                let size = node.node_size();
                if target > pos && target < pos + size {
                    if let Some(e) = dom_element_at(kids, pos + 1, target) {
                        return Some(e);
                    }
                }
                pos += size;
            }
        }
    }
    None
}

// ---- diff / patch -------------------------------------------------------

/// Same type + attrs + marks — i.e. only the inline content differs.
fn same_markup(a: &Node, b: &Node) -> bool {
    a.node_type() == b.node_type() && a.attrs() == b.attrs() && a.marks() == b.marks()
}

/// Patch the children of `parent_dom` in place. Returns the new descriptors.
fn patch_children(
    document: &Document,
    parent_dom: &Element,
    old: &[ViewDesc],
    new: &[Node],
) -> Vec<ViewDesc> {
    let mut result = Vec::with_capacity(new.len());
    for (i, new_node) in new.iter().enumerate() {
        if let Some(old_desc) = old.get(i) {
            if let Some(patched) = try_patch(document, old_desc, new_node) {
                result.push(patched);
                continue;
            }
            // Different enough that we must replace.
            let fresh = render(new_node, document);
            let _ = parent_dom.replace_child(&fresh.dom_node(), &old_desc.dom_node());
            result.push(fresh);
        } else {
            // New child past the old length: append.
            let fresh = render(new_node, document);
            let _ = parent_dom.append_child(&fresh.dom_node());
            result.push(fresh);
        }
    }
    // Remove leftover old DOM nodes the new tree no longer needs.
    for stale in old.iter().skip(new.len()) {
        let _ = parent_dom.remove_child(&stale.dom_node());
    }
    result
}

/// Try to update `old` in place to match `new`; return the new desc if the
/// patch could be applied, or `None` if the caller must remove + re-render.
fn try_patch(document: &Document, old: &ViewDesc, new: &Node) -> Option<ViewDesc> {
    // Structurally identical → keep the existing desc / DOM untouched.
    if old.node() == new {
        return Some(old.clone());
    }

    match old {
        ViewDesc::Text {
            node,
            text,
            wrapper,
        } => {
            if !new.is_text() || !same_markup(node, new) {
                return None;
            }
            let val = new.text().unwrap_or("");
            if text.data() != val {
                text.set_data(val);
            }
            Some(ViewDesc::Text {
                node: new.clone(),
                text: text.clone(),
                wrapper: wrapper.clone(),
            })
        }
        ViewDesc::Element {
            node,
            dom,
            children,
        } => {
            if new.is_text() || node.node_type() != new.node_type() || node.attrs() != new.attrs() {
                return None;
            }
            // If the old view had no children, the DOM may carry foreign nodes:
            // our trailing <br>, or text the browser typed into a previously
            // empty block that the read-back just folded into the model. Clear
            // them so `patch_children` rebuilds from the model without
            // duplicating content.
            if children.is_empty() {
                while let Some(c) = dom.first_child() {
                    if dom.remove_child(&c).is_err() {
                        break; // never spin if a child can't be removed
                    }
                }
            }
            let new_kids: Vec<Node> = new.content().iter().cloned().collect();
            let new_children = patch_children(document, dom, children, &new_kids);
            // Keep the empty-textblock trailing break in sync.
            if is_textblock(new) {
                reconcile_trailing_break(document, dom, new_children.is_empty());
            }
            Some(ViewDesc::Element {
                node: new.clone(),
                dom: dom.clone(),
                children: new_children,
            })
        }
    }
}

fn find_diff(a: &str, b: &str) -> Option<(usize, usize, String)> {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let a_len = a_chars.len();
    let b_len = b_chars.len();

    let mut prefix_len = 0;
    while prefix_len < a_len && prefix_len < b_len && a_chars[prefix_len] == b_chars[prefix_len] {
        prefix_len += 1;
    }

    if prefix_len == a_len && prefix_len == b_len {
        return None;
    }

    let mut suffix_len = 0;
    while suffix_len < a_len - prefix_len
        && suffix_len < b_len - prefix_len
        && a_chars[a_len - 1 - suffix_len] == b_chars[b_len - 1 - suffix_len]
    {
        suffix_len += 1;
    }

    let old_start = prefix_len;
    let old_end = a_len - suffix_len;
    let new_end = b_len - suffix_len;

    let new_part: String = b_chars[old_start..new_end].iter().collect();
    Some((old_start, old_end - old_start, new_part))
}