forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

codeblock.rs800 lines, 28.6 KiBHistoryRawDownload
1//! Code block headers: a bar over the top strip of every code block with a language picker,
2//! Format, Copy and a per-user auto-format toggle. The bars live in an overlay on the mount
3//! (like presence). The editor change listener is O(1): it records state and schedules work.
4//! Positions are read and written in one animation frame; language detection runs in a
5//! debounced timer and is cached per block.
6
7use std::cell::{Cell, RefCell};
8use std::collections::{HashMap, HashSet};
9use std::rc::{Rc, Weak};
10
11use wasm_bindgen::prelude::*;
12use wasm_bindgen::JsCast;
13use wasm_bindgen_futures::{spawn_local, JsFuture};
14use web_sys::{
15 AbortController, AddEventListenerOptions, Document, Event, EventTarget, FocusEvent, Headers, HtmlElement,
16 HtmlSelectElement, RequestInit, Response,
17};
18
19use super::{h, listen, Ctx, Ed};
20use crate::core::model::{Blk, Model};
21use crate::editor::Editor;
22use crate::strings::Strings;
23use note_model::flat::Kind;
24use note_model::lang::{detect, find, Lang, LANGS};
25
26/// localStorage key of the per-user auto-format setting ("0" or "1", on by default).
27const PREF_KEY: &str = "project-note-autoformat";
28/// Quiet period after a change before languages are detected again.
29const DETECT_MS: i32 = 300;
30const FAILED_MS: i32 = 4_000;
31const COPIED_MS: i32 = 1_500;
32/// Height of the header, over the top of the block (its 1px border is inset).
33const HEAD_H: f64 = 34.0;
34
35pub fn install(ed: &Ed, cx: &Ctx) {
36 let Some(window) = web_sys::window() else { return };
37
38 let layer = h(&cx.document, "div", &[("class", "code-layer")], None);
39 set_all(
40 &layer,
41 &[
42 ("position", "absolute".into()),
43 ("top", "0".into()),
44 ("left", "0".into()),
45 ("right", "0".into()),
46 ("bottom", "0".into()),
47 ("pointer-events", "none".into()),
48 ],
49 );
50 let _ = cx.mount.append_child(&layer);
51
52 let auto = read_pref();
53 let bars = Rc::new(Bars {
54 document: cx.document.clone(),
55 layer,
56 labels: Labels::load(&cx.strings),
57 ed: Rc::downgrade(ed),
58 heads: RefCell::default(),
59 detected: RefCell::default(),
60 tracked: RefCell::default(),
61 leaving: RefCell::default(),
62 auto: Cell::new(auto),
63 frame_pending: Cell::new(false),
64 detect_timer: Cell::new(None),
65 torn: Cell::new(false),
66 });
67
68 // Every change and caret move: O(1), only records state and schedules work.
69 {
70 let weak = Rc::downgrade(&bars);
71 ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| {
72 if let Some(b) = weak.upgrade() {
73 b.on_change(e, changed);
74 }
75 }));
76 }
77 // Leaving the editor (focus moves anywhere else) ends the tracked block.
78 let root = ed.borrow().view.root.clone();
79 let target: &EventTarget = root.as_ref();
80 let weak = Rc::downgrade(&bars);
81 listen::<FocusEvent>(target, "focusout", cx, ed, move |e, _| {
82 if let Some(b) = weak.upgrade() {
83 b.track(e);
84 }
85 });
86
87 // Scroll (any container, so capture) and resize move the headers.
88 for (name, opts) in [("scroll", listen_opts(cx, true, true)), ("resize", listen_opts(cx, false, false))] {
89 let weak = Rc::downgrade(&bars);
90 let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
91 if let Some(b) = weak.upgrade() {
92 b.schedule_draw();
93 }
94 });
95 let _ = window.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts);
96 cb.forget();
97 }
98
99 // Removes the headers and any in-flight format; the editor listener stays inert after this.
100 {
101 let bars = bars.clone();
102 let on_detach = Closure::<dyn FnMut()>::new(move || bars.teardown());
103 let _ = window.add_event_listener_with_callback_and_add_event_listener_options(
104 "note:detach",
105 on_detach.as_ref().unchecked_ref(),
106 &cx.opts,
107 );
108 on_detach.forget();
109 }
110
111 bars.detect_now();
112 bars.schedule_draw();
113}
114
115/// The strings the headers show, loaded once.
116struct Labels {
117 language: String,
118 auto: String,
119 format: String,
120 formatting: String,
121 format_failed: String,
122 format_unsupported: String,
123 copy: String,
124 copied: String,
125 auto_format: String,
126}
127
128impl Labels {
129 fn load(s: &Strings) -> Self {
130 Labels {
131 language: s.get("codeLanguage"),
132 auto: s.get("codeAuto"),
133 format: s.get("codeFormat"),
134 formatting: s.get("codeFormatting"),
135 format_failed: s.get("codeFormatFailed"),
136 format_unsupported: s.get("codeFormatUnsupported"),
137 copy: s.get("codeCopy"),
138 copied: s.get("codeCopied"),
139 auto_format: s.get("codeAutoFormat"),
140 }
141 }
142}
143
144/// One header and the DOM it owns. Dropping it removes its listeners with it.
145struct Head {
146 el: HtmlElement,
147 select: HtmlSelectElement,
148 /// The first option: "Auto", with the detected language name when there is one.
149 auto_opt: HtmlElement,
150 auto_label: String,
151 /// An option for a `language` attr this build does not know (kept as typed).
152 extra: Option<HtmlElement>,
153 format: HtmlElement,
154 auto: HtmlElement,
155 status: HtmlElement,
156 status_timer: Option<i32>,
157 /// The format request in flight, if any.
158 job: Option<AbortController>,
159 _listeners: Vec<Closure<dyn FnMut(Event)>>,
160}
161
162impl Head {
163 fn dispose(&mut self) {
164 if let Some(job) = self.job.take() {
165 job.abort();
166 }
167 clear_timer(self.status_timer.take());
168 self.el.remove();
169 }
170}
171
172struct Bars {
173 document: Document,
174 layer: HtmlElement,
175 labels: Labels,
176 ed: Weak<RefCell<Editor>>,
177 heads: RefCell<HashMap<u32, Head>>,
178 /// Per code block: the code the language was detected for, and the id found.
179 detected: RefCell<HashMap<u32, (String, Option<&'static str>)>>,
180 /// The code block the caret is in, with its code as it was when the caret entered.
181 tracked: RefCell<Option<(u32, String)>>,
182 /// Blocks the caret has left since the last check, with the code remembered for them.
183 leaving: RefCell<Vec<(u32, String)>>,
184 auto: Cell<bool>,
185 frame_pending: Cell<bool>,
186 detect_timer: Cell<Option<i32>>,
187 torn: Cell<bool>,
188}
189
190/// What a header shows for its block.
191struct Info {
192 explicit: Option<String>,
193 detected: Option<&'static Lang>,
194 effective: Option<&'static Lang>,
195}
196
197impl Bars {
198 fn on_change(self: &Rc<Self>, e: &Editor, changed: bool) {
199 if self.torn.get() {
200 return;
201 }
202 if changed {
203 self.schedule_detect();
204 }
205 self.track(e);
206 self.schedule_draw();
207 }
208
209 /// Remembers the code of the block the caret is in; when the caret leaves it, the
210 /// block is checked for a change. Reads one block, and only when the block changes.
211 fn track(self: &Rc<Self>, e: &Editor) {
212 let cur = if self.auto.get() && e.focused() { caret_block(e) } else { None };
213 let mut tracked = self.tracked.borrow_mut();
214 if tracked.as_ref().map(|(id, _)| id) == cur.as_ref() {
215 return;
216 }
217 let mut left = false;
218 if let Some(old) = tracked.take() {
219 self.leaving.borrow_mut().push(old);
220 left = true;
221 }
222 if let Some(id) = cur
223 && let Some(code) = code_of(e, id)
224 {
225 *tracked = Some((id, code));
226 }
227 drop(tracked);
228 if left {
229 self.schedule_detect();
230 }
231 }
232
233 /// Runs the detection after a quiet period (restarted by each change).
234 fn schedule_detect(self: &Rc<Self>) {
235 let Some(win) = web_sys::window() else { return };
236 clear_timer(self.detect_timer.take());
237 let weak = Rc::downgrade(self);
238 let cb = Closure::once_into_js(move || {
239 if let Some(b) = weak.upgrade() {
240 b.detect_timer.set(None);
241 b.detect_now();
242 }
243 });
244 if let Ok(id) = win.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), DETECT_MS) {
245 self.detect_timer.set(Some(id));
246 }
247 }
248
249 /// Detects languages of changed blocks, then formats the blocks the caret has left
250 /// with changed code (when auto-format is on and the language can be formatted).
251 fn detect_now(self: &Rc<Self>) {
252 if self.torn.get() {
253 return;
254 }
255 let Some(ed) = self.ed.upgrade() else { return };
256 let jobs = {
257 let Ok(e) = ed.try_borrow() else { return };
258 let live = live_code(&e);
259 let mut detected = self.detected.borrow_mut();
260 for (id, b) in &live {
261 // Detection only reads the start of the code.
262 let code = code_prefix(&e.m, b);
263 if detected.get(id).is_some_and(|(seen, _)| *seen == code) {
264 continue;
265 }
266 let found = detect(&code);
267 detected.insert(*id, (code, found));
268 }
269 detected.retain(|id, _| live.iter().any(|(live_id, _)| live_id == id));
270
271 let leaving = std::mem::take(&mut *self.leaving.borrow_mut());
272 if self.auto.get() {
273 let heads = self.heads.borrow();
274 leaving
275 .into_iter()
276 .filter(|(id, remembered)| {
277 // A request already in flight (Format was clicked) covers this block.
278 if heads.get(id).is_some_and(|h| h.job.is_some()) {
279 return false;
280 }
281 let Some(b) = block_of(&e, *id) else { return false };
282 if b.kind() != Kind::Code || e.m.plain(b.start, b.sep) == *remembered {
283 return false;
284 }
285 let det = detected.get(id).and_then(|(_, d)| *d);
286 effective(explicit_of(&b).as_deref(), det).is_some_and(|l| l.formattable)
287 })
288 .map(|(id, _)| id)
289 .collect::<Vec<_>>()
290 } else {
291 Vec::new()
292 }
293 };
294 for id in jobs {
295 self.start_format(id);
296 }
297 self.schedule_draw();
298 }
299
300 /// Redraws the headers in the next animation frame, at most once per frame.
301 fn schedule_draw(self: &Rc<Self>) {
302 if self.torn.get() || self.frame_pending.replace(true) {
303 return;
304 }
305 let Some(win) = web_sys::window() else {
306 self.frame_pending.set(false);
307 return;
308 };
309 let weak = Rc::downgrade(self);
310 let cb = Closure::once_into_js(move || {
311 if let Some(b) = weak.upgrade() {
312 b.frame_pending.set(false);
313 b.draw();
314 }
315 });
316 let _ = win.request_animation_frame(cb.unchecked_ref());
317 }
318
319 /// Positions every header over its block and syncs its controls. Only place that reads layout.
320 fn draw(self: &Rc<Self>) {
321 if self.torn.get() {
322 return;
323 }
324 let Some(ed) = self.ed.upgrade() else { return };
325 let Ok(e) = ed.try_borrow() else { return };
326 self.layer.set_hidden(!e.editable);
327 if !e.editable {
328 return;
329 }
330 let code = live_code(&e);
331 let mut heads = self.heads.borrow_mut();
332 if code.is_empty() {
333 // No code shown: nothing to place, and measuring would force a layout.
334 heads.retain(|_, head| {
335 head.dispose();
336 false
337 });
338 return;
339 }
340 let origin = self.layer.get_bounding_client_rect();
341 let focus = self.document.active_element();
342 let detected = self.detected.borrow();
343 let mut live = HashSet::new();
344
345 for (id, b) in code {
346 live.insert(id);
347 if !heads.contains_key(&id) {
348 let head = self.build_head(id);
349 heads.insert(id, head);
350 }
351 let Some(head) = heads.get_mut(&id) else { continue };
352
353 let det_id = detected.get(&id).and_then(|(_, d)| *d);
354 let explicit = explicit_of(&b);
355 let info = Info {
356 detected: det_id.and_then(find),
357 effective: effective(explicit.as_deref(), det_id),
358 explicit,
359 };
360
361 let Some(el) = e.view.element(b.index) else { continue };
362 let rect = el.get_bounding_client_rect();
363 head.el.set_hidden(rect.width() <= 0.0 && rect.height() <= 0.0);
364 set_all(
365 &head.el,
366 &[
367 ("left", px(rect.left() - origin.left() + 1.0)),
368 ("top", px(rect.top() - origin.top() + 1.0)),
369 ("width", px((rect.width() - 2.0).max(0.0))),
370 ("height", px(HEAD_H)),
371 ],
372 );
373 let has_focus = focus.as_ref().is_some_and(|a| head.el.contains(Some(a)));
374 sync(head, &self.document, &self.labels, &info, has_focus, self.auto.get());
375 }
376
377 heads.retain(|id, head| {
378 let keep = live.contains(id);
379 if !keep {
380 head.dispose();
381 }
382 keep
383 });
384 }
385
386 fn build_head(self: &Rc<Self>, id: u32) -> Head {
387 let d = &self.document;
388 let l = &self.labels;
389 let el = h(d, "div", &[("class", "code-head")], None);
390
391 let select: HtmlSelectElement =
392 h(d, "select", &[("class", "code-lang"), ("aria-label", l.language.as_str())], None).unchecked_into();
393 let auto_opt = h(d, "option", &[("value", "")], Some(l.auto.as_str()));
394 let _ = select.append_child(&auto_opt);
395 for lang in LANGS {
396 let opt = h(d, "option", &[("value", lang.id)], Some(lang.name));
397 let _ = select.append_child(&opt);
398 }
399
400 let spacer = h(d, "span", &[("class", "code-spacer"), ("aria-hidden", "true")], None);
401 let status = h(d, "span", &[("class", "code-status"), ("role", "status"), ("aria-live", "polite")], None);
402 let format = button(d, "code-btn code-format", &l.format, ICON_FORMAT);
403 let copy = button(d, "code-btn code-copy", &l.copy, ICON_COPY);
404 let auto = button(d, "code-btn code-auto", &l.auto_format, ICON_WAND);
405 let _ = auto.set_attribute("aria-pressed", if self.auto.get() { "true" } else { "false" });
406
407 let _ = el.append_child(&select);
408 let _ = el.append_child(&spacer);
409 let _ = el.append_child(&status);
410 let _ = el.append_child(&format);
411 let _ = el.append_child(&copy);
412 let _ = el.append_child(&auto);
413 let _ = self.layer.append_child(&el);
414
415 let mut listeners = Vec::new();
416 {
417 let (weak, id, sel) = (Rc::downgrade(self), id.clone(), select.clone());
418 listeners.push(on_el(select.as_ref(), "change", move |_| {
419 let Some(b) = weak.upgrade() else { return };
420 let Some(ed) = b.ed.upgrade() else { return };
421 let v = sel.value();
422 if let Ok(mut e) = ed.try_borrow_mut()
423 && let Some(b) = block_of(&e, id)
424 {
425 e.set_code_language(b.start, (!v.is_empty()).then_some(v.as_str()));
426 }
427 }));
428 }
429 {
430 let (weak, id) = (Rc::downgrade(self), id.clone());
431 listeners.push(on_el(format.as_ref(), "click", move |_| {
432 if let Some(b) = weak.upgrade() {
433 b.start_format(id);
434 }
435 }));
436 }
437 {
438 let (weak, id) = (Rc::downgrade(self), id.clone());
439 listeners.push(on_el(copy.as_ref(), "click", move |_| {
440 if let Some(b) = weak.upgrade() {
441 b.copy(id);
442 }
443 }));
444 }
445 {
446 let weak = Rc::downgrade(self);
447 listeners.push(on_el(auto.as_ref(), "click", move |_| {
448 if let Some(b) = weak.upgrade() {
449 b.toggle_auto();
450 }
451 }));
452 }
453
454 Head {
455 el,
456 select,
457 auto_label: l.auto.clone(),
458 auto_opt,
459 extra: None,
460 format,
461 auto,
462 status,
463 status_timer: None,
464 job: None,
465 _listeners: listeners,
466 }
467 }
468
469 /// Effective language of a block: its `language` attr when set, else the detected one.
470 fn lang_of(&self, e: &Editor, id: u32) -> Option<&'static Lang> {
471 let b = block_of(e, id)?;
472 let det = self.detected.borrow().get(&id).and_then(|(_, d)| *d);
473 effective(explicit_of(&b).as_deref(), det)
474 }
475
476 /// Sends the block's code to /format and replaces it with the answer.
477 fn start_format(self: &Rc<Self>, id: u32) {
478 if self.torn.get() {
479 return;
480 }
481 let Some(ed) = self.ed.upgrade() else { return };
482 let (code, lang) = {
483 let Ok(e) = ed.try_borrow() else { return };
484 let Some(code) = code_of(&e, id) else { return };
485 (code, self.lang_of(&e, id))
486 };
487 let Some(lang) = lang.filter(|l| l.formattable) else { return };
488 let Ok(ctrl) = AbortController::new() else { return };
489 {
490 let mut heads = self.heads.borrow_mut();
491 let Some(head) = heads.get_mut(&id) else { return };
492 if let Some(old) = head.job.replace(ctrl.clone()) {
493 old.abort();
494 }
495 }
496 self.show_status(id, &self.labels.formatting, "", None);
497 self.schedule_draw();
498
499 let weak = Rc::downgrade(self);
500 let id = id.clone();
501 spawn_local(async move {
502 let res = fetch_format(&ctrl, lang.id, &code).await;
503 // Aborted by a newer request for this block, or by teardown: that one owns the state.
504 if ctrl.signal().aborted() {
505 return;
506 }
507 if let Some(b) = weak.upgrade() {
508 b.finish_format(id, &code, res);
509 }
510 });
511 }
512
513 fn finish_format(self: &Rc<Self>, id: u32, sent: &str, res: Result<(u16, String), JsValue>) {
514 self.clear_job(id);
515 match res {
516 Ok((200, text)) => {
517 if let Some(ed) = self.ed.upgrade()
518 && let Ok(mut e) = ed.try_borrow_mut()
519 && let Some(b) = block_of(&e, id)
520 {
521 e.replace_code(b.start, sent, &text);
522 }
523 self.show_status(id, "", "", None);
524 }
525 other => {
526 let msg = match other {
527 Ok((_, msg)) => msg,
528 Err(_) => String::new(),
529 };
530 self.show_status(id, &self.labels.format_failed, &msg, Some(FAILED_MS));
531 }
532 }
533 self.schedule_draw();
534 }
535
536 fn clear_job(&self, id: u32) {
537 if let Some(head) = self.heads.borrow_mut().get_mut(&id) {
538 head.job = None;
539 }
540 }
541
542 /// Copies the block's code to the clipboard and says so for a moment.
543 fn copy(self: &Rc<Self>, id: u32) {
544 let Some(ed) = self.ed.upgrade() else { return };
545 let Some(code) = ed.try_borrow().ok().and_then(|e| code_of(&e, id)) else { return };
546 let Some(win) = web_sys::window() else { return };
547 let nav: JsValue = win.navigator().into();
548 let Ok(clip) = js_sys::Reflect::get(&nav, &"clipboard".into()) else { return };
549 let Ok(clip) = clip.dyn_into::<web_sys::Clipboard>() else { return };
550 let promise = clip.write_text(&code);
551 let weak = Rc::downgrade(self);
552 let id = id.clone();
553 spawn_local(async move {
554 if JsFuture::from(promise).await.is_ok()
555 && let Some(b) = weak.upgrade()
556 {
557 b.show_status(id, &b.labels.copied, "", Some(COPIED_MS));
558 }
559 });
560 }
561
562 fn toggle_auto(self: &Rc<Self>) {
563 let on = !self.auto.get();
564 self.auto.set(on);
565 store_pref(on);
566 if let Some(ed) = self.ed.upgrade()
567 && let Ok(e) = ed.try_borrow()
568 {
569 self.track(&e);
570 }
571 self.schedule_draw();
572 }
573
574 /// Sets a header's status text and tooltip; `hold_ms` clears it again after that long.
575 fn show_status(self: &Rc<Self>, id: u32, text: &str, title: &str, hold_ms: Option<i32>) {
576 let mut heads = self.heads.borrow_mut();
577 let Some(head) = heads.get_mut(&id) else { return };
578 clear_timer(head.status_timer.take());
579 head.status.set_text_content(Some(text));
580 if title.is_empty() {
581 let _ = head.status.remove_attribute("title");
582 } else {
583 let _ = head.status.set_attribute("title", title);
584 }
585 if let Some(ms) = hold_ms {
586 let weak = Rc::downgrade(self);
587 let id = id.clone();
588 let cb = Closure::once_into_js(move || {
589 if let Some(b) = weak.upgrade() {
590 b.show_status(id, "", "", None);
591 }
592 });
593 head.status_timer = web_sys::window()
594 .and_then(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(cb.unchecked_ref(), ms).ok());
595 }
596 }
597
598 /// Removes every header and aborts requests. Runs on `note:detach`.
599 fn teardown(&self) {
600 self.torn.set(true);
601 clear_timer(self.detect_timer.take());
602 let mut heads = self.heads.borrow_mut();
603 for head in heads.values_mut() {
604 head.dispose();
605 }
606 heads.clear();
607 self.layer.remove();
608 }
609}
610
611/// Updates one header to match its block. Language controls are left alone while the
612/// header has focus, so an open dropdown is not disturbed.
613fn sync(head: &mut Head, d: &Document, l: &Labels, info: &Info, has_focus: bool, auto_on: bool) {
614 let auto_text = match info.detected {
615 Some(lang) => format!("{} \u{b7} {}", l.auto, lang.name),
616 None => l.auto.clone(),
617 };
618 if head.auto_label != auto_text {
619 head.auto_opt.set_text_content(Some(&auto_text));
620 head.auto_label = auto_text;
621 }
622
623 if !has_focus {
624 let unknown = info.explicit.as_deref().filter(|raw| find(raw).is_none());
625 match (unknown, head.extra.take()) {
626 (Some(raw), Some(opt)) => {
627 if opt.get_attribute("value").as_deref() != Some(raw) {
628 let _ = opt.set_attribute("value", raw);
629 opt.set_text_content(Some(raw));
630 }
631 head.extra = Some(opt);
632 }
633 (Some(raw), None) => {
634 let opt = h(d, "option", &[("value", raw)], Some(raw));
635 let _ = head.select.append_child(&opt);
636 head.extra = Some(opt);
637 }
638 (None, Some(opt)) => opt.remove(),
639 (None, None) => {}
640 }
641 let want = match &info.explicit {
642 Some(raw) => find(raw).map_or_else(|| raw.clone(), |lang| lang.id.to_owned()),
643 None => String::new(),
644 };
645 if head.select.value() != want {
646 head.select.set_value(&want);
647 }
648 }
649
650 let formattable = info.effective.is_some_and(|lang| lang.formattable);
651 set_flag(&head.format, "disabled", !formattable || head.job.is_some());
652 let _ = head.format.set_attribute("title", if formattable { l.format.as_str() } else { l.format_unsupported.as_str() });
653 let _ = head.auto.set_attribute("aria-pressed", if auto_on { "true" } else { "false" });
654}
655
656/// The effective language: the explicit `language` attr when set (unknown values give none),
657/// else the detected id.
658fn effective(explicit: Option<&str>, detected: Option<&'static str>) -> Option<&'static Lang> {
659 match explicit {
660 Some(raw) => find(raw),
661 None => detected.and_then(find),
662 }
663}
664
665/// The block's `language` attr, if set and not blank.
666fn explicit_of(b: &Blk) -> Option<String> {
667 b.attrs.lang.clone().filter(|s| !s.trim().is_empty())
668}
669
670/// The first 20 000 characters of a code block: all `detect` looks at.
671fn code_prefix(m: &Model, b: &Blk) -> String {
672 m.plain(b.start, (b.start + 20_000).min(b.sep))
673}
674
675/// The block with `key`, if it is rendered.
676fn block_of(e: &Editor, key: u32) -> Option<Blk> {
677 e.view.find_key(key).and_then(|i| e.m.block(i))
678}
679
680/// The rendered code blocks, with their keys.
681fn live_code(e: &Editor) -> Vec<(u32, Blk)> {
682 e.view
683 .live_blocks()
684 .filter(|(_, v)| v.attrs.kind == Kind::Code)
685 .filter_map(|(i, v)| Some((v.key, e.m.block(i)?)))
686 .collect()
687}
688
689/// The text of a code block, or None when `id` is not one.
690fn code_of(e: &Editor, id: u32) -> Option<String> {
691 let b = block_of(e, id)?;
692 (b.kind() == Kind::Code).then(|| e.m.plain(b.start, b.sep))
693}
694
695/// The code block the caret is in (the head of the selection), if any.
696fn caret_block(e: &Editor) -> Option<u32> {
697 let b = e.m.at(e.sel.head()?);
698 if b.kind() != Kind::Code {
699 return None;
700 }
701 e.view.bview(b.index).map(|v| v.key)
702}
703
704/// POST /format with the language and code as JSON. Resolves to the status and the body.
705async fn fetch_format(ctrl: &AbortController, lang: &str, code: &str) -> Result<(u16, String), JsValue> {
706 let obj: JsValue = js_sys::Object::new().into();
707 js_sys::Reflect::set(&obj, &"language".into(), &lang.into())?;
708 js_sys::Reflect::set(&obj, &"code".into(), &code.into())?;
709 let body: JsValue = js_sys::JSON::stringify(&obj)?.into();
710
711 let headers = Headers::new()?;
712 headers.set("content-type", "application/json")?;
713 let init = RequestInit::new();
714 init.set_method("POST");
715 init.set_headers(&headers);
716 init.set_body(&body);
717 init.set_signal(Some(&ctrl.signal()));
718
719 let win = web_sys::window().ok_or("no window")?;
720 let resp: Response = JsFuture::from(win.fetch_with_str_and_init("/format", &init)).await?.dyn_into()?;
721 let status = resp.status();
722 let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default();
723 Ok((status, text))
724}
725
726/// Whether auto-format is on. Missing or unreadable storage counts as on.
727fn read_pref() -> bool {
728 let raw = web_sys::window()
729 .and_then(|w| w.local_storage().ok().flatten())
730 .and_then(|s| s.get_item(PREF_KEY).ok().flatten());
731 raw.as_deref() != Some("0")
732}
733
734fn store_pref(on: bool) {
735 let storage = web_sys::window().and_then(|w| w.local_storage().ok().flatten());
736 if let Some(s) = storage {
737 // Storage errors are ignored: the setting then lasts for this page only.
738 let _ = s.set_item(PREF_KEY, if on { "1" } else { "0" });
739 }
740}
741
742fn clear_timer(id: Option<i32>) {
743 if let (Some(id), Some(win)) = (id, web_sys::window()) {
744 win.clear_timeout_with_handle(id);
745 }
746}
747
748/// Adds a listener to an element and returns its closure; the caller keeps it alive.
749fn on_el(target: &EventTarget, name: &str, f: impl FnMut(Event) + 'static) -> Closure<dyn FnMut(Event)> {
750 let cb = Closure::<dyn FnMut(Event)>::new(f);
751 let _ = target.add_event_listener_with_callback(name, cb.as_ref().unchecked_ref());
752 cb
753}
754
755/// Listener options that also carry the detach signal of the UI context.
756fn listen_opts(cx: &Ctx, capture: bool, passive: bool) -> AddEventListenerOptions {
757 let o = AddEventListenerOptions::new();
758 o.set_capture(capture);
759 o.set_passive(passive);
760 if let Some(sig) = cx.opts.get_signal() {
761 o.set_signal(&sig);
762 }
763 o
764}
765
766fn button(d: &Document, class: &str, label: &str, inner: &str) -> HtmlElement {
767 let b = h(d, "button", &[("type", "button"), ("class", class), ("aria-label", label), ("title", label)], None);
768 b.set_inner_html(&icon(inner));
769 b
770}
771
772fn icon(inner: &str) -> String {
773 format!(
774 r#"<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">{inner}</svg>"#
775 )
776}
777
778const ICON_FORMAT: &str = r#"<path d="M4 6h16M4 12h10M4 18h14"/>"#;
779const ICON_COPY: &str = r#"<rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>"#;
780const ICON_WAND: &str = r#"<path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8z"/><path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9z"/>"#;
781
782fn px(v: f64) -> String {
783 format!("{v}px")
784}
785
786fn set_flag(el: &HtmlElement, name: &str, on: bool) {
787 if on {
788 let _ = el.set_attribute(name, "");
789 } else {
790 let _ = el.remove_attribute(name);
791 }
792}
793
794/// Sets inline style properties. Invalid values are ignored by the browser.
795fn set_all(el: &HtmlElement, props: &[(&str, String)]) {
796 let style = el.style();
797 for (k, v) in props {
798 let _ = style.set_property(k, v);
799 }
800}