//! Formatting toolbar (web/src/toolbar.ts): icon buttons in five groups inside //! `#editor-toolbar`, kept in sync with the editor after every change. Roving tabindex //! keeps the bar to one Tab stop; mousedown is swallowed so the editor keeps its //! selection and focus. use std::rc::Rc; use wasm_bindgen::JsCast; use web_sys::{EventTarget, HtmlButtonElement, HtmlElement, KeyboardEvent}; use super::media::{Media, STATUS_ID}; use super::{Ctx, Ed, h, mod_keys, request_link, tooltip}; use crate::core::commands::{self as c, Cx, can_link, ancestor_kind, is_block_active}; use crate::core::doc::Kind; use crate::core::marks::MarkType; use crate::editor::Editor; use note_model::flat; // Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML. const ICON_UNDO: &str = r#""#; const ICON_REDO: &str = r#""#; const ICON_PARAGRAPH: &str = r#""#; const ICON_H1: &str = r#""#; const ICON_H2: &str = r#""#; const ICON_H3: &str = r#""#; const ICON_BOLD: &str = r#""#; const ICON_ITALIC: &str = r#""#; const ICON_CODE: &str = r#""#; const ICON_LINK: &str = r#""#; const ICON_BULLETS: &str = r#""#; const ICON_ORDERED: &str = r#""#; const ICON_QUOTE: &str = r#""#; const ICON_CODE_BLOCK: &str = r#""#; const ICON_RULE: &str = r#""#; const ICON_ATTACH: &str = r#""#; const ICON_MIC: &str = r#""#; const HEADING_KEYS: [&str; 3] = ["1", "2", "3"]; /// What a button does. Mirrors the `run` of the TS items, with the arguments baked in. #[derive(Clone, Copy)] enum Run { Undo, Redo, Paragraph, /// Toggle the textblock type (headings, code block). Block(Kind), /// Toggle an inline mark. Mark(MarkType), /// Toggle a list of the given kind. List(Kind), Quote, Rule, /// Opens the link popover; never dispatches. Link, /// Opens the file picker; never dispatches. Attach, /// Starts or stops a microphone recording; never dispatches. Record, } /// What decides the pressed state of a toggle button. #[derive(Clone, Copy)] enum Active { Block(Kind), Mark(MarkType), Ancestor(fn(Kind) -> bool), } fn exec(run: Run, cx: &mut Cx, apply: bool) -> bool { match run { Run::Undo | Run::Redo => false, Run::Paragraph => c::set_block_type(cx, Kind::Paragraph, apply), Run::Block(k) => c::toggle_block(cx, k, apply), Run::Mark(t) => c::toggle_mark(cx, t, apply), Run::List(k) => c::toggle_list(cx, k, apply), Run::Quote => c::toggle_quote(cx, apply), Run::Rule => c::insert_rule(cx, apply), Run::Link => can_link(cx), // Media lands at the selection, which must be in text outside a code block. Run::Attach | Run::Record => cx.head_block().is_some_and(|b| b.kind().is_text() && b.kind() != flat::Kind::Code), } } fn is_active(active: Active, cx: &Cx) -> bool { match active { Active::Block(k) => is_block_active(cx, k), Active::Mark(t) => c::mark_active_within(cx, t, c::MARK_STATE_UNITS), Active::Ancestor(pred) => ancestor_kind(cx, pred).is_some(), } } /// One button spec, before its DOM exists. struct Spec { id: &'static str, label: String, keys: Vec<&'static str>, icon: &'static str, run: Run, active: Option, } /// A button after it was created: the element plus what it drives. struct Btn { el: HtmlButtonElement, run: Run, active: Option, } fn spec(id: &'static str, label: String, keys: Vec<&'static str>, icon: &'static str, run: Run, active: Option) -> Spec { Spec { id, label, keys, icon, run, active } } /// Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8". fn aria_keys(keys: &[&str]) -> String { keys.iter() .map(|k| match *k { "Ctrl" => "Control", "⌘" => "Meta", "Shift" | "⇧" => "Shift", "Alt" | "⌥" => "Alt", other => other, }) .collect::>() .join("+") } fn svg(path: &str) -> String { format!( r#""# ) } /// Adds a listener removed on detach (same abort signal as `ui::listen`). The callback /// gets the raw event and never borrows the editor by itself. fn on(target: &EventTarget, name: &str, cx: &Ctx, cb: wasm_bindgen::closure::Closure) { let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts); cb.forget(); } fn is_node(a: &web_sys::Node, b: &HtmlButtonElement) -> bool { let bn: &web_sys::Node = b.as_ref(); a.is_same_node(Some(bn)) } fn set_stop(btns: &[Btn], index: usize) { for (i, b) in btns.iter().enumerate() { b.el.set_tab_index(if i == index { 0 } else { -1 }); } } /// Updates disabled, pressed and the single tab stop from the editor state. fn sync(btns: &[Btn], ed: &Editor, media: &Media) { for b in btns { let enabled = match b.run { Run::Undo => ed.can_undo(), Run::Redo => ed.can_redo(), // A running recording can always be stopped, even when the caret is elsewhere. Run::Record => media.recording() || ed.can(|cx| exec(b.run, cx, false)), run => ed.can(|cx| exec(run, cx, false)), }; b.el.set_disabled(!enabled); if let Some(active) = b.active { let on = ed.can(|cx| is_active(active, cx)); let value = if on { "true" } else { "false" }; let _ = b.el.set_attribute("data-active", value); let _ = b.el.set_attribute("aria-pressed", value); } } // Keep one enabled button in the tab order, preferring the last one focused. let stop = btns .iter() .position(|b| b.el.tab_index() == 0 && !b.el.disabled()) .or_else(|| btns.iter().position(|b| !b.el.disabled())); if let Some(i) = stop { set_stop(btns, i); } } pub fn install(ed: &Ed, cx: &Ctx, media: &Media) { let document = &cx.document; let root: HtmlElement = ed.borrow().view.root.clone(); let m = mod_keys(); let (md, sh, al) = (m.0, m.1, m.2); let s = &cx.strings; // Reuse the page's #editor-toolbar when present; otherwise create it just before the editor. let el: HtmlElement = match document.get_element_by_id("editor-toolbar").and_then(|e| e.dyn_into::().ok()) { Some(el) => el, None => { let el = h(document, "div", &[("id", "editor-toolbar")], None); if let Some(parent) = cx.mount.parent_node() { let mount_node: &web_sys::Node = &cx.mount; let node: &web_sys::Node = ⪙ let _ = parent.insert_before(node, Some(mount_node)); } el } }; let _ = el.class_list().add_1("editor-toolbar"); let _ = el.set_attribute("role", "toolbar"); let _ = el.set_attribute("aria-label", &s.get("toolbarLabel")); let heading = |level: u8, icon: &'static str| { spec( match level { 1 => "h1", 2 => "h2", _ => "h3", }, s.get(&format!("heading{level}")), vec![md, al, HEADING_KEYS[usize::from(level) - 1]], icon, Run::Block(Kind::Heading(level)), Some(Active::Block(Kind::Heading(level))), ) }; // One inner vec per group, in the order of the TS `buildItems` separators. let groups: [(&str, Vec); 5] = [ ( "history", vec![ spec("undo", s.get("undo"), vec![md, "Z"], ICON_UNDO, Run::Undo, None), spec("redo", s.get("redo"), vec![md, sh, "Z"], ICON_REDO, Run::Redo, None), ], ), ( "headings", vec![ spec( "paragraph", s.get("paragraph"), vec![md, al, "0"], ICON_PARAGRAPH, Run::Paragraph, Some(Active::Block(Kind::Paragraph)), ), heading(1, ICON_H1), heading(2, ICON_H2), heading(3, ICON_H3), ], ), ( "marks", vec![ spec("bold", s.get("bold"), vec![md, "B"], ICON_BOLD, Run::Mark(MarkType::Strong), Some(Active::Mark(MarkType::Strong))), spec("italic", s.get("italic"), vec![md, "I"], ICON_ITALIC, Run::Mark(MarkType::Em), Some(Active::Mark(MarkType::Em))), spec( "code", s.get("inlineCode"), vec![md, "E"], ICON_CODE, Run::Mark(MarkType::Code), Some(Active::Mark(MarkType::Code)), ), spec("link", s.get("link"), vec![md, "K"], ICON_LINK, Run::Link, Some(Active::Mark(MarkType::Link))), ], ), ( "blocks", vec![ spec( "bullets", s.get("bulletList"), vec![md, sh, "8"], ICON_BULLETS, Run::List(Kind::BulletList), Some(Active::Ancestor(|k| k == Kind::BulletList)), ), spec( "ordered", s.get("numberedList"), vec![md, sh, "9"], ICON_ORDERED, Run::List(Kind::OrderedList), Some(Active::Ancestor(|k| k == Kind::OrderedList)), ), spec( "quote", s.get("quote"), vec![">"], ICON_QUOTE, Run::Quote, Some(Active::Ancestor(|k| k == Kind::Blockquote)), ), spec( "codeblock", s.get("codeBlock"), vec!["```"], ICON_CODE_BLOCK, Run::Block(Kind::CodeBlock), Some(Active::Block(Kind::CodeBlock)), ), spec("rule", s.get("divider"), vec!["---"], ICON_RULE, Run::Rule, None), ], ), ( "media", vec![ spec("attach", s.get("attach"), vec![], ICON_ATTACH, Run::Attach, None), spec("record", s.get("recordAudio"), vec![], ICON_MIC, Run::Record, None), ], ), ]; let reason = s.get("unavailable"); let mut btns: Vec = Vec::new(); // The m:ss readout and the status line sit at the end of the media group. let mut rec_time: Option = None; for (name, specs) in groups { let group = h(document, "div", &[("class", "editor-toolbar-group"), ("data-group", name)], None); for sp in specs { let btn: HtmlButtonElement = h( document, "button", &[ ("type", "button"), ("class", "editor-toolbar-btn"), ("aria-label", &sp.label), ("aria-keyshortcuts", &aria_keys(&sp.keys)), ("data-command", sp.id), ("tabindex", "-1"), ], None, ) .unchecked_into(); let icon = h(document, "span", &[("class", "editor-toolbar-icon"), ("aria-hidden", "true")], None); icon.set_inner_html(&svg(sp.icon)); let _ = btn.append_child(&icon); let _ = btn.append_child(&tooltip(document, &sp.label, &sp.keys, Some(&reason))); btn.set_disabled(true); let _ = group.append_child(&btn); btns.push(Btn { el: btn, run: sp.run, active: sp.active }); } if name == "media" { let time = h(document, "span", &[("class", "editor-rec-time"), ("hidden", ""), ("aria-hidden", "true")], Some("0:00")); let status = h(document, "span", &[("id", STATUS_ID), ("class", "editor-media-status"), ("role", "status"), ("aria-live", "polite")], None); let _ = group.append_child(&time); let _ = group.append_child(&status); rec_time = Some(time); } let _ = el.append_child(&group); } if let (Some(rec), Some(time)) = (btns.iter().find(|b| matches!(b.run, Run::Record)), rec_time) { media.bind_record(rec.el.clone(), time); } let btns = Rc::new(btns); // Mousedown must not steal focus or the selection from the editor. let target: &EventTarget = el.as_ref(); on(target, "mousedown", cx, wasm_bindgen::closure::Closure::new(|ev: web_sys::Event| ev.prevent_default())); // Roving tabindex: arrows, Home and End move among enabled buttons. { let btns = btns.clone(); let document = document.clone(); let cb = wasm_bindgen::closure::Closure::::new(move |ev: web_sys::Event| { let Some(key) = ev.dyn_ref::().map(|k| k.key()) else { return }; let enabled: Vec = (0..btns.len()).filter(|&i| !btns[i].el.disabled()).collect(); if enabled.is_empty() { return; } let active = document.active_element(); let pos = enabled .iter() .position(|&i| active.as_ref().is_some_and(|a| is_node(a, &btns[i].el))) .map_or(-1, |p| p as isize); let len = enabled.len() as isize; let next = match key.as_str() { "ArrowRight" => (pos + 1).rem_euclid(len), "ArrowLeft" => (pos - 1).rem_euclid(len), "Home" => 0, "End" => len - 1, _ => return, } as usize; ev.prevent_default(); let i = enabled[next]; set_stop(&btns, i); let _ = btns[i].el.focus(); }); on(target, "keydown", cx, cb); } // Clicks run the command, then return focus to the editor. Link is handled apart: // the popover opens with the editor borrow released, since it reads the editor. for b in btns.iter() { let run = b.run; let weak = Rc::downgrade(ed); let root = root.clone(); let media = media.clone(); let cb = wasm_bindgen::closure::Closure::::new(move |_: web_sys::Event| { // Media takes no editor borrow: the file picker and the microphone run on their own. if matches!(run, Run::Attach | Run::Record) { if matches!(run, Run::Attach) { media.attach(); } else { media.toggle_record(); } let _ = root.focus(); return; } let Some(ed) = weak.upgrade() else { return }; if matches!(run, Run::Link) { let open = ed.try_borrow().is_ok_and(|e| e.can(|cx| can_link(cx))); if open { request_link(&root); } } else if let Ok(mut e) = ed.try_borrow_mut() { match run { Run::Undo => { e.undo(); } Run::Redo => { e.redo(); } _ => { e.run(|cx| exec(run, cx, true)); } } } let _ = root.focus(); }); let target: &EventTarget = b.el.as_ref(); on(target, "click", cx, cb); } // Initial state, then after every change of doc or selection. if let Ok(e) = ed.try_borrow() { sync(&btns, &e, media); } let btns_l = btns.clone(); let media_l = media.clone(); ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, _changed: bool| sync(&btns_l, e, &media_l))); }