lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
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
//! `RichTextEditor` and its toolbar, command, and content parts.
//!
//! On the web and desktop the content is a `contenteditable` region and commands run through
//! `document.execCommand` with `eval`; the toolbar's pressed states are kept in Rust from
//! `queryCommandState`. Dioxus Native has no `contenteditable` or JavaScript, so in
//! [`RichTextEditorMode::Auto`] the content falls back to a plain-text `<textarea>` there.

// cspell:words onmousedown onmouseup

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::hooks::use_unique_id;

/// The commands that toggle a pressed state, like `lumenRichTextToggleCommands`.
pub(crate) const RICH_TEXT_TOGGLE_COMMANDS: [&str; 8] = [
    "bold",
    "italic",
    "strikeThrough",
    "subscript",
    "superscript",
    "underline",
    "insertOrderedList",
    "insertUnorderedList",
];

/// The editing command for a keyboard shortcut, like `getLumenRichTextShortcut`: Ctrl or Cmd
/// with B, I, U, Z; with Shift, X (strike), Z (redo), 7 (numbered list), and 8 (bullet list).
pub(crate) fn rich_text_shortcut(
    key: &str,
    code: &str,
    modifiers: Modifiers,
) -> Option<&'static str> {
    if !modifiers.intersects(Modifiers::CONTROL | Modifiers::META)
        || modifiers.contains(Modifiers::ALT)
    {
        return None;
    }

    let key = key.to_lowercase();

    if !modifiers.contains(Modifiers::SHIFT) {
        return match key.as_str() {
            "b" => Some("bold"),
            "i" => Some("italic"),
            "u" => Some("underline"),
            "z" => Some("undo"),
            _ => None,
        };
    }

    match code {
        "Digit7" => return Some("insertOrderedList"),
        "Digit8" => return Some("insertUnorderedList"),
        _ => {}
    }

    match key.as_str() {
        "x" => Some("strikeThrough"),
        "z" => Some("redo"),
        _ => None,
    }
}

/// How the content region edits text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RichTextEditorMode {
    /// Rich editing where `eval` works (web, desktop); plain text on Dioxus Native.
    #[default]
    Auto,
    /// Always a `contenteditable` region.
    Rich,
    /// Always a plain-text `<textarea>`; formatting commands are disabled.
    Plain,
}

/// The editor content after an edit or command.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RichTextEditorChange {
    /// The HTML of the editable region (escaped text in plain mode).
    pub html: String,
    /// The text content.
    pub text: String,
}

/// A command the editor ran.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RichTextEditorCommandDetail {
    /// The command name, such as `bold` or `formatBlock`.
    pub command: String,
    /// Whether the command ran.
    pub executed: bool,
    /// The command value, such as `h2` for `formatBlock`.
    pub value: Option<String>,
}

/// Shared state between the editor parts.
#[derive(Clone, Copy)]
struct RichTextContext {
    /// The id the editor generates for its content region.
    generated_id: CopyValue<String>,
    /// The id of the rendered content region: its own `id` when the app sets one, otherwise the
    /// generated id. Commands and change reports look the region up by this id.
    content_id: CopyValue<String>,
    plain: Signal<bool>,
    /// Toggle commands that are currently on.
    active: Signal<Vec<String>>,
    /// The current block format, such as `p` or `h2`.
    block: Signal<String>,
    on_change: CopyValue<Option<EventHandler<RichTextEditorChange>>>,
    on_command: CopyValue<Option<EventHandler<RichTextEditorCommandDetail>>>,
    command_handler: CopyValue<Option<Callback<RichTextEditorCommandDetail, bool>>>,
}

/// Runs `script` with the content id, command, and value, and returns the editor state.
const COMMAND_SCRIPT: &str = r"
const [id, command, value, run] = await dioxus.recv();
const editable = document.getElementById(id);
let executed = false;
if (editable && run) {
  editable.focus();
  executed = value === null ? document.execCommand(command) : document.execCommand(command, false, value);
}
const toggles = ['bold', 'italic', 'strikeThrough', 'subscript', 'superscript', 'underline', 'insertOrderedList', 'insertUnorderedList'];
const states = toggles.map(name => { try { return document.queryCommandState(name); } catch { return false; } });
let block = '';
try { block = String(document.queryCommandValue('formatBlock') || '').split('<').join('').split('>').join('').toLowerCase(); } catch {}
return [executed, states, block, editable ? editable.innerHTML : '', editable ? editable.textContent : ''];
";

