1use dioxus::prelude::*;
11
12use crate::class::{Glass, compose};
13use crate::hooks::use_unique_id;
14
15pub(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
27pub(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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum RichTextEditorMode {
69 #[default]
71 Auto,
72 Rich,
74 Plain,
76}
77
78#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct RichTextEditorChange {
81 pub html: String,
83 pub text: String,
85}
86
87#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct RichTextEditorCommandDetail {
90 pub command: String,
92 pub executed: bool,
94 pub value: Option<String>,
96}
97
98#[derive(Clone, Copy)]
100struct RichTextContext {
101 generated_id: CopyValue<String>,
103 content_id: CopyValue<String>,
106 plain: Signal<bool>,
107 active: Signal<Vec<String>>,
109 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
116const 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 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#[derive(Props, Clone, PartialEq)]
239pub struct RichTextEditorProps {
240 #[props(default)]
242 pub mode: RichTextEditorMode,
243 pub on_change: Option<EventHandler<RichTextEditorChange>>,
245 pub on_command: Option<EventHandler<RichTextEditorCommandDetail>>,
247 pub command_handler: Option<Callback<RichTextEditorCommandDetail, bool>>,
250 #[props(default, into)]
252 pub glass: Glass,
253 #[props(into)]
255 pub class: Option<String>,
256 #[props(extends = GlobalAttributes, extends = section)]
258 pub attributes: Vec<Attribute>,
259 pub children: Element,
261}
262
263#[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 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#[derive(Props, Clone, PartialEq)]
326pub struct RichTextEditorToolbarProps {
327 #[props(into)]
329 pub class: Option<String>,
330 #[props(extends = GlobalAttributes, extends = div)]
332 pub attributes: Vec<Attribute>,
333 pub children: Element,
335}
336
337#[component]
339pub fn RichTextEditorToolbar(props: RichTextEditorToolbarProps) -> Element {
340 rsx! {
341 div { class: props.class, role: "toolbar", ..props.attributes, {props.children} }
342 }
343}
344
345#[derive(Props, Clone, PartialEq)]
347pub struct RichTextEditorCommandProps {
348 #[props(into)]
350 pub command: String,
351 #[props(into)]
353 pub value: Option<String>,
354 #[props(into)]
356 pub class: Option<String>,
357 #[props(extends = GlobalAttributes, extends = button)]
359 pub attributes: Vec<Attribute>,
360 pub children: Element,
362}
363
364#[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 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#[derive(Props, Clone, PartialEq)]
412pub struct RichTextEditorContentProps {
413 #[props(into)]
415 pub default_text: Option<String>,
416 #[props(into)]
418 pub class: Option<String>,
419 #[props(extends = GlobalAttributes, extends = div)]
421 pub attributes: Vec<Attribute>,
422 pub children: Element,
424}
425
426fn 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("&"),
446 '<' => escaped.push_str("<"),
447 '>' => escaped.push_str(">"),
448 '"' => escaped.push_str("""),
449 _ => escaped.push(character),
450 }
451 }
452
453 escaped
454}
455
456#[component]
459pub fn RichTextEditorContent(props: RichTextEditorContentProps) -> Element {
460 let context = use_rich_text("RichTextEditorContent");
461 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 "<b>"a" & b</b>"
571 );
572 }
573}