diff --git a/crates/i18n/translations/en.json b/crates/i18n/translations/en.json index e4c8fc78..52f8b0dd 100644 --- a/crates/i18n/translations/en.json +++ b/crates/i18n/translations/en.json @@ -441,6 +441,7 @@ "menu": { "cut": "Cut", "copy": "Copy", + "copyMarkdown": "Copy as Markdown", "paste": "Paste", "selectAll": "Select all" }, @@ -1014,6 +1015,7 @@ "taskList": "Task list", "quote": "Quote", "codeBlock": "Code block", + "copyMarkdown": "Copy as Markdown", "markdown": "Typed at the start of a line, then a space: heading, list, numbered list, task, quote, code block" }, "palette": { diff --git a/crates/i18n/translations/fr.json b/crates/i18n/translations/fr.json index 0f4bc046..e2b96acc 100644 --- a/crates/i18n/translations/fr.json +++ b/crates/i18n/translations/fr.json @@ -441,6 +441,7 @@ "menu": { "cut": "Couper", "copy": "Copier", + "copyMarkdown": "Copier en Markdown", "paste": "Coller", "selectAll": "Tout sélectionner" }, @@ -1014,6 +1015,7 @@ "taskList": "Liste de tâches", "quote": "Citation", "codeBlock": "Bloc de code", + "copyMarkdown": "Copier en Markdown", "markdown": "Tapés en début de ligne, suivis d’une espace : titre, liste, liste numérotée, tâche, citation, bloc de code" }, "palette": { diff --git a/crates/richtext/src/edit.rs b/crates/richtext/src/edit.rs index 27e43bd6..43957d55 100644 --- a/crates/richtext/src/edit.rs +++ b/crates/richtext/src/edit.rs @@ -53,6 +53,156 @@ pub fn selected_text(document: &Document, selection: &Selection) -> String { out.join("\n") } +/// What a copy puts on the clipboard: the selected text, each line led by the blocks it sits +/// in — `- `, `3. `, `- [x] ` on an item's first line, two spaces a level of nesting, `> ` in a +/// quote. Inline marks come out as their text. Within one leaf, its text alone. +pub fn copied(document: &Document, selection: &Selection) -> String { + let (start, end) = ordered(selection); + if start.path == end.path { + return selected_text(document, selection); + } + let mut out = Vec::new(); + lines(&fragment(document, selection).blocks, ("", ""), &mut out); + out.join("\n") +} + +/// The selection as the Markdown a Note is stored in, marks included. +pub fn copied_markdown(document: &Document, selection: &Selection) -> String { + crate::write(&fragment(document, selection)) +} + +/// The selected blocks, the first and the last leaf cut at the selection's ends. +pub fn fragment(document: &Document, selection: &Selection) -> Document { + let (start, end) = ordered(selection); + let (from, to) = ((&start.path[..], start.offset), (&end.path[..], end.offset)); + Document { + blocks: slice(&document.blocks, Some(from), Some(to)), + } +} + +/// One end of a cut, as a path below the level it is read at and an offset; `None`, open. +type End<'a> = Option<(&'a [usize], usize)>; + +/// The indices kept at this level. +fn kept(from: End<'_>, to: End<'_>) -> std::ops::RangeInclusive { + let index = |end: End<'_>| end.and_then(|(path, _)| path.first().copied()); + index(from).unwrap_or(0)..=index(to).unwrap_or(usize::MAX) +} + +/// An end, one level down inside the block or item at `index`: open when it lies elsewhere. +fn below(end: End<'_>, index: usize) -> End<'_> { + end.filter(|(path, _)| path.first() == Some(&index)) + .map(|(path, offset)| (&path[1..], offset)) +} + +fn slice(blocks: &[Block], from: End<'_>, to: End<'_>) -> Vec { + let kept = kept(from, to); + blocks + .iter() + .enumerate() + .filter(|(index, _)| kept.contains(index)) + .map(|(index, block)| cut_block(block, below(from, index), below(to, index))) + .collect() +} + +fn cut_block(block: &Block, from: End<'_>, to: End<'_>) -> Block { + let (start, end) = (from.map(|(_, at)| at), to.map(|(_, at)| at)); + match block { + Block::Paragraph(content) => Block::Paragraph(cut_inlines(content, start, end)), + Block::Heading { level, content } => Block::Heading { + level: *level, + content: cut_inlines(content, start, end), + }, + Block::CodeBlock { language, text } => Block::CodeBlock { + language: language.clone(), + text: text + .chars() + .take(end.unwrap_or(usize::MAX)) + .skip(start.unwrap_or(0)) + .collect(), + }, + Block::List { kind, items } => { + let kept = kept(from, to); + // A numbered item keeps its number. + let kind = match *kind { + ListKind::Ordered { start } => ListKind::Ordered { + start: start + u64::try_from(*kept.start()).unwrap_or(0), + }, + other => other, + }; + let items = items + .iter() + .enumerate() + .filter(|(index, _)| kept.contains(index)) + .map(|(index, item)| Item { + checked: item.checked, + blocks: slice(&item.blocks, below(from, index), below(to, index)), + }) + .collect(); + Block::List { kind, items } + } + Block::Quote(inner) => Block::Quote(slice(inner, from, to)), + Block::Table(_) | Block::Image { .. } | Block::Rule => block.clone(), + } +} + +fn cut_inlines(content: &[Inline], start: Option, end: Option) -> Vec { + let before_end = match end { + Some(end) => inlines::split(content, end).0, + None => content.to_vec(), + }; + match start { + Some(start) => inlines::split(&before_end, start).1, + None => before_end, + } +} + +/// The blocks as lines of text, `first` before the first line, `rest` before every other. +fn lines(blocks: &[Block], (first, rest): (&str, &str), out: &mut Vec) { + for (index, block) in blocks.iter().enumerate() { + let lead = if index == 0 { first } else { rest }; + match block { + Block::Paragraph(content) | Block::Heading { content, .. } => { + text_lines(&inlines::plain(content), (lead, rest), out); + } + Block::CodeBlock { text, .. } => text_lines(text, (lead, rest), out), + Block::List { kind, items } => { + let nested = format!("{rest} "); + for (at, item) in items.iter().enumerate() { + let lead = if at == 0 { lead } else { rest }; + let marked = format!("{lead}{}", marker(*kind, at, item.checked)); + lines(&item.blocks, (&marked, &nested), out); + } + } + Block::Quote(inner) => { + lines(inner, (&format!("{lead}> "), &format!("{rest}> ")), out); + } + Block::Table(rows) => { + for (at, cell) in rows.iter().flatten().enumerate() { + let lead = if at == 0 { lead } else { rest }; + text_lines(&inlines::plain(cell), (lead, rest), out); + } + } + Block::Image { .. } | Block::Rule => {} + } + } +} + +fn text_lines(text: &str, (lead, rest): (&str, &str), out: &mut Vec) { + for (at, line) in text.split('\n').enumerate() { + out.push(format!("{}{line}", if at == 0 { lead } else { rest })); + } +} + +fn marker(kind: ListKind, at: usize, checked: bool) -> String { + match kind { + ListKind::Bullet => "- ".to_owned(), + ListKind::Ordered { start } => format!("{}. ", start + u64::try_from(at).unwrap_or(0)), + ListKind::Task if checked => "- [x] ".to_owned(), + ListKind::Task => "- [ ] ".to_owned(), + } +} + /// Text typed at the caret, in place of what is selected. pub fn insert_text( document: &mut Document, diff --git a/crates/richtext/src/edit/tests.rs b/crates/richtext/src/edit/tests.rs index ce0dce44..68ed6c71 100644 --- a/crates/richtext/src/edit/tests.rs +++ b/crates/richtext/src/edit/tests.rs @@ -241,3 +241,57 @@ fn a_paragraph_left_empty_after_a_code_block_is_not_written() { leave_code(&mut document, &caret_at(&[0], 1)); assert_eq!(read(&write(&document)), read("```\na\n```")); } + +fn whole(document: &Document) -> Selection { + let leaves = tree::leaves(document); + let last = leaves.last().unwrap(); + let length = tree::leaf(document, last).unwrap().len(); + range((&leaves[0], 0), (last, length)) +} + +#[test] +fn a_copy_keeps_the_markers_of_its_blocks_and_none_of_the_marks() { + let cases = [ + ("- one\n- two", "- one\n- two"), + ("3. three\n4. four", "3. three\n4. four"), + ("- [ ] open\n- [x] done", "- [ ] open\n- [x] done"), + ("- one\n - nested\n- two", "- one\n - nested\n- two"), + ("> quoted\n>\n> again", "> quoted\n> again"), + ("# Title\n\n**bold** and `code`", "Title\nbold and code"), + ]; + for (markdown, expected) in cases { + let document = read(markdown); + assert_eq!(copied(&document, &whole(&document)), expected, "{markdown}"); + } +} + +#[test] +fn a_copy_cut_inside_items_keeps_their_numbers_and_within_one_item_its_text_alone() { + let document = read("1. first\n2. second\n3. third"); + let from_second = range((&[0, 1, 0], 3), (&[0, 2, 0], 2)); + assert_eq!(copied(&document, &from_second), "2. ond\n3. th"); + let within = range((&[0, 1, 0], 0), (&[0, 1, 0], 6)); + assert_eq!(copied(&document, &within), "second"); +} + +#[test] +fn copied_as_markdown_reads_back_to_the_same_blocks() { + for markdown in [ + "- one **bold**\n- two", + "3. three\n4. four", + "- [ ] open\n- [x] done", + "- one\n - nested\n- two", + "> quoted", + "# Title\n\n**bold** and `code`", + ] { + let document = read(markdown); + let copied = copied_markdown(&document, &whole(&document)); + assert_eq!(read(&copied), document, "{markdown} gave {copied}"); + } + let document = read("1. first\n2. second\n3. third"); + let from_second = range((&[0, 1, 0], 0), (&[0, 2, 0], 5)); + assert_eq!( + copied_markdown(&document, &from_second), + "2. second\n3. third" + ); +} diff --git a/crates/ui/src/app/captures.rs b/crates/ui/src/app/captures.rs index 3c03933b..1ee90863 100644 --- a/crates/ui/src/app/captures.rs +++ b/crates/ui/src/app/captures.rs @@ -2034,3 +2034,52 @@ fn an_empty_folder_opened() { settle(&mut harness); capture(&mut harness, "folder-empty"); } + +#[test] +fn a_wrapped_list_selected_whole() { + use engine::notes::kind::NoteKind; + use engine::notes::language::Language; + let profile = tempfile::tempdir().unwrap(); + let mut harness = launch(profile.path()); + type_into(&mut harness, "vault-passphrase", PASSPHRASE); + type_into(&mut harness, "vault-confirmation", PASSPHRASE); + click(&mut harness, "vault-submit"); + settle(&mut harness); + let backend = &harness.state().backend; + let space = crate::testing::note(backend, "seed").space_id.clone(); + let long = + "Une tâche assez longue pour tenir sur plusieurs lignes de la Note ouverte. ".repeat(3); + let content = format!( + "- {}\n- Relire la procédure\n- {}", + long.trim_end(), + long.trim_end() + ); + engine::db::run_here(backend.engine(), move |engine| { + let draft = engine::notes::model::NoteDraft { + kind: NoteKind::Note, + language: Language::Txt, + content, + ..crate::testing::snippet(space, "Mise en production".to_owned()) + }; + engine::notes::create_note(engine, draft) + }) + .unwrap(); + harness.state_mut().state.revision.bump(); + settle(&mut harness); + harness + .get_by(|node| { + node.author_id() == Some("note-card-open") + && node.label().as_deref() == Some("Mise en production") + }) + .click(); + settle(&mut harness); + click(&mut harness, "editor-rich"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + settle(&mut harness); + capture(&mut harness, "note-list-selected"); + harness + .get_by(|node| node.author_id() == Some("editor-rich")) + .click_secondary(); + settle(&mut harness); + capture(&mut harness, "note-menu"); +} diff --git a/crates/ui/src/notes/overlays/editor/rich.rs b/crates/ui/src/notes/overlays/editor/rich.rs index 594887dd..58db0f0b 100644 --- a/crates/ui/src/notes/overlays/editor/rich.rs +++ b/crates/ui/src/notes/overlays/editor/rich.rs @@ -516,6 +516,7 @@ pub(super) fn show(ui: &mut Ui, view: &mut RichEditor, state: &AppState) -> Show surface.request_focus(); } pointer(ui, view, &surface); + menu(view, &surface, state.language); if focused { lock_keys(ui, surface.id); shown.code_paste = keys(ui, view, state.clipboard.as_ref()); @@ -629,7 +630,7 @@ fn keys( modifiers, .. } => { - let shortcut = key_pressed(view, key, physical_key, modifiers); + let shortcut = key_pressed(ui, view, key, physical_key, modifiers); if shortcut { ran.push((modifiers, key)); } @@ -671,22 +672,72 @@ fn paste( None } +/// The selection as text, its lists' markers kept. fn copy(ui: &Ui, view: &RichEditor) { if !view.selection.is_empty() { ui.ctx() - .copy_text(edit::selected_text(&view.document, &view.selection)); + .copy_text(edit::copied(&view.document, &view.selection)); } } +fn copy_markdown(ui: &Ui, view: &RichEditor) { + if !view.selection.is_empty() { + ui.ctx() + .copy_text(edit::copied_markdown(&view.document, &view.selection)); + } +} + +/// Cut, copy, copy as Markdown, paste, select all. Paste asks the window for the clipboard: it +/// arrives at the next frame as an event the keys take. +fn menu(view: &mut RichEditor, surface: &egui::Response, language: Language) { + use i18n::keys::editor::menu as words; + let popup = egui::Popup::context_menu(surface).frame(crate::widgets::menu_frame(&surface.ctx)); + popup.show(|ui| { + crate::widgets::fitted_menu(ui, 0.0, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let entries = [ + (words::CUT, "rich-menu-cut"), + (words::COPY, "rich-menu-copy"), + (words::COPY_MARKDOWN, "rich-menu-copy-markdown"), + (words::PASTE, "rich-menu-paste"), + (words::SELECT_ALL, "rich-menu-select-all"), + ]; + for (key, author_id) in entries { + let label = i18n::translate(language, key, &[]); + if !crate::widgets::menu_entry(ui, &label, author_id, false, false, false).clicked() + { + continue; + } + match author_id { + "rich-menu-cut" if !view.selection.is_empty() => { + copy(ui, view); + view.change(Step::Other, edit::delete_selection); + } + "rich-menu-copy" => copy(ui, view), + "rich-menu-copy-markdown" => copy_markdown(ui, view), + "rich-menu-paste" => ui + .ctx() + .send_viewport_cmd(egui::ViewportCommand::RequestPaste), + "rich-menu-select-all" => view.select_all(), + _ => {} + } + ui.close(); + surface.request_focus(); + } + }); + }); +} + /// `true` when the key was one of the text's shortcuts. fn key_pressed( + ui: &Ui, view: &mut RichEditor, key: Key, physical: Option, modifiers: Modifiers, ) -> bool { if let Some(command) = shortcuts::find(key, physical, modifiers) { - run_command(view, command); + run_command(ui, view, command); return true; } if let Some(shortcut) = images::key_pressed(view, key, modifiers) { @@ -707,7 +758,7 @@ fn key_pressed( false } -fn run_command(view: &mut RichEditor, command: shortcuts::Command) { +fn run_command(ui: &Ui, view: &mut RichEditor, command: shortcuts::Command) { use shortcuts::Command; use toolbar::Tool; match command { @@ -732,6 +783,7 @@ fn run_command(view: &mut RichEditor, command: shortcuts::Command) { Command::Undo => view.undo(false), Command::Redo => view.undo(true), Command::SelectAll => view.select_all(), + Command::CopyMarkdown => copy_markdown(ui, view), } } diff --git a/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs b/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs index e4f14bd7..e386742a 100644 --- a/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs +++ b/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs @@ -20,9 +20,10 @@ pub(super) enum Command { Undo, Redo, SelectAll, + CopyMarkdown, } -pub(super) const SHORTCUTS: [(&str, Command); 21] = [ +pub(super) const SHORTCUTS: [(&str, Command); 22] = [ ("Mod-b", Command::Bold), ("Mod-i", Command::Italic), ("Mod-Shift-s", Command::Strike), @@ -44,6 +45,8 @@ pub(super) const SHORTCUTS: [(&str, Command); 21] = [ ("Mod-z", Command::Undo), ("Shift-Mod-z", Command::Redo), ("Mod-y", Command::Redo), + // Ctrl+C alone is the window's copy event; with Shift it reaches the editor as a key. + ("Mod-Shift-c", Command::CopyMarkdown), ]; /// `Mod-a` is the editor's own, with the other keys of its keymap. diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index e4ef5aa7..4e50f2de 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -741,3 +741,115 @@ fn shift_and_a_double_click_stretch_the_selection_to_the_word() { type_in(&mut harness, "Z"); assert_eq!(surface_text(&harness), "Z gamma"); } + +/// What the last frames put on the clipboard. +fn clipboard(harness: &mut Harness<'_>) -> Option { + let mut copied = None; + for _ in 0..5 { + harness.step(); + copied = copied.or_else(|| { + let commands = &harness.output().platform_output.commands; + commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) + }); + } + copied +} + +#[test] +fn a_copied_list_keeps_its_markers_and_drops_the_inline_marks() { + let (mut harness, _) = note("- one **bold**\n- two\n\n1. first\n2. second"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Copy); + assert_eq!( + clipboard(&mut harness).as_deref(), + Some("- one bold\n- two\n1. first\n2. second") + ); +} + +/// Clicked, the frame left to `clipboard`: its copy is read there. +fn menu_entry(harness: &Harness<'_>, author_id: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .click(); +} + +#[test] +fn ctrl_shift_c_and_the_menu_copy_the_selection_as_markdown() { + let (mut harness, _) = note("- one **bold**\n- two"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::A); + // Pressed alone: kittest gives a release a pass of its own, whose output would be the frame's. + let held = Modifiers::COMMAND | Modifiers::SHIFT; + harness.event(egui::Event::ModifiersChanged(held)); + harness.event(egui::Event::Key { + key: Key::C, + physical_key: Some(Key::C), + pressed: true, + repeat: false, + modifiers: held, + }); + assert_eq!( + clipboard(&mut harness).as_deref(), + Some("- one **bold**\n- two") + ); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + + harness + .get_by(|node| node.author_id() == Some("editor-rich")) + .click_secondary(); + settle(&mut harness); + menu_entry(&harness, "rich-menu-copy-markdown"); + assert_eq!( + clipboard(&mut harness).as_deref(), + Some("- one **bold**\n- two") + ); + harness + .get_by(|node| node.author_id() == Some("editor-rich")) + .click_secondary(); + settle(&mut harness); + menu_entry(&harness, "rich-menu-copy"); + assert_eq!( + clipboard(&mut harness).as_deref(), + Some("- one bold\n- two") + ); +} + +#[test] +fn select_all_lights_every_row_of_a_wrapped_item() { + let long = "a sentence long enough to wrap ".repeat(12); + let (mut harness, _) = note(&format!("- {}\n- short", long.trim_end())); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::A); + + let shapes = &harness.output().shapes; + let item = shapes + .iter() + .find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().starts_with("a sentence") => Some( + text.galley + .rows + .iter() + .map(|row| row.rect().translate(text.pos.to_vec2())), + ), + _ => None, + }) + .expect("the item is painted") + .collect::>(); + assert!(item.len() >= 3, "wrapped on {} rows", item.len()); + let lit = crate::theme::palette(&harness.ctx) + .amber_fill + .gamma_multiply(0.3); + for row in &item { + let covered = shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Rect(shape) + if shape.fill == lit + && (shape.rect.center().y - row.center().y).abs() < 1.0 + && shape.rect.width() > row.width() * 0.9) + }); + assert!(covered, "row {row:?} is lit"); + } +} diff --git a/crates/ui/src/services/shortcut_sheet.json b/crates/ui/src/services/shortcut_sheet.json index cd5751d6..d303dd5d 100644 --- a/crates/ui/src/services/shortcut_sheet.json +++ b/crates/ui/src/services/shortcut_sheet.json @@ -72,6 +72,7 @@ { "keys": ["Ctrl", "Shift", "9"], "label": "shortcuts.note.taskList" }, { "keys": ["Ctrl", "Shift", "B"], "label": "shortcuts.note.quote" }, { "keys": ["Ctrl", "Alt", "C"], "label": "shortcuts.note.codeBlock" }, + { "keys": ["Ctrl", "Shift", "C"], "label": "shortcuts.note.copyMarkdown" }, { "keys": ["#", "-", "1.", "[ ]", ">", "```"], "label": "shortcuts.note.markdown" } ] }, diff --git a/crates/ui/src/widgets/editor/mod.rs b/crates/ui/src/widgets/editor/mod.rs index 37ac8fa5..3af2398c 100644 --- a/crates/ui/src/widgets/editor/mod.rs +++ b/crates/ui/src/widgets/editor/mod.rs @@ -631,7 +631,12 @@ pub(crate) fn selection_rects( let to = range.end.min(row_end); let last = index + 1 == rows; if from < to || (last && past_end) { - let x0 = galley.pos_from_cursor(CCursor::new(from)).left(); + // A row's start is also the end of the row above when the line wraps there: on this one. + let start = CCursor { + index: from.into(), + prefer_next_row: true, + }; + let x0 = galley.pos_from_cursor(start).left(); let mut x1 = galley.pos_from_cursor(CCursor::new(to)).left(); if last && past_end { x1 += char_width; diff --git a/crates/ui/src/widgets/editor/tests.rs b/crates/ui/src/widgets/editor/tests.rs index 4f617f56..3fe3210c 100644 --- a/crates/ui/src/widgets/editor/tests.rs +++ b/crates/ui/src/widgets/editor/tests.rs @@ -298,3 +298,36 @@ fn budgets() { ); } } + +#[test] +fn a_wrapped_line_selected_whole_is_lit_on_each_of_its_rows() { + let text = "one two three four five six seven eight nine ten eleven twelve".to_owned(); + let length = text.chars().count(); + let ctx = egui::Context::default(); + let mut laid = None; + let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| { + let body = egui::FontId::proportional(font::BODY); + let galley = + ctx.fonts_mut(|fonts| fonts.layout(text.clone(), body, egui::Color32::WHITE, 120.0)); + laid = Some(galley); + }); + output.textures_delta.clear(); + let galley = laid.unwrap(); + assert!( + galley.rows.len() >= 3, + "wrapped: {} rows", + galley.rows.len() + ); + + let rects = selection_rects(&galley, 0..length, false, 4.0); + + assert_eq!(rects.len(), galley.rows.len()); + for (row, rect) in galley.rows.iter().zip(&rects) { + assert!(rect.width() > 1.0, "{rect:?}"); + assert!( + (rect.left() - row.rect().left()).abs() < 0.5, + "from its own start: {rect:?}" + ); + assert!((rect.center().y - row.rect().center().y).abs() < 0.5); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 351f905a..5e7479f7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1407,6 +1407,11 @@ and exporting write a Note as the Markdown it is, where a snippet is fenced. blocks (`richtext::from_html`, on `html5ever`'s tokenizer; `golden/html-paste` passes whole); code pasted into an empty Note makes it a snippet, the conversion detecting its language; anything else is text. A pasted image becomes an attachment, as in every editor. +- **Two copies**: Ctrl+C, Cut and the menu put text on the clipboard that keeps its blocks — + `- `, `3. `, `- [ ] ` on an item's first line, two spaces a level, `> ` in a quote — and none of the + inline marks (`richtext::edit::copied`); « Copy as Markdown » (Ctrl+Shift+C, the right-click + menu) writes the same selection as the Note's Markdown (`copied_markdown`). Both walk one + fragment, the selection cut out of the document; within one leaf, a copy is its text alone. - **An embedded drawing is read where it is shown**: `devnotes:drawing/` asks `LibraryCaches.pictures` (the large picture, by id, decoded off the frame and kept with the thumbnails' limit); a drawing saved again drops it. Any other image stays as written: a Note diff --git a/e2e/src/lib.rs b/e2e/src/lib.rs index e7914f66..21db6d0f 100644 --- a/e2e/src/lib.rs +++ b/e2e/src/lib.rs @@ -386,6 +386,29 @@ impl App { self.apply(vec![press(true), press(false), press(true), press(false)]); } + /// Ctrl+C as the window delivers it: a copy, not a key. + pub fn copy(&mut self) { + self.apply(vec![Event::Copy]); + } + + /// Until the system's clipboard holds text that `holds` accepts. + pub fn clipboard_holds(&mut self, what: &str, holds: impl Fn(&str) -> bool) { + use platform::clipboard::Clipboard; + let until = Instant::now() + PATIENCE; + loop { + let held = platform::clipboard::System.text().unwrap_or_default(); + if holds(&held) { + return; + } + assert!( + Instant::now() < until, + "{what}: still not true after {PATIENCE:?}; the clipboard holds {held:?}" + ); + // A frame between two reads. + let _ = self.tree(); + } + } + /// A press at `from` and a release at `to`, in points from the control's corner. pub fn drag_in(&mut self, author_id: &str, from: (f32, f32), to: (f32, f32)) { self.wait_for(author_id); diff --git a/e2e/tests/03_editing_a_note.rs b/e2e/tests/03_editing_a_note.rs index 06c6685c..c777ba47 100644 --- a/e2e/tests/03_editing_a_note.rs +++ b/e2e/tests/03_editing_a_note.rs @@ -3,8 +3,9 @@ //! and the find bar finding in it. Then a drawing: drawn on its stage, shown on its card from the //! picture kept beside it, written as a PNG, and Escape stepping back through it. Then Notes: //! the sample opens formatted and a box ticked there is kept, one typed from the toolbar keeps -//! « 2 * 3 * 4 » as typed, and a double click takes a word to type over. The editor sits beside the cards: J steps to the next one, and -//! Escape leaves full screen before it closes. +//! « 2 * 3 * 4 » as typed, a double click takes a word to type over, and a list copied keeps its +//! markers. The editor sits beside the cards: J steps to the next one, and Escape leaves full +//! screen before it closes. use e2e::{App, Tree, step}; use egui::{Key, Modifiers}; @@ -323,6 +324,26 @@ fn notes(app: &mut App) { }); close(app); }); + + step("a list copied keeps its markers, a long item whole", || { + let long = "un élément assez long pour passer à la ligne plus d’une fois ".repeat(4); + let long = long.trim_end(); + app.click("new-note-kind"); + app.click("new-note-note"); + app.click("editor-rich"); + for glyph in ["-", " "] { + app.type_text(glyph); + } + app.type_text(long); + app.press(Key::Enter, Modifiers::NONE); + app.type_text("court"); + app.eventually("both items typed", |tree| rich(tree).ends_with("court")); + app.press(Key::A, Modifiers::COMMAND); + app.copy(); + let expected = format!("- {long}\n- court"); + app.clipboard_holds("the list with its markers", |held| held == expected); + close(app); + }); } #[test]