type EditorState = (bool, Vec<bool>, String, String, String);

impl RichTextContext {
    /// Runs a command (or only refreshes the toolbar when `run` is false) and syncs the state.
    fn run(self, command: Option<String>, value: Option<String>, run: bool) {
        if *self.plain.peek() {
            return;
        }

        let id = self.content_id.peek().clone();
        let handler = *self.command_handler.peek();
        let on_command = *self.on_command.peek();
        let on_change = *self.on_change.peek();
        let mut context = self;

        spawn(async move {
            let name = command.clone().unwrap_or_default();
            let mut executed_by_app = None;

            if run && let Some(handler) = handler {
                executed_by_app = Some(handler.call(RichTextEditorCommandDetail {
                    command: name.clone(),
                    executed: false,
                    value: value.clone(),
                }));
            }

            let eval = document::eval(COMMAND_SCRIPT);
            let run_in_page = run && executed_by_app.is_none();

            if eval
                .send((id, name.clone(), value.clone(), run_in_page))
                .is_err()
            {
                return;
            }

            let Ok((executed, states, block, html, text)) = eval.join::<EditorState>().await else {
                return;
            };

            let active: Vec<String> = RICH_TEXT_TOGGLE_COMMANDS
                .iter()
                .zip(states)
                .filter(|(_, on)| *on)
                .map(|(command, _)| (*command).to_string())
                .collect();

            if *context.active.peek() != active {
                context.active.set(active);
            }

            if *context.block.peek() != block {
                context.block.set(block);
            }

            if run {
                if let Some(handler) = on_command {
                    handler.call(RichTextEditorCommandDetail {
                        command: name,
                        executed: executed_by_app.unwrap_or(executed),
                        value,
                    });
                }

                if let Some(handler) = on_change {
                    handler.call(RichTextEditorChange { html, text });
                }
            }
        });
    }

    fn emit_change(self) {
        self.run(None, None, false);

        let id = self.content_id.peek().clone();
        let on_change = *self.on_change.peek();

        if on_change.is_none() || *self.plain.peek() {
            return;
        }

        spawn(async move {
            let eval = document::eval(
                "const [id] = await dioxus.recv(); const el = document.getElementById(id); return el ? [el.innerHTML, el.textContent] : ['', ''];",
            );

            if eval.send((id,)).is_err() {
                return;
            }

            if let Ok((html, text)) = eval.join::<(String, String)>().await
                && let Some(handler) = on_change
            {
                handler.call(RichTextEditorChange { html, text });
            }
        });
    }
}

fn use_rich_text(component: &str) -> RichTextContext {
    try_use_context::<RichTextContext>()
        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen RichTextEditor."))
}

/// Props for [`RichTextEditor`].
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorProps {
    /// How the content edits text. Read when the editor mounts.
    #[props(default)]
    pub mode: RichTextEditorMode,
    /// Called with the content after every edit and command.
    pub on_change: Option<EventHandler<RichTextEditorChange>>,
    /// Called after every command.
    pub on_command: Option<EventHandler<RichTextEditorCommandDetail>>,
    /// Runs commands with your own engine instead of `document.execCommand`; return whether the
    /// command ran.
    pub command_handler: Option<Callback<RichTextEditorCommandDetail, bool>>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// A [`RichTextEditorToolbar`] and a [`RichTextEditorContent`].
    pub children: Element,
}

