forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

mod.rs170 lines, 5.9 KiBHistoryRawDownload
1//! Editor chrome: toolbar, floating menus, note links, clipboard and presence.
2//! Each module exposes `install`, called once from `lib.rs` after the editor exists.
3
4pub mod clipboard;
5pub mod codeblock;
6pub mod floating;
7pub mod media;
8pub mod notelinks;
9pub mod presence;
10pub mod toolbar;
11
12use std::cell::RefCell;
13use std::rc::Rc;
14
15use wasm_bindgen::prelude::*;
16use web_sys::{AddEventListenerOptions, Document, Element, EventTarget, HtmlElement};
17
18use crate::core::pos::Pos;
19use crate::editor::Editor;
20use crate::strings::Strings;
21
22pub type Ed = Rc<RefCell<Editor>>;
23
24/// What every `install` gets.
25pub struct Ctx {
26 pub document: Document,
27 /// `#editor`, the element around the editable root.
28 pub mount: Element,
29 pub note_id: String,
30 pub strings: Rc<Strings>,
31 /// Carries the abort signal that removes every listener on `note:detach`.
32 pub opts: AddEventListenerOptions,
33}
34
35/// Adds an event listener (removed on `note:detach`) that runs `f` with the editor
36/// borrowed mutably; skipped when the editor is already busy.
37pub fn listen<E: JsCast + 'static>(
38 target: &EventTarget,
39 name: &str,
40 cx: &Ctx,
41 ed: &Ed,
42 mut f: impl FnMut(&mut Editor, &E) + 'static,
43) {
44 let weak = Rc::downgrade(ed);
45 let cb = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {
46 let Some(ed) = weak.upgrade() else { return };
47 let Ok(mut ed) = ed.try_borrow_mut() else { return };
48 if let Ok(ev) = ev.dyn_into::<E>() {
49 f(&mut ed, &ev);
50 }
51 });
52 let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts);
53 cb.forget();
54}
55
56/// Name of the DOM event (on the editable root) that opens the link popover.
57pub const LINK_EVENT: &str = "editor:link";
58
59/// Asks the floating UI to open the link popover for the current selection.
60pub fn request_link(root: &HtmlElement) {
61 if let Ok(ev) = web_sys::CustomEvent::new(LINK_EVENT) {
62 let _ = root.dispatch_event(&ev);
63 }
64}
65
66/// Creates an element with attributes and text. Only pass trusted literals as text.
67pub fn h(document: &Document, tag: &str, attrs: &[(&str, &str)], text: Option<&str>) -> HtmlElement {
68 let el: HtmlElement = document.create_element(tag).unwrap().unchecked_into();
69 for (k, v) in attrs {
70 let _ = el.set_attribute(k, v);
71 }
72 if let Some(t) = text {
73 el.set_text_content(Some(t));
74 }
75 el
76}
77
78pub fn is_mac() -> bool {
79 web_sys::window()
80 .and_then(|w| w.navigator().platform().ok())
81 .is_some_and(|p| p.contains("Mac") || p.contains("iP"))
82}
83
84/// Modifier labels for keycaps: (Mod, Shift, Alt).
85pub fn mod_keys() -> (&'static str, &'static str, &'static str) {
86 if is_mac() { ("⌘", "⇧", "⌥") } else { ("Ctrl", "Shift", "Alt") }
87}
88
89/// Mono keycap chips, e.g. `keycaps(doc, &["Ctrl", "K"])`. Decorative (aria-hidden).
90pub fn keycaps(document: &Document, keys: &[&str]) -> HtmlElement {
91 let wrap = h(document, "span", &[("class", "keycaps"), ("aria-hidden", "true")], None);
92 for k in keys {
93 let _ = wrap.append_child(&h(document, "kbd", &[("class", "keycap")], Some(k)));
94 }
95 wrap
96}
97
98/// Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason.
99pub fn tooltip(document: &Document, label: &str, keys: &[&str], reason: Option<&str>) -> HtmlElement {
100 let tip = h(document, "span", &[("class", "tip"), ("aria-hidden", "true"), ("role", "presentation")], None);
101 let _ = tip.append_child(&h(document, "span", &[("class", "tip-label")], Some(label)));
102 if !keys.is_empty() {
103 let _ = tip.append_child(&keycaps(document, keys));
104 }
105 if let Some(r) = reason {
106 let _ = tip.append_child(&h(document, "span", &[("class", "tip-reason")], Some(r)));
107 }
108 tip
109}
110
111/// A viewport box.
112#[derive(Clone, Copy, Debug, Default)]
113pub struct Box {
114 pub top: f64,
115 pub bottom: f64,
116 pub left: f64,
117 pub right: f64,
118}
119
120/// Viewport box of the caret at `p` (zero width), like PM's `coordsAtPos`.
121pub fn coords_at(ed: &Editor, p: Pos) -> Option<Box> {
122 let (node, off) = ed.view.pos_to_dom(&ed.m, p)?;
123 let document = node.owner_document()?;
124 let range = document.create_range().ok()?;
125 range.set_start(&node, off).ok()?;
126 range.set_end(&node, off).ok()?;
127 let rects = range.get_client_rects()?;
128 let r = match rects.get(0) {
129 Some(r) => r,
130 None => {
131 // Empty block: use the block element's box.
132 let el = ed.view.element(ed.m.at(p).index)?;
133 el.get_bounding_client_rect()
134 }
135 };
136 Some(Box { top: r.top(), bottom: r.bottom(), left: r.left(), right: r.left() })
137}
138
139/// Box around the text between two positions (spans lines when needed).
140pub fn range_box(ed: &Editor, from: Pos, to: Pos) -> Option<Box> {
141 let a = coords_at(ed, from)?;
142 let b = coords_at(ed, to)?;
143 Some(Box { top: a.top.min(b.top), bottom: a.bottom.max(b.bottom), left: a.left.min(b.left), right: a.right.max(b.right) })
144}
145
146const GAP: f64 = 8.0;
147
148/// Positions a fixed element next to a box, centred horizontally and clamped to the
149/// viewport. `above` flips below when there is no room; below flips above at the bottom.
150pub fn place_floating(el: &HtmlElement, b: Box, above: bool) {
151 let w = web_sys::window().unwrap();
152 let vw = w.inner_width().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
153 let vh = w.inner_height().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
154 let width = el.offset_width() as f64;
155 let height = el.offset_height() as f64;
156 let up = b.top - height - GAP;
157 let down = b.bottom + GAP;
158 let top = if above {
159 if up >= GAP { up } else { down }
160 } else if down + height <= vh - GAP {
161 down
162 } else {
163 up
164 };
165 let center = (b.left + b.right) / 2.0;
166 let left = (center - width / 2.0).max(GAP).min(vw - width - GAP);
167 let st = el.style();
168 let _ = st.set_property("top", &format!("{}px", top.max(GAP)));
169 let _ = st.set_property("left", &format!("{}px", left.max(GAP)));
170}