//! Editor chrome: toolbar, floating menus, note links, clipboard and presence. //! Each module exposes `install`, called once from `lib.rs` after the editor exists. pub mod clipboard; pub mod codeblock; pub mod floating; pub mod media; pub mod notelinks; pub mod presence; pub mod toolbar; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use web_sys::{AddEventListenerOptions, Document, Element, EventTarget, HtmlElement}; use crate::core::pos::Pos; use crate::editor::Editor; use crate::strings::Strings; pub type Ed = Rc>; /// What every `install` gets. pub struct Ctx { pub document: Document, /// `#editor`, the element around the editable root. pub mount: Element, pub note_id: String, pub strings: Rc, /// Carries the abort signal that removes every listener on `note:detach`. pub opts: AddEventListenerOptions, } /// Adds an event listener (removed on `note:detach`) that runs `f` with the editor /// borrowed mutably; skipped when the editor is already busy. pub fn listen( target: &EventTarget, name: &str, cx: &Ctx, ed: &Ed, mut f: impl FnMut(&mut Editor, &E) + 'static, ) { let weak = Rc::downgrade(ed); let cb = Closure::::new(move |ev: web_sys::Event| { let Some(ed) = weak.upgrade() else { return }; let Ok(mut ed) = ed.try_borrow_mut() else { return }; if let Ok(ev) = ev.dyn_into::() { f(&mut ed, &ev); } }); let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &cx.opts); cb.forget(); } /// Name of the DOM event (on the editable root) that opens the link popover. pub const LINK_EVENT: &str = "editor:link"; /// Asks the floating UI to open the link popover for the current selection. pub fn request_link(root: &HtmlElement) { if let Ok(ev) = web_sys::CustomEvent::new(LINK_EVENT) { let _ = root.dispatch_event(&ev); } } /// Creates an element with attributes and text. Only pass trusted literals as text. pub fn h(document: &Document, tag: &str, attrs: &[(&str, &str)], text: Option<&str>) -> HtmlElement { let el: HtmlElement = document.create_element(tag).unwrap().unchecked_into(); for (k, v) in attrs { let _ = el.set_attribute(k, v); } if let Some(t) = text { el.set_text_content(Some(t)); } el } pub fn is_mac() -> bool { web_sys::window() .and_then(|w| w.navigator().platform().ok()) .is_some_and(|p| p.contains("Mac") || p.contains("iP")) } /// Modifier labels for keycaps: (Mod, Shift, Alt). pub fn mod_keys() -> (&'static str, &'static str, &'static str) { if is_mac() { ("⌘", "⇧", "⌥") } else { ("Ctrl", "Shift", "Alt") } } /// Mono keycap chips, e.g. `keycaps(doc, &["Ctrl", "K"])`. Decorative (aria-hidden). pub fn keycaps(document: &Document, keys: &[&str]) -> HtmlElement { let wrap = h(document, "span", &[("class", "keycaps"), ("aria-hidden", "true")], None); for k in keys { let _ = wrap.append_child(&h(document, "kbd", &[("class", "keycap")], Some(k))); } wrap } /// Tooltip shown on hover/focus of its parent button: label, keycaps, optional reason. pub fn tooltip(document: &Document, label: &str, keys: &[&str], reason: Option<&str>) -> HtmlElement { let tip = h(document, "span", &[("class", "tip"), ("aria-hidden", "true"), ("role", "presentation")], None); let _ = tip.append_child(&h(document, "span", &[("class", "tip-label")], Some(label))); if !keys.is_empty() { let _ = tip.append_child(&keycaps(document, keys)); } if let Some(r) = reason { let _ = tip.append_child(&h(document, "span", &[("class", "tip-reason")], Some(r))); } tip } /// A viewport box. #[derive(Clone, Copy, Debug, Default)] pub struct Box { pub top: f64, pub bottom: f64, pub left: f64, pub right: f64, } /// Viewport box of the caret at `p` (zero width), like PM's `coordsAtPos`. pub fn coords_at(ed: &Editor, p: Pos) -> Option { let (node, off) = ed.view.pos_to_dom(&ed.m, p)?; let document = node.owner_document()?; let range = document.create_range().ok()?; range.set_start(&node, off).ok()?; range.set_end(&node, off).ok()?; let rects = range.get_client_rects()?; let r = match rects.get(0) { Some(r) => r, None => { // Empty block: use the block element's box. let el = ed.view.element(ed.m.at(p).index)?; el.get_bounding_client_rect() } }; Some(Box { top: r.top(), bottom: r.bottom(), left: r.left(), right: r.left() }) } /// Box around the text between two positions (spans lines when needed). pub fn range_box(ed: &Editor, from: Pos, to: Pos) -> Option { let a = coords_at(ed, from)?; let b = coords_at(ed, to)?; 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) }) } const GAP: f64 = 8.0; /// Positions a fixed element next to a box, centred horizontally and clamped to the /// viewport. `above` flips below when there is no room; below flips above at the bottom. pub fn place_floating(el: &HtmlElement, b: Box, above: bool) { let w = web_sys::window().unwrap(); let vw = w.inner_width().ok().and_then(|v| v.as_f64()).unwrap_or(0.0); let vh = w.inner_height().ok().and_then(|v| v.as_f64()).unwrap_or(0.0); let width = el.offset_width() as f64; let height = el.offset_height() as f64; let up = b.top - height - GAP; let down = b.bottom + GAP; let top = if above { if up >= GAP { up } else { down } } else if down + height <= vh - GAP { down } else { up }; let center = (b.left + b.right) / 2.0; let left = (center - width / 2.0).max(GAP).min(vw - width - GAP); let st = el.style(); let _ = st.set_property("top", &format!("{}px", top.max(GAP))); let _ = st.set_property("left", &format!("{}px", left.max(GAP))); }