Skip to main content

lumen_dioxus/pickers/
rich_text.rs

1//! `RichTextEditor` and its toolbar, command, and content parts.
2//!
3//! On the web and desktop the content is a `contenteditable` region and commands run through
4//! `document.execCommand` with `eval`; the toolbar's pressed states are kept in Rust from
5//! `queryCommandState`. Dioxus Native has no `contenteditable` or JavaScript, so in
6//! [`RichTextEditorMode::Auto`] the content falls back to a plain-text `<textarea>` there.
7
8// cspell:words onmousedown onmouseup
9
10use dioxus::prelude::*;
11
12use crate::class::{Glass, compose};
13use crate::hooks::use_unique_id;
14
15/// The commands that toggle a pressed state, like `lumenRichTextToggleCommands`.
16pub(crate) const RICH_TEXT_TOGGLE_COMMANDS: [&str; 8] = [
17    "bold",
18    "italic",
19    "strikeThrough",
20    "subscript",
21    "superscript",
22    "underline",
23    "insertOrderedList",
24    "insertUnorderedList",
25];
26
27/// The editing command for a keyboard shortcut, like `getLumenRichTextShortcut`: Ctrl or Cmd
28/// with B, I, U, Z; with Shift, X (strike), Z (redo), 7 (numbered list), and 8 (bullet list).
29pub(crate) fn rich_text_shortcut(
30    key: &str,
31    code: &str,
32    modifiers: Modifiers,
33) -> Option<&'static str> {
34    if !modifiers.intersects(Modifiers::CONTROL | Modifiers::META)
35        || modifiers.contains(Modifiers::ALT)
36    {
37        return None;
38    }
39
40    let key = key.to_lowercase();
41
42    if !modifiers.contains(Modifiers::SHIFT) {
43        return match key.as_str() {
44            "b" => Some("bold"),
45            "i" => Some("italic"),
46            "u" => Some("underline"),
47            "z" => Some("undo"),
48            _ => None,
49        };
50    }
51
52    match code {
53        "Digit7" => return Some("insertOrderedList"),
54        "Digit8" => return Some("insertUnorderedList"),
55        _ => {}
56    }
57
58    match key.as_str() {
59        "x" => Some("strikeThrough"),
60        "z" => Some("redo"),
61        _ => None,
62    }
63}
64
65/// How the content region edits text.
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum RichTextEditorMode {
69    /// Rich editing where `eval` works (web, desktop); plain text on Dioxus Native.
70    #[default]
71    Auto,
72    /// Always a `contenteditable` region.
73    Rich,
74    /// Always a plain-text `<textarea>`; formatting commands are disabled.
75    Plain,
76}
77
78/// The editor content after an edit or command.
79#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct RichTextEditorChange {
81    /// The HTML of the editable region (escaped text in plain mode).
82    pub html: String,
83    /// The text content.
84    pub text: String,
85}
86
87/// A command the editor ran.
88#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct RichTextEditorCommandDetail {
90    /// The command name, such as `bold` or `formatBlock`.
91    pub command: String,
92    /// Whether the command ran.
93    pub executed: bool,
94    /// The command value, such as `h2` for `formatBlock`.
95    pub value: Option<String>,
96}
97
98/// Shared state between the editor parts.
99#[derive(Clone, Copy)]
100struct RichTextContext {
101    /// The id the editor generates for its content region.
102    generated_id: CopyValue<String>,
103    /// The id of the rendered content region: its own `id` when the app sets one, otherwise the
104    /// generated id. Commands and change reports look the region up by this id.
105    content_id: CopyValue<String>,
106    plain: Signal<bool>,
107    /// Toggle commands that are currently on.
108    active: Signal<Vec<String>>,
109    /// The current block format, such as `p` or `h2`.
110    block: Signal<String>,
111    on_change: CopyValue<Option<EventHandler<RichTextEditorChange>>>,
112    on_command: CopyValue<Option<EventHandler<RichTextEditorCommandDetail>>>,
113    command_handler: CopyValue<Option<Callback<RichTextEditorCommandDetail, bool>>>,
114}
115
116/// Runs `script` with the content id, command, and value, and returns the editor state.
117const COMMAND_SCRIPT: &str = r"
118const [id, command, value, run] = await dioxus.recv();
119const editable = document.getElementById(id);
120let executed = false;
121if (editable && run) {
122  editable.focus();
123  executed = value === null ? document.execCommand(command) : document.execCommand(command, false, value);
124}
125const toggles = ['bold', 'italic', 'strikeThrough', 'subscript', 'superscript', 'underline', 'insertOrderedList', 'insertUnorderedList'];
126const states = toggles.map(name => { try { return document.queryCommandState(name); } catch { return false; } });
127let block = '';
128try { block = String(document.queryCommandValue('formatBlock') || '').split('<').join('').split('>').join('').toLowerCase(); } catch {}
129return [executed, states, block, editable ? editable.innerHTML : '', editable ? editable.textContent : ''];
130";
131
132type EditorState = (bool, Vec<bool>, String, String, String);
133
134impl RichTextContext {
135    /// Runs a command (or only refreshes the toolbar when `run` is false) and syncs the state.
136    fn run(self, command: Option<String>, value: Option<String>, run: bool) {
137        if *self.plain.peek() {
138            return;
139        }
140
141        let id = self.content_id.peek().clone();
142        let handler = *self.command_handler.peek();
143        let on_command = *self.on_command.peek();
144        let on_change = *self.on_change.peek();
145        let mut context = self;
146
147        spawn(async move {
148            let name = command.clone().unwrap_or_default();
149            let mut executed_by_app = None;
150
151            if run && let Some(handler) = handler {
152                executed_by_app = Some(handler.call(RichTextEditorCommandDetail {
153                    command: name.clone(),
154                    executed: false,
155                    value: value.clone(),
156                }));
157            }
158
159            let eval = document::eval(COMMAND_SCRIPT);
160            let run_in_page = run && executed_by_app.is_none();
161
162            if eval
163                .send((id, name.clone(), value.clone(), run_in_page))
164                .is_err()
165            {
166                return;
167            }
168
169            let Ok((executed, states, block, html, text)) = eval.join::<EditorState>().await else {
170                return;
171            };
172
173            let active: Vec<String> = RICH_TEXT_TOGGLE_COMMANDS
174                .iter()
175                .zip(states)
176                .filter(|(_, on)| *on)
177                .map(|(command, _)| (*command).to_string())
178                .collect();
179
180            if *context.active.peek() != active {
181                context.active.set(active);
182            }
183
184            if *context.block.peek() != block {
185                context.block.set(block);
186            }
187
188            if run {
189                if let Some(handler) = on_command {
190                    handler.call(RichTextEditorCommandDetail {
191                        command: name,
192                        executed: executed_by_app.unwrap_or(executed),
193                        value,
194                    });
195                }
196
197                if let Some(handler) = on_change {
198                    handler.call(RichTextEditorChange { html, text });
199                }
200            }
201        });
202    }
203
204    fn emit_change(self) {
205        self.run(None, None, false);
206
207        let id = self.content_id.peek().clone();
208        let on_change = *self.on_change.peek();
209
210        if on_change.is_none() || *self.plain.peek() {
211            return;
212        }
213
214        spawn(async move {
215            let eval = document::eval(
216                "const [id] = await dioxus.recv(); const el = document.getElementById(id); return el ? [el.innerHTML, el.textContent] : ['', ''];",
217            );
218
219            if eval.send((id,)).is_err() {
220                return;
221            }
222
223            if let Ok((html, text)) = eval.join::<(String, String)>().await
224                && let Some(handler) = on_change
225            {
226                handler.call(RichTextEditorChange { html, text });
227            }
228        });
229    }
230}
231
232fn use_rich_text(component: &str) -> RichTextContext {
233    try_use_context::<RichTextContext>()
234        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen RichTextEditor."))
235}
236
237/// Props for [`RichTextEditor`].
238#[derive(Props, Clone, PartialEq)]
239pub struct RichTextEditorProps {
240    /// How the content edits text. Read when the editor mounts.
241    #[props(default)]
242    pub mode: RichTextEditorMode,
243    /// Called with the content after every edit and command.
244    pub on_change: Option<EventHandler<RichTextEditorChange>>,
245    /// Called after every command.
246    pub on_command: Option<EventHandler<RichTextEditorCommandDetail>>,
247    /// Runs commands with your own engine instead of `document.execCommand`; return whether the
248    /// command ran.
249    pub command_handler: Option<Callback<RichTextEditorCommandDetail, bool>>,
250    /// Glass intensity.
251    #[props(default, into)]
252    pub glass: Glass,
253    /// Extra classes appended after the Lumen classes.
254    #[props(into)]
255    pub class: Option<String>,
256    /// Any other `<section>` or global attribute.
257    #[props(extends = GlobalAttributes, extends = section)]
258    pub attributes: Vec<Attribute>,
259    /// A [`RichTextEditorToolbar`] and a [`RichTextEditorContent`].
260    pub children: Element,
261}
262
263/// A rich text editor frame. Compose it from [`RichTextEditorToolbar`],
264/// [`RichTextEditorCommand`], and [`RichTextEditorContent`].
265#[component]
266pub fn RichTextEditor(props: RichTextEditorProps) -> Element {
267    let unique = use_unique_id();
268    let context = use_context_provider(|| {
269        let generated = format!("ui-rich-text-{unique}-content");
270
271        RichTextContext {
272            generated_id: CopyValue::new(generated.clone()),
273            content_id: CopyValue::new(generated),
274            plain: Signal::new(props.mode == RichTextEditorMode::Plain),
275            active: Signal::new(Vec::new()),
276            block: Signal::new(String::new()),
277            on_change: CopyValue::new(None),
278            on_command: CopyValue::new(None),
279            command_handler: CopyValue::new(None),
280        }
281    });
282    let (mut on_change, mut on_command, mut command_handler) = (
283        context.on_change,
284        context.on_command,
285        context.command_handler,
286    );
287    on_change.set(props.on_change);
288    on_command.set(props.on_command);
289    command_handler.set(props.command_handler);
290
291    let mode = props.mode;
292
293    use_effect(move || {
294        if mode != RichTextEditorMode::Auto {
295            return;
296        }
297
298        spawn(async move {
299            // Dioxus Native has no JavaScript: a failed probe switches to plain text.
300            if document::eval("return true;").join::<bool>().await.is_err() {
301                let mut plain = context.plain;
302                plain.set(true);
303            }
304        });
305    });
306
307    let glass = props.glass.class("ui-rich-text-editor");
308    let class = compose([
309        Some("ui-rich-text-editor"),
310        glass.as_deref(),
311        props.class.as_deref(),
312    ]);
313
314    rsx! {
315        section {
316            class,
317            "data-ui-rich-text-editor": "true",
318            ..props.attributes,
319            {props.children}
320        }
321    }
322}
323
324/// Props for [`RichTextEditorToolbar`].
325#[derive(Props, Clone, PartialEq)]
326pub struct RichTextEditorToolbarProps {
327    /// Extra classes.
328    #[props(into)]
329    pub class: Option<String>,
330    /// Any other `<div>` or global attribute. Name the toolbar with `aria_label`.
331    #[props(extends = GlobalAttributes, extends = div)]
332    pub attributes: Vec<Attribute>,
333    /// [`RichTextEditorCommand`]s, usually grouped.
334    pub children: Element,
335}
336
337/// The editor's `toolbar`.
338#[component]
339pub fn RichTextEditorToolbar(props: RichTextEditorToolbarProps) -> Element {
340    rsx! {
341        div { class: props.class, role: "toolbar", ..props.attributes, {props.children} }
342    }
343}
344
345/// Props for [`RichTextEditorCommand`].
346#[derive(Props, Clone, PartialEq)]
347pub struct RichTextEditorCommandProps {
348    /// The `document.execCommand` name, such as `bold`, `insertUnorderedList`, or `formatBlock`.
349    #[props(into)]
350    pub command: String,
351    /// The command value, such as `h2` for `formatBlock`.
352    #[props(into)]
353    pub value: Option<String>,
354    /// Extra classes appended after the Lumen button classes.
355    #[props(into)]
356    pub class: Option<String>,
357    /// Any other `<button>` or global attribute. Name icon buttons with `aria_label`.
358    #[props(extends = GlobalAttributes, extends = button)]
359    pub attributes: Vec<Attribute>,
360    /// Button content, usually an [`Icon`](crate::Icon).
361    pub children: Element,
362}
363
364/// A ghost icon button that runs an editing command. Toggle commands report `aria-pressed`, and
365/// `data-state` is `on` while the command (or the `formatBlock` value) is active.
366#[component]
367pub fn RichTextEditorCommand(props: RichTextEditorCommandProps) -> Element {
368    let context = use_rich_text("RichTextEditorCommand");
369    let is_toggle = RICH_TEXT_TOGGLE_COMMANDS.contains(&props.command.as_str());
370    let active = if is_toggle {
371        context.active.read().contains(&props.command)
372    } else if props.command == "formatBlock" {
373        props.value.as_deref().is_some_and(|value| {
374            value
375                .chars()
376                .filter(|character| *character != '<' && *character != '>')
377                .collect::<String>()
378                .eq_ignore_ascii_case(&context.block.read())
379        })
380    } else {
381        false
382    };
383    let plain = *context.plain.read();
384    let class = compose([
385        Some("ui-button ui-button--ghost ui-button--icon"),
386        props.class.as_deref(),
387    ]);
388    let command = props.command.clone();
389    let value = props.value.clone();
390
391    rsx! {
392        button {
393            aria_pressed: is_toggle.then_some(if active { "true" } else { "false" }),
394            class,
395            "data-slot": "button",
396            "data-state": if active { "on" } else { "off" },
397            "data-ui-editor-command": props.command.clone(),
398            "data-ui-editor-value": props.value.clone(),
399            disabled: plain,
400            r#type: "button",
401            // Keep the text selection in the editable region while pressing the button.
402            onmousedown: move |event| event.prevent_default(),
403            onclick: move |_| context.run(Some(command.clone()), value.clone(), true),
404            ..props.attributes,
405            span { class: "ui-button__content", {props.children} }
406        }
407    }
408}
409
410/// Props for [`RichTextEditorContent`].
411#[derive(Props, Clone, PartialEq)]
412pub struct RichTextEditorContentProps {
413    /// Initial text in plain mode.
414    #[props(into)]
415    pub default_text: Option<String>,
416    /// Extra classes.
417    #[props(into)]
418    pub class: Option<String>,
419    /// Any other `<div>` or global attribute. Name the region with `aria_label`.
420    #[props(extends = GlobalAttributes, extends = div)]
421    pub attributes: Vec<Attribute>,
422    /// Initial rich content.
423    pub children: Element,
424}
425
426/// The text value of a non-empty `id` the app spread on the content region.
427fn custom_id(attributes: &[Attribute]) -> Option<String> {
428    attributes
429        .iter()
430        .rev()
431        .find(|attribute| attribute.name == "id")
432        .and_then(|attribute| match &attribute.value {
433            dioxus::core::AttributeValue::Text(text) => Some(text.clone()),
434            dioxus::core::AttributeValue::Int(value) => Some(value.to_string()),
435            _ => None,
436        })
437        .filter(|id| !id.trim().is_empty())
438}
439
440fn escape_html(text: &str) -> String {
441    let mut escaped = String::with_capacity(text.len());
442
443    for character in text.chars() {
444        match character {
445            '&' => escaped.push_str("&amp;"),
446            '<' => escaped.push_str("&lt;"),
447            '>' => escaped.push_str("&gt;"),
448            '"' => escaped.push_str("&quot;"),
449            _ => escaped.push(character),
450        }
451    }
452
453    escaped
454}
455
456/// The editable region: `contenteditable` with `role="textbox"` and `aria-multiline`, or a
457/// `<textarea>` in plain mode. Ctrl or Cmd shortcuts run the matching commands.
458#[component]
459pub fn RichTextEditorContent(props: RichTextEditorContentProps) -> Element {
460    let context = use_rich_text("RichTextEditorContent");
461    // A custom `id` replaces the generated one everywhere: on the region, and in the lookups of
462    // commands and change reports, which run after this render.
463    let id = custom_id(&props.attributes).unwrap_or_else(|| context.generated_id.peek().clone());
464    let mut content_id = context.content_id;
465
466    if *content_id.peek() != id {
467        content_id.set(id.clone());
468    }
469
470    let attributes: Vec<Attribute> = props
471        .attributes
472        .into_iter()
473        .filter(|attribute| attribute.name != "id")
474        .collect();
475    let mut text = use_signal(|| props.default_text.clone().unwrap_or_default());
476
477    if *context.plain.read() {
478        let class = compose([Some("ui-textarea"), props.class.as_deref()]);
479
480        return rsx! {
481            textarea {
482                aria_multiline: "true",
483                class,
484                "data-ui-rich-text-editable": "true",
485                id,
486                rows: "8",
487                value: text(),
488                oninput: move |event: FormEvent| {
489                    let next = event.value();
490                    text.set(next.clone());
491
492                    if let Some(handler) = *context.on_change.peek() {
493                        handler.call(RichTextEditorChange { html: escape_html(&next), text: next });
494                    }
495                },
496                ..attributes,
497            }
498        };
499    }
500
501    rsx! {
502        div {
503            aria_multiline: "true",
504            class: props.class,
505            contenteditable: "true",
506            "data-ui-rich-text-editable": "true",
507            id,
508            role: "textbox",
509            oninput: move |_| context.emit_change(),
510            onkeydown: move |event: KeyboardEvent| {
511                let shortcut = rich_text_shortcut(
512                    &event.key().to_string(),
513                    &event.code().to_string(),
514                    event.modifiers(),
515                );
516
517                if let Some(command) = shortcut {
518                    event.prevent_default();
519                    context.run(Some(command.to_string()), None, true);
520                }
521            },
522            onkeyup: move |_| context.run(None, None, false),
523            onmouseup: move |_| context.run(None, None, false),
524            ..attributes,
525            {props.children}
526        }
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::{escape_html, rich_text_shortcut};
533    use dioxus::prelude::Modifiers;
534
535    #[test]
536    fn shortcuts_match_lumen_core() {
537        let ctrl = Modifiers::CONTROL;
538        let shift = Modifiers::CONTROL | Modifiers::SHIFT;
539        let plain = |key: &str| rich_text_shortcut(key, "", ctrl);
540        assert_eq!(plain("b"), Some("bold"));
541        assert_eq!(plain("I"), Some("italic"));
542        assert_eq!(plain("u"), Some("underline"));
543        assert_eq!(plain("z"), Some("undo"));
544        assert_eq!(plain("k"), None);
545        assert_eq!(
546            rich_text_shortcut("b", "KeyB", Modifiers::META),
547            Some("bold")
548        );
549        assert_eq!(rich_text_shortcut("b", "KeyB", ctrl | Modifiers::ALT), None);
550        assert_eq!(rich_text_shortcut("b", "KeyB", Modifiers::empty()), None);
551        assert_eq!(
552            rich_text_shortcut("X", "KeyX", shift),
553            Some("strikeThrough")
554        );
555        assert_eq!(rich_text_shortcut("Z", "KeyZ", shift), Some("redo"));
556        assert_eq!(
557            rich_text_shortcut("&", "Digit7", shift),
558            Some("insertOrderedList")
559        );
560        assert_eq!(
561            rich_text_shortcut("*", "Digit8", Modifiers::META | Modifiers::SHIFT),
562            Some("insertUnorderedList")
563        );
564    }
565
566    #[test]
567    fn plain_text_is_escaped() {
568        assert_eq!(
569            escape_html("<b>\"a\" & b</b>"),
570            "&lt;b&gt;&quot;a&quot; &amp; b&lt;/b&gt;"
571        );
572    }
573}