forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

clipboard.rs571 lines, 19.9 KiBHistoryRawDownload
1//! Copy, cut, paste and drop. Rich content goes out as `text/html` in the editor's
2//! own markup and comes back in through a whitelist walk of the parsed HTML.
3
4use std::cell::{Cell, RefCell};
5use std::rc::{Rc, Weak};
6
7use wasm_bindgen::closure::Closure;
8use wasm_bindgen::{JsCast, JsValue};
9use web_sys::{ClipboardEvent, DataTransfer, DomParser, DragEvent, Document, Element, EventTarget, KeyboardEvent, Node, SupportedType};
10
11use super::{listen, media, Ctx, Ed};
12use crate::core::commands;
13use crate::core::pos::Selection;
14use crate::editor::Editor;
15use note_model::marks::Marks;
16use note_model::write::{Block, Inline};
17
18/// How long after Ctrl/Cmd+Shift+V a paste counts as plain text (as in editing.ts).
19const PLAIN_PASTE_MS: f64 = 1000.0;
20
21pub fn install(ed: &Ed, cx: &Ctx) {
22 let root = ed.borrow().view.root.clone();
23 let target: &EventTarget = root.as_ref();
24
25 // Ctrl/Cmd+Shift+V arms the plain-text flag. Shift+Insert never does (key is "Insert").
26 let plain_until = Rc::new(Cell::new(0.0_f64));
27 {
28 let plain_until = plain_until.clone();
29 listen::<KeyboardEvent>(target, "keydown", cx, ed, move |_, ev| {
30 if (ev.meta_key() || ev.ctrl_key()) && ev.shift_key() && ev.key().eq_ignore_ascii_case("v") {
31 plain_until.set(js_sys::Date::now() + PLAIN_PASTE_MS);
32 }
33 });
34 }
35
36 listen::<ClipboardEvent>(target, "copy", cx, ed, |ed, ev| {
37 ev.prevent_default();
38 write_selection(ed, ev);
39 });
40
41 listen::<ClipboardEvent>(target, "cut", cx, ed, |ed, ev| {
42 ev.prevent_default();
43 write_selection(ed, ev);
44 ed.run(|cx| commands::delete_selection(cx, true));
45 });
46
47 {
48 let plain_until = plain_until.clone();
49 // Files are uploaded into the editor they were pasted in, held weakly.
50 let host = Rc::downgrade(ed);
51 listen::<ClipboardEvent>(target, "paste", cx, ed, move |ed, ev| {
52 ev.prevent_default();
53 let plain = plain_until.get() >= js_sys::Date::now();
54 plain_until.set(0.0);
55 let dt = ev.clipboard_data();
56 paste_from(ed, &host, dt.as_ref(), plain);
57 });
58 }
59
60 listen::<DragEvent>(target, "dragstart", cx, ed, |_, ev| {
61 // Moving content inside the editor by drag is not supported yet.
62 ev.prevent_default();
63 });
64
65 // Dragging files over the editor must allow the drop, or the browser opens the file instead.
66 {
67 let cb = Closure::<dyn FnMut(web_sys::Event)>::new(|ev: web_sys::Event| {
68 let Some(dt) = ev.dyn_ref::<DragEvent>().and_then(|e| e.data_transfer()) else { return };
69 if dt.types().includes(&JsValue::from_str("Files"), 0) {
70 ev.prevent_default();
71 }
72 });
73 let _ = target.add_event_listener_with_callback_and_add_event_listener_options("dragover", cb.as_ref().unchecked_ref(), &cx.opts);
74 cb.forget();
75 }
76
77 {
78 let document = cx.document.clone();
79 let host = Rc::downgrade(ed);
80 listen::<DragEvent>(target, "drop", cx, ed, move |ed, ev| {
81 ev.prevent_default();
82 let at = caret_at(&document, ev.client_x() as f64, ev.client_y() as f64);
83 if let Some(pos) = at.and_then(|(node, off)| ed.view.dom_to_pos(&ed.m, &node, off)) {
84 ed.sel = Selection::caret(pos);
85 ed.stored = None;
86 }
87 let dt = ev.data_transfer();
88 paste_from(ed, &host, dt.as_ref(), false);
89 });
90 }
91}
92
93// ---------------------------------------------------------------------------
94// Copy and cut
95// ---------------------------------------------------------------------------
96
97fn write_selection(ed: &Editor, ev: &ClipboardEvent) {
98 let blocks = commands::selected_blocks(&ed.m, &ed.sel);
99 if blocks.is_empty() {
100 return;
101 }
102 let Some(dt) = ev.clipboard_data() else { return };
103 let _ = dt.set_data("text/html", &to_html(&blocks));
104 let _ = dt.set_data("text/plain", &to_text(&blocks));
105}
106
107fn to_html(blocks: &[Block]) -> String {
108 let mut out = String::new();
109 for b in blocks {
110 block_html(b, &mut out);
111 }
112 out
113}
114
115fn block_html(b: &Block, out: &mut String) {
116 match b {
117 Block::Paragraph(inl) => {
118 out.push_str("<p>");
119 inlines_html(inl, out);
120 out.push_str("</p>");
121 }
122 Block::Heading(level, inl) => {
123 let l = (*level).clamp(1, 6);
124 out.push_str(&format!("<h{l}>"));
125 inlines_html(inl, out);
126 out.push_str(&format!("</h{l}>"));
127 }
128 Block::Quote(blocks) => {
129 out.push_str("<blockquote>");
130 blocks.iter().for_each(|b| block_html(b, out));
131 out.push_str("</blockquote>");
132 }
133 Block::Code { lang, text } => {
134 out.push_str("<pre");
135 if let Some(l) = lang {
136 out.push_str(&format!(" data-language=\"{}\"", escape(l)));
137 }
138 out.push_str("><code>");
139 out.push_str(&escape(text));
140 out.push_str("</code></pre>");
141 }
142 Block::Rule => out.push_str("<hr>"),
143 Block::List { ordered, start, items } => {
144 let tag = if *ordered { "ol" } else { "ul" };
145 out.push('<');
146 out.push_str(tag);
147 if *ordered && *start != 1 {
148 out.push_str(&format!(" start=\"{start}\""));
149 }
150 out.push('>');
151 for item in items {
152 out.push_str("<li>");
153 item.iter().for_each(|b| block_html(b, out));
154 out.push_str("</li>");
155 }
156 out.push_str("</");
157 out.push_str(tag);
158 out.push('>');
159 }
160 }
161}
162
163fn inlines_html(inl: &[Inline], out: &mut String) {
164 for i in inl {
165 match i {
166 Inline::Text(s, m) => {
167 // Outermost first: link, em, strong, code.
168 let mut close = Vec::new();
169 if let Some((href, title)) = &m.link {
170 out.push_str(&format!("<a href=\"{}\"", escape(href)));
171 if let Some(t) = title {
172 out.push_str(&format!(" title=\"{}\"", escape(t)));
173 }
174 out.push('>');
175 close.push("</a>");
176 }
177 if m.em {
178 out.push_str("<em>");
179 close.push("</em>");
180 }
181 if m.strong {
182 out.push_str("<strong>");
183 close.push("</strong>");
184 }
185 if m.code {
186 out.push_str("<code>");
187 close.push("</code>");
188 }
189 out.push_str(&escape(s));
190 for c in close.iter().rev() {
191 out.push_str(c);
192 }
193 }
194 Inline::HardBreak => out.push_str("<br>"),
195 Inline::Image { src, alt, title } => {
196 out.push_str(&format!("<img src=\"{}\" alt=\"{}\"", escape(src), escape(alt)));
197 if let Some(t) = title {
198 out.push_str(&format!(" title=\"{}\"", escape(t)));
199 }
200 out.push('>');
201 }
202 }
203 }
204}
205
206fn escape(s: &str) -> String {
207 let mut out = String::with_capacity(s.len());
208 for c in s.chars() {
209 match c {
210 '&' => out.push_str("&amp;"),
211 '<' => out.push_str("&lt;"),
212 '>' => out.push_str("&gt;"),
213 '"' => out.push_str("&quot;"),
214 '\'' => out.push_str("&#39;"),
215 _ => out.push(c),
216 }
217 }
218 out
219}
220
221fn to_text(blocks: &[Block]) -> String {
222 let mut parts = Vec::new();
223 blocks.iter().for_each(|b| text_parts(b, &mut parts));
224 parts.join("\n\n")
225}
226
227fn text_parts(b: &Block, parts: &mut Vec<String>) {
228 match b {
229 Block::Paragraph(inl) | Block::Heading(_, inl) => {
230 let mut s = String::new();
231 for i in inl {
232 match i {
233 Inline::Text(t, _) => s.push_str(t),
234 Inline::HardBreak => s.push('\n'),
235 Inline::Image { .. } => {}
236 }
237 }
238 parts.push(s);
239 }
240 Block::Quote(blocks) => blocks.iter().for_each(|b| text_parts(b, parts)),
241 Block::Code { text, .. } => parts.push(text.clone()),
242 Block::Rule => {}
243 Block::List { items, .. } => {
244 for item in items {
245 item.iter().for_each(|b| text_parts(b, parts));
246 }
247 }
248 }
249}
250
251// ---------------------------------------------------------------------------
252// Paste and drop
253// ---------------------------------------------------------------------------
254
255/// Inserts what the data transfer holds. `plain` forces text/plain. Files with no text
256/// beside them are uploaded instead; `host` is the editor they land in.
257fn paste_from(ed: &mut Editor, host: &Weak<RefCell<Editor>>, dt: Option<&DataTransfer>, plain: bool) {
258 let Some(dt) = dt else { return };
259 let text = dt.get_data("text/plain").unwrap_or_default();
260 let html = if plain { String::new() } else { dt.get_data("text/html").unwrap_or_default() };
261 // An image copied from a page brings html that holds no text; rich text still wins.
262 if !plain && text.trim().is_empty() {
263 let files = media::files_of(dt.files());
264 if !files.is_empty() && to_text(&html_blocks(&html)).trim().is_empty() {
265 if let Some(host) = host.upgrade() {
266 media::insert_files(&host, files);
267 }
268 return;
269 }
270 }
271 let mut blocks = if html.trim().is_empty() { Vec::new() } else { html_blocks(&html) };
272 if blocks.is_empty() {
273 blocks = plain_blocks(&text);
274 }
275 if blocks.is_empty() {
276 return;
277 }
278 ed.run(|cx| commands::insert_blocks(cx, &blocks));
279}
280
281fn plain_blocks(text: &str) -> Vec<Block> {
282 let text = text.replace("\r\n", "\n").replace('\r', "\n");
283 let text = text.strip_suffix('\n').unwrap_or(&text);
284 if text.is_empty() {
285 return Vec::new();
286 }
287 text.split('\n')
288 .map(|line| {
289 let inl = if line.is_empty() { Vec::new() } else { vec![Inline::Text(line.to_owned(), Marks::default())] };
290 Block::Paragraph(inl)
291 })
292 .collect()
293}
294
295/// The caret point under the pointer: `caretPositionFromPoint`, else `caretRangeFromPoint`.
296fn caret_at(document: &Document, x: f64, y: f64) -> Option<(Node, u32)> {
297 let d: &JsValue = document.as_ref();
298 let args = (JsValue::from_f64(x), JsValue::from_f64(y));
299 let pos_fn = js_sys::Reflect::get(d, &"caretPositionFromPoint".into()).ok()?;
300 if let Ok(f) = pos_fn.dyn_into::<js_sys::Function>() {
301 let r = f.call2(d, &args.0, &args.1).ok()?;
302 if r.is_null() || r.is_undefined() {
303 return None;
304 }
305 let node = js_sys::Reflect::get(&r, &"offsetNode".into()).ok()?;
306 let off = js_sys::Reflect::get(&r, &"offset".into()).ok()?.as_f64()?;
307 return Some((node.dyn_into::<Node>().ok()?, off as u32));
308 }
309 let range_fn = js_sys::Reflect::get(d, &"caretRangeFromPoint".into()).ok()?;
310 let f = range_fn.dyn_into::<js_sys::Function>().ok()?;
311 let r = f.call2(d, &args.0, &args.1).ok()?;
312 if r.is_null() || r.is_undefined() {
313 return None;
314 }
315 let node = js_sys::Reflect::get(&r, &"startContainer".into()).ok()?;
316 let off = js_sys::Reflect::get(&r, &"startOffset".into()).ok()?.as_f64()?;
317 Some((node.dyn_into::<Node>().ok()?, off as u32))
318}
319
320// ---------------------------------------------------------------------------
321// HTML import
322// ---------------------------------------------------------------------------
323
324fn html_blocks(html: &str) -> Vec<Block> {
325 let Ok(parser) = DomParser::new() else { return Vec::new() };
326 let Ok(doc) = parser.parse_from_string(html, SupportedType::TextHtml) else { return Vec::new() };
327 let Some(body) = doc.body() else { return Vec::new() };
328 let mut acc = Acc::default();
329 walk_children(&body, &Marks::default(), &mut acc);
330 acc.finish()
331}
332
333/// Blocks under construction, with the inline run that is not yet in a block.
334#[derive(Default)]
335struct Acc {
336 blocks: Vec<Block>,
337 inl: Vec<Inline>,
338}
339
340impl Acc {
341 /// Appends collapsed text the way HTML renders it: runs of whitespace become one
342 /// space, and no space leads a line.
343 fn text(&mut self, s: &str, marks: &Marks) {
344 let mut out = String::with_capacity(s.len());
345 let mut prev_space = false;
346 for c in s.chars() {
347 if matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{0c}') {
348 if !prev_space {
349 out.push(' ');
350 }
351 prev_space = true;
352 } else {
353 out.push(c);
354 prev_space = false;
355 }
356 }
357 let at_line_start = match self.inl.last() {
358 None | Some(Inline::HardBreak) | Some(Inline::Image { .. }) => true,
359 Some(Inline::Text(t, _)) => t.ends_with(' '),
360 };
361 if at_line_start {
362 out = out.trim_start_matches(' ').to_owned();
363 }
364 if !out.is_empty() {
365 self.inl.push(Inline::Text(out, marks.clone()));
366 }
367 }
368
369 /// Turns the pending inline run into a block (a heading when `level` is set).
370 fn flush(&mut self, level: Option<i64>) {
371 let mut inl = std::mem::take(&mut self.inl);
372 trim_edges(&mut inl);
373 if inl.is_empty() {
374 return;
375 }
376 self.blocks.push(match level {
377 Some(l) => Block::Heading(l, inl),
378 None => Block::Paragraph(inl),
379 });
380 }
381
382 fn finish(mut self) -> Vec<Block> {
383 self.flush(None);
384 self.blocks
385 }
386}
387
388/// Drops the space at both ends of an inline run (block edges collapse whitespace).
389fn trim_edges(inl: &mut Vec<Inline>) {
390 while let Some(Inline::Text(s, _)) = inl.first_mut() {
391 *s = s.trim_start_matches(' ').to_owned();
392 if !s.is_empty() {
393 break;
394 }
395 inl.remove(0);
396 }
397 while let Some(Inline::Text(s, _)) = inl.last_mut() {
398 *s = s.trim_end_matches(' ').to_owned();
399 if !s.is_empty() {
400 break;
401 }
402 inl.pop();
403 }
404}
405
406fn children(el: &Node) -> Vec<Node> {
407 let kids = el.child_nodes();
408 (0..kids.length()).filter_map(|i| kids.item(i)).collect()
409}
410
411fn walk_children(el: &Node, marks: &Marks, acc: &mut Acc) {
412 for k in children(el) {
413 walk(&k, marks, acc);
414 }
415}
416
417/// Tags that only group content: they end the current block and do not style it.
418const CONTAINERS: &[&str] = &[
419 "div", "section", "article", "header", "footer", "main", "nav", "aside", "figure", "figcaption", "address", "body",
420 "html", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "dl", "dt", "dd", "li", "p",
421];
422
423fn walk(node: &Node, marks: &Marks, acc: &mut Acc) {
424 match node.node_type() {
425 Node::TEXT_NODE => {
426 if let Some(s) = node.node_value() {
427 acc.text(&s, marks);
428 }
429 return;
430 }
431 Node::ELEMENT_NODE => {}
432 _ => return,
433 }
434 let Some(el) = node.dyn_ref::<Element>() else { return };
435 let tag = el.tag_name().to_ascii_lowercase();
436 let tag = tag.as_str();
437 match tag {
438 "script" | "style" | "meta" | "head" | "template" | "noscript" | "title" => {}
439 "br" => acc.inl.push(Inline::HardBreak),
440 "img" => {
441 if let Some(src) = el.get_attribute("src").filter(|s| !s.is_empty()) {
442 acc.inl.push(Inline::Image {
443 src,
444 alt: el.get_attribute("alt").unwrap_or_default(),
445 title: el.get_attribute("title").filter(|t| !t.is_empty()),
446 });
447 }
448 }
449 "hr" => {
450 acc.flush(None);
451 acc.blocks.push(Block::Rule);
452 }
453 _ if tag == "pre" || is_preformatted(el) => {
454 acc.flush(None);
455 let lang = el
456 .get_attribute("data-language")
457 .or_else(|| el.get_attribute("class").and_then(|c| language_class(&c)))
458 .filter(|l| !l.is_empty());
459 let mut text = String::new();
460 pre_text(node, &mut text);
461 let text = text.strip_suffix('\n').unwrap_or(&text).replace('\u{a0}', " ");
462 acc.blocks.push(Block::Code { lang, text });
463 }
464 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
465 acc.flush(None);
466 let level = tag[1..].parse::<i64>().unwrap_or(1);
467 walk_children(node, marks, acc);
468 acc.flush(Some(level));
469 }
470 "blockquote" => {
471 acc.flush(None);
472 let mut sub = Acc::default();
473 walk_children(node, marks, &mut sub);
474 let blocks = sub.finish();
475 if !blocks.is_empty() {
476 acc.blocks.push(Block::Quote(blocks));
477 }
478 }
479 "ul" | "ol" => {
480 acc.flush(None);
481 let items: Vec<Vec<Block>> = children(node)
482 .iter()
483 .filter(|c| is_tag(c, "li"))
484 .map(|li| {
485 let mut sub = Acc::default();
486 walk_children(li, marks, &mut sub);
487 sub.finish()
488 })
489 .filter(|v| !v.is_empty())
490 .collect();
491 if !items.is_empty() {
492 let start = if tag == "ol" {
493 el.get_attribute("start").and_then(|s| s.trim().parse::<i64>().ok()).unwrap_or(1)
494 } else {
495 1
496 };
497 acc.blocks.push(Block::List { ordered: tag == "ol", start, items });
498 }
499 }
500 "a" => {
501 let mut m = marks.clone();
502 if let Some(href) = el.get_attribute("href").filter(|h| !h.is_empty()) {
503 let title = el.get_attribute("title").filter(|t| !t.is_empty());
504 m.link = Some((href, title));
505 }
506 walk_children(node, &m, acc);
507 }
508 "strong" | "b" => {
509 let mut m = marks.clone();
510 m.strong = true;
511 walk_children(node, &m, acc);
512 }
513 "em" | "i" => {
514 let mut m = marks.clone();
515 m.em = true;
516 walk_children(node, &m, acc);
517 }
518 "code" => {
519 let mut m = marks.clone();
520 m.code = true;
521 walk_children(node, &m, acc);
522 }
523 t if CONTAINERS.contains(&t) => {
524 acc.flush(None);
525 walk_children(node, marks, acc);
526 acc.flush(None);
527 }
528 _ => walk_children(node, marks, acc),
529 }
530}
531
532fn is_tag(n: &Node, want: &str) -> bool {
533 n.dyn_ref::<Element>().is_some_and(|e| e.tag_name().eq_ignore_ascii_case(want))
534}
535
536/// Code editors (VS Code, JetBrains) copy a `div` styled `white-space: pre`, one
537/// child `div` per line.
538fn is_preformatted(el: &Element) -> bool {
539 el.get_attribute("style").is_some_and(|s| {
540 let s = s.to_ascii_lowercase().replace(' ', "");
541 s.contains("white-space:pre")
542 })
543}
544
545/// Text of preformatted content: line `div`s/`p`s and `br`s become newlines.
546fn pre_text(node: &Node, out: &mut String) {
547 for child in children(node) {
548 match child.node_type() {
549 Node::TEXT_NODE => out.push_str(&child.text_content().unwrap_or_default()),
550 Node::ELEMENT_NODE => match child.node_name().to_ascii_lowercase().as_str() {
551 "br" => out.push('\n'),
552 "div" | "p" => {
553 if !out.is_empty() && !out.ends_with('\n') {
554 out.push('\n');
555 }
556 pre_text(&child, out);
557 if !out.ends_with('\n') {
558 out.push('\n');
559 }
560 }
561 _ => pre_text(&child, out),
562 },
563 _ => {}
564 }
565 }
566}
567
568/// `language-x` among the classes of a `pre`, read before the classes are dropped.
569fn language_class(class: &str) -> Option<String> {
570 class.split_whitespace().find_map(|c| c.strip_prefix("language-")).map(str::to_owned)
571}