//! Copy, cut, paste and drop. Rich content goes out as `text/html` in the editor's //! own markup and comes back in through a whitelist walk of the parsed HTML. use std::cell::{Cell, RefCell}; use std::rc::{Rc, Weak}; use wasm_bindgen::closure::Closure; use wasm_bindgen::{JsCast, JsValue}; use web_sys::{ClipboardEvent, DataTransfer, DomParser, DragEvent, Document, Element, EventTarget, KeyboardEvent, Node, SupportedType}; use super::{listen, media, Ctx, Ed}; use crate::core::commands; use crate::core::pos::Selection; use crate::editor::Editor; use note_model::marks::Marks; use note_model::write::{Block, Inline}; /// How long after Ctrl/Cmd+Shift+V a paste counts as plain text (as in editing.ts). const PLAIN_PASTE_MS: f64 = 1000.0; pub fn install(ed: &Ed, cx: &Ctx) { let root = ed.borrow().view.root.clone(); let target: &EventTarget = root.as_ref(); // Ctrl/Cmd+Shift+V arms the plain-text flag. Shift+Insert never does (key is "Insert"). let plain_until = Rc::new(Cell::new(0.0_f64)); { let plain_until = plain_until.clone(); listen::(target, "keydown", cx, ed, move |_, ev| { if (ev.meta_key() || ev.ctrl_key()) && ev.shift_key() && ev.key().eq_ignore_ascii_case("v") { plain_until.set(js_sys::Date::now() + PLAIN_PASTE_MS); } }); } listen::(target, "copy", cx, ed, |ed, ev| { ev.prevent_default(); write_selection(ed, ev); }); listen::(target, "cut", cx, ed, |ed, ev| { ev.prevent_default(); write_selection(ed, ev); ed.run(|cx| commands::delete_selection(cx, true)); }); { let plain_until = plain_until.clone(); // Files are uploaded into the editor they were pasted in, held weakly. let host = Rc::downgrade(ed); listen::(target, "paste", cx, ed, move |ed, ev| { ev.prevent_default(); let plain = plain_until.get() >= js_sys::Date::now(); plain_until.set(0.0); let dt = ev.clipboard_data(); paste_from(ed, &host, dt.as_ref(), plain); }); } listen::(target, "dragstart", cx, ed, |_, ev| { // Moving content inside the editor by drag is not supported yet. ev.prevent_default(); }); // Dragging files over the editor must allow the drop, or the browser opens the file instead. { let cb = Closure::::new(|ev: web_sys::Event| { let Some(dt) = ev.dyn_ref::().and_then(|e| e.data_transfer()) else { return }; if dt.types().includes(&JsValue::from_str("Files"), 0) { ev.prevent_default(); } }); let _ = target.add_event_listener_with_callback_and_add_event_listener_options("dragover", cb.as_ref().unchecked_ref(), &cx.opts); cb.forget(); } { let document = cx.document.clone(); let host = Rc::downgrade(ed); listen::(target, "drop", cx, ed, move |ed, ev| { ev.prevent_default(); let at = caret_at(&document, ev.client_x() as f64, ev.client_y() as f64); if let Some(pos) = at.and_then(|(node, off)| ed.view.dom_to_pos(&ed.m, &node, off)) { ed.sel = Selection::caret(pos); ed.stored = None; } let dt = ev.data_transfer(); paste_from(ed, &host, dt.as_ref(), false); }); } } // --------------------------------------------------------------------------- // Copy and cut // --------------------------------------------------------------------------- fn write_selection(ed: &Editor, ev: &ClipboardEvent) { let blocks = commands::selected_blocks(&ed.m, &ed.sel); if blocks.is_empty() { return; } let Some(dt) = ev.clipboard_data() else { return }; let _ = dt.set_data("text/html", &to_html(&blocks)); let _ = dt.set_data("text/plain", &to_text(&blocks)); } fn to_html(blocks: &[Block]) -> String { let mut out = String::new(); for b in blocks { block_html(b, &mut out); } out } fn block_html(b: &Block, out: &mut String) { match b { Block::Paragraph(inl) => { out.push_str("

"); inlines_html(inl, out); out.push_str("

