taino-edit-dioxus 0.5.3

Dioxus adapter for taino-edit, the native-Rust WYSIWYG rich-text editor.
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
//! `taino-edit-dioxus` — the Dioxus adapter for taino-edit.
//!
//! Mirrors `taino-edit-leptos`: a [`TainoEditor`] component takes a
//! [`Signal<EditorState>`] and mounts a [`taino_edit_dom::EditorView`]
//! inside its rendered `<div>`, reconciling the DOM on every signal
//! change and folding browser-side edits back into the signal.
//!
//! Browser events (`input`, `compositionstart`/`compositionend`, `paste`,
//! pointer `mousedown`/`mousemove`/`mouseup`, `selectionchange`) are wired
//! with the same raw `web-sys` listeners the Leptos adapter uses — they are
//! registered on the mounted element (and, for `selectionchange`, on
//! `document`) and kept alive in the component's runtime slot. Optional
//! [`ViewPlugin`]s (e.g. `TableView`) can be installed via the [`ViewPlugins`]
//! prop, giving full event- and plugin-wiring parity with `taino-edit-leptos`.

#![deny(unsafe_code)]
#![forbid(unstable_features)]
#![warn(missing_docs, rust_2018_idioms)]

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use dioxus::prelude::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

/// The [`schema!`](taino_edit_core::schema) builder macro.
pub use taino_edit_core::schema;
/// Re-export the core types adapter consumers reach for most.
#[doc(no_inline)]
pub use taino_edit_core::{
    base_keymap, lift, remove_mark, select_all, set_block_type, set_mark, split_block, toggle_mark,
    wrap_in, AttrSpec, AttrValue, Attrs, Command, Dispatch, EditorState, KeyPress, Keymap, Mark,
    MarkSpec, MarkType, Node, NodeSpec, NodeType, Plugin, PluginKey, PluginSet, ResolvedPos,
    Schema, SchemaBuilder, Selection, Slice, Transaction, Transform,
};
/// Re-export the DOM-bridge surface.
#[doc(no_inline)]
pub use taino_edit_dom::{Decoration, EditorView, ViewAction, ViewDesc, ViewPlugin};

/// A move-once container of DOM-aware [`ViewPlugin`]s for the
/// [`TainoEditor`] `plugins` prop.
///
/// Dioxus props must be `Clone + PartialEq`; a bare
/// `Vec<Box<dyn ViewPlugin>>` is neither, so the plugins live behind a shared
/// cell that is cheap to clone. They are installed on the view exactly once
/// at mount and never compared afterwards, so this type is deliberately
/// "always equal": changing the prop after mount has no effect and must not
/// trigger a re-render.
///
/// ```ignore
/// use taino_edit_dioxus::{TainoEditor, ViewPlugins};
/// use taino_edit_table_view::TableView;
///
/// rsx! { TainoEditor { state, plugins: ViewPlugins::new(vec![Box::new(TableView::new())]) } }
/// ```
#[derive(Clone, Default)]
pub struct ViewPlugins(PluginCell);

/// The shared, take-once backing store behind [`ViewPlugins`].
type PluginCell = Rc<RefCell<Option<Vec<Box<dyn ViewPlugin>>>>>;

impl ViewPlugins {
    /// Wrap a set of view plugins for the `plugins` prop.
    pub fn new(plugins: Vec<Box<dyn ViewPlugin>>) -> Self {
        Self(Rc::new(RefCell::new(Some(plugins))))
    }

    /// Take the plugins out, leaving the container empty. Called once at
    /// mount; any later call yields an empty vec.
    fn take(&self) -> Vec<Box<dyn ViewPlugin>> {
        self.0.borrow_mut().take().unwrap_or_default()
    }
}

impl PartialEq for ViewPlugins {
    // Mount-only and never re-read: every value compares equal so the prop
    // can't cause spurious re-renders of `TainoEditor`.
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl std::fmt::Debug for ViewPlugins {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let n = self.0.borrow().as_ref().map_or(0, Vec::len);
        f.debug_struct("ViewPlugins").field("pending", &n).finish()
    }
}