/// A rich text editor frame. Compose it from [`RichTextEditorToolbar`],
/// [`RichTextEditorCommand`], and [`RichTextEditorContent`].
#[component]
pub fn RichTextEditor(props: RichTextEditorProps) -> Element {
    let unique = use_unique_id();
    let context = use_context_provider(|| {
        let generated = format!("ui-rich-text-{unique}-content");

        RichTextContext {
            generated_id: CopyValue::new(generated.clone()),
            content_id: CopyValue::new(generated),
            plain: Signal::new(props.mode == RichTextEditorMode::Plain),
            active: Signal::new(Vec::new()),
            block: Signal::new(String::new()),
            on_change: CopyValue::new(None),
            on_command: CopyValue::new(None),
            command_handler: CopyValue::new(None),
        }
    });
    let (mut on_change, mut on_command, mut command_handler) = (
        context.on_change,
        context.on_command,
        context.command_handler,
    );
    on_change.set(props.on_change);
    on_command.set(props.on_command);
    command_handler.set(props.command_handler);

    let mode = props.mode;

    use_effect(move || {
        if mode != RichTextEditorMode::Auto {
            return;
        }

        spawn(async move {
            // Dioxus Native has no JavaScript: a failed probe switches to plain text.
            if document::eval("return true;").join::<bool>().await.is_err() {
                let mut plain = context.plain;
                plain.set(true);
            }
        });
    });

    let glass = props.glass.class("ui-rich-text-editor");
    let class = compose([
        Some("ui-rich-text-editor"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        section {
            class,
            "data-ui-rich-text-editor": "true",
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`RichTextEditorToolbar`].
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorToolbarProps {
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the toolbar with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// [`RichTextEditorCommand`]s, usually grouped.
    pub children: Element,
}

/// The editor's `toolbar`.
#[component]
pub fn RichTextEditorToolbar(props: RichTextEditorToolbarProps) -> Element {
    rsx! {
        div { class: props.class, role: "toolbar", ..props.attributes, {props.children} }
    }
}

/// Props for [`RichTextEditorCommand`].
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorCommandProps {
    /// The `document.execCommand` name, such as `bold`, `insertUnorderedList`, or `formatBlock`.
    #[props(into)]
    pub command: String,
    /// The command value, such as `h2` for `formatBlock`.
    #[props(into)]
    pub value: Option<String>,
    /// Extra classes appended after the Lumen button classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute. Name icon buttons with `aria_label`.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button content, usually an [`Icon`](crate::Icon).
    pub children: Element,
}

/// A ghost icon button that runs an editing command. Toggle commands report `aria-pressed`, and
/// `data-state` is `on` while the command (or the `formatBlock` value) is active.
#[component]
pub fn RichTextEditorCommand(props: RichTextEditorCommandProps) -> Element {
    let context = use_rich_text("RichTextEditorCommand");
    let is_toggle = RICH_TEXT_TOGGLE_COMMANDS.contains(&props.command.as_str());
    let active = if is_toggle {
        context.active.read().contains(&props.command)
    } else if props.command == "formatBlock" {
        props.value.as_deref().is_some_and(|value| {
            value
                .chars()
                .filter(|character| *character != '<' && *character != '>')
                .collect::<String>()
                .eq_ignore_ascii_case(&context.block.read())
        })
    } else {
        false
    };
    let plain = *context.plain.read();
    let class = compose([
        Some("ui-button ui-button--ghost ui-button--icon"),
        props.class.as_deref(),
    ]);
    let command = props.command.clone();
    let value = props.value.clone();

    rsx! {
        button {
            aria_pressed: is_toggle.then_some(if active { "true" } else { "false" }),
            class,
            "data-slot": "button",
            "data-state": if active { "on" } else { "off" },
            "data-ui-editor-command": props.command.clone(),
            "data-ui-editor-value": props.value.clone(),
            disabled: plain,
            r#type: "button",
            // Keep the text selection in the editable region while pressing the button.
            onmousedown: move |event| event.prevent_default(),
            onclick: move |_| context.run(Some(command.clone()), value.clone(), true),
            ..props.attributes,
            span { class: "ui-button__content", {props.children} }
        }
    }
}

/// Props for [`RichTextEditorContent`].
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorContentProps {
    /// Initial text in plain mode.
    #[props(into)]
    pub default_text: Option<String>,
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the region with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Initial rich content.
    pub children: Element,
}

/// The text value of a non-empty `id` the app spread on the content region.
fn custom_id(attributes: &[Attribute]) -> Option<String> {
    attributes
        .iter()
        .rev()
        .find(|attribute| attribute.name == "id")
        .and_then(|attribute| match &attribute.value {
            dioxus::core::AttributeValue::Text(text) => Some(text.clone()),
            dioxus::core::AttributeValue::Int(value) => Some(value.to_string()),
            _ => None,
        })
        .filter(|id| !id.trim().is_empty())
}

fn escape_html(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());

    for character in text.chars() {
        match character {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            _ => escaped.push(character),
        }
    }

    escaped
}

/// The editable region: `contenteditable` with `role="textbox"` and `aria-multiline`, or a
/// `<textarea>` in plain mode. Ctrl or Cmd shortcuts run the matching commands.
#[component]
pub fn RichTextEditorContent(props: RichTextEditorContentProps) -> Element {
    let context = use_rich_text("RichTextEditorContent");
    // A custom `id` replaces the generated one everywhere: on the region, and in the lookups of
    // commands and change reports, which run after this render.
    let id = custom_id(&props.attributes).unwrap_or_else(|| context.generated_id.peek().clone());
    let mut content_id = context.content_id;

    if *content_id.peek() != id {
        content_id.set(id.clone());
    }

    let attributes: Vec<Attribute> = props
        .attributes
        .into_iter()
        .filter(|attribute| attribute.name != "id")
        .collect();
    let mut text = use_signal(|| props.default_text.clone().unwrap_or_default());

    if *context.plain.read() {
        let class = compose([Some("ui-textarea"), props.class.as_deref()]);

        return rsx! {
            textarea {
                aria_multiline: "true",
                class,
                "data-ui-rich-text-editable": "true",
                id,
                rows: "8",
                value: text(),
                oninput: move |event: FormEvent| {
                    let next = event.value();
                    text.set(next.clone());

                    if let Some(handler) = *context.on_change.peek() {
                        handler.call(RichTextEditorChange { html: escape_html(&next), text: next });
                    }
                },
                ..attributes,
            }
        };
    }

    rsx! {
        div {
            aria_multiline: "true",
            class: props.class,
            contenteditable: "true",
            "data-ui-rich-text-editable": "true",
            id,
            role: "textbox",
            oninput: move |_| context.emit_change(),
            onkeydown: move |event: KeyboardEvent| {
                let shortcut = rich_text_shortcut(
                    &event.key().to_string(),
                    &event.code().to_string(),
                    event.modifiers(),
                );

                if let Some(command) = shortcut {
                    event.prevent_default();
                    context.run(Some(command.to_string()), None, true);
                }
            },
            onkeyup: move |_| context.run(None, None, false),
            onmouseup: move |_| context.run(None, None, false),
            ..attributes,
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{escape_html, rich_text_shortcut};
    use dioxus::prelude::Modifiers;

    #[test]
    fn shortcuts_match_lumen_core() {
        let ctrl = Modifiers::CONTROL;
        let shift = Modifiers::CONTROL | Modifiers::SHIFT;
        let plain = |key: &str| rich_text_shortcut(key, "", ctrl);
        assert_eq!(plain("b"), Some("bold"));
        assert_eq!(plain("I"), Some("italic"));
        assert_eq!(plain("u"), Some("underline"));
        assert_eq!(plain("z"), Some("undo"));
        assert_eq!(plain("k"), None);
        assert_eq!(
            rich_text_shortcut("b", "KeyB", Modifiers::META),
            Some("bold")
        );
        assert_eq!(rich_text_shortcut("b", "KeyB", ctrl | Modifiers::ALT), None);
        assert_eq!(rich_text_shortcut("b", "KeyB", Modifiers::empty()), None);
        assert_eq!(
            rich_text_shortcut("X", "KeyX", shift),
            Some("strikeThrough")
        );
        assert_eq!(rich_text_shortcut("Z", "KeyZ", shift), Some("redo"));
        assert_eq!(
            rich_text_shortcut("&", "Digit7", shift),
            Some("insertOrderedList")
        );
        assert_eq!(
            rich_text_shortcut("*", "Digit8", Modifiers::META | Modifiers::SHIFT),
            Some("insertUnorderedList")
        );
    }

    #[test]
    fn plain_text_is_escaped() {
        assert_eq!(
            escape_html("<b>\"a\" & b</b>"),
            "&lt;b&gt;&quot;a&quot; &amp; b&lt;/b&gt;"
        );
    }
}