forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

floating.rs966 lines, 34.2 KiBHistoryRawDownload
1//! Floating editor UI (port of `web/src/floating.ts`): the selection bubble menu, the
2//! link popover (edit mode for Mod-K and the buttons, view mode for a clicked link) and
3//! the slash "/" block menu. Everything is plain DOM on <body>, positioned from the
4//! caret boxes.
5//!
6//! State lives in `Ui` (DOM handles, item tables, `St`). Editor borrows use
7//! `try_borrow*` and are released before anything that can re-enter the editor
8//! (`run`, `focus`, the `editor:link` dispatch), so those calls go through `spawn_local`
9//! or happen after the borrow is dropped.
10
11use std::cell::RefCell;
12use std::rc::Rc;
13
14use wasm_bindgen::prelude::*;
15use wasm_bindgen_futures::spawn_local;
16use web_sys::{
17 AbortSignal, AddEventListenerOptions, Document, Element, Event, EventTarget, HtmlElement, HtmlInputElement, KeyboardEvent,
18 MouseEvent, Node as DomNode, ScrollIntoViewOptions, ScrollLogicalPosition,
19};
20
21use super::{Ctx, Ed, LINK_EVENT, h, keycaps, mod_keys, place_floating, range_box, request_link, tooltip};
22use loro::TextDelta;
23
24use crate::core::commands::{self as c, Command, Cx};
25use crate::core::doc::Kind;
26use crate::core::marks::{MarkType, Marks};
27use crate::core::pos::{self, Pos, Selection};
28use crate::editor::Editor;
29use crate::strings::Strings;
30
31struct Bubble {
32 id: &'static str,
33 label: String,
34 glyph: &'static str,
35 keys: Vec<&'static str>,
36 run: Command,
37 active: fn(&Cx) -> bool,
38}
39
40struct SlashItem {
41 id: &'static str,
42 label: String,
43 /// English words the filter also matches, so "h2" or "list" work in either language.
44 keywords: &'static str,
45 keys: Vec<&'static str>,
46 run: Command,
47}
48
49/// Mutable UI state. Never held across a call that can run an editor command.
50#[derive(Default)]
51struct St {
52 bubble_dismissed: bool,
53 last_sel: Option<Selection>,
54 link: Option<LinkState>,
55 slash: Option<SlashState>,
56 slash_dismissed: Option<Pos>,
57}
58
59struct LinkState {
60 from: Pos,
61 to: Pos,
62 /// Existing href at the range, if any.
63 href: Option<String>,
64}
65
66struct SlashState {
67 /// Position of the "/" that opened the menu.
68 from: Pos,
69 query: String,
70 index: usize,
71 /// Indexes into `Ui::slash_items` that match the query.
72 filtered: Vec<usize>,
73}
74
75struct Ui {
76 ed: Ed,
77 st: RefCell<St>,
78 document: Document,
79 root: HtmlElement,
80 strings: Rc<Strings>,
81 signal: AbortSignal,
82 bubble: HtmlElement,
83 bubble_btns: Vec<HtmlElement>,
84 bubble_items: Vec<Bubble>,
85 link_pop: HtmlElement,
86 edit_panel: HtmlElement,
87 link_input: HtmlInputElement,
88 link_error: HtmlElement,
89 edit_remove: HtmlElement,
90 edit_open: HtmlElement,
91 view_panel: HtmlElement,
92 link_href: HtmlElement,
93 view_edit: HtmlElement,
94 view_remove: HtmlElement,
95 view_open: HtmlElement,
96 slash_menu: HtmlElement,
97 slash_list: HtmlElement,
98 slash_items: Vec<SlashItem>,
99}
100
101pub fn install(ed: &Ed, cx: &Ctx) {
102 let Some(signal) = js_sys::Reflect::get(&cx.opts, &"signal".into()).ok().and_then(|s| s.dyn_into::<AbortSignal>().ok()) else {
103 return;
104 };
105 let document = cx.document.clone();
106 let strings = cx.strings.clone();
107 let root = ed.borrow().view.root.clone();
108 let s = |k: &str| strings.get(k);
109 let (m, sh, alt) = mod_keys();
110
111 let bubble_items = vec![
112 Bubble {
113 id: "bold",
114 label: s("bold"),
115 glyph: "B",
116 keys: vec![m, "B"],
117 run: |cx, a| c::toggle_mark(cx, MarkType::Strong, a),
118 active: |cx| c::mark_active_within(cx, MarkType::Strong, c::MARK_STATE_UNITS),
119 },
120 Bubble {
121 id: "italic",
122 label: s("italic"),
123 glyph: "I",
124 keys: vec![m, "I"],
125 run: |cx, a| c::toggle_mark(cx, MarkType::Em, a),
126 active: |cx| c::mark_active_within(cx, MarkType::Em, c::MARK_STATE_UNITS),
127 },
128 Bubble {
129 id: "code",
130 label: s("inlineCode"),
131 glyph: "</>",
132 keys: vec![m, "E"],
133 run: |cx, a| c::toggle_mark(cx, MarkType::Code, a),
134 active: |cx| c::mark_active_within(cx, MarkType::Code, c::MARK_STATE_UNITS),
135 },
136 Bubble {
137 id: "link",
138 label: s("link"),
139 glyph: "Link",
140 keys: vec![m, "K"],
141 // Opens the popover (see `bubble_click`); the command only reports availability.
142 run: |cx, _| c::can_link(cx),
143 active: |cx| c::mark_active_within(cx, MarkType::Link, c::MARK_STATE_UNITS),
144 },
145 Bubble {
146 id: "h1",
147 label: s("heading1"),
148 glyph: "H1",
149 keys: vec![m, alt, "1"],
150 run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
151 active: |cx| c::is_block_active(cx, Kind::Heading(1)),
152 },
153 Bubble {
154 id: "h2",
155 label: s("heading2"),
156 glyph: "H2",
157 keys: vec![m, alt, "2"],
158 run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
159 active: |cx| c::is_block_active(cx, Kind::Heading(2)),
160 },
161 Bubble {
162 id: "h3",
163 label: s("heading3"),
164 glyph: "H3",
165 keys: vec![m, alt, "3"],
166 run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
167 active: |cx| c::is_block_active(cx, Kind::Heading(3)),
168 },
169 ];
170
171 let slash_items = vec![
172 SlashItem {
173 id: "text",
174 label: s("paragraph"),
175 keywords: "text paragraph p",
176 keys: vec![m, alt, "0"],
177 run: |cx, a| c::set_block_type(cx, Kind::Paragraph, a),
178 },
179 SlashItem {
180 id: "h1",
181 label: s("heading1"),
182 keywords: "heading title h1",
183 keys: vec![m, alt, "1"],
184 run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
185 },
186 SlashItem {
187 id: "h2",
188 label: s("heading2"),
189 keywords: "heading subtitle h2",
190 keys: vec![m, alt, "2"],
191 run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
192 },
193 SlashItem {
194 id: "h3",
195 label: s("heading3"),
196 keywords: "heading h3",
197 keys: vec![m, alt, "3"],
198 run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
199 },
200 SlashItem {
201 id: "bullets",
202 label: s("bulletList"),
203 keywords: "list ul bullet unordered",
204 keys: vec![m, sh, "8"],
205 run: |cx, a| c::toggle_list(cx, Kind::BulletList, a),
206 },
207 SlashItem {
208 id: "ordered",
209 label: s("numberedList"),
210 keywords: "list ol number ordered",
211 keys: vec![m, sh, "9"],
212 run: |cx, a| c::toggle_list(cx, Kind::OrderedList, a),
213 },
214 SlashItem { id: "quote", label: s("quote"), keywords: "blockquote quote", keys: vec![">"], run: |cx, a| c::toggle_quote(cx, a) },
215 SlashItem {
216 id: "codeblock",
217 label: s("codeBlock"),
218 keywords: "code pre fence",
219 keys: vec!["```"],
220 run: |cx, a| c::toggle_block(cx, Kind::CodeBlock, a),
221 },
222 SlashItem { id: "divider", label: s("divider"), keywords: "hr rule line divider", keys: vec!["---"], run: |cx, a| c::insert_rule(cx, a) },
223 ];
224
225 // Bubble menu.
226 let bubble_label = s("bubbleLabel");
227 let bubble = h(&document, "div", &[("class", "bubble"), ("role", "toolbar"), ("aria-label", bubble_label.as_str())], None);
228 bubble.set_hidden(true);
229 let mut bubble_btns = Vec::new();
230 for item in &bubble_items {
231 let btn = h(
232 &document,
233 "button",
234 &[("type", "button"), ("class", "bubble-btn"), ("aria-label", item.label.as_str()), ("data-command", item.id)],
235 None,
236 );
237 btn.append_child(&h(&document, "span", &[("class", "bubble-glyph"), ("aria-hidden", "true")], Some(item.glyph)))
238 .ok();
239 btn.append_child(&tooltip(&document, &item.label, &item.keys, None)).ok();
240 bubble.append_child(&btn).ok();
241 bubble_btns.push(btn);
242 }
243
244 // Link popover: the edit and view panels share one element.
245 let link_dialog = s("linkDialog");
246 let link_pop = h(&document, "div", &[("class", "popover link-popover"), ("role", "dialog"), ("aria-label", link_dialog.as_str())], None);
247 link_pop.set_hidden(true);
248 let edit_panel = h(&document, "form", &[("class", "link-edit"), ("novalidate", "")], None);
249 let link_url = s("linkUrl");
250 let link_input: HtmlInputElement = h(
251 &document,
252 "input",
253 &[
254 ("type", "text"),
255 ("class", "link-input"),
256 ("inputmode", "url"),
257 ("autocomplete", "off"),
258 ("autocapitalize", "off"),
259 ("spellcheck", "false"),
260 ("placeholder", "https://"),
261 ("aria-label", link_url.as_str()),
262 ("aria-describedby", "link-error"),
263 ],
264 None,
265 )
266 .unchecked_into();
267 let link_error = h(&document, "p", &[("class", "link-error"), ("id", "link-error"), ("role", "alert")], None);
268 link_error.set_hidden(true);
269 let apply_btn = h(&document, "button", &[("type", "submit"), ("class", "btn btn-primary")], Some(&s("apply")));
270 apply_btn.append_child(&keycaps(&document, &["↵"])).ok();
271 let edit_remove = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("remove")));
272 let edit_open = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("open")));
273 let row = h(&document, "div", &[("class", "link-row")], None);
274 row.append_child(&link_input).ok();
275 row.append_child(&apply_btn).ok();
276 let edit_actions = h(&document, "div", &[("class", "link-actions")], None);
277 edit_actions.append_child(&edit_remove).ok();
278 edit_actions.append_child(&edit_open).ok();
279 edit_panel.append_child(&row).ok();
280 edit_panel.append_child(&link_error).ok();
281 edit_panel.append_child(&edit_actions).ok();
282
283 // View mode is a small menu: the href as its label, then Edit / Remove / Open.
284 let link_menu = s("linkMenu");
285 let view_panel = h(&document, "div", &[("class", "link-view"), ("role", "menu"), ("aria-label", link_menu.as_str())], None);
286 let link_href = h(&document, "span", &[("class", "link-href")], None);
287 let view_edit = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("edit")));
288 let view_remove = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("remove")));
289 let view_open = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("open")));
290 let view_actions = h(&document, "div", &[("class", "link-actions"), ("role", "none")], None);
291 view_actions.append_child(&view_edit).ok();
292 view_actions.append_child(&view_remove).ok();
293 view_actions.append_child(&view_open).ok();
294 view_panel.append_child(&link_href).ok();
295 view_panel.append_child(&view_actions).ok();
296 link_pop.append_child(&edit_panel).ok();
297 link_pop.append_child(&view_panel).ok();
298
299 // Slash menu.
300 let slash_menu = h(&document, "div", &[("class", "popover slash-menu"), ("role", "presentation")], None);
301 slash_menu.set_hidden(true);
302 let block_menu = s("blockMenu");
303 let slash_list = h(&document, "div", &[("class", "slash-list"), ("role", "listbox"), ("aria-label", block_menu.as_str())], None);
304 let footer = h(&document, "div", &[("class", "slash-footer"), ("aria-hidden", "true")], None);
305 footer.append_child(&keycaps(&document, &["↑", "↓"])).ok();
306 footer.append_child(&document.create_text_node(&format!(" {} ", s("navigate")))).ok();
307 footer.append_child(&keycaps(&document, &["↵"])).ok();
308 footer.append_child(&document.create_text_node(&format!(" {} ", s("insert")))).ok();
309 footer.append_child(&keycaps(&document, &["Esc"])).ok();
310 footer.append_child(&document.create_text_node(&format!(" {}", s("close")))).ok();
311 slash_menu.append_child(&slash_list).ok();
312 slash_menu.append_child(&footer).ok();
313
314 if let Some(body) = document.body() {
315 body.append_child(&bubble).ok();
316 body.append_child(&link_pop).ok();
317 body.append_child(&slash_menu).ok();
318 }
319
320 let ui = Rc::new(Ui {
321 ed: ed.clone(),
322 st: RefCell::default(),
323 document,
324 root,
325 strings,
326 signal,
327 bubble,
328 bubble_btns,
329 bubble_items,
330 link_pop,
331 edit_panel,
332 link_input,
333 link_error,
334 edit_remove,
335 edit_open,
336 view_panel,
337 link_href,
338 view_edit,
339 view_remove,
340 view_open,
341 slash_menu,
342 slash_list,
343 slash_items,
344 });
345 attach(&ui);
346
347 // Keeps the popovers in sync after every doc or selection change.
348 let l = ui.clone();
349 ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| {
350 let mut s = l.st.borrow_mut();
351 if s.last_sel.as_ref() != Some(&e.sel) {
352 s.bubble_dismissed = false;
353 s.last_sel = Some(e.sel.clone());
354 }
355 // A popover refers to a fixed range; a doc change invalidates it.
356 if changed && s.link.is_some() {
357 s.link = None;
358 l.link_pop.set_hidden(true);
359 }
360 update_slash(e, &mut s, &l);
361 render(e, &s, &l);
362 }));
363}
364
365/// Registers the DOM handlers. Every listener uses the editor's abort signal, so it is
366/// removed on `note:detach`.
367fn attach(ui: &Rc<Ui>) {
368 let sig = &ui.signal;
369
370 for (i, btn) in ui.bubble_btns.iter().enumerate() {
371 let (u, is_link, run) = (ui.clone(), ui.bubble_items[i].id == "link", ui.bubble_items[i].run);
372 on(btn.as_ref(), "click", sig, false, move |_| bubble_click(&u, is_link, run));
373 }
374 // Keep the text selection while pressing bubble and slash buttons.
375 on(ui.bubble.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
376 on(ui.slash_menu.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
377
378 let u = ui.clone();
379 on(ui.edit_panel.as_ref(), "submit", sig, false, move |ev| {
380 ev.prevent_default();
381 submit_link(&u);
382 });
383 // One delegated listener for the slash items, which are rebuilt on every filter change.
384 let u = ui.clone();
385 on(ui.slash_list.as_ref(), "click", sig, false, move |ev| {
386 let item = ev.target().and_then(|t| t.dyn_into::<Element>().ok()).and_then(|t| t.closest(".slash-item").ok().flatten());
387 let gi = item.and_then(|el| el.get_attribute("data-index")).and_then(|v| v.parse::<usize>().ok());
388 if let Some(gi) = gi {
389 slash_click(&u, gi);
390 }
391 });
392 let u = ui.clone();
393 on(ui.link_pop.as_ref(), "keydown", sig, false, move |ev| link_keydown(&u, ev));
394
395 for btn in [&ui.edit_remove, &ui.view_remove] {
396 let u = ui.clone();
397 on(btn.as_ref(), "click", sig, false, move |_| remove_link(&u));
398 }
399 for btn in [&ui.edit_open, &ui.view_open] {
400 let u = ui.clone();
401 on(btn.as_ref(), "click", sig, false, move |_| open_href(&u));
402 }
403 let u = ui.clone();
404 on(ui.view_edit.as_ref(), "click", sig, false, move |_| {
405 let range = u.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
406 if let (Some((from, to)), Ok(e)) = (range, u.ed.try_borrow()) {
407 show_link(&u, &e, from, to, true);
408 }
409 });
410
411 // Capture phase so the keys are seen before the editor's own keydown listener.
412 let u = ui.clone();
413 on(ui.root.as_ref(), "keydown", sig, true, move |ev| {
414 let Some(k) = ev.dyn_ref::<KeyboardEvent>() else { return };
415 if key_down(&u, k) {
416 ev.prevent_default();
417 ev.stop_immediate_propagation();
418 }
419 });
420 let u = ui.clone();
421 on(ui.root.as_ref(), "click", sig, false, move |ev| root_click(&u, ev));
422 // Mod-K and the toolbar dispatch this synchronously from inside an editor borrow, so
423 // the popover opens on the next microtask instead.
424 let u = ui.clone();
425 on(ui.root.as_ref(), LINK_EVENT, sig, false, move |_| {
426 let u = u.clone();
427 spawn_local(async move { open_for_selection(&u) });
428 });
429
430 // Clicking outside the link popover closes it (without moving focus).
431 let u = ui.clone();
432 on(ui.document.as_ref(), "mousedown", sig, true, move |ev| {
433 let target = ev.target().and_then(|t| t.dyn_into::<DomNode>().ok());
434 let inside = target.as_ref().is_some_and(|t| u.link_pop.contains(Some(t)));
435 if !inside {
436 close_link(&u);
437 }
438 });
439
440 if let Some(win) = web_sys::window() {
441 let u = ui.clone();
442 on(win.as_ref(), "scroll", sig, true, move |_| refresh(&u));
443 let u = ui.clone();
444 on(win.as_ref(), "resize", sig, false, move |_| refresh(&u));
445 let u = ui.clone();
446 on(win.as_ref(), "note:detach", sig, false, move |_| {
447 u.bubble.remove();
448 u.link_pop.remove();
449 u.slash_menu.remove();
450 });
451 }
452}
453
454/// Adds a DOM listener that is removed when `signal` aborts.
455fn on(target: &EventTarget, name: &str, signal: &AbortSignal, capture: bool, f: impl FnMut(&Event) + 'static) {
456 let opts = AddEventListenerOptions::new();
457 opts.set_signal(signal);
458 opts.set_capture(capture);
459 let mut f = f;
460 let cb = Closure::<dyn FnMut(Event)>::new(move |ev: Event| f(&ev));
461 let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts);
462 cb.forget();
463}
464
465// ---------------------------------------------------------------------------
466// Visibility and placement
467// ---------------------------------------------------------------------------
468
469fn bool_str(b: bool) -> &'static str {
470 if b { "true" } else { "false" }
471}
472
473fn set_flag(el: &Element, name: &str, on: bool) {
474 if on {
475 let _ = el.set_attribute(name, "");
476 } else {
477 let _ = el.remove_attribute(name);
478 }
479}
480
481fn bubble_visible(e: &Editor, s: &St) -> bool {
482 let Selection::Text { anchor, head } = &e.sel else { return false };
483 anchor != head && e.view.composing.is_none() && !s.bubble_dismissed && s.link.is_none()
484}
485
486/// Shows and places every floating surface from the current state.
487fn render(e: &Editor, s: &St, ui: &Ui) {
488 let show = bubble_visible(e, s);
489 ui.bubble.set_hidden(!show);
490 if show {
491 let cur = e.cx();
492 for (btn, item) in ui.bubble_btns.iter().zip(&ui.bubble_items) {
493 let on = (item.active)(&cur);
494 let _ = btn.set_attribute("data-active", bool_str(on));
495 let _ = btn.set_attribute("aria-pressed", bool_str(on));
496 let enabled = e.can(|cx| (item.run)(cx, false));
497 set_flag(btn, "disabled", !enabled);
498 }
499 if let Some((from, to)) = pos::text_range(&e.m, &e.sel)
500 && let Some(b) = range_box(e, from, to)
501 {
502 place_floating(&ui.bubble, b, true);
503 }
504 }
505 if let Some(l) = &s.link
506 && let Some(b) = range_box(e, l.from, l.to)
507 {
508 place_floating(&ui.link_pop, b, true);
509 }
510 if let Some(sl) = &s.slash
511 && let Some(caret) = e.sel.cursor()
512 && let Some(b) = range_box(e, sl.from, caret)
513 {
514 place_floating(&ui.slash_menu, b, false);
515 }
516}
517
518/// Re-places the floating UI on scroll and resize.
519fn refresh(ui: &Ui) {
520 if let Ok(e) = ui.ed.try_borrow() {
521 render(&e, &ui.st.borrow(), ui);
522 }
523}
524
525// ---------------------------------------------------------------------------
526// Bubble menu
527// ---------------------------------------------------------------------------
528
529fn bubble_click(ui: &Rc<Ui>, is_link: bool, run: Command) {
530 if is_link {
531 let can = match ui.ed.try_borrow() {
532 Ok(e) => e.can(|cx| c::can_link(cx)),
533 Err(_) => return,
534 };
535 if can {
536 request_link(&ui.root);
537 }
538 return;
539 }
540 {
541 let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
542 e.run(|cx| run(cx, true));
543 }
544 let _ = ui.root.focus();
545}
546
547// ---------------------------------------------------------------------------
548// Link popover
549// ---------------------------------------------------------------------------
550
551/// Removes the popover state and hides it. Returns the state that was open.
552fn take_link(ui: &Ui) -> Option<LinkState> {
553 let taken = ui.st.borrow_mut().link.take();
554 if taken.is_some() {
555 ui.link_pop.set_hidden(true);
556 }
557 taken
558}
559
560fn close_link(ui: &Ui) -> bool {
561 take_link(ui).is_some()
562}
563
564/// Shows the popover for `[from, to)`. Callers must not hold an editor borrow that a
565/// focus change could re-enter; this only reads the editor.
566fn show_link(ui: &Ui, e: &Editor, from: Pos, to: Pos, edit: bool) {
567 {
568 let mut s = ui.st.borrow_mut();
569 s.slash = None;
570 }
571 hide_slash(ui);
572 let href = href_in_range(e, from, to);
573 ui.st.borrow_mut().link = Some(LinkState { from: from.clone(), to: to.clone(), href: href.clone() });
574
575 ui.link_pop.set_hidden(false);
576 ui.edit_panel.set_hidden(!edit);
577 ui.view_panel.set_hidden(edit);
578 ui.link_error.set_hidden(true);
579 let _ = ui.link_input.remove_attribute("aria-invalid");
580 let text = href.clone().unwrap_or_default();
581 ui.link_input.set_value(&text);
582 ui.link_href.set_text_content(Some(&text));
583 let needs_link = ui.strings.get("linkNeedsLink");
584 for btn in [&ui.edit_remove, &ui.edit_open, &ui.view_remove, &ui.view_open] {
585 let none = href.is_none();
586 set_flag(btn, "disabled", none);
587 let _ = btn.set_attribute("title", if none { needs_link.as_str() } else { "" });
588 }
589
590 render(e, &ui.st.borrow(), ui);
591 if edit {
592 let _ = ui.link_input.focus();
593 ui.link_input.select();
594 } else {
595 let _ = ui.view_edit.focus();
596 }
597}
598
599/// Mod-K and the toolbar: edit the selection's link, or the link the caret is in.
600fn open_for_selection(ui: &Rc<Ui>) {
601 let Ok(e) = ui.ed.try_borrow() else { return };
602 let range = match &e.sel {
603 Selection::Text { anchor, head } if anchor != head => Some(((*anchor).min(*head), (*anchor).max(*head))),
604 Selection::Text { head, .. } => c::link_range_at(&e.m, *head).map(|(a, b, _)| (a, b)),
605 _ => None,
606 };
607 if let Some((from, to)) = range {
608 show_link(ui, &e, from, to, true);
609 }
610}
611
612fn submit_link(ui: &Rc<Ui>) {
613 let range = ui.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
614 let Some((from, to)) = range else { return };
615 let Some(href) = normalize_href(&ui.link_input.value()) else {
616 ui.link_error.set_text_content(Some(&ui.strings.get("linkInvalid")));
617 ui.link_error.set_hidden(false);
618 let _ = ui.link_input.set_attribute("aria-invalid", "true");
619 let _ = ui.link_input.focus();
620 return;
621 };
622 close_link(ui);
623 {
624 let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
625 e.run(move |cx| {
626 c::set_link(cx, from, to, Some(&href));
627 true
628 });
629 }
630 let _ = ui.root.focus();
631}
632
633fn remove_link(ui: &Rc<Ui>) {
634 let Some(link) = take_link(ui) else { return };
635 {
636 let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
637 e.run(move |cx| {
638 c::set_link(cx, link.from, link.to, None);
639 true
640 });
641 }
642 let _ = ui.root.focus();
643}
644
645fn open_href(ui: &Ui) {
646 let href = ui.st.borrow().link.as_ref().and_then(|l| l.href.clone());
647 let Some(href) = href else { return };
648 let Some(win) = web_sys::window() else { return };
649 // Note links open in this tab; external links keep opening in a new one.
650 if is_note_href(&href) {
651 let _ = win.location().assign(&href);
652 } else {
653 let _ = win.open_with_url_and_target_and_features(&href, "_blank", "noopener,noreferrer");
654 }
655}
656
657/// Escape closes; Up and Down move between the enabled items in view mode.
658fn link_keydown(ui: &Rc<Ui>, ev: &Event) {
659 let Some(k) = ev.dyn_ref::<KeyboardEvent>() else { return };
660 let key = k.key();
661 if key == "Escape" {
662 ev.prevent_default();
663 ev.stop_propagation();
664 if close_link(ui) {
665 let _ = ui.root.focus();
666 }
667 return;
668 }
669 if (key == "ArrowDown" || key == "ArrowUp") && !ui.view_panel.hidden() {
670 let items: Vec<&HtmlElement> = [&ui.view_edit, &ui.view_remove, &ui.view_open]
671 .into_iter()
672 .filter(|b| !b.has_attribute("disabled"))
673 .collect();
674 if items.is_empty() {
675 return;
676 }
677 let active = ui.document.active_element();
678 let index = items.iter().position(|b| {
679 let el: &Element = b.as_ref();
680 active.as_ref() == Some(el)
681 });
682 let step: i64 = if key == "ArrowDown" { 1 } else { -1 };
683 let current = index.map_or(-1, |i| i as i64);
684 let next = (current + step).rem_euclid(items.len() as i64) as usize;
685 ev.prevent_default();
686 let _ = items[next].focus();
687 }
688}
689
690/// Port of ProseMirror's `handleClick`: a click on a link opens the view-mode popover.
691fn root_click(ui: &Rc<Ui>, ev: &Event) {
692 let Some(target) = ev.target().and_then(|t| t.dyn_into::<Element>().ok()) else { return };
693 let Ok(Some(anchor)) = target.closest("a") else { return };
694 // Ctrl/Cmd+click navigates to a note, so no popover opens for it.
695 if let Some(m) = ev.dyn_ref::<MouseEvent>()
696 && (m.ctrl_key() || m.meta_key())
697 && anchor.get_attribute("href").is_some_and(|h| is_note_href(&h))
698 {
699 return;
700 }
701 let Ok(e) = ui.ed.try_borrow() else { return };
702 let Some(node) = anchor.first_child() else { return };
703 let Some(p) = e.view.dom_to_pos(&e.m, &node, 0) else { return };
704 let Some((a, b, _)) = c::link_range_at(&e.m, p) else { return };
705 show_link(ui, &e, a, b, false);
706}
707
708/// The href of the first link mark in `[from, to)`, across the textblocks in between.
709fn href_in_range(e: &Editor, from: Pos, to: Pos) -> Option<String> {
710 if from > to {
711 return None;
712 }
713 for d in e.m.slice(from, to) {
714 if let TextDelta::Insert { attributes, .. } = d
715 && let Some(link) = Marks::from_attrs(attributes.as_ref()).link
716 {
717 return Some(link.href);
718 }
719 }
720 None
721}
722
723/// Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes.
724pub fn normalize_href(raw: &str) -> Option<String> {
725 let href = raw.trim();
726 if href.is_empty() {
727 return None;
728 }
729 // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too.
730 let squashed: String = href.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect::<String>().to_lowercase();
731 if ["javascript:", "data:", "vbscript:"].iter().any(|p| squashed.starts_with(p)) {
732 return None;
733 }
734 if has_scheme(href) || href.starts_with('/') || href.starts_with('#') {
735 return Some(href.to_owned());
736 }
737 Some(format!("https://{href}"))
738}
739
740/// `/^[a-z][a-z\d+.-]*:/i`
741fn has_scheme(s: &str) -> bool {
742 let mut chars = s.chars();
743 match chars.next() {
744 Some(c) if c.is_ascii_alphabetic() => {}
745 _ => return false,
746 }
747 for c in chars {
748 if c == ':' {
749 return true;
750 }
751 if !(c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) {
752 return false;
753 }
754 }
755 false
756}
757
758/// Notes are linked as `/notes/...`; those open in the same tab.
759fn is_note_href(href: &str) -> bool {
760 href.starts_with("/notes/")
761}
762
763// ---------------------------------------------------------------------------
764// Slash menu
765// ---------------------------------------------------------------------------
766
767/// The "/query" before the caret, when the caret is in a textblock outside code.
768/// The "/" must start the block or follow whitespace.
769fn slash_context(e: &Editor) -> Option<(Pos, String)> {
770 let Selection::Text { anchor, head } = &e.sel else { return None };
771 if anchor != head {
772 return None;
773 }
774 let head = *head;
775 let block = e.m.at(head);
776 if !block.kind().is_text() || block.kind() == note_model::flat::Kind::Code {
777 return None;
778 }
779 let from = head.saturating_sub(256).max(block.start);
780 let before = e.m.plain(from, head);
781 let chars: Vec<char> = before.chars().collect();
782 let mut i = chars.len();
783 while i > 0 && !chars[i - 1].is_whitespace() && chars[i - 1] != '/' {
784 i -= 1;
785 }
786 if i == 0 || chars[i - 1] != '/' {
787 return None;
788 }
789 let slash = i - 1;
790 if (slash > 0 || from > block.start) && !chars.get(slash.wrapping_sub(1)).is_some_and(|c| c.is_whitespace()) {
791 return None;
792 }
793 let query: String = chars[i..].iter().collect();
794 let off: usize = from + chars[..slash].iter().map(|c| c.len_utf16()).sum::<usize>();
795 Some((off, query))
796}
797
798fn filter_items(query: &str, items: &[SlashItem]) -> Vec<usize> {
799 let q = query.to_lowercase();
800 (0..items.len())
801 .filter(|&i| {
802 let it = &items[i];
803 q.is_empty() || it.label.to_lowercase().contains(&q) || it.keywords.split(' ').any(|w| w.starts_with(&q))
804 })
805 .collect()
806}
807
808/// Opens, filters or closes the slash menu from the current selection.
809fn update_slash(e: &Editor, s: &mut St, ui: &Rc<Ui>) {
810 match slash_context(e) {
811 None => {
812 s.slash_dismissed = None;
813 s.slash = None;
814 }
815 Some((from, query)) => {
816 if s.slash_dismissed.as_ref() == Some(&from) || s.link.is_some() {
817 s.slash = None;
818 } else {
819 let index = match &s.slash {
820 Some(sl) if sl.from == from && sl.query == query => sl.index,
821 _ => 0,
822 };
823 s.slash = Some(SlashState { from, query, index, filtered: Vec::new() });
824 }
825 }
826 }
827 match s.slash.as_mut() {
828 Some(sl) => {
829 sl.filtered = filter_items(&sl.query, &ui.slash_items);
830 if sl.index >= sl.filtered.len() {
831 sl.index = 0;
832 }
833 draw_slash(sl, ui);
834 ui.slash_menu.set_hidden(false);
835 }
836 None => hide_slash(ui),
837 }
838}
839
840fn hide_slash(ui: &Ui) {
841 ui.slash_menu.set_hidden(true);
842 let _ = ui.root.remove_attribute("aria-activedescendant");
843}
844
845/// Rebuilds the list for the current filter and highlights the active item.
846fn draw_slash(sl: &SlashState, ui: &Rc<Ui>) {
847 ui.slash_list.set_text_content(Some(""));
848 if sl.filtered.is_empty() {
849 ui.slash_list.append_child(&h(&ui.document, "div", &[("class", "slash-empty"), ("role", "presentation")], Some(&ui.strings.get("noMatches")))).ok();
850 let _ = ui.root.remove_attribute("aria-activedescendant");
851 return;
852 }
853 let mut active: Option<HtmlElement> = None;
854 for (pos, &gi) in sl.filtered.iter().enumerate() {
855 let item = &ui.slash_items[gi];
856 let selected = pos == sl.index;
857 let id = format!("slash-opt-{}", item.id);
858 let index = gi.to_string();
859 let el = h(
860 &ui.document,
861 "div",
862 &[
863 ("class", "slash-item"),
864 ("role", "option"),
865 ("id", id.as_str()),
866 ("aria-selected", bool_str(selected)),
867 ("data-index", index.as_str()),
868 ],
869 None,
870 );
871 el.append_child(&h(&ui.document, "span", &[("class", "slash-label")], Some(&item.label))).ok();
872 el.append_child(&keycaps(&ui.document, &item.keys)).ok();
873 ui.slash_list.append_child(&el).ok();
874 if selected {
875 let _ = ui.root.set_attribute("aria-activedescendant", &id);
876 active = Some(el);
877 }
878 }
879 if let Some(el) = active {
880 let opts = ScrollIntoViewOptions::new();
881 opts.set_block(ScrollLogicalPosition::Nearest);
882 el.scroll_into_view_with_scroll_into_view_options(&opts);
883 }
884}
885
886fn slash_click(ui: &Rc<Ui>, gi: usize) {
887 if let Ok(mut e) = ui.ed.try_borrow_mut() {
888 apply_slash(&mut e, ui, gi);
889 }
890 let _ = ui.root.focus();
891}
892
893/// Removes the typed "/query" and runs the chosen block command, as one edit.
894fn apply_slash(e: &mut Editor, ui: &Rc<Ui>, gi: usize) {
895 let taken = ui.st.borrow_mut().slash.take();
896 hide_slash(ui);
897 let Some(sl) = taken else { return };
898 let Some(to) = e.sel.cursor() else { return };
899 if e.m.at(to).index != e.m.at(sl.from).index || to < sl.from {
900 return;
901 }
902 let from = sl.from;
903 let run = ui.slash_items[gi].run;
904 e.run(move |cx| {
905 cx.m.delete(from, to);
906 cx.sel = Selection::caret(from);
907 // The deletion is already applied, so the edit commits even if the command declines.
908 run(cx, true);
909 true
910 });
911}
912
913/// Keys while a menu or popover is open. Returns true when the key was consumed.
914fn key_down(ui: &Rc<Ui>, k: &KeyboardEvent) -> bool {
915 if k.is_composing() {
916 return false;
917 }
918 let key = k.key();
919 let (open, n) = {
920 let s = ui.st.borrow();
921 (s.slash.is_some(), s.slash.as_ref().map_or(0, |sl| sl.filtered.len()))
922 };
923 if open {
924 match key.as_str() {
925 "ArrowDown" | "ArrowUp" if n > 0 => {
926 let mut s = ui.st.borrow_mut();
927 if let Some(sl) = s.slash.as_mut() {
928 sl.index = if key == "ArrowDown" { (sl.index + 1) % n } else { (sl.index + n - 1) % n };
929 draw_slash(sl, ui);
930 }
931 return true;
932 }
933 "Enter" if n > 0 => {
934 let gi = {
935 let s = ui.st.borrow();
936 s.slash.as_ref().and_then(|sl| sl.filtered.get(sl.index).copied())
937 };
938 let Some(gi) = gi else { return false };
939 let Ok(mut e) = ui.ed.try_borrow_mut() else { return false };
940 apply_slash(&mut e, ui, gi);
941 drop(e);
942 let _ = ui.root.focus();
943 return true;
944 }
945 "Escape" => {
946 let taken = ui.st.borrow_mut().slash.take();
947 if let Some(sl) = taken {
948 ui.st.borrow_mut().slash_dismissed = Some(sl.from);
949 }
950 hide_slash(ui);
951 return true;
952 }
953 _ => {}
954 }
955 }
956 if key == "Escape" {
957 let Ok(e) = ui.ed.try_borrow() else { return false };
958 if !bubble_visible(&e, &ui.st.borrow()) {
959 return false;
960 }
961 ui.st.borrow_mut().bubble_dismissed = true;
962 render(&e, &ui.st.borrow(), ui);
963 return true;
964 }
965 false
966}