/// A take-once container for the [`TainoEditor`] `keymap` prop. Mirrors
/// [`ViewPlugins`]: Dioxus props must be `Clone + PartialEq` and [`Keymap`] is
/// neither, so the keymap lives behind a shared cell and is moved into the
/// view at mount.
///
/// ```ignore
/// rsx! { TainoEditor { state, keymap: KeymapProp::new(my_keymap) } }
/// ```
#[derive(Clone, Default)]
pub struct KeymapProp(Rc<RefCell<Option<Keymap>>>);

impl KeymapProp {
    /// Wrap a keymap for the `keymap` prop.
    pub fn new(keymap: Keymap) -> Self {
        Self(Rc::new(RefCell::new(Some(keymap))))
    }

    /// Take the keymap out (once, at mount).
    fn take(&self) -> Option<Keymap> {
        self.0.borrow_mut().take()
    }
}

impl PartialEq for KeymapProp {
    // Mount-only; never re-read, so the prop never forces a re-render.
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl std::fmt::Debug for KeymapProp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KeymapProp").finish_non_exhaustive()
    }
}

/// A Dioxus component that renders an editor backed by a
/// [`Signal<EditorState>`]. Whenever the signal changes, the mounted DOM is
/// reconciled via [`EditorView::update`]; browser-side edits (typing, IME
/// commits, paste, selection changes) feed back into the signal by applying
/// the transforms the DOM bridge produces.
///
/// ```ignore
/// use dioxus::prelude::*;
/// use taino_edit_dioxus::{EditorState, TainoEditor};
///
/// #[component]
/// fn App(state: Signal<EditorState>) -> Element {
///     rsx! { TainoEditor { state } }
/// }
/// ```
#[component]
pub fn TainoEditor(
    state: Signal<EditorState>,
    /// Optional DOM-aware [`ViewPlugin`]s (e.g. `TableView` for table
    /// cell-drag-select + resize). Installed on the view at mount; the
    /// component wires pointer events to them and refreshes their
    /// decorations on every state change.
    #[props(default)]
    plugins: ViewPlugins,
    /// Optional [`Keymap`] for keyboard editing. When provided, the component
    /// owns `keydown`: it reads the *live* DOM selection, runs the matching
    /// command, and applies the result to the view **synchronously** (so the
    /// caret and DOM never lag the model). Build it with
    /// `taino_edit_extensions::build_keymap_with`.
    #[props(default)]
    keymap: KeymapProp,
) -> Element {
    // The mounted view + its event closures live here across renders.
    // EditorView is !Send + !Sync, which Dioxus signals tolerate.
    let mut runtime: Signal<Option<EditorRuntime>> = use_signal(|| None);

    // On every state change, patch the DOM and re-sync the selection.
    use_effect(move || {
        let snapshot = state.read().clone();
        if let Some(rt) = runtime.write().as_mut() {
            rt.view.update(snapshot.doc().clone());
            // Only re-sync the DOM selection when the editor is focused, so we
            // never steal focus back from another element (e.g. a search box).
            //
            // Never for updates that merely mirror a selection the browser
            // already has (`selection_from_dom`): the effect runs after the
            // `selectionchange` handler, and the user may have extended the
            // selection further in between (e.g. mid drag-select). Writing
            // the mirrored — by now stale — range back would clip the live
            // selection's tail.
            let mirrored_from_dom = rt.selection_from_dom.replace(false);
            if !mirrored_from_dom
                && rt.view.has_focus()
                && rt.view.read_selection() != Some(snapshot.selection())
            {
                rt.applying_selection.set(true);
                let _ = rt.view.set_selection(snapshot.selection());
                rt.applying_selection.set(false);
            }
            // Refresh plugin decorations (e.g. table cell-selection
            // highlight) for the current selection.
            rt.view.refresh_view_decorations(Some(snapshot.selection()));
        }
    });

    let on_mounted = move |evt: Event<MountedData>| {
        let Some(element) = evt.data().downcast::<web_sys::Element>().cloned() else {
            return;
        };
        let snapshot = state.read().clone();
        let mut view = EditorView::mount(
            snapshot.doc().clone(),
            snapshot.schema().clone(),
            element.clone(),
        );
        view.set_view_plugins(plugins.take());
        view.refresh_view_decorations(Some(snapshot.selection()));
        let applying = Rc::new(Cell::new(false));
        let from_dom = Rc::new(Cell::new(false));
        // Park the keymap behind a shared cell so the keydown closure (and
        // the runtime, for diagnostics) can reach it.
        let keymap_cell: Rc<RefCell<Option<Keymap>>> = Rc::new(RefCell::new(keymap.take()));
        let closures = wire_events(
            &element,
            runtime,
            state,
            applying.clone(),
            from_dom.clone(),
            keymap_cell.clone(),
        );
        runtime.set(Some(EditorRuntime {
            view,
            closures,
            applying_selection: applying,
            selection_from_dom: from_dom,
            keymap: keymap_cell,
        }));
    };

    rsx! {
        div {
            class: "taino-editor",
            onmounted: on_mounted,
        }
    }
}

