//! Floating editor UI (port of `web/src/floating.ts`): the selection bubble menu, the
//! link popover (edit mode for Mod-K and the buttons, view mode for a clicked link) and
//! the slash "/" block menu. Everything is plain DOM on
, positioned from the
//! caret boxes.
//!
//! State lives in `Ui` (DOM handles, item tables, `St`). Editor borrows use
//! `try_borrow*` and are released before anything that can re-enter the editor
//! (`run`, `focus`, the `editor:link` dispatch), so those calls go through `spawn_local`
//! or happen after the borrow is dropped.
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::spawn_local;
use web_sys::{
AbortSignal, AddEventListenerOptions, Document, Element, Event, EventTarget, HtmlElement, HtmlInputElement, KeyboardEvent,
MouseEvent, Node as DomNode, ScrollIntoViewOptions, ScrollLogicalPosition,
};
use super::{Ctx, Ed, LINK_EVENT, h, keycaps, mod_keys, place_floating, range_box, request_link, tooltip};
use loro::TextDelta;
use crate::core::commands::{self as c, Command, Cx};
use crate::core::doc::Kind;
use crate::core::marks::{MarkType, Marks};
use crate::core::pos::{self, Pos, Selection};
use crate::editor::Editor;
use crate::strings::Strings;
struct Bubble {
id: &'static str,
label: String,
glyph: &'static str,
keys: Vec<&'static str>,
run: Command,
active: fn(&Cx) -> bool,
}
struct SlashItem {
id: &'static str,
label: String,
/// English words the filter also matches, so "h2" or "list" work in either language.
keywords: &'static str,
keys: Vec<&'static str>,
run: Command,
}
/// Mutable UI state. Never held across a call that can run an editor command.
#[derive(Default)]
struct St {
bubble_dismissed: bool,
last_sel: Option,
link: Option,
slash: Option,
slash_dismissed: Option,
}
struct LinkState {
from: Pos,
to: Pos,
/// Existing href at the range, if any.
href: Option,
}
struct SlashState {
/// Position of the "/" that opened the menu.
from: Pos,
query: String,
index: usize,
/// Indexes into `Ui::slash_items` that match the query.
filtered: Vec,
}
struct Ui {
ed: Ed,
st: RefCell,
document: Document,
root: HtmlElement,
strings: Rc,
signal: AbortSignal,
bubble: HtmlElement,
bubble_btns: Vec,
bubble_items: Vec,
link_pop: HtmlElement,
edit_panel: HtmlElement,
link_input: HtmlInputElement,
link_error: HtmlElement,
edit_remove: HtmlElement,
edit_open: HtmlElement,
view_panel: HtmlElement,
link_href: HtmlElement,
view_edit: HtmlElement,
view_remove: HtmlElement,
view_open: HtmlElement,
slash_menu: HtmlElement,
slash_list: HtmlElement,
slash_items: Vec,
}
pub fn install(ed: &Ed, cx: &Ctx) {
let Some(signal) = js_sys::Reflect::get(&cx.opts, &"signal".into()).ok().and_then(|s| s.dyn_into::().ok()) else {
return;
};
let document = cx.document.clone();
let strings = cx.strings.clone();
let root = ed.borrow().view.root.clone();
let s = |k: &str| strings.get(k);
let (m, sh, alt) = mod_keys();
let bubble_items = vec![
Bubble {
id: "bold",
label: s("bold"),
glyph: "B",
keys: vec![m, "B"],
run: |cx, a| c::toggle_mark(cx, MarkType::Strong, a),
active: |cx| c::mark_active_within(cx, MarkType::Strong, c::MARK_STATE_UNITS),
},
Bubble {
id: "italic",
label: s("italic"),
glyph: "I",
keys: vec![m, "I"],
run: |cx, a| c::toggle_mark(cx, MarkType::Em, a),
active: |cx| c::mark_active_within(cx, MarkType::Em, c::MARK_STATE_UNITS),
},
Bubble {
id: "code",
label: s("inlineCode"),
glyph: ">",
keys: vec![m, "E"],
run: |cx, a| c::toggle_mark(cx, MarkType::Code, a),
active: |cx| c::mark_active_within(cx, MarkType::Code, c::MARK_STATE_UNITS),
},
Bubble {
id: "link",
label: s("link"),
glyph: "Link",
keys: vec![m, "K"],
// Opens the popover (see `bubble_click`); the command only reports availability.
run: |cx, _| c::can_link(cx),
active: |cx| c::mark_active_within(cx, MarkType::Link, c::MARK_STATE_UNITS),
},
Bubble {
id: "h1",
label: s("heading1"),
glyph: "H1",
keys: vec![m, alt, "1"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
active: |cx| c::is_block_active(cx, Kind::Heading(1)),
},
Bubble {
id: "h2",
label: s("heading2"),
glyph: "H2",
keys: vec![m, alt, "2"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
active: |cx| c::is_block_active(cx, Kind::Heading(2)),
},
Bubble {
id: "h3",
label: s("heading3"),
glyph: "H3",
keys: vec![m, alt, "3"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
active: |cx| c::is_block_active(cx, Kind::Heading(3)),
},
];
let slash_items = vec![
SlashItem {
id: "text",
label: s("paragraph"),
keywords: "text paragraph p",
keys: vec![m, alt, "0"],
run: |cx, a| c::set_block_type(cx, Kind::Paragraph, a),
},
SlashItem {
id: "h1",
label: s("heading1"),
keywords: "heading title h1",
keys: vec![m, alt, "1"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(1), a),
},
SlashItem {
id: "h2",
label: s("heading2"),
keywords: "heading subtitle h2",
keys: vec![m, alt, "2"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(2), a),
},
SlashItem {
id: "h3",
label: s("heading3"),
keywords: "heading h3",
keys: vec![m, alt, "3"],
run: |cx, a| c::toggle_block(cx, Kind::Heading(3), a),
},
SlashItem {
id: "bullets",
label: s("bulletList"),
keywords: "list ul bullet unordered",
keys: vec![m, sh, "8"],
run: |cx, a| c::toggle_list(cx, Kind::BulletList, a),
},
SlashItem {
id: "ordered",
label: s("numberedList"),
keywords: "list ol number ordered",
keys: vec![m, sh, "9"],
run: |cx, a| c::toggle_list(cx, Kind::OrderedList, a),
},
SlashItem { id: "quote", label: s("quote"), keywords: "blockquote quote", keys: vec![">"], run: |cx, a| c::toggle_quote(cx, a) },
SlashItem {
id: "codeblock",
label: s("codeBlock"),
keywords: "code pre fence",
keys: vec!["```"],
run: |cx, a| c::toggle_block(cx, Kind::CodeBlock, a),
},
SlashItem { id: "divider", label: s("divider"), keywords: "hr rule line divider", keys: vec!["---"], run: |cx, a| c::insert_rule(cx, a) },
];
// Bubble menu.
let bubble_label = s("bubbleLabel");
let bubble = h(&document, "div", &[("class", "bubble"), ("role", "toolbar"), ("aria-label", bubble_label.as_str())], None);
bubble.set_hidden(true);
let mut bubble_btns = Vec::new();
for item in &bubble_items {
let btn = h(
&document,
"button",
&[("type", "button"), ("class", "bubble-btn"), ("aria-label", item.label.as_str()), ("data-command", item.id)],
None,
);
btn.append_child(&h(&document, "span", &[("class", "bubble-glyph"), ("aria-hidden", "true")], Some(item.glyph)))
.ok();
btn.append_child(&tooltip(&document, &item.label, &item.keys, None)).ok();
bubble.append_child(&btn).ok();
bubble_btns.push(btn);
}
// Link popover: the edit and view panels share one element.
let link_dialog = s("linkDialog");
let link_pop = h(&document, "div", &[("class", "popover link-popover"), ("role", "dialog"), ("aria-label", link_dialog.as_str())], None);
link_pop.set_hidden(true);
let edit_panel = h(&document, "form", &[("class", "link-edit"), ("novalidate", "")], None);
let link_url = s("linkUrl");
let link_input: HtmlInputElement = h(
&document,
"input",
&[
("type", "text"),
("class", "link-input"),
("inputmode", "url"),
("autocomplete", "off"),
("autocapitalize", "off"),
("spellcheck", "false"),
("placeholder", "https://"),
("aria-label", link_url.as_str()),
("aria-describedby", "link-error"),
],
None,
)
.unchecked_into();
let link_error = h(&document, "p", &[("class", "link-error"), ("id", "link-error"), ("role", "alert")], None);
link_error.set_hidden(true);
let apply_btn = h(&document, "button", &[("type", "submit"), ("class", "btn btn-primary")], Some(&s("apply")));
apply_btn.append_child(&keycaps(&document, &["↵"])).ok();
let edit_remove = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("remove")));
let edit_open = h(&document, "button", &[("type", "button"), ("class", "btn")], Some(&s("open")));
let row = h(&document, "div", &[("class", "link-row")], None);
row.append_child(&link_input).ok();
row.append_child(&apply_btn).ok();
let edit_actions = h(&document, "div", &[("class", "link-actions")], None);
edit_actions.append_child(&edit_remove).ok();
edit_actions.append_child(&edit_open).ok();
edit_panel.append_child(&row).ok();
edit_panel.append_child(&link_error).ok();
edit_panel.append_child(&edit_actions).ok();
// View mode is a small menu: the href as its label, then Edit / Remove / Open.
let link_menu = s("linkMenu");
let view_panel = h(&document, "div", &[("class", "link-view"), ("role", "menu"), ("aria-label", link_menu.as_str())], None);
let link_href = h(&document, "span", &[("class", "link-href")], None);
let view_edit = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("edit")));
let view_remove = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("remove")));
let view_open = h(&document, "button", &[("type", "button"), ("class", "btn"), ("role", "menuitem")], Some(&s("open")));
let view_actions = h(&document, "div", &[("class", "link-actions"), ("role", "none")], None);
view_actions.append_child(&view_edit).ok();
view_actions.append_child(&view_remove).ok();
view_actions.append_child(&view_open).ok();
view_panel.append_child(&link_href).ok();
view_panel.append_child(&view_actions).ok();
link_pop.append_child(&edit_panel).ok();
link_pop.append_child(&view_panel).ok();
// Slash menu.
let slash_menu = h(&document, "div", &[("class", "popover slash-menu"), ("role", "presentation")], None);
slash_menu.set_hidden(true);
let block_menu = s("blockMenu");
let slash_list = h(&document, "div", &[("class", "slash-list"), ("role", "listbox"), ("aria-label", block_menu.as_str())], None);
let footer = h(&document, "div", &[("class", "slash-footer"), ("aria-hidden", "true")], None);
footer.append_child(&keycaps(&document, &["↑", "↓"])).ok();
footer.append_child(&document.create_text_node(&format!(" {} ", s("navigate")))).ok();
footer.append_child(&keycaps(&document, &["↵"])).ok();
footer.append_child(&document.create_text_node(&format!(" {} ", s("insert")))).ok();
footer.append_child(&keycaps(&document, &["Esc"])).ok();
footer.append_child(&document.create_text_node(&format!(" {}", s("close")))).ok();
slash_menu.append_child(&slash_list).ok();
slash_menu.append_child(&footer).ok();
if let Some(body) = document.body() {
body.append_child(&bubble).ok();
body.append_child(&link_pop).ok();
body.append_child(&slash_menu).ok();
}
let ui = Rc::new(Ui {
ed: ed.clone(),
st: RefCell::default(),
document,
root,
strings,
signal,
bubble,
bubble_btns,
bubble_items,
link_pop,
edit_panel,
link_input,
link_error,
edit_remove,
edit_open,
view_panel,
link_href,
view_edit,
view_remove,
view_open,
slash_menu,
slash_list,
slash_items,
});
attach(&ui);
// Keeps the popovers in sync after every doc or selection change.
let l = ui.clone();
ed.borrow_mut().listeners.push(Box::new(move |e: &Editor, changed: bool| {
let mut s = l.st.borrow_mut();
if s.last_sel.as_ref() != Some(&e.sel) {
s.bubble_dismissed = false;
s.last_sel = Some(e.sel.clone());
}
// A popover refers to a fixed range; a doc change invalidates it.
if changed && s.link.is_some() {
s.link = None;
l.link_pop.set_hidden(true);
}
update_slash(e, &mut s, &l);
render(e, &s, &l);
}));
}
/// Registers the DOM handlers. Every listener uses the editor's abort signal, so it is
/// removed on `note:detach`.
fn attach(ui: &Rc) {
let sig = &ui.signal;
for (i, btn) in ui.bubble_btns.iter().enumerate() {
let (u, is_link, run) = (ui.clone(), ui.bubble_items[i].id == "link", ui.bubble_items[i].run);
on(btn.as_ref(), "click", sig, false, move |_| bubble_click(&u, is_link, run));
}
// Keep the text selection while pressing bubble and slash buttons.
on(ui.bubble.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
on(ui.slash_menu.as_ref(), "mousedown", sig, false, |ev| ev.prevent_default());
let u = ui.clone();
on(ui.edit_panel.as_ref(), "submit", sig, false, move |ev| {
ev.prevent_default();
submit_link(&u);
});
// One delegated listener for the slash items, which are rebuilt on every filter change.
let u = ui.clone();
on(ui.slash_list.as_ref(), "click", sig, false, move |ev| {
let item = ev.target().and_then(|t| t.dyn_into::().ok()).and_then(|t| t.closest(".slash-item").ok().flatten());
let gi = item.and_then(|el| el.get_attribute("data-index")).and_then(|v| v.parse::().ok());
if let Some(gi) = gi {
slash_click(&u, gi);
}
});
let u = ui.clone();
on(ui.link_pop.as_ref(), "keydown", sig, false, move |ev| link_keydown(&u, ev));
for btn in [&ui.edit_remove, &ui.view_remove] {
let u = ui.clone();
on(btn.as_ref(), "click", sig, false, move |_| remove_link(&u));
}
for btn in [&ui.edit_open, &ui.view_open] {
let u = ui.clone();
on(btn.as_ref(), "click", sig, false, move |_| open_href(&u));
}
let u = ui.clone();
on(ui.view_edit.as_ref(), "click", sig, false, move |_| {
let range = u.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
if let (Some((from, to)), Ok(e)) = (range, u.ed.try_borrow()) {
show_link(&u, &e, from, to, true);
}
});
// Capture phase so the keys are seen before the editor's own keydown listener.
let u = ui.clone();
on(ui.root.as_ref(), "keydown", sig, true, move |ev| {
let Some(k) = ev.dyn_ref::() else { return };
if key_down(&u, k) {
ev.prevent_default();
ev.stop_immediate_propagation();
}
});
let u = ui.clone();
on(ui.root.as_ref(), "click", sig, false, move |ev| root_click(&u, ev));
// Mod-K and the toolbar dispatch this synchronously from inside an editor borrow, so
// the popover opens on the next microtask instead.
let u = ui.clone();
on(ui.root.as_ref(), LINK_EVENT, sig, false, move |_| {
let u = u.clone();
spawn_local(async move { open_for_selection(&u) });
});
// Clicking outside the link popover closes it (without moving focus).
let u = ui.clone();
on(ui.document.as_ref(), "mousedown", sig, true, move |ev| {
let target = ev.target().and_then(|t| t.dyn_into::().ok());
let inside = target.as_ref().is_some_and(|t| u.link_pop.contains(Some(t)));
if !inside {
close_link(&u);
}
});
if let Some(win) = web_sys::window() {
let u = ui.clone();
on(win.as_ref(), "scroll", sig, true, move |_| refresh(&u));
let u = ui.clone();
on(win.as_ref(), "resize", sig, false, move |_| refresh(&u));
let u = ui.clone();
on(win.as_ref(), "note:detach", sig, false, move |_| {
u.bubble.remove();
u.link_pop.remove();
u.slash_menu.remove();
});
}
}
/// Adds a DOM listener that is removed when `signal` aborts.
fn on(target: &EventTarget, name: &str, signal: &AbortSignal, capture: bool, f: impl FnMut(&Event) + 'static) {
let opts = AddEventListenerOptions::new();
opts.set_signal(signal);
opts.set_capture(capture);
let mut f = f;
let cb = Closure::::new(move |ev: Event| f(&ev));
let _ = target.add_event_listener_with_callback_and_add_event_listener_options(name, cb.as_ref().unchecked_ref(), &opts);
cb.forget();
}
// ---------------------------------------------------------------------------
// Visibility and placement
// ---------------------------------------------------------------------------
fn bool_str(b: bool) -> &'static str {
if b { "true" } else { "false" }
}
fn set_flag(el: &Element, name: &str, on: bool) {
if on {
let _ = el.set_attribute(name, "");
} else {
let _ = el.remove_attribute(name);
}
}
fn bubble_visible(e: &Editor, s: &St) -> bool {
let Selection::Text { anchor, head } = &e.sel else { return false };
anchor != head && e.view.composing.is_none() && !s.bubble_dismissed && s.link.is_none()
}
/// Shows and places every floating surface from the current state.
fn render(e: &Editor, s: &St, ui: &Ui) {
let show = bubble_visible(e, s);
ui.bubble.set_hidden(!show);
if show {
let cur = e.cx();
for (btn, item) in ui.bubble_btns.iter().zip(&ui.bubble_items) {
let on = (item.active)(&cur);
let _ = btn.set_attribute("data-active", bool_str(on));
let _ = btn.set_attribute("aria-pressed", bool_str(on));
let enabled = e.can(|cx| (item.run)(cx, false));
set_flag(btn, "disabled", !enabled);
}
if let Some((from, to)) = pos::text_range(&e.m, &e.sel)
&& let Some(b) = range_box(e, from, to)
{
place_floating(&ui.bubble, b, true);
}
}
if let Some(l) = &s.link
&& let Some(b) = range_box(e, l.from, l.to)
{
place_floating(&ui.link_pop, b, true);
}
if let Some(sl) = &s.slash
&& let Some(caret) = e.sel.cursor()
&& let Some(b) = range_box(e, sl.from, caret)
{
place_floating(&ui.slash_menu, b, false);
}
}
/// Re-places the floating UI on scroll and resize.
fn refresh(ui: &Ui) {
if let Ok(e) = ui.ed.try_borrow() {
render(&e, &ui.st.borrow(), ui);
}
}
// ---------------------------------------------------------------------------
// Bubble menu
// ---------------------------------------------------------------------------
fn bubble_click(ui: &Rc, is_link: bool, run: Command) {
if is_link {
let can = match ui.ed.try_borrow() {
Ok(e) => e.can(|cx| c::can_link(cx)),
Err(_) => return,
};
if can {
request_link(&ui.root);
}
return;
}
{
let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
e.run(|cx| run(cx, true));
}
let _ = ui.root.focus();
}
// ---------------------------------------------------------------------------
// Link popover
// ---------------------------------------------------------------------------
/// Removes the popover state and hides it. Returns the state that was open.
fn take_link(ui: &Ui) -> Option {
let taken = ui.st.borrow_mut().link.take();
if taken.is_some() {
ui.link_pop.set_hidden(true);
}
taken
}
fn close_link(ui: &Ui) -> bool {
take_link(ui).is_some()
}
/// Shows the popover for `[from, to)`. Callers must not hold an editor borrow that a
/// focus change could re-enter; this only reads the editor.
fn show_link(ui: &Ui, e: &Editor, from: Pos, to: Pos, edit: bool) {
{
let mut s = ui.st.borrow_mut();
s.slash = None;
}
hide_slash(ui);
let href = href_in_range(e, from, to);
ui.st.borrow_mut().link = Some(LinkState { from: from.clone(), to: to.clone(), href: href.clone() });
ui.link_pop.set_hidden(false);
ui.edit_panel.set_hidden(!edit);
ui.view_panel.set_hidden(edit);
ui.link_error.set_hidden(true);
let _ = ui.link_input.remove_attribute("aria-invalid");
let text = href.clone().unwrap_or_default();
ui.link_input.set_value(&text);
ui.link_href.set_text_content(Some(&text));
let needs_link = ui.strings.get("linkNeedsLink");
for btn in [&ui.edit_remove, &ui.edit_open, &ui.view_remove, &ui.view_open] {
let none = href.is_none();
set_flag(btn, "disabled", none);
let _ = btn.set_attribute("title", if none { needs_link.as_str() } else { "" });
}
render(e, &ui.st.borrow(), ui);
if edit {
let _ = ui.link_input.focus();
ui.link_input.select();
} else {
let _ = ui.view_edit.focus();
}
}
/// Mod-K and the toolbar: edit the selection's link, or the link the caret is in.
fn open_for_selection(ui: &Rc) {
let Ok(e) = ui.ed.try_borrow() else { return };
let range = match &e.sel {
Selection::Text { anchor, head } if anchor != head => Some(((*anchor).min(*head), (*anchor).max(*head))),
Selection::Text { head, .. } => c::link_range_at(&e.m, *head).map(|(a, b, _)| (a, b)),
_ => None,
};
if let Some((from, to)) = range {
show_link(ui, &e, from, to, true);
}
}
fn submit_link(ui: &Rc) {
let range = ui.st.borrow().link.as_ref().map(|l| (l.from.clone(), l.to.clone()));
let Some((from, to)) = range else { return };
let Some(href) = normalize_href(&ui.link_input.value()) else {
ui.link_error.set_text_content(Some(&ui.strings.get("linkInvalid")));
ui.link_error.set_hidden(false);
let _ = ui.link_input.set_attribute("aria-invalid", "true");
let _ = ui.link_input.focus();
return;
};
close_link(ui);
{
let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
e.run(move |cx| {
c::set_link(cx, from, to, Some(&href));
true
});
}
let _ = ui.root.focus();
}
fn remove_link(ui: &Rc) {
let Some(link) = take_link(ui) else { return };
{
let Ok(mut e) = ui.ed.try_borrow_mut() else { return };
e.run(move |cx| {
c::set_link(cx, link.from, link.to, None);
true
});
}
let _ = ui.root.focus();
}
fn open_href(ui: &Ui) {
let href = ui.st.borrow().link.as_ref().and_then(|l| l.href.clone());
let Some(href) = href else { return };
let Some(win) = web_sys::window() else { return };
// Note links open in this tab; external links keep opening in a new one.
if is_note_href(&href) {
let _ = win.location().assign(&href);
} else {
let _ = win.open_with_url_and_target_and_features(&href, "_blank", "noopener,noreferrer");
}
}
/// Escape closes; Up and Down move between the enabled items in view mode.
fn link_keydown(ui: &Rc, ev: &Event) {
let Some(k) = ev.dyn_ref::() else { return };
let key = k.key();
if key == "Escape" {
ev.prevent_default();
ev.stop_propagation();
if close_link(ui) {
let _ = ui.root.focus();
}
return;
}
if (key == "ArrowDown" || key == "ArrowUp") && !ui.view_panel.hidden() {
let items: Vec<&HtmlElement> = [&ui.view_edit, &ui.view_remove, &ui.view_open]
.into_iter()
.filter(|b| !b.has_attribute("disabled"))
.collect();
if items.is_empty() {
return;
}
let active = ui.document.active_element();
let index = items.iter().position(|b| {
let el: &Element = b.as_ref();
active.as_ref() == Some(el)
});
let step: i64 = if key == "ArrowDown" { 1 } else { -1 };
let current = index.map_or(-1, |i| i as i64);
let next = (current + step).rem_euclid(items.len() as i64) as usize;
ev.prevent_default();
let _ = items[next].focus();
}
}
/// Port of ProseMirror's `handleClick`: a click on a link opens the view-mode popover.
fn root_click(ui: &Rc, ev: &Event) {
let Some(target) = ev.target().and_then(|t| t.dyn_into::().ok()) else { return };
let Ok(Some(anchor)) = target.closest("a") else { return };
// Ctrl/Cmd+click navigates to a note, so no popover opens for it.
if let Some(m) = ev.dyn_ref::()
&& (m.ctrl_key() || m.meta_key())
&& anchor.get_attribute("href").is_some_and(|h| is_note_href(&h))
{
return;
}
let Ok(e) = ui.ed.try_borrow() else { return };
let Some(node) = anchor.first_child() else { return };
let Some(p) = e.view.dom_to_pos(&e.m, &node, 0) else { return };
let Some((a, b, _)) = c::link_range_at(&e.m, p) else { return };
show_link(ui, &e, a, b, false);
}
/// The href of the first link mark in `[from, to)`, across the textblocks in between.
fn href_in_range(e: &Editor, from: Pos, to: Pos) -> Option {
if from > to {
return None;
}
for d in e.m.slice(from, to) {
if let TextDelta::Insert { attributes, .. } = d
&& let Some(link) = Marks::from_attrs(attributes.as_ref()).link
{
return Some(link.href);
}
}
None
}
/// Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes.
pub fn normalize_href(raw: &str) -> Option {
let href = raw.trim();
if href.is_empty() {
return None;
}
// Whitespace and control characters are removed before the check, so "java\tscript:" is caught too.
let squashed: String = href.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect::().to_lowercase();
if ["javascript:", "data:", "vbscript:"].iter().any(|p| squashed.starts_with(p)) {
return None;
}
if has_scheme(href) || href.starts_with('/') || href.starts_with('#') {
return Some(href.to_owned());
}
Some(format!("https://{href}"))
}
/// `/^[a-z][a-z\d+.-]*:/i`
fn has_scheme(s: &str) -> bool {
let mut chars = s.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() => {}
_ => return false,
}
for c in chars {
if c == ':' {
return true;
}
if !(c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) {
return false;
}
}
false
}
/// Notes are linked as `/notes/...`; those open in the same tab.
fn is_note_href(href: &str) -> bool {
href.starts_with("/notes/")
}
// ---------------------------------------------------------------------------
// Slash menu
// ---------------------------------------------------------------------------
/// The "/query" before the caret, when the caret is in a textblock outside code.
/// The "/" must start the block or follow whitespace.
fn slash_context(e: &Editor) -> Option<(Pos, String)> {
let Selection::Text { anchor, head } = &e.sel else { return None };
if anchor != head {
return None;
}
let head = *head;
let block = e.m.at(head);
if !block.kind().is_text() || block.kind() == note_model::flat::Kind::Code {
return None;
}
let from = head.saturating_sub(256).max(block.start);
let before = e.m.plain(from, head);
let chars: Vec = before.chars().collect();
let mut i = chars.len();
while i > 0 && !chars[i - 1].is_whitespace() && chars[i - 1] != '/' {
i -= 1;
}
if i == 0 || chars[i - 1] != '/' {
return None;
}
let slash = i - 1;
if (slash > 0 || from > block.start) && !chars.get(slash.wrapping_sub(1)).is_some_and(|c| c.is_whitespace()) {
return None;
}
let query: String = chars[i..].iter().collect();
let off: usize = from + chars[..slash].iter().map(|c| c.len_utf16()).sum::();
Some((off, query))
}
fn filter_items(query: &str, items: &[SlashItem]) -> Vec {
let q = query.to_lowercase();
(0..items.len())
.filter(|&i| {
let it = &items[i];
q.is_empty() || it.label.to_lowercase().contains(&q) || it.keywords.split(' ').any(|w| w.starts_with(&q))
})
.collect()
}
/// Opens, filters or closes the slash menu from the current selection.
fn update_slash(e: &Editor, s: &mut St, ui: &Rc) {
match slash_context(e) {
None => {
s.slash_dismissed = None;
s.slash = None;
}
Some((from, query)) => {
if s.slash_dismissed.as_ref() == Some(&from) || s.link.is_some() {
s.slash = None;
} else {
let index = match &s.slash {
Some(sl) if sl.from == from && sl.query == query => sl.index,
_ => 0,
};
s.slash = Some(SlashState { from, query, index, filtered: Vec::new() });
}
}
}
match s.slash.as_mut() {
Some(sl) => {
sl.filtered = filter_items(&sl.query, &ui.slash_items);
if sl.index >= sl.filtered.len() {
sl.index = 0;
}
draw_slash(sl, ui);
ui.slash_menu.set_hidden(false);
}
None => hide_slash(ui),
}
}
fn hide_slash(ui: &Ui) {
ui.slash_menu.set_hidden(true);
let _ = ui.root.remove_attribute("aria-activedescendant");
}
/// Rebuilds the list for the current filter and highlights the active item.
fn draw_slash(sl: &SlashState, ui: &Rc) {
ui.slash_list.set_text_content(Some(""));
if sl.filtered.is_empty() {
ui.slash_list.append_child(&h(&ui.document, "div", &[("class", "slash-empty"), ("role", "presentation")], Some(&ui.strings.get("noMatches")))).ok();
let _ = ui.root.remove_attribute("aria-activedescendant");
return;
}
let mut active: Option = None;
for (pos, &gi) in sl.filtered.iter().enumerate() {
let item = &ui.slash_items[gi];
let selected = pos == sl.index;
let id = format!("slash-opt-{}", item.id);
let index = gi.to_string();
let el = h(
&ui.document,
"div",
&[
("class", "slash-item"),
("role", "option"),
("id", id.as_str()),
("aria-selected", bool_str(selected)),
("data-index", index.as_str()),
],
None,
);
el.append_child(&h(&ui.document, "span", &[("class", "slash-label")], Some(&item.label))).ok();
el.append_child(&keycaps(&ui.document, &item.keys)).ok();
ui.slash_list.append_child(&el).ok();
if selected {
let _ = ui.root.set_attribute("aria-activedescendant", &id);
active = Some(el);
}
}
if let Some(el) = active {
let opts = ScrollIntoViewOptions::new();
opts.set_block(ScrollLogicalPosition::Nearest);
el.scroll_into_view_with_scroll_into_view_options(&opts);
}
}
fn slash_click(ui: &Rc, gi: usize) {
if let Ok(mut e) = ui.ed.try_borrow_mut() {
apply_slash(&mut e, ui, gi);
}
let _ = ui.root.focus();
}
/// Removes the typed "/query" and runs the chosen block command, as one edit.
fn apply_slash(e: &mut Editor, ui: &Rc, gi: usize) {
let taken = ui.st.borrow_mut().slash.take();
hide_slash(ui);
let Some(sl) = taken else { return };
let Some(to) = e.sel.cursor() else { return };
if e.m.at(to).index != e.m.at(sl.from).index || to < sl.from {
return;
}
let from = sl.from;
let run = ui.slash_items[gi].run;
e.run(move |cx| {
cx.m.delete(from, to);
cx.sel = Selection::caret(from);
// The deletion is already applied, so the edit commits even if the command declines.
run(cx, true);
true
});
}
/// Keys while a menu or popover is open. Returns true when the key was consumed.
fn key_down(ui: &Rc, k: &KeyboardEvent) -> bool {
if k.is_composing() {
return false;
}
let key = k.key();
let (open, n) = {
let s = ui.st.borrow();
(s.slash.is_some(), s.slash.as_ref().map_or(0, |sl| sl.filtered.len()))
};
if open {
match key.as_str() {
"ArrowDown" | "ArrowUp" if n > 0 => {
let mut s = ui.st.borrow_mut();
if let Some(sl) = s.slash.as_mut() {
sl.index = if key == "ArrowDown" { (sl.index + 1) % n } else { (sl.index + n - 1) % n };
draw_slash(sl, ui);
}
return true;
}
"Enter" if n > 0 => {
let gi = {
let s = ui.st.borrow();
s.slash.as_ref().and_then(|sl| sl.filtered.get(sl.index).copied())
};
let Some(gi) = gi else { return false };
let Ok(mut e) = ui.ed.try_borrow_mut() else { return false };
apply_slash(&mut e, ui, gi);
drop(e);
let _ = ui.root.focus();
return true;
}
"Escape" => {
let taken = ui.st.borrow_mut().slash.take();
if let Some(sl) = taken {
ui.st.borrow_mut().slash_dismissed = Some(sl.from);
}
hide_slash(ui);
return true;
}
_ => {}
}
}
if key == "Escape" {
let Ok(e) = ui.ed.try_borrow() else { return false };
if !bubble_visible(&e, &ui.st.borrow()) {
return false;
}
ui.st.borrow_mut().bubble_dismissed = true;
render(&e, &ui.st.borrow(), ui);
return true;
}
false
}