"); } Block::Heading(level, inl) => { let l = (*level).clamp(1, 6); out.push_str(&format!("")); inlines_html(inl, out); out.push_str(&format!("")); } Block::Quote(blocks) => { out.push_str("
"); blocks.iter().for_each(|b| block_html(b, out)); out.push_str("
"); } Block::Code { lang, text } => { out.push_str(""); out.push_str(&escape(text)); out.push_str(""); } Block::Rule => out.push_str("
"), Block::List { ordered, start, items } => { let tag = if *ordered { "ol" } else { "ul" }; out.push('<'); out.push_str(tag); if *ordered && *start != 1 { out.push_str(&format!(" start=\"{start}\"")); } out.push('>'); for item in items { out.push_str("
  • "); item.iter().for_each(|b| block_html(b, out)); out.push_str("
  • "); } out.push_str("'); } } } fn inlines_html(inl: &[Inline], out: &mut String) { for i in inl { match i { Inline::Text(s, m) => { // Outermost first: link, em, strong, code. let mut close = Vec::new(); if let Some((href, title)) = &m.link { out.push_str(&format!("'); close.push(""); } if m.em { out.push_str(""); close.push(""); } if m.strong { out.push_str(""); close.push(""); } if m.code { out.push_str(""); close.push(""); } out.push_str(&escape(s)); for c in close.iter().rev() { out.push_str(c); } } Inline::HardBreak => out.push_str("
    "), Inline::Image { src, alt, title } => { out.push_str(&format!("\"{}\"",'); } } } } fn escape(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), '\'' => out.push_str("'"), _ => out.push(c), } } out } fn to_text(blocks: &[Block]) -> String { let mut parts = Vec::new(); blocks.iter().for_each(|b| text_parts(b, &mut parts)); parts.join("\n\n") } fn text_parts(b: &Block, parts: &mut Vec) { match b { Block::Paragraph(inl) | Block::Heading(_, inl) => { let mut s = String::new(); for i in inl { match i { Inline::Text(t, _) => s.push_str(t), Inline::HardBreak => s.push('\n'), Inline::Image { .. } => {} } } parts.push(s); } Block::Quote(blocks) => blocks.iter().for_each(|b| text_parts(b, parts)), Block::Code { text, .. } => parts.push(text.clone()), Block::Rule => {} Block::List { items, .. } => { for item in items { item.iter().for_each(|b| text_parts(b, parts)); } } } } // --------------------------------------------------------------------------- // Paste and drop // --------------------------------------------------------------------------- /// Inserts what the data transfer holds. `plain` forces text/plain. Files with no text /// beside them are uploaded instead; `host` is the editor they land in. fn paste_from(ed: &mut Editor, host: &Weak>, dt: Option<&DataTransfer>, plain: bool) { let Some(dt) = dt else { return }; let text = dt.get_data("text/plain").unwrap_or_default(); let html = if plain { String::new() } else { dt.get_data("text/html").unwrap_or_default() }; // An image copied from a page brings html that holds no text; rich text still wins. if !plain && text.trim().is_empty() { let files = media::files_of(dt.files()); if !files.is_empty() && to_text(&html_blocks(&html)).trim().is_empty() { if let Some(host) = host.upgrade() { media::insert_files(&host, files); } return; } } let mut blocks = if html.trim().is_empty() { Vec::new() } else { html_blocks(&html) }; if blocks.is_empty() { blocks = plain_blocks(&text); } if blocks.is_empty() { return; } ed.run(|cx| commands::insert_blocks(cx, &blocks)); } fn plain_blocks(text: &str) -> Vec { let text = text.replace("\r\n", "\n").replace('\r', "\n"); let text = text.strip_suffix('\n').unwrap_or(&text); if text.is_empty() { return Vec::new(); } text.split('\n') .map(|line| { let inl = if line.is_empty() { Vec::new() } else { vec![Inline::Text(line.to_owned(), Marks::default())] }; Block::Paragraph(inl) }) .collect() } /// The caret point under the pointer: `caretPositionFromPoint`, else `caretRangeFromPoint`. fn caret_at(document: &Document, x: f64, y: f64) -> Option<(Node, u32)> { let d: &JsValue = document.as_ref(); let args = (JsValue::from_f64(x), JsValue::from_f64(y)); let pos_fn = js_sys::Reflect::get(d, &"caretPositionFromPoint".into()).ok()?; if let Ok(f) = pos_fn.dyn_into::() { let r = f.call2(d, &args.0, &args.1).ok()?; if r.is_null() || r.is_undefined() { return None; } let node = js_sys::Reflect::get(&r, &"offsetNode".into()).ok()?; let off = js_sys::Reflect::get(&r, &"offset".into()).ok()?.as_f64()?; return Some((node.dyn_into::().ok()?, off as u32)); } let range_fn = js_sys::Reflect::get(d, &"caretRangeFromPoint".into()).ok()?; let f = range_fn.dyn_into::().ok()?; let r = f.call2(d, &args.0, &args.1).ok()?; if r.is_null() || r.is_undefined() { return None; } let node = js_sys::Reflect::get(&r, &"startContainer".into()).ok()?; let off = js_sys::Reflect::get(&r, &"startOffset".into()).ok()?.as_f64()?; Some((node.dyn_into::().ok()?, off as u32)) } // --------------------------------------------------------------------------- // HTML import // --------------------------------------------------------------------------- fn html_blocks(html: &str) -> Vec { let Ok(parser) = DomParser::new() else { return Vec::new() }; let Ok(doc) = parser.parse_from_string(html, SupportedType::TextHtml) else { return Vec::new() }; let Some(body) = doc.body() else { return Vec::new() }; let mut acc = Acc::default(); walk_children(&body, &Marks::default(), &mut acc); acc.finish() } /// Blocks under construction, with the inline run that is not yet in a block. #[derive(Default)] struct Acc { blocks: Vec, inl: Vec, } impl Acc { /// Appends collapsed text the way HTML renders it: runs of whitespace become one /// space, and no space leads a line. fn text(&mut self, s: &str, marks: &Marks) { let mut out = String::with_capacity(s.len()); let mut prev_space = false; for c in s.chars() { if matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{0c}') { if !prev_space { out.push(' '); } prev_space = true; } else { out.push(c); prev_space = false; } } let at_line_start = match self.inl.last() { None | Some(Inline::HardBreak) | Some(Inline::Image { .. }) => true, Some(Inline::Text(t, _)) => t.ends_with(' '), }; if at_line_start { out = out.trim_start_matches(' ').to_owned(); } if !out.is_empty() { self.inl.push(Inline::Text(out, marks.clone())); } } /// Turns the pending inline run into a block (a heading when `level` is set). fn flush(&mut self, level: Option) { let mut inl = std::mem::take(&mut self.inl); trim_edges(&mut inl); if inl.is_empty() { return; } self.blocks.push(match level { Some(l) => Block::Heading(l, inl), None => Block::Paragraph(inl), }); } fn finish(mut self) -> Vec { self.flush(None); self.blocks } } /// Drops the space at both ends of an inline run (block edges collapse whitespace). fn trim_edges(inl: &mut Vec) { while let Some(Inline::Text(s, _)) = inl.first_mut() { *s = s.trim_start_matches(' ').to_owned(); if !s.is_empty() { break; } inl.remove(0); } while let Some(Inline::Text(s, _)) = inl.last_mut() { *s = s.trim_end_matches(' ').to_owned(); if !s.is_empty() { break; } inl.pop(); } } fn children(el: &Node) -> Vec { let kids = el.child_nodes(); (0..kids.length()).filter_map(|i| kids.item(i)).collect() } fn walk_children(el: &Node, marks: &Marks, acc: &mut Acc) { for k in children(el) { walk(&k, marks, acc); } } /// Tags that only group content: they end the current block and do not style it. const CONTAINERS: &[&str] = &[ "div", "section", "article", "header", "footer", "main", "nav", "aside", "figure", "figcaption", "address", "body", "html", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "dl", "dt", "dd", "li", "p", ]; fn walk(node: &Node, marks: &Marks, acc: &mut Acc) { match node.node_type() { Node::TEXT_NODE => { if let Some(s) = node.node_value() { acc.text(&s, marks); } return; } Node::ELEMENT_NODE => {} _ => return, } let Some(el) = node.dyn_ref::() else { return }; let tag = el.tag_name().to_ascii_lowercase(); let tag = tag.as_str(); match tag { "script" | "style" | "meta" | "head" | "template" | "noscript" | "title" => {} "br" => acc.inl.push(Inline::HardBreak), "img" => { if let Some(src) = el.get_attribute("src").filter(|s| !s.is_empty()) { acc.inl.push(Inline::Image { src, alt: el.get_attribute("alt").unwrap_or_default(), title: el.get_attribute("title").filter(|t| !t.is_empty()), }); } } "hr" => { acc.flush(None); acc.blocks.push(Block::Rule); } _ if tag == "pre" || is_preformatted(el) => { acc.flush(None); let lang = el .get_attribute("data-language") .or_else(|| el.get_attribute("class").and_then(|c| language_class(&c))) .filter(|l| !l.is_empty()); let mut text = String::new(); pre_text(node, &mut text); let text = text.strip_suffix('\n').unwrap_or(&text).replace('\u{a0}', " "); acc.blocks.push(Block::Code { lang, text }); } "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => { acc.flush(None); let level = tag[1..].parse::().unwrap_or(1); walk_children(node, marks, acc); acc.flush(Some(level)); } "blockquote" => { acc.flush(None); let mut sub = Acc::default(); walk_children(node, marks, &mut sub); let blocks = sub.finish(); if !blocks.is_empty() { acc.blocks.push(Block::Quote(blocks)); } } "ul" | "ol" => { acc.flush(None); let items: Vec> = children(node) .iter() .filter(|c| is_tag(c, "li")) .map(|li| { let mut sub = Acc::default(); walk_children(li, marks, &mut sub); sub.finish() }) .filter(|v| !v.is_empty()) .collect(); if !items.is_empty() { let start = if tag == "ol" { el.get_attribute("start").and_then(|s| s.trim().parse::().ok()).unwrap_or(1) } else { 1 }; acc.blocks.push(Block::List { ordered: tag == "ol", start, items }); } } "a" => { let mut m = marks.clone(); if let Some(href) = el.get_attribute("href").filter(|h| !h.is_empty()) { let title = el.get_attribute("title").filter(|t| !t.is_empty()); m.link = Some((href, title)); } walk_children(node, &m, acc); } "strong" | "b" => { let mut m = marks.clone(); m.strong = true; walk_children(node, &m, acc); } "em" | "i" => { let mut m = marks.clone(); m.em = true; walk_children(node, &m, acc); } "code" => { let mut m = marks.clone(); m.code = true; walk_children(node, &m, acc); } t if CONTAINERS.contains(&t) => { acc.flush(None); walk_children(node, marks, acc); acc.flush(None); } _ => walk_children(node, marks, acc), } } fn is_tag(n: &Node, want: &str) -> bool { n.dyn_ref::().is_some_and(|e| e.tag_name().eq_ignore_ascii_case(want)) } /// Code editors (VS Code, JetBrains) copy a `div` styled `white-space: pre`, one /// child `div` per line. fn is_preformatted(el: &Element) -> bool { el.get_attribute("style").is_some_and(|s| { let s = s.to_ascii_lowercase().replace(' ', ""); s.contains("white-space:pre") }) } /// Text of preformatted content: line `div`s/`p`s and `br`s become newlines. fn pre_text(node: &Node, out: &mut String) { for child in children(node) { match child.node_type() { Node::TEXT_NODE => out.push_str(&child.text_content().unwrap_or_default()), Node::ELEMENT_NODE => match child.node_name().to_ascii_lowercase().as_str() { "br" => out.push('\n'), "div" | "p" => { if !out.is_empty() && !out.ends_with('\n') { out.push('\n'); } pre_text(&child, out); if !out.ends_with('\n') { out.push('\n'); } } _ => pre_text(&child, out), }, _ => {} } } } /// `language-x` among the classes of a `pre`, read before the classes are dropped. fn language_class(class: &str) -> Option { class.split_whitespace().find_map(|c| c.strip_prefix("language-")).map(str::to_owned) }