use dioxus::prelude::*;
use crate::class::{Glass, compose};
use crate::hooks::use_unique_id;
pub(crate) const RICH_TEXT_TOGGLE_COMMANDS: [&str; 8] = [
"bold",
"italic",
"strikeThrough",
"subscript",
"superscript",
"underline",
"insertOrderedList",
"insertUnorderedList",
];
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,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RichTextEditorMode {
#[default]
Auto,
Rich,
Plain,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RichTextEditorChange {
pub html: String,
pub text: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RichTextEditorCommandDetail {
pub command: String,
pub executed: bool,
pub value: Option<String>,
}
#[derive(Clone, Copy)]
struct RichTextContext {
generated_id: CopyValue<String>,
content_id: CopyValue<String>,
plain: Signal<bool>,
active: Signal<Vec<String>>,
block: Signal<String>,
on_change: CopyValue<Option<EventHandler<RichTextEditorChange>>>,
on_command: CopyValue<Option<EventHandler<RichTextEditorCommandDetail>>>,
command_handler: CopyValue<Option<Callback<RichTextEditorCommandDetail, bool>>>,
}
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 {
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."))
}
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorProps {
#[props(default)]
pub mode: RichTextEditorMode,
pub on_change: Option<EventHandler<RichTextEditorChange>>,
pub on_command: Option<EventHandler<RichTextEditorCommandDetail>>,
pub command_handler: Option<Callback<RichTextEditorCommandDetail, bool>>,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = section)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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 {
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}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorToolbarProps {
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn RichTextEditorToolbar(props: RichTextEditorToolbarProps) -> Element {
rsx! {
div { class: props.class, role: "toolbar", ..props.attributes, {props.children} }
}
}
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorCommandProps {
#[props(into)]
pub command: String,
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = button)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[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",
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} }
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct RichTextEditorContentProps {
#[props(into)]
pub default_text: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
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("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
_ => escaped.push(character),
}
}
escaped
}
#[component]
pub fn RichTextEditorContent(props: RichTextEditorContentProps) -> Element {
let context = use_rich_text("RichTextEditorContent");
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>"),
"<b>"a" & b</b>"
);
}
}