/// What a mounted `TainoEditor` owns. Dropping this both drops the view
/// (frees the DOM-bound `EditorView`) and detaches every event listener.
struct EditorRuntime {
    view: EditorView,
    #[allow(dead_code)] // kept alive so the listeners they back stay attached.
    closures: Vec<EventCloser>,
    /// Set while the effect pushes state's selection into the DOM, so the
    /// `selectionchange` listener can ignore the resulting echo.
    applying_selection: Rc<Cell<bool>>,
    /// Set by the `selectionchange` listener when a state update merely
    /// mirrors a selection the browser already has; consumed by the effect,
    /// which must then *not* write that (possibly already stale) selection
    /// back into the DOM.
    selection_from_dom: Rc<Cell<bool>>,
    /// The installed keymap (if any). Shared with the `keydown` closure so it
    /// can run commands synchronously against the live state.
    #[allow(dead_code)] // accessed via the keydown closure's clone of the Rc.
    keymap: Rc<RefCell<Option<Keymap>>>,
}

/// A `Closure` registered on a DOM target; on drop the listener is removed.
struct EventCloser {
    event: &'static str,
    target: web_sys::EventTarget,
    closure: Closure<dyn FnMut(web_sys::Event)>,
    /// Whether the listener was registered in the capture phase (must match on
    /// removal). Used for `scroll`, which does not bubble.
    capture: bool,
}

impl Drop for EventCloser {
    fn drop(&mut self) {
        let _ = self.target.remove_event_listener_with_callback_and_bool(
            self.event,
            self.closure.as_ref().unchecked_ref(),
            self.capture,
        );
    }
}

fn push_listener(
    closers: &mut Vec<EventCloser>,
    target: web_sys::EventTarget,
    event: &'static str,
    closure: Closure<dyn FnMut(web_sys::Event)>,
) {
    push_listener_capture(closers, target, event, closure, false);
}

fn push_listener_capture(
    closers: &mut Vec<EventCloser>,
    target: web_sys::EventTarget,
    event: &'static str,
    closure: Closure<dyn FnMut(web_sys::Event)>,
    capture: bool,
) {
    if target
        .add_event_listener_with_callback_and_bool(event, closure.as_ref().unchecked_ref(), capture)
        .is_ok()
    {
        closers.push(EventCloser {
            event,
            target,
            closure,
            capture,
        });
    }
}

fn wire_events(
    el: &web_sys::Element,
    mut runtime: Signal<Option<EditorRuntime>>,
    mut state: Signal<EditorState>,
    applying_selection: Rc<Cell<bool>>,
    selection_from_dom: Rc<Cell<bool>>,
    keymap_cell: Rc<RefCell<Option<Keymap>>>,
) -> Vec<EventCloser> {
    let target: web_sys::EventTarget = el.clone().into();
    let mut closers: Vec<EventCloser> = Vec::new();

    // `input`: text typed or deleted in a text node.
    let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
        if let Some(Some(t)) = with_view(runtime, |v| v.read_dom_changes()) {
            apply_transform(state, &t);
        }
    });
    push_listener(&mut closers, target.clone(), "input", cb);

    // `keydown`: with a keymap installed, the editor owns keyboard editing.
    // Read the *live* DOM selection so the command acts on the real caret,
    // not a lagging model selection; then apply view.update + set_selection
    // **synchronously** so the DOM/caret can't fall out of step before the
    // next keystroke.
    let km_for_keydown = keymap_cell;
    let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
        let Ok(kev) = ev.dyn_into::<web_sys::KeyboardEvent>() else {
            return;
        };
        let key = KeyPress {
            key: kev.key(),
            ctrl: kev.ctrl_key(),
            alt: kev.alt_key(),
            shift: kev.shift_key(),
            meta: kev.meta_key(),
        };
        let mut cur = state.peek().clone();
        if let Some(Some(live)) = with_view(runtime, |v| v.read_selection()) {
            if live != cur.selection() {
                let mut tx = cur.tr();
                tx.set_selection(live);
                tx.no_history();
                cur = cur.apply(tx);
            }
        }
        let mut next = None;
        let handled = match km_for_keydown.borrow().as_ref() {
            Some(km) => {
                let mut d = |t: Transaction| next = Some(cur.apply(t));
                km.handle(&cur, &key, Some(&mut d))
            }
            None => false,
        };
        if let Some(n) = next {
            // Apply synchronously to the mounted view, then publish to state.
            if let Some(rt) = runtime.write().as_mut() {
                rt.view.update(n.doc().clone());
                rt.applying_selection.set(true);
                let _ = rt.view.set_selection(n.selection());
                rt.applying_selection.set(false);
                rt.view.refresh_view_decorations(Some(n.selection()));
            }
            state.set(n);
        }
        // Structural keys are model-authoritative.
        let structural = matches!(key.key.as_str(), "Enter" | "Backspace" | "Delete");
        if handled || structural {
            kev.prevent_default();
        }
    });
    push_listener(&mut closers, target.clone(), "keydown", cb);

    // IME composition: suspend reads while composing, commit on end.
    let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
        with_view(runtime, |v| v.composition_start());
    });
    push_listener(&mut closers, target.clone(), "compositionstart", cb);

    let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
        let t = with_view(runtime, |v| {
            v.composition_end();
            v.read_dom_changes()
        })
        .flatten();
        if let Some(t) = t {
            apply_transform(state, &t);
        }
    });
    push_listener(&mut closers, target.clone(), "compositionend", cb);

    // Paste: prefer Markdown, then HTML, then plain text — all sanitised
    // through the schema-aware paths in core.
    let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
        let Ok(clip) = ev.dyn_into::<web_sys::ClipboardEvent>() else {
            return;
        };
        clip.prevent_default();
        let Some(data) = clip.clipboard_data() else {
            return;
        };
        let md = data.get_data("text/markdown").unwrap_or_default();
        let html = data.get_data("text/html").unwrap_or_default();
        let text = data.get_data("text/plain").unwrap_or_default();
        let t = with_view(runtime, |v| {
            if !md.is_empty() {
                v.paste_markdown(&md)
            } else if !html.is_empty() {
                v.paste_html(&html)
            } else if !text.is_empty() {
                v.paste_text(&text)
            } else {
                None
            }
        })
        .flatten();
        if let Some(t) = t {
            apply_transform(state, &t);
        }
    });
    push_listener(&mut closers, target.clone(), "paste", cb);

    // Pointer events → view plugins (table cell-drag-select, resize). Each
    // fires `handle_view_event`; a returned action is applied to state.
    // No-op when no plugin claims the event.
    for kind in ["mousedown", "mousemove", "mouseup"] {
        let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
            if let Some(Some(action)) = with_view(runtime, |v| v.handle_view_event(&ev)) {
                apply_view_action(state, action);
            }
        });
        push_listener(&mut closers, target.clone(), kind, cb);
    }

    // `selectionchange` only fires on `document`; mirror the browser
    // selection into state so toolbar/keymap commands see the right
    // anchor/head. Drop the echo from our own effect-driven set_selection.
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        let doc_target: web_sys::EventTarget = doc.into();
        let applying = applying_selection;
        let from_dom = selection_from_dom;
        let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
            if applying.get() {
                return;
            }
            let Some(Some(sel)) = with_view(runtime, |v| v.read_selection()) else {
                return;
            };
            let cur = state.peek().selection();
            if sel == cur {
                return;
            }
            // Mark this update as a DOM-driven mirror so the effect doesn't
            // write it back into the browser (see the effect for why).
            from_dom.set(true);
            let mut s = state;
            let next = {
                let snap = s.peek();
                let mut tx = snap.tr();
                tx.set_selection(sel);
                tx.no_history();
                snap.apply(tx)
            };
            s.set(next);
        });
        push_listener(&mut closers, doc_target, "selectionchange", cb);
    }

    // Reposition inline-decoration overlays when the layout shifts without a
    // document edit. `scroll` is captured (it doesn't bubble) so editor- or
    // ancestor-level scrolling is caught too; `resize` fires on `window`.
    if let Some(window) = web_sys::window() {
        let win_target: web_sys::EventTarget = window.unchecked_into();
        let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
            with_view(runtime, |v| v.reposition_inline_decorations());
        });
        push_listener_capture(&mut closers, win_target.clone(), "scroll", cb, true);
        let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |_ev: web_sys::Event| {
            with_view(runtime, |v| v.reposition_inline_decorations());
        });
        push_listener(&mut closers, win_target, "resize", cb);
    }

    closers
}

/// Run `f` against the mounted `EditorView`, if any.
fn with_view<R>(
    runtime: Signal<Option<EditorRuntime>>,
    f: impl FnOnce(&EditorView) -> R,
) -> Option<R> {
    runtime.peek().as_ref().map(|rt| f(&rt.view))
}

/// Apply a [`ViewAction`] produced by a view plugin to the state signal.
fn apply_view_action(mut state: Signal<EditorState>, action: ViewAction) {
    match action {
        ViewAction::Select(sel) => {
            let next = {
                let snap = state.peek();
                let mut tx = snap.tr();
                tx.set_selection(sel);
                tx.no_history();
                snap.apply(tx)
            };
            state.set(next);
        }
        ViewAction::Command(cmd) => {
            let snapshot = state.peek().clone();
            let mut next = None;
            {
                let mut d = |tx: Transaction| next = Some(snapshot.apply(tx));
                cmd(&snapshot, Some(&mut d));
            }
            if let Some(n) = next {
                state.set(n);
            }
        }
    }
}

/// Fold a DOM-bridge transform into the state signal.
fn apply_transform(mut state: Signal<EditorState>, tr: &Transform) {
    let next = {
        let snap = state.peek();
        let mut tx = snap.tr();
        let mut ok = true;
        for step in tr.steps() {
            if tx.transform().step(step.clone(), snap.schema()).is_err() {
                ok = false;
                break;
            }
        }
        if !ok {
            return;
        }
        snap.apply(tx)
    };
    state.set(next);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A trivial plugin (all-default trait impl) for exercising `ViewPlugins`.
    struct Dummy;
    impl ViewPlugin for Dummy {}

    #[test]
    fn view_plugins_take_is_once() {
        let p = ViewPlugins::new(vec![Box::new(Dummy), Box::new(Dummy)]);
        assert_eq!(p.take().len(), 2, "first take yields the installed plugins");
        assert_eq!(
            p.take().len(),
            0,
            "the container is empty after the first take"
        );
    }

    #[test]
    fn view_plugins_always_compare_equal() {
        // Mount-only prop: every value is "equal" so it never forces a
        // re-render of `TainoEditor`.
        assert_eq!(
            ViewPlugins::new(vec![Box::new(Dummy)]),
            ViewPlugins::default()
        );
    }
}