forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

toolbar.rs435 lines, 17.7 KiBHistoryRawDownload
1//! Formatting toolbar (web/src/toolbar.ts): icon buttons in five groups inside
2//! `#editor-toolbar`, kept in sync with the editor after every change. Roving tabindex
3//! keeps the bar to one Tab stop; mousedown is swallowed so the editor keeps its
4//! selection and focus.
5
6use std::rc::Rc;
7
8use wasm_bindgen::JsCast;
9use web_sys::{EventTarget, HtmlButtonElement, HtmlElement, KeyboardEvent};
10
11use super::media::{Media, STATUS_ID};
12use super::{Ctx, Ed, h, mod_keys, request_link, tooltip};
13use crate::core::commands::{self as c, Cx, can_link, ancestor_kind, is_block_active};
14use crate::core::doc::Kind;
15use crate::core::marks::MarkType;
16use crate::editor::Editor;
17use note_model::flat;
18
19// Lucide-style glyphs (24x24, stroke based). Static strings, safe for innerHTML.
20const ICON_UNDO: &str = r#"<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>"#;
21const ICON_REDO: &str = r#"<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/>"#;
22const ICON_PARAGRAPH: &str = r#"<path d="M13 4v16"/><path d="M17 4v16"/><path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13"/>"#;
23const ICON_H1: &str = r#"<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/>"#;
24const ICON_H2: &str = r#"<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/>"#;
25const ICON_H3: &str = r#"<path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"/><path d="M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"/>"#;
26const ICON_BOLD: &str = r#"<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>"#;
27const ICON_ITALIC: &str = r#"<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>"#;
28const ICON_CODE: &str = r#"<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>"#;
29const ICON_LINK: &str = r#"<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>"#;
30const ICON_BULLETS: &str = r#"<line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/>"#;
31const ICON_ORDERED: &str = r#"<line x1="10" x2="21" y1="6" y2="6"/><line x1="10" x2="21" y1="12" y2="12"/><line x1="10" x2="21" y1="18" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>"#;
32const ICON_QUOTE: &str = r#"<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>"#;
33const ICON_CODE_BLOCK: &str = r#"<rect x="3" y="3" width="18" height="18" rx="2"/><path d="m10 9-3 3 3 3"/><path d="m14 15 3-3-3-3"/>"#;
34const ICON_RULE: &str = r#"<line x1="5" x2="19" y1="12" y2="12"/>"#;
35const ICON_ATTACH: &str = r#"<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>"#;
36const ICON_MIC: &str = r#"<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>"#;
37
38const HEADING_KEYS: [&str; 3] = ["1", "2", "3"];
39
40/// What a button does. Mirrors the `run` of the TS items, with the arguments baked in.
41#[derive(Clone, Copy)]
42enum Run {
43 Undo,
44 Redo,
45 Paragraph,
46 /// Toggle the textblock type (headings, code block).
47 Block(Kind),
48 /// Toggle an inline mark.
49 Mark(MarkType),
50 /// Toggle a list of the given kind.
51 List(Kind),
52 Quote,
53 Rule,
54 /// Opens the link popover; never dispatches.
55 Link,
56 /// Opens the file picker; never dispatches.
57 Attach,
58 /// Starts or stops a microphone recording; never dispatches.
59 Record,
60}
61
62/// What decides the pressed state of a toggle button.
63#[derive(Clone, Copy)]
64enum Active {
65 Block(Kind),
66 Mark(MarkType),
67 Ancestor(fn(Kind) -> bool),
68}
69
70fn exec(run: Run, cx: &mut Cx, apply: bool) -> bool {
71 match run {
72 Run::Undo | Run::Redo => false,
73 Run::Paragraph => c::set_block_type(cx, Kind::Paragraph, apply),
74 Run::Block(k) => c::toggle_block(cx, k, apply),
75 Run::Mark(t) => c::toggle_mark(cx, t, apply),
76 Run::List(k) => c::toggle_list(cx, k, apply),
77 Run::Quote => c::toggle_quote(cx, apply),
78 Run::Rule => c::insert_rule(cx, apply),
79 Run::Link => can_link(cx),
80 // Media lands at the selection, which must be in text outside a code block.
81 Run::Attach | Run::Record => cx.head_block().is_some_and(|b| b.kind().is_text() && b.kind() != flat::Kind::Code),
82 }
83}
84
85fn is_active(active: Active, cx: &Cx) -> bool {
86 match active {
87 Active::Block(k) => is_block_active(cx, k),
88 Active::Mark(t) => c::mark_active_within(cx, t, c::MARK_STATE_UNITS),
89 Active::Ancestor(pred) => ancestor_kind(cx, pred).is_some(),
90 }
91}
92
93/// One button spec, before its DOM exists.
94struct Spec {
95 id: &'static str,
96 label: String,
97 keys: Vec<&'static str>,
98 icon: &'static str,
99 run: Run,
100 active: Option<Active>,
101}
102
103/// A button after it was created: the element plus what it drives.
104struct Btn {
105 el: HtmlButtonElement,
106 run: Run,
107 active: Option<Active>,
108}
109
110fn spec(id: &'static str, label: String, keys: Vec<&'static str>, icon: &'static str, run: Run, active: Option<Active>) -> Spec {
111 Spec { id, label, keys, icon, run, active }
112}
113
114/// Keyboard shortcut in aria-keyshortcuts form, e.g. "Control+B" or "Meta+Shift+8".
115fn aria_keys(keys: &[&str]) -> String {
116 keys.iter()
117 .map(|k| match *k {
118 "Ctrl" => "Control",
119 "⌘" => "Meta",
120 "Shift" | "⇧" => "Shift",
121 "Alt" | "⌥" => "Alt",
122 other => other,
123 })
124 .collect::<Vec<_>>()
125 .join("+")
126}
127
128fn svg(path: &str) -> String {
129 format!(
130 r#"<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{path}</svg>"#
131 )
132}
133
134/// Adds a listener removed on detach (same abort signal as `ui::listen`). The callback
135/// gets the raw event and never borrows the editor by itself.
136fn on(target: &EventTarget, name: &str, cx: &Ctx, cb: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>) {
137 let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts);
138 cb.forget();
139}
140
141fn is_node(a: &web_sys::Node, b: &HtmlButtonElement) -> bool {
142 let bn: &web_sys::Node = b.as_ref();
143 a.is_same_node(Some(bn))
144}
145
146fn set_stop(btns: &[Btn], index: usize) {
147 for (i, b) in btns.iter().enumerate() {
148 b.el.set_tab_index(if i == index { 0 } else { -1 });
149 }
150}
151
152/// Updates disabled, pressed and the single tab stop from the editor state.
153fn sync(btns: &[Btn], ed: &Editor, media: &Media) {
154 for b in btns {
155 let enabled = match b.run {
156 Run::Undo => ed.can_undo(),
157 Run::Redo => ed.can_redo(),
158 // A running recording can always be stopped, even when the caret is elsewhere.
159 Run::Record => media.recording() || ed.can(|cx| exec(b.run, cx, false)),
160 run => ed.can(|cx| exec(run, cx, false)),
161 };
162 b.el.set_disabled(!enabled);
163 if let Some(active) = b.active {
164 let on = ed.can(|cx| is_active(active, cx));
165 let value = if on { "true" } else { "false" };
166 let _ = b.el.set_attribute("data-active", value);
167 let _ = b.el.set_attribute("aria-pressed", value);
168 }
169 }
170 // Keep one enabled button in the tab order, preferring the last one focused.
171 let stop = btns
172 .iter()
173 .position(|b| b.el.tab_index() == 0 && !b.el.disabled())
174 .or_else(|| btns.iter().position(|b| !b.el.disabled()));
175 if let Some(i) = stop {
176 set_stop(btns, i);
177 }
178}
179
180pub fn install(ed: &Ed, cx: &Ctx, media: &Media) {
181 let document = &cx.document;
182 let root: HtmlElement = ed.borrow().view.root.clone();
183 let m = mod_keys();
184 let (md, sh, al) = (m.0, m.1, m.2);
185 let s = &cx.strings;
186
187 // Reuse the page's #editor-toolbar when present; otherwise create it just before the editor.
188 let el: HtmlElement = match document.get_element_by_id("editor-toolbar").and_then(|e| e.dyn_into::<HtmlElement>().ok()) {
189 Some(el) => el,
190 None => {
191 let el = h(document, "div", &[("id", "editor-toolbar")], None);
192 if let Some(parent) = cx.mount.parent_node() {
193 let mount_node: &web_sys::Node = &cx.mount;
194 let node: &web_sys::Node = &el;
195 let _ = parent.insert_before(node, Some(mount_node));
196 }
197 el
198 }
199 };
200 let _ = el.class_list().add_1("editor-toolbar");
201 let _ = el.set_attribute("role", "toolbar");
202 let _ = el.set_attribute("aria-label", &s.get("toolbarLabel"));
203
204 let heading = |level: u8, icon: &'static str| {
205 spec(
206 match level {
207 1 => "h1",
208 2 => "h2",
209 _ => "h3",
210 },
211 s.get(&format!("heading{level}")),
212 vec![md, al, HEADING_KEYS[usize::from(level) - 1]],
213 icon,
214 Run::Block(Kind::Heading(level)),
215 Some(Active::Block(Kind::Heading(level))),
216 )
217 };
218
219 // One inner vec per group, in the order of the TS `buildItems` separators.
220 let groups: [(&str, Vec<Spec>); 5] = [
221 (
222 "history",
223 vec![
224 spec("undo", s.get("undo"), vec![md, "Z"], ICON_UNDO, Run::Undo, None),
225 spec("redo", s.get("redo"), vec![md, sh, "Z"], ICON_REDO, Run::Redo, None),
226 ],
227 ),
228 (
229 "headings",
230 vec![
231 spec(
232 "paragraph",
233 s.get("paragraph"),
234 vec![md, al, "0"],
235 ICON_PARAGRAPH,
236 Run::Paragraph,
237 Some(Active::Block(Kind::Paragraph)),
238 ),
239 heading(1, ICON_H1),
240 heading(2, ICON_H2),
241 heading(3, ICON_H3),
242 ],
243 ),
244 (
245 "marks",
246 vec![
247 spec("bold", s.get("bold"), vec![md, "B"], ICON_BOLD, Run::Mark(MarkType::Strong), Some(Active::Mark(MarkType::Strong))),
248 spec("italic", s.get("italic"), vec![md, "I"], ICON_ITALIC, Run::Mark(MarkType::Em), Some(Active::Mark(MarkType::Em))),
249 spec(
250 "code",
251 s.get("inlineCode"),
252 vec![md, "E"],
253 ICON_CODE,
254 Run::Mark(MarkType::Code),
255 Some(Active::Mark(MarkType::Code)),
256 ),
257 spec("link", s.get("link"), vec![md, "K"], ICON_LINK, Run::Link, Some(Active::Mark(MarkType::Link))),
258 ],
259 ),
260 (
261 "blocks",
262 vec![
263 spec(
264 "bullets",
265 s.get("bulletList"),
266 vec![md, sh, "8"],
267 ICON_BULLETS,
268 Run::List(Kind::BulletList),
269 Some(Active::Ancestor(|k| k == Kind::BulletList)),
270 ),
271 spec(
272 "ordered",
273 s.get("numberedList"),
274 vec![md, sh, "9"],
275 ICON_ORDERED,
276 Run::List(Kind::OrderedList),
277 Some(Active::Ancestor(|k| k == Kind::OrderedList)),
278 ),
279 spec(
280 "quote",
281 s.get("quote"),
282 vec![">"],
283 ICON_QUOTE,
284 Run::Quote,
285 Some(Active::Ancestor(|k| k == Kind::Blockquote)),
286 ),
287 spec(
288 "codeblock",
289 s.get("codeBlock"),
290 vec!["```"],
291 ICON_CODE_BLOCK,
292 Run::Block(Kind::CodeBlock),
293 Some(Active::Block(Kind::CodeBlock)),
294 ),
295 spec("rule", s.get("divider"), vec!["---"], ICON_RULE, Run::Rule, None),
296 ],
297 ),
298 (
299 "media",
300 vec![
301 spec("attach", s.get("attach"), vec![], ICON_ATTACH, Run::Attach, None),
302 spec("record", s.get("recordAudio"), vec![], ICON_MIC, Run::Record, None),
303 ],
304 ),
305 ];
306
307 let reason = s.get("unavailable");
308 let mut btns: Vec<Btn> = Vec::new();
309 // The m:ss readout and the status line sit at the end of the media group.
310 let mut rec_time: Option<HtmlElement> = None;
311 for (name, specs) in groups {
312 let group = h(document, "div", &[("class", "editor-toolbar-group"), ("data-group", name)], None);
313 for sp in specs {
314 let btn: HtmlButtonElement = h(
315 document,
316 "button",
317 &[
318 ("type", "button"),
319 ("class", "editor-toolbar-btn"),
320 ("aria-label", &sp.label),
321 ("aria-keyshortcuts", &aria_keys(&sp.keys)),
322 ("data-command", sp.id),
323 ("tabindex", "-1"),
324 ],
325 None,
326 )
327 .unchecked_into();
328 let icon = h(document, "span", &[("class", "editor-toolbar-icon"), ("aria-hidden", "true")], None);
329 icon.set_inner_html(&svg(sp.icon));
330 let _ = btn.append_child(&icon);
331 let _ = btn.append_child(&tooltip(document, &sp.label, &sp.keys, Some(&reason)));
332 btn.set_disabled(true);
333 let _ = group.append_child(&btn);
334 btns.push(Btn { el: btn, run: sp.run, active: sp.active });
335 }
336 if name == "media" {
337 let time = h(document, "span", &[("class", "editor-rec-time"), ("hidden", ""), ("aria-hidden", "true")], Some("0:00"));
338 let status = h(document, "span", &[("id", STATUS_ID), ("class", "editor-media-status"), ("role", "status"), ("aria-live", "polite")], None);
339 let _ = group.append_child(&time);
340 let _ = group.append_child(&status);
341 rec_time = Some(time);
342 }
343 let _ = el.append_child(&group);
344 }
345 if let (Some(rec), Some(time)) = (btns.iter().find(|b| matches!(b.run, Run::Record)), rec_time) {
346 media.bind_record(rec.el.clone(), time);
347 }
348 let btns = Rc::new(btns);
349
350 // Mousedown must not steal focus or the selection from the editor.
351 let target: &EventTarget = el.as_ref();
352 on(target, "mousedown", cx, wasm_bindgen::closure::Closure::new(|ev: web_sys::Event| ev.prevent_default()));
353
354 // Roving tabindex: arrows, Home and End move among enabled buttons.
355 {
356 let btns = btns.clone();
357 let document = document.clone();
358 let cb = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
359 let Some(key) = ev.dyn_ref::<KeyboardEvent>().map(|k| k.key()) else { return };
360 let enabled: Vec<usize> = (0..btns.len()).filter(|&i| !btns[i].el.disabled()).collect();
361 if enabled.is_empty() {
362 return;
363 }
364 let active = document.active_element();
365 let pos = enabled
366 .iter()
367 .position(|&i| active.as_ref().is_some_and(|a| is_node(a, &btns[i].el)))
368 .map_or(-1, |p| p as isize);
369 let len = enabled.len() as isize;
370 let next = match key.as_str() {
371 "ArrowRight" => (pos + 1).rem_euclid(len),
372 "ArrowLeft" => (pos - 1).rem_euclid(len),
373 "Home" => 0,
374 "End" => len - 1,
375 _ => return,
376 } as usize;
377 ev.prevent_default();
378 let i = enabled[next];
379 set_stop(&btns, i);
380 let _ = btns[i].el.focus();
381 });
382 on(target, "keydown", cx, cb);
383 }
384
385 // Clicks run the command, then return focus to the editor. Link is handled apart:
386 // the popover opens with the editor borrow released, since it reads the editor.
387 for b in btns.iter() {
388 let run = b.run;
389 let weak = Rc::downgrade(ed);
390 let root = root.clone();
391 let media = media.clone();
392 let cb = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::Event)>::new(move |_: web_sys::Event| {
393 // Media takes no editor borrow: the file picker and the microphone run on their own.
394 if matches!(run, Run::Attach | Run::Record) {
395 if matches!(run, Run::Attach) {
396 media.attach();
397 } else {
398 media.toggle_record();
399 }
400 let _ = root.focus();
401 return;
402 }
403 let Some(ed) = weak.upgrade() else { return };
404 if matches!(run, Run::Link) {
405 let open = ed.try_borrow().is_ok_and(|e| e.can(|cx| can_link(cx)));
406 if open {
407 request_link(&root);
408 }
409 } else if let Ok(mut e) = ed.try_borrow_mut() {
410 match run {
411 Run::Undo => {
412 e.undo();
413 }
414 Run::Redo => {
415 e.redo();
416 }
417 _ => {
418 e.run(|cx| exec(run, cx, true));
419 }
420 }
421 }
422 let _ = root.focus();
423 });
424 let target: &EventTarget = b.el.as_ref();
425 on(target, "click", cx, cb);
426 }
427
428 // Initial state, then after every change of doc or selection.
429 if let Ok(e) = ed.try_borrow() {
430 sync(&btns, &e, media);
431 }
432 let btns_l = btns.clone();
433 let media_l = media.clone();
434 ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, _changed: bool| sync(&btns_l, e, &media_l)));
435}