//! Code block headers: a bar over the top strip of every code block with a language picker, //! Format, Copy and a per-user auto-format toggle. The bars live in an overlay on the mount //! (like presence). The editor change listener is O(1): it records state and schedules work. //! Positions are read and written in one animation frame; language detection runs in a //! debounced timer and is cached per block. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::rc::{Rc, Weak}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::{spawn_local, JsFuture}; use web_sys::{ AbortController, AddEventListenerOptions, Document, Event, EventTarget, FocusEvent, Headers, HtmlElement, HtmlSelectElement, RequestInit, Response, }; use super::{h, listen, Ctx, Ed}; use crate::core::model::{Blk, Model}; use crate::editor::Editor; use crate::strings::Strings; use note_model::flat::Kind; use note_model::lang::{detect, find, Lang, LANGS}; /// localStorage key of the per-user auto-format setting ("0" or "1", on by default). const PREF_KEY: &str = "project-note-autoformat"; /// Quiet period after a change before languages are detected again. const DETECT_MS: i32 = 300; const FAILED_MS: i32 = 4_000; const COPIED_MS: i32 = 1_500; /// Height of the header, over the top of the block (its 1px border is inset). const HEAD_H: f64 = 34.0; pub fn install(ed: &Ed, cx: &Ctx) { let Some(window) = web_sys::window() else { return }; let layer = h(&cx.document, "div", &[("class", "code-layer")], None); set_all( &layer, &[ ("position", "absolute".into()), ("top", "0".into()), ("left", "0".into()), ("right", "0".into()), ("bottom", "0".into()), ("pointer-events", "none".into()), ], ); let _ = cx.mount.append_child(&layer); let auto = read_pref(); let bars = Rc::new(Bars { document: cx.document.clone(), layer, labels: Labels::load(&cx.strings), ed: Rc::downgrade(ed), heads: RefCell::default(), detected: RefCell::default(), tracked: RefCell::default(), leaving: RefCell::default(), auto: Cell::new(auto), frame_pending: Cell::new(false), detect_timer: Cell::new(None), torn: Cell::new(false), }); // Every change and caret move: O(1), only records state and schedules work. { let weak = Rc::downgrade(&bars); ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| { if let Some(b) = weak.upgrade() { b.on_change(e, changed); } })); } // Leaving the editor (focus moves anywhere else) ends the tracked block. let root = ed.borrow().view.root.clone(); let target: &EventTarget = root.as_ref(); let weak = Rc::downgrade(&bars); listen::(target, "focusout", cx, ed, move |e, _| { if let Some(b) = weak.upgrade() { b.track(e); } }); // Scroll (any container, so capture) and resize move the headers. for (name, opts) in [("scroll", listen_opts(cx, true, true)), ("resize", listen_opts(cx, false, false))] { let weak = Rc::downgrade(&bars); let cb = Closure::::new(move |_: Event| { if let Some(b) = weak.upgrade() { b.schedule_draw(); } }); let _ = window.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts); cb.forget(); } // Removes the headers and any in-flight format; the editor listener stays inert after this. { let bars = bars.clone(); let on_detach = Closure::::new(move || bars.teardown()); let _ = window.add_event_listener_with_callback_and_add_event_listener_options( "note:detach", on_detach.as_ref().unchecked_ref(), &cx.opts, ); on_detach.forget(); } bars.detect_now(); bars.schedule_draw(); } /// The strings the headers show, loaded once. struct Labels { language: String, auto: String, format: String, formatting: String, format_failed: String, format_unsupported: String, copy: String, copied: String, auto_format: String, } impl Labels { fn load(s: &Strings) -> Self { Labels { language: s.get("codeLanguage"), auto: s.get("codeAuto"), format: s.get("codeFormat"), formatting: s.get("codeFormatting"), format_failed: s.get("codeFormatFailed"), format_unsupported: s.get("codeFormatUnsupported"), copy: s.get("codeCopy"), copied: s.get("codeCopied"), auto_format: s.get("codeAutoFormat"), } } } /// One header and the DOM it owns. Dropping it removes its listeners with it. struct Head { el: HtmlElement, select: HtmlSelectElement, /// The first option: "Auto", with the detected language name when there is one. auto_opt: HtmlElement, auto_label: String, /// An option for a `language` attr this build does not know (kept as typed). extra: Option, format: HtmlElement, auto: HtmlElement, status: HtmlElement, status_timer: Option, /// The format request in flight, if any. job: Option, _listeners: Vec>, } impl Head { fn dispose(&mut self) { if let Some(job) = self.job.take() { job.abort(); } clear_timer(self.status_timer.take()); self.el.remove(); } } struct Bars { document: Document, layer: HtmlElement, labels: Labels, ed: Weak>, heads: RefCell>, /// Per code block: the code the language was detected for, and the id found. detected: RefCell)>>, /// The code block the caret is in, with its code as it was when the caret entered. tracked: RefCell>, /// Blocks the caret has left since the last check, with the code remembered for them. leaving: RefCell>, auto: Cell, frame_pending: Cell, detect_timer: Cell>, torn: Cell, } /// What a header shows for its block. struct Info { explicit: Option, detected: Option<&'static Lang>, effective: Option<&'static Lang>, } impl Bars { fn on_change(self: &Rc, e: &Editor, changed: bool) { if self.torn.get() { return; } if changed { self.schedule_detect(); } self.track(e); self.schedule_draw(); } /// Remembers the code of the block the caret is in; when the caret leaves it, the /// block is checked for a change. Reads one block, and only when the block changes. fn track(self: &Rc, e: &Editor) { let cur = if self.auto.get() && e.focused() { caret_block(e) } else { None }; let mut tracked = self.tracked.borrow_mut(); if tracked.as_ref().map(|(id, _)| id) == cur.as_ref() { return; } let mut left = false; if let Some(old) = tracked.take() { self.leaving.borrow_mut().push(old); left = true; } if let Some(id) = cur && let Some(code) = code_of(e, id) { *tracked = Some((id, code)); } drop(tracked); if left { self.schedule_detect(); } } /// Runs the detection after a quiet period (restarted by each change). fn schedule_detect(self: &Rc) { let Some(win) = web_sys::window() else { return }; clear_timer(self.detect_timer.take()); let weak = Rc::downgrade(self); let cb = Closure::once_into_js(move || { if let Some(b) = weak.upgrade() { b.detect_timer.set(None); b.detect_now(); } }); if let Ok(id) = win.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), DETECT_MS) { self.detect_timer.set(Some(id)); } } /// Detects languages of changed blocks, then formats the blocks the caret has left /// with changed code (when auto-format is on and the language can be formatted). fn detect_now(self: &Rc) { if self.torn.get() { return; } let Some(ed) = self.ed.upgrade() else { return }; let jobs = { let Ok(e) = ed.try_borrow() else { return }; let live = live_code(&e); let mut detected = self.detected.borrow_mut(); for (id, b) in &live { // Detection only reads the start of the code. let code = code_prefix(&e.m, b); if detected.get(id).is_some_and(|(seen, _)| *seen == code) { continue; } let found = detect(&code); detected.insert(*id, (code, found)); } detected.retain(|id, _| live.iter().any(|(live_id, _)| live_id == id)); let leaving = std::mem::take(&mut *self.leaving.borrow_mut()); if self.auto.get() { let heads = self.heads.borrow(); leaving .into_iter() .filter(|(id, remembered)| { // A request already in flight (Format was clicked) covers this block. if heads.get(id).is_some_and(|h| h.job.is_some()) { return false; } let Some(b) = block_of(&e, *id) else { return false }; if b.kind() != Kind::Code || e.m.plain(b.start, b.sep) == *remembered { return false; } let det = detected.get(id).and_then(|(_, d)| *d); effective(explicit_of(&b).as_deref(), det).is_some_and(|l| l.formattable) }) .map(|(id, _)| id) .collect::>() } else { Vec::new() } }; for id in jobs { self.start_format(id); } self.schedule_draw(); } /// Redraws the headers in the next animation frame, at most once per frame. fn schedule_draw(self: &Rc) { if self.torn.get() || self.frame_pending.replace(true) { return; } let Some(win) = web_sys::window() else { self.frame_pending.set(false); return; }; let weak = Rc::downgrade(self); let cb = Closure::once_into_js(move || { if let Some(b) = weak.upgrade() { b.frame_pending.set(false); b.draw(); } }); let _ = win.request_animation_frame(cb.unchecked_ref()); } /// Positions every header over its block and syncs its controls. Only place that reads layout. fn draw(self: &Rc) { if self.torn.get() { return; } let Some(ed) = self.ed.upgrade() else { return }; let Ok(e) = ed.try_borrow() else { return }; self.layer.set_hidden(!e.editable); if !e.editable { return; } let code = live_code(&e); let mut heads = self.heads.borrow_mut(); if code.is_empty() { // No code shown: nothing to place, and measuring would force a layout. heads.retain(|_, head| { head.dispose(); false }); return; } let origin = self.layer.get_bounding_client_rect(); let focus = self.document.active_element(); let detected = self.detected.borrow(); let mut live = HashSet::new(); for (id, b) in code { live.insert(id); if !heads.contains_key(&id) { let head = self.build_head(id); heads.insert(id, head); } let Some(head) = heads.get_mut(&id) else { continue }; let det_id = detected.get(&id).and_then(|(_, d)| *d); let explicit = explicit_of(&b); let info = Info { detected: det_id.and_then(find), effective: effective(explicit.as_deref(), det_id), explicit, }; let Some(el) = e.view.element(b.index) else { continue }; let rect = el.get_bounding_client_rect(); head.el.set_hidden(rect.width() <= 0.0 && rect.height() <= 0.0); set_all( &head.el, &[ ("left", px(rect.left() - origin.left() + 1.0)), ("top", px(rect.top() - origin.top() + 1.0)), ("width", px((rect.width() - 2.0).max(0.0))), ("height", px(HEAD_H)), ], ); let has_focus = focus.as_ref().is_some_and(|a| head.el.contains(Some(a))); sync(head, &self.document, &self.labels, &info, has_focus, self.auto.get()); } heads.retain(|id, head| { let keep = live.contains(id); if !keep { head.dispose(); } keep }); } fn build_head(self: &Rc, id: u32) -> Head { let d = &self.document; let l = &self.labels; let el = h(d, "div", &[("class", "code-head")], None); let select: HtmlSelectElement = h(d, "select", &[("class", "code-lang"), ("aria-label", l.language.as_str())], None).unchecked_into(); let auto_opt = h(d, "option", &[("value", "")], Some(l.auto.as_str())); let _ = select.append_child(&auto_opt); for lang in LANGS { let opt = h(d, "option", &[("value", lang.id)], Some(lang.name)); let _ = select.append_child(&opt); } let spacer = h(d, "span", &[("class", "code-spacer"), ("aria-hidden", "true")], None); let status = h(d, "span", &[("class", "code-status"), ("role", "status"), ("aria-live", "polite")], None); let format = button(d, "code-btn code-format", &l.format, ICON_FORMAT); let copy = button(d, "code-btn code-copy", &l.copy, ICON_COPY); let auto = button(d, "code-btn code-auto", &l.auto_format, ICON_WAND); let _ = auto.set_attribute("aria-pressed", if self.auto.get() { "true" } else { "false" }); let _ = el.append_child(&select); let _ = el.append_child(&spacer); let _ = el.append_child(&status); let _ = el.append_child(&format); let _ = el.append_child(©); let _ = el.append_child(&auto); let _ = self.layer.append_child(&el); let mut listeners = Vec::new(); { let (weak, id, sel) = (Rc::downgrade(self), id.clone(), select.clone()); listeners.push(on_el(select.as_ref(), "change", move |_| { let Some(b) = weak.upgrade() else { return }; let Some(ed) = b.ed.upgrade() else { return }; let v = sel.value(); if let Ok(mut e) = ed.try_borrow_mut() && let Some(b) = block_of(&e, id) { e.set_code_language(b.start, (!v.is_empty()).then_some(v.as_str())); } })); } { let (weak, id) = (Rc::downgrade(self), id.clone()); listeners.push(on_el(format.as_ref(), "click", move |_| { if let Some(b) = weak.upgrade() { b.start_format(id); } })); } { let (weak, id) = (Rc::downgrade(self), id.clone()); listeners.push(on_el(copy.as_ref(), "click", move |_| { if let Some(b) = weak.upgrade() { b.copy(id); } })); } { let weak = Rc::downgrade(self); listeners.push(on_el(auto.as_ref(), "click", move |_| { if let Some(b) = weak.upgrade() { b.toggle_auto(); } })); } Head { el, select, auto_label: l.auto.clone(), auto_opt, extra: None, format, auto, status, status_timer: None, job: None, _listeners: listeners, } } /// Effective language of a block: its `language` attr when set, else the detected one. fn lang_of(&self, e: &Editor, id: u32) -> Option<&'static Lang> { let b = block_of(e, id)?; let det = self.detected.borrow().get(&id).and_then(|(_, d)| *d); effective(explicit_of(&b).as_deref(), det) } /// Sends the block's code to /format and replaces it with the answer. fn start_format(self: &Rc, id: u32) { if self.torn.get() { return; } let Some(ed) = self.ed.upgrade() else { return }; let (code, lang) = { let Ok(e) = ed.try_borrow() else { return }; let Some(code) = code_of(&e, id) else { return }; (code, self.lang_of(&e, id)) }; let Some(lang) = lang.filter(|l| l.formattable) else { return }; let Ok(ctrl) = AbortController::new() else { return }; { let mut heads = self.heads.borrow_mut(); let Some(head) = heads.get_mut(&id) else { return }; if let Some(old) = head.job.replace(ctrl.clone()) { old.abort(); } } self.show_status(id, &self.labels.formatting, "", None); self.schedule_draw(); let weak = Rc::downgrade(self); let id = id.clone(); spawn_local(async move { let res = fetch_format(&ctrl, lang.id, &code).await; // Aborted by a newer request for this block, or by teardown: that one owns the state. if ctrl.signal().aborted() { return; } if let Some(b) = weak.upgrade() { b.finish_format(id, &code, res); } }); } fn finish_format(self: &Rc, id: u32, sent: &str, res: Result<(u16, String), JsValue>) { self.clear_job(id); match res { Ok((200, text)) => { if let Some(ed) = self.ed.upgrade() && let Ok(mut e) = ed.try_borrow_mut() && let Some(b) = block_of(&e, id) { e.replace_code(b.start, sent, &text); } self.show_status(id, "", "", None); } other => { let msg = match other { Ok((_, msg)) => msg, Err(_) => String::new(), }; self.show_status(id, &self.labels.format_failed, &msg, Some(FAILED_MS)); } } self.schedule_draw(); } fn clear_job(&self, id: u32) { if let Some(head) = self.heads.borrow_mut().get_mut(&id) { head.job = None; } } /// Copies the block's code to the clipboard and says so for a moment. fn copy(self: &Rc, id: u32) { let Some(ed) = self.ed.upgrade() else { return }; let Some(code) = ed.try_borrow().ok().and_then(|e| code_of(&e, id)) else { return }; let Some(win) = web_sys::window() else { return }; let nav: JsValue = win.navigator().into(); let Ok(clip) = js_sys::Reflect::get(&nav, &"clipboard".into()) else { return }; let Ok(clip) = clip.dyn_into::() else { return }; let promise = clip.write_text(&code); let weak = Rc::downgrade(self); let id = id.clone(); spawn_local(async move { if JsFuture::from(promise).await.is_ok() && let Some(b) = weak.upgrade() { b.show_status(id, &b.labels.copied, "", Some(COPIED_MS)); } }); } fn toggle_auto(self: &Rc) { let on = !self.auto.get(); self.auto.set(on); store_pref(on); if let Some(ed) = self.ed.upgrade() && let Ok(e) = ed.try_borrow() { self.track(&e); } self.schedule_draw(); } /// Sets a header's status text and tooltip; `hold_ms` clears it again after that long. fn show_status(self: &Rc, id: u32, text: &str, title: &str, hold_ms: Option) { let mut heads = self.heads.borrow_mut(); let Some(head) = heads.get_mut(&id) else { return }; clear_timer(head.status_timer.take()); head.status.set_text_content(Some(text)); if title.is_empty() { let _ = head.status.remove_attribute("title"); } else { let _ = head.status.set_attribute("title", title); } if let Some(ms) = hold_ms { let weak = Rc::downgrade(self); let id = id.clone(); let cb = Closure::once_into_js(move || { if let Some(b) = weak.upgrade() { b.show_status(id, "", "", None); } }); head.status_timer = web_sys::window() .and_then(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), ms).ok()); } } /// Removes every header and aborts requests. Runs on `note:detach`. fn teardown(&self) { self.torn.set(true); clear_timer(self.detect_timer.take()); let mut heads = self.heads.borrow_mut(); for head in heads.values_mut() { head.dispose(); } heads.clear(); self.layer.remove(); } } /// Updates one header to match its block. Language controls are left alone while the /// header has focus, so an open dropdown is not disturbed. fn sync(head: &mut Head, d: &Document, l: &Labels, info: &Info, has_focus: bool, auto_on: bool) { let auto_text = match info.detected { Some(lang) => format!("{} \u{b7} {}", l.auto, lang.name), None => l.auto.clone(), }; if head.auto_label != auto_text { head.auto_opt.set_text_content(Some(&auto_text)); head.auto_label = auto_text; } if !has_focus { let unknown = info.explicit.as_deref().filter(|raw| find(raw).is_none()); match (unknown, head.extra.take()) { (Some(raw), Some(opt)) => { if opt.get_attribute("value").as_deref() != Some(raw) { let _ = opt.set_attribute("value", raw); opt.set_text_content(Some(raw)); } head.extra = Some(opt); } (Some(raw), None) => { let opt = h(d, "option", &[("value", raw)], Some(raw)); let _ = head.select.append_child(&opt); head.extra = Some(opt); } (None, Some(opt)) => opt.remove(), (None, None) => {} } let want = match &info.explicit { Some(raw) => find(raw).map_or_else(|| raw.clone(), |lang| lang.id.to_owned()), None => String::new(), }; if head.select.value() != want { head.select.set_value(&want); } } let formattable = info.effective.is_some_and(|lang| lang.formattable); set_flag(&head.format, "disabled", !formattable || head.job.is_some()); let _ = head.format.set_attribute("title", if formattable { l.format.as_str() } else { l.format_unsupported.as_str() }); let _ = head.auto.set_attribute("aria-pressed", if auto_on { "true" } else { "false" }); } /// The effective language: the explicit `language` attr when set (unknown values give none), /// else the detected id. fn effective(explicit: Option<&str>, detected: Option<&'static str>) -> Option<&'static Lang> { match explicit { Some(raw) => find(raw), None => detected.and_then(find), } } /// The block's `language` attr, if set and not blank. fn explicit_of(b: &Blk) -> Option { b.attrs.lang.clone().filter(|s| !s.trim().is_empty()) } /// The first 20 000 characters of a code block: all `detect` looks at. fn code_prefix(m: &Model, b: &Blk) -> String { m.plain(b.start, (b.start + 20_000).min(b.sep)) } /// The block with `key`, if it is rendered. fn block_of(e: &Editor, key: u32) -> Option { e.view.find_key(key).and_then(|i| e.m.block(i)) } /// The rendered code blocks, with their keys. fn live_code(e: &Editor) -> Vec<(u32, Blk)> { e.view .live_blocks() .filter(|(_, v)| v.attrs.kind == Kind::Code) .filter_map(|(i, v)| Some((v.key, e.m.block(i)?))) .collect() } /// The text of a code block, or None when `id` is not one. fn code_of(e: &Editor, id: u32) -> Option { let b = block_of(e, id)?; (b.kind() == Kind::Code).then(|| e.m.plain(b.start, b.sep)) } /// The code block the caret is in (the head of the selection), if any. fn caret_block(e: &Editor) -> Option { let b = e.m.at(e.sel.head()?); if b.kind() != Kind::Code { return None; } e.view.bview(b.index).map(|v| v.key) } /// POST /format with the language and code as JSON. Resolves to the status and the body. async fn fetch_format(ctrl: &AbortController, lang: &str, code: &str) -> Result<(u16, String), JsValue> { let obj: JsValue = js_sys::Object::new().into(); js_sys::Reflect::set(&obj, &"language".into(), &lang.into())?; js_sys::Reflect::set(&obj, &"code".into(), &code.into())?; let body: JsValue = js_sys::JSON::stringify(&obj)?.into(); let headers = Headers::new()?; headers.set("content-type", "application/json")?; let init = RequestInit::new(); init.set_method("POST"); init.set_headers(&headers); init.set_body(&body); init.set_signal(Some(&ctrl.signal())); let win = web_sys::window().ok_or("no window")?; let resp: Response = JsFuture::from(win.fetch_with_str_and_init("/format", &init)).await?.dyn_into()?; let status = resp.status(); let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default(); Ok((status, text)) } /// Whether auto-format is on. Missing or unreadable storage counts as on. fn read_pref() -> bool { let raw = web_sys::window() .and_then(|w| w.local_storage().ok().flatten()) .and_then(|s| s.get_item(PREF_KEY).ok().flatten()); raw.as_deref() != Some("0") } fn store_pref(on: bool) { let storage = web_sys::window().and_then(|w| w.local_storage().ok().flatten()); if let Some(s) = storage { // Storage errors are ignored: the setting then lasts for this page only. let _ = s.set_item(PREF_KEY, if on { "1" } else { "0" }); } } fn clear_timer(id: Option) { if let (Some(id), Some(win)) = (id, web_sys::window()) { win.clear_timeout_with_handle(id); } } /// Adds a listener to an element and returns its closure; the caller keeps it alive. fn on_el(target: &EventTarget, name: &str, f: impl FnMut(Event) + 'static) -> Closure { let cb = Closure::::new(f); let _ = target.add_event_listener_with_callback(name, cb.as_ref().unchecked_ref()); cb } /// Listener options that also carry the detach signal of the UI context. fn listen_opts(cx: &Ctx, capture: bool, passive: bool) -> AddEventListenerOptions { let o = AddEventListenerOptions::new(); o.set_capture(capture); o.set_passive(passive); if let Some(sig) = cx.opts.get_signal() { o.set_signal(&sig); } o } fn button(d: &Document, class: &str, label: &str, inner: &str) -> HtmlElement { let b = h(d, "button", &[("type", "button"), ("class", class), ("aria-label", label), ("title", label)], None); b.set_inner_html(&icon(inner)); b } fn icon(inner: &str) -> String { format!( r#""# ) } const ICON_FORMAT: &str = r#""#; const ICON_COPY: &str = r#""#; const ICON_WAND: &str = r#""#; fn px(v: f64) -> String { format!("{v}px") } fn set_flag(el: &HtmlElement, name: &str, on: bool) { if on { let _ = el.set_attribute(name, ""); } else { let _ = el.remove_attribute(name); } } /// Sets inline style properties. Invalid values are ignored by the browser. fn set_all(el: &HtmlElement, props: &[(&str, String)]) { let style = el.style(); for (k, v) in props { let _ = style.set_property(k, v); } }