ElyMark: right-click menu by target; Copy as HTML Code and Plain Text

R4.10. Clipboard row, Copy / Paste As, format and block rows, Table or
Paragraph, Insert, link, image, code and raw-block items; source and
preview menus. Component pin 1b5fb07. Records the user's rule that
ElyMark must work, not match Typora one to one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-14 18:41:24 -04:00
1 parent f012eaa624
commit d5ceaf9aac
18 files changed
+840 -67

No files matched your search

+8 -1
View File
@@ -45,7 +45,9 @@ actions!(
Strike,
Hyperlink,
InsertImage,
ClearFormat
ClearFormat,
DeleteBlock,
DeleteImage
]
);
@@ -150,6 +152,7 @@ pub(crate) fn refusal(why: EditRefusal, cx: &App) -> SharedString {
EditRefusal::FrontMatter => "mark.refused.front_matter",
EditRefusal::Outside => "mark.refused.outside",
EditRefusal::Table => "mark.refused.table",
EditRefusal::NoImage => "mark.refused.no_image",
EditRefusal::Present => "mark.refused.present",
EditRefusal::Across => "mark.refused.across",
EditRefusal::TooLong => "mark.refused.too_long",
@@ -226,11 +229,15 @@ impl Desk {
Hyperlink => |d, cx| d.format(F::Link, cx),
InsertImage => |d, cx| d.format(F::Image, cx),
ClearFormat => |d, cx| d.format(F::Clear, cx),
DeleteBlock => |d, cx| d.block(B::Delete, cx),
DeleteImage => |d, cx| d.delete_image(cx),
)
}
}
// macOS menus are the system's, not drawn.
#[cfg(test)]
mod context;
#[cfg(all(test, not(target_os = "macos")))]
mod menus;
#[cfg(test)]
+163
View File
@@ -0,0 +1,163 @@
//! The right-click menu, driven as a user would (R4.10).
use ely_gpui_component::theme::{ActiveTheme as _, TextSize};
use gpui::{
ClipboardItem, Entity, Modifiers, MouseButton, Point, TestAppContext, VisualTestContext, point,
px,
};
use super::tests::{current, document, opened, toasted};
use crate::{desk::Desk, view::Mode};
/// A right press on block `ix`'s first line, character `k`.
fn right_on(ix: usize, k: usize, cx: &mut VisualTestContext) {
let block = cx
.debug_bounds(Box::leak(format!("markdown-block-{ix}").into_boxed_str()))
.expect("the block is drawn");
let size = cx.update(|window, cx| {
cx.theme()
.text_size(TextSize::Base)
.to_pixels(window.rem_size())
});
// The test text system sets glyphs 0.6 em apart.
let x = block.left() + px(13.0) + size * 0.6 * (k as f32 + 0.25);
right_at(point(x, block.top() + px(10.0)), cx);
}
fn right_at(at: Point<gpui::Pixels>, cx: &mut VisualTestContext) {
cx.simulate_mouse_down(at, MouseButton::Right, Modifiers::none());
cx.simulate_mouse_up(at, MouseButton::Right, Modifiers::none());
cx.run_until_parked();
}
/// Arrow `keys`, then Enter; menus choose on its release.
fn choose(keys: &str, cx: &mut VisualTestContext) {
if !keys.is_empty() {
cx.simulate_keystrokes(keys);
}
cx.simulate_keystrokes("enter");
let enter = gpui::Keystroke::parse("enter").expect("a key");
cx.simulate_event(gpui::KeyUpEvent { keystroke: enter });
cx.run_until_parked();
}
fn clipboard(cx: &mut VisualTestContext) -> Option<String> {
cx.read_from_clipboard().and_then(|item| item.text())
}
fn switch(desk: &Entity<Desk>, mode: Mode, cx: &mut VisualTestContext) {
desk.update_in(cx, |desk, window, cx| desk.switch(mode, window, cx));
cx.run_until_parked();
}
#[gpui::test]
fn paste_from_the_menu_lands_at_the_pressed_caret(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("Intro\n", cx);
cx.write_to_clipboard(ClipboardItem::new_string("New ".into()));
right_on(0, 0, cx);
choose("down", cx);
assert_eq!(current(&desk, cx), "New Intro\n");
}
#[gpui::test]
fn a_link_opens_and_copies_its_address(cx: &mut TestAppContext) {
let (_desk, cx, _files) = opened("[docs](https://x.test)\n", cx);
right_on(0, 1, cx);
choose("down", cx);
assert_eq!(cx.opened_url().as_deref(), Some("https://x.test"));
right_on(0, 1, cx);
choose("down down down", cx);
assert_eq!(clipboard(cx).as_deref(), Some("https://x.test"));
}
#[gpui::test]
fn a_code_block_copies_its_code_and_deletes_by_name(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("```rust\nlet x = 1;\n```\n\nNext\n", cx);
right_on(0, 0, cx);
choose("down down down", cx);
assert_eq!(clipboard(cx).as_deref(), Some("let x = 1;"));
right_on(0, 0, cx);
choose("up", cx);
assert!(
!current(&desk, cx).contains("let x"),
"{}",
current(&desk, cx)
);
}
#[gpui::test]
fn a_quote_is_deleted_from_the_last_row(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("> quoted\n\nNext\n", cx);
right_on(0, 1, cx);
choose("up", cx);
let text = current(&desk, cx);
assert!(!text.contains("quoted") && text.contains("Next"), "{text}");
}
#[gpui::test]
fn a_picture_shows_its_file_or_goes(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("Lead.\n\n![pic](missing.png)\n", cx);
right_on(1, 1, cx);
choose("down", cx);
assert_eq!(toasted(&desk, "no file here", cx), 1);
right_on(1, 1, cx);
choose("down down", cx);
assert!(!current(&desk, cx).contains("!["), "{}", current(&desk, cx));
}
#[gpui::test]
fn source_cuts_the_selection_a_right_press_keeps(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("alpha beta\n", cx);
switch(&desk, Mode::Source, cx);
let editor = document(&desk, cx).read_with(cx, |document, _| document.editor().clone());
editor.update(cx, |editor, cx| editor.select(std::iter::once(0..5), cx));
let line = cx.debug_bounds("editor-line-0").expect("drawn");
right_at(point(line.left() + px(20.0), line.top() + px(6.0)), cx);
choose("down", cx);
assert_eq!(current(&desk, cx), " beta\n");
assert_eq!(clipboard(cx).as_deref(), Some("alpha"));
}
#[gpui::test]
fn an_open_block_copies_its_selection_and_stays(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("Intro words\n", cx);
let block = cx.debug_bounds("markdown-block-0").expect("drawn");
cx.simulate_mouse_down(block.center(), MouseButton::Left, Modifiers::none());
cx.simulate_mouse_up(block.center(), MouseButton::Left, Modifiers::none());
cx.run_until_parked();
cx.simulate_keystrokes("home shift-right shift-right shift-right shift-right shift-right");
let field = cx.debug_bounds("markdown-open").expect("open");
right_at(point(field.left() + px(20.0), field.top() + px(14.0)), cx);
choose("down right", cx);
assert_eq!(clipboard(cx).as_deref(), Some("Intro"));
assert!(
cx.debug_bounds("markdown-open").is_some(),
"the block stays open"
);
assert_eq!(current(&desk, cx), "Intro words\n");
}
#[gpui::test]
fn preview_offers_copies_only(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("alpha **beta**\n", cx);
switch(&desk, Mode::Preview, cx);
let block = cx.debug_bounds("markdown-block-0").expect("drawn");
right_at(block.center(), cx);
choose("down", cx);
assert_eq!(clipboard(cx).as_deref(), Some("alpha beta\n"));
right_at(block.center(), cx);
choose("down down", cx);
assert_eq!(clipboard(cx).as_deref(), Some("alpha **beta**\n"));
}
#[gpui::test]
fn html_code_keeps_picture_addresses(cx: &mut TestAppContext) {
let (_desk, cx, _files) = opened("![pic](missing.png) and *it*\n", cx);
cx.dispatch_action(crate::export::CopyHtml);
cx.run_until_parked();
let html = clipboard(cx).expect("copied");
assert!(
html.contains("src=\"missing.png\"") && html.contains("<em>it</em>"),
"{html}"
);
}
+2 -1
View File
@@ -58,7 +58,8 @@ fn a_menu_formats_the_open_blocks_selection(cx: &mut TestAppContext) {
fn a_menu_copies_the_open_blocks_selection(cx: &mut TestAppContext) {
let (desk, cx, _files) = opened("alpha beta\n", cx);
select_alpha(&desk, cx);
choose(edit_menu, 1, cx);
// Copy as Markdown, after Copy as Plain Text.
choose(edit_menu, 2, cx);
let copied = cx.read_from_clipboard().and_then(|item| item.text());
assert_eq!(copied.as_deref(), Some("alpha"));
}
+1 -1
View File
@@ -63,7 +63,7 @@ pub(super) fn press(keys: &str, cx: &mut VisualTestContext) {
}
/// The window's toasts that hold `words`.
fn toasted(desk: &Entity<Desk>, words: &str, cx: &mut VisualTestContext) -> usize {
pub(super) fn toasted(desk: &Entity<Desk>, words: &str, cx: &mut VisualTestContext) -> usize {
let root = desk.read_with(cx, |desk, _| desk.core.root.upgrade().expect("the window"));
let toasts = root.read_with(cx, |root, cx| root.toasts(cx));
toasts
+95
View File
@@ -0,0 +1,95 @@
//! Rich, HTML code and plain text copies (R4.10).
use std::path::PathBuf;
use ely_gpui_component::primitives::Severity;
use ely_office::prelude::*;
use ely_platform::clipboard::{self, Clip};
use ely_ui::i18n::text;
use gpui::{ClipboardItem, Context, Div, InteractiveElement as _, actions};
use crate::desk::Desk;
use crate::output::{self, Pictures};
actions!(mark, [CopyRich, CopyHtml, CopyPlain]);
impl Desk {
pub(super) fn copy_actions(root: Div, cx: &mut Context<Self>) -> Div {
root.on_action(cx.listener(|desk, _: &CopyRich, _, cx| desk.copy_rich(cx)))
.on_action(cx.listener(|desk, _: &CopyHtml, _, cx| desk.copy_html(cx)))
.on_action(cx.listener(|desk, _: &CopyPlain, _, cx| desk.copy_plain(cx)))
}
/// The selection or whole text, and the file's folder.
fn copied_text(&mut self, cx: &mut Context<Self>) -> Option<(String, Option<PathBuf>)> {
let Some(view) = self.active_view() else {
self.no_document(cx);
return None;
};
let document = view.read(cx).document().read(cx);
let selected = document.selected(cx);
let markdown = match selected.is_empty() {
true => document.text(cx),
false => selected,
};
let beside = (self.active_tab())
.and_then(|tab| tab.session.path())
.and_then(|path| path.parent())
.map(PathBuf::from);
Some((markdown, beside))
}
fn copy_failed(&mut self, error: &std::io::Error, cx: &mut Context<Self>) {
let said = text(cx, "mark.copy.failed", &[("error", &error.to_string())]);
self.toast(said, Severity::Danger, cx);
}
/// HTML for pasting, the Markdown beside it.
fn copy_rich(&mut self, cx: &mut Context<Self>) {
let Some((markdown, beside)) = self.copied_text(cx) else {
return;
};
let copied =
output::body(&markdown, beside.as_deref(), &Pictures::Inline).and_then(|mut page| {
let clip = Clip::Html {
html: std::mem::take(&mut page.html),
text: markdown,
};
clipboard::write(&clip)
.map(|()| page)
.map_err(|error| std::io::Error::other(format!("{error:#}")))
});
match copied {
Ok(page) => self.left_out(&page, cx),
Err(error) => self.copy_failed(&error, cx),
}
}
/// The HTML as text; pictures keep their addresses.
fn copy_html(&mut self, cx: &mut Context<Self>) {
let Some((markdown, beside)) = self.copied_text(cx) else {
return;
};
match output::body(&markdown, beside.as_deref(), &Pictures::Written) {
Ok(mut page) => {
log::info!("mark: {} bytes copied as HTML code", page.html.len());
cx.write_to_clipboard(ClipboardItem::new_string(std::mem::take(&mut page.html)));
self.left_out(&page, cx);
}
Err(error) => self.copy_failed(&error, cx),
}
}
fn copy_plain(&mut self, cx: &mut Context<Self>) {
let Some((markdown, _)) = self.copied_text(cx) else {
return;
};
match output::plain(&markdown) {
Ok(plain) => {
log::info!("mark: {} bytes copied as plain text", plain.len());
cx.write_to_clipboard(ClipboardItem::new_string(plain));
}
Err(error) => self.copy_failed(&error, cx),
}
}
}
+8 -40
View File
@@ -9,20 +9,20 @@ use ely_gpui_component::{
theme::ControlSize,
};
use ely_office::prelude::*;
use ely_platform::clipboard::{self, Clip};
use ely_ui::{
commands::{Export, Print},
i18n::text,
};
use gpui::{
AnyElement, Context, Div, InteractiveElement, IntoElement, ParentElement as _, TaskExt as _,
actions,
};
use crate::desk::Desk;
use crate::output::{self, Format, Page, Pictures, Target};
use crate::output::{self, Format, Page, Target};
actions!(mark, [CopyRich]);
mod copy;
pub use copy::{CopyHtml, CopyPlain, CopyRich};
const FORMATS: [(Format, &str, &str); 4] = [
(Format::Page, "page", "html"),
@@ -41,9 +41,10 @@ fn key(format: Format) -> &'static str {
impl Desk {
pub fn output_actions(root: Div, cx: &mut Context<Self>) -> Div {
root.on_action(cx.listener(|desk, _: &Export, _, cx| desk.ask_export(cx)))
.on_action(cx.listener(|desk, _: &Print, _, cx| desk.print(cx)))
.on_action(cx.listener(|desk, _: &CopyRich, _, cx| desk.copy_rich(cx)))
let root = root
.on_action(cx.listener(|desk, _: &Export, _, cx| desk.ask_export(cx)))
.on_action(cx.listener(|desk, _: &Print, _, cx| desk.print(cx)));
Self::copy_actions(root, cx)
}
pub(crate) fn no_document(&self, cx: &mut Context<Self>) {
@@ -275,39 +276,6 @@ impl Desk {
})
.detach_and_log_err(cx);
}
/// The selection, or the whole text, as HTML.
fn copy_rich(&mut self, cx: &mut Context<Self>) {
let Some(view) = self.active_view() else {
return self.no_document(cx);
};
let document = view.read(cx).document().clone();
let selected = document.read(cx).selected(cx);
let markdown = match selected.is_empty() {
true => document.read(cx).text(cx),
false => selected,
};
let beside = self
.active_tab()
.and_then(|tab| tab.session.path())
.and_then(|path| path.parent());
let copied = output::body(&markdown, beside, &Pictures::Inline).and_then(|mut page| {
let clip = Clip::Html {
html: std::mem::take(&mut page.html),
text: markdown,
};
clipboard::write(&clip)
.map(|()| page)
.map_err(|error| std::io::Error::other(format!("{error:#}")))
});
match copied {
Ok(page) => self.left_out(&page, cx),
Err(error) => {
let said = text(cx, "mark.copy.failed", &[("error", &error.to_string())]);
self.toast(said, Severity::Danger, cx);
}
}
}
}
/// A file of its own for each print job.
+2
View File
@@ -54,7 +54,9 @@ pub fn menus(look: &crate::look::Look, cx: &App) -> Vec<Menu> {
let item = |key: &str, action: Box<dyn Action>| item(key, action, cx);
vec![
Menu::new(text(cx, "menu.edit", &[])).items([
item("mark.copy.plain", Box::new(crate::export::CopyPlain)),
item("mark.copy.markdown", Box::new(crate::clip::CopyMarkdown)),
item("mark.copy.html", Box::new(crate::export::CopyHtml)),
item("mark.copy.rich", Box::new(crate::export::CopyRich)),
item("mark.paste.plain", Box::new(crate::clip::PastePlain)),
MenuItem::separator(),
+1 -1
View File
@@ -13,7 +13,7 @@ use std::{io, path::Path};
use ely_gpui_component::documents::markdown_options;
pub use files::{Format, Target, write};
pub use pictures::Pictures;
pub use pictures::{Pictures, picture_file};
pub use plain::plain;
/// A page and what it could not carry.
+26 -14
View File
@@ -19,6 +19,8 @@ pub enum Pictures {
Folder(PathBuf),
/// Copied into this folder, in formats MuPDF reads.
Pdf(PathBuf),
/// Addresses as the text writes them.
Written,
}
/// Picture formats MuPDF reads from files.
@@ -40,6 +42,22 @@ pub(super) struct Placed<'a> {
pub made: bool,
}
/// A picture address's file; none for other schemes.
pub fn picture_file(url: &str, beside: Option<&Path>) -> Option<PathBuf> {
if url.to_lowercase().starts_with("file://") {
return Some(file_path(&url["file://".len()..]));
}
if scheme(url).is_some() {
return None;
}
let path = PathBuf::from(decoded(url));
match (path.is_absolute(), beside) {
(true, _) => Some(path),
(false, Some(beside)) => Some(beside.join(path)),
(false, None) => None,
}
}
impl<'a> Placed<'a> {
pub fn new(beside: Option<&'a Path>, pictures: &'a Pictures) -> Self {
Self {
@@ -56,6 +74,9 @@ impl<'a> Placed<'a> {
/// The `src` for `url`; none when it is not carried.
pub fn place(&mut self, url: &str) -> io::Result<Option<String>> {
if matches!(self.pictures, Pictures::Written) {
return Ok(Some(url.to_owned()));
}
let lower = url.to_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") {
return Ok((!self.pdf()).then(|| url.to_owned()));
@@ -67,20 +88,10 @@ impl<'a> Placed<'a> {
};
return Ok(readable.then(|| url.to_owned()));
}
let path = match (lower.starts_with("file://"), scheme(url)) {
(true, _) => file_path(&url["file://".len()..]),
// Other schemes are no picture of the document's.
(false, Some(_)) => return Ok(None),
(false, None) => {
let path = PathBuf::from(decoded(url));
match (path.is_absolute(), self.beside) {
(true, _) => path,
(false, Some(beside)) => beside.join(path),
(false, None) => return Ok(None),
}
}
};
self.carried(&path)
match picture_file(url, self.beside) {
Some(path) => self.carried(&path),
None => Ok(None),
}
}
fn carried(&mut self, path: &Path) -> io::Result<Option<String>> {
@@ -98,6 +109,7 @@ impl<'a> Placed<'a> {
}
Pictures::Pdf(_) if !READABLE.contains(&extension.as_str()) => return Ok(None),
Pictures::Folder(folder) | Pictures::Pdf(folder) => folder.clone(),
Pictures::Written => unreachable!("written addresses are not carried"),
};
let named = match self.copied.iter().find(|(from, _)| from == path) {
Some((_, name)) => name.clone(),
+16 -2
View File
@@ -7,7 +7,8 @@ use ely_gpui_component::documents::{
};
use gpui::{
AppContext as _, Context, Entity, EventEmitter, FocusHandle, Focusable as _,
InteractiveElement as _, IntoElement, ParentElement as _, Render, Styled as _, Window, div,
InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Render, Styled as _,
Window, div,
};
use crate::engine::{Doc, mark};
@@ -86,6 +87,8 @@ pub struct MarkView {
pub(crate) shown: bool,
/// Trackpad pixels toward the next size step.
wheel: f32,
/// The last right-click menu asked.
offer: Option<ely_office::menu::Offer<menu::Asked>>,
pub focus: FocusHandle,
}
@@ -132,6 +135,7 @@ impl MarkView {
folder: None,
shown: false,
wheel: 0.0,
offer: None,
focus,
}
}
@@ -278,6 +282,10 @@ impl MarkView {
if let DocumentEvent::EditRefused(why) = event {
return cx.emit(Refused(*why));
}
if let DocumentEvent::Pointed(target) = event {
let at = window.mouse_position();
return self.ask_menu(menu::Asked::Text(target.clone()), at, cx);
}
if *event == DocumentEvent::Changed {
let text = document.read(cx).text(cx);
self.doc.lock().expect("the text lock").current = text;
@@ -313,7 +321,7 @@ impl MarkView {
}
impl Render for MarkView {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let view = cx.entity();
// Ctrl and the wheel size text, as Ctrl+= does.
let zoom = ely_ui::wheel::zoom_layer(move |event, window, cx| {
@@ -329,10 +337,16 @@ impl Render for MarkView {
.relative()
.size_full()
.track_focus(&self.focus)
.on_mouse_down(
MouseButton::Right,
cx.listener(|view, event, _, cx| view.pressed(event, cx)),
)
.child(self.document.clone())
.child(zoom)
.children(self.context_menu(window, cx))
}
}
mod menu;
#[cfg(test)]
mod tests;
+457
View File
@@ -0,0 +1,457 @@
//! The right-click menu, as Typora's (R4.10).
use std::rc::Rc;
use ely_gpui_component::{
documents::{DocumentTarget, TargetBlock},
menus::{ContextMenu, Menu, MenuItem},
primitives::IconName,
};
use ely_office::menu::Offer;
use ely_ui::i18n::text;
use gpui::{
Action, App, ClipboardItem, Context, Keystroke, MouseDownEvent, Pixels, Point, SharedString,
Window,
};
use super::{Failed, MarkView, Mode};
use crate::{blocks as b, clip, export, tools};
/// What a right press asked a menu for.
pub(crate) enum Asked {
/// The visual mode's target.
Text(DocumentTarget),
Source,
Preview,
}
impl MarkView {
pub(super) fn ask_menu(&mut self, asked: Asked, at: Point<Pixels>, cx: &mut Context<Self>) {
self.offer = Some(Offer::new(self.offer.as_ref(), 0, asked, at));
cx.notify();
}
/// A right press the visual blocks left alone.
pub(super) fn pressed(&mut self, event: &MouseDownEvent, cx: &mut Context<Self>) {
let asked = match self.mode {
Mode::Visual => return,
Mode::Source => Asked::Source,
Mode::Preview => Asked::Preview,
};
log::info!("mark: a right press in {}", self.mode.name());
self.ask_menu(asked, event.position, cx);
}
pub(super) fn context_menu(
&self,
window: &Window,
cx: &mut Context<Self>,
) -> Option<ContextMenu> {
let offer = self.offer.as_ref()?;
let selected = !self.document.read(cx).selected(cx).is_empty();
let menu = match &offer.what {
Asked::Text(target) => self.text_menu(target, selected, window, cx),
Asked::Source => Rows::default()
.buttons(clipboard(selected, cx))
.row(MenuItem::submenu(
said("mark.menu.copy_as", cx),
copy_as(window, cx),
))
.menu(),
Asked::Preview => copies(window, cx).into_iter().fold(Menu::new(), Menu::item),
};
Some(offer.host("mark-menu", menu))
}
/// Typora's groups, shown as the target allows.
fn text_menu(
&self,
target: &DocumentTarget,
selected: bool,
window: &Window,
cx: &mut Context<Self>,
) -> Menu {
use TargetBlock as K;
let view = cx.entity();
let block = target.block;
let is = |kinds: &[K]| block.is_some_and(|block| kinds.contains(&block));
let inline = is(&[
K::Paragraph,
K::Quote,
K::Alert,
K::List,
K::Table,
K::Footnote,
]) || matches!(block, Some(K::Heading(_)));
let mut rows = Rows::default();
if let Some(url) = &target.image {
let url = url.clone();
let key = match web(&url) {
true => "mark.image.browser",
false => "mark.image.location",
};
let view = view.clone();
rows =
rows.row(MenuItem::new(said(key, cx)).on_click(move |_, cx| {
view.update(cx, |view, cx| view.show_picture(&url, cx))
}))
.row(run(
said("mark.image.delete", cx),
Box::new(b::DeleteImage),
window,
))
.line();
}
if let Some(url) = &target.link {
let (url, view) = (url.clone(), view.clone());
rows = rows
.row(
MenuItem::new(said("mark.link.open", cx))
.on_click(move |_, cx| view.update(cx, |view, cx| view.follow(&url, cx))),
)
.line();
}
if is(&[K::Math, K::Html]) {
let (at, view) = (target.at, view.clone());
rows = rows.row(MenuItem::new(said("mark.block.edit", cx)).on_click(
move |window, cx| {
let document = view.read(cx).document.clone();
document.update(cx, |document, cx| document.show_match(at..at, window, cx));
},
));
}
rows = rows.buttons(clipboard(selected, cx));
if let Some(url) = &target.link {
rows = rows.row(copy_text(said("mark.link.copy", cx), url));
}
rows = rows.row(MenuItem::submenu(
said("mark.menu.copy_as", cx),
copy_as(window, cx),
));
if let Some(code) = &target.code {
rows = rows.row(copy_text(said("mark.code.copy", cx), code));
}
rows = rows.line();
if inline {
rows = rows.buttons(formats(window, cx));
}
if !is(&[K::Math, K::Html, K::FrontMatter]) {
rows = rows.buttons(wraps(window, cx));
}
rows = rows.line();
if target.in_table {
rows = rows.row(MenuItem::submenu(
said("mark.menu.table", cx),
table(window, cx),
));
} else if block.is_some() && !is(&[K::Math, K::Html]) {
let name = kind(block, cx);
rows = rows.row(MenuItem::submenu(name, paragraph(window, cx)));
}
rows = rows.row(MenuItem::submenu(
said("mark.menu.insert", cx),
insert(inline, window, cx),
));
if block.is_some() && !is(&[K::Paragraph]) && !matches!(block, Some(K::Heading(_))) {
let name = kind(block, cx);
let label = text(cx, "mark.block.delete", &[("block", &name)]);
rows = rows
.line()
.row(run(label, Box::new(b::DeleteBlock), window));
}
rows.menu()
}
/// Shows a local picture's file, or opens a web one.
fn show_picture(&mut self, url: &str, cx: &mut Context<Self>) {
if web(url) {
log::info!("mark: a picture opens in the browser");
return cx.open_url(url);
}
match crate::output::picture_file(url, self.folder.as_deref()) {
Some(path) if path.is_file() => cx.reveal_path(&path),
_ => {
log::info!("mark: a picture with no file here");
cx.emit(Failed(said("mark.image.no_file", cx).to_string()));
}
}
}
}
fn web(url: &str) -> bool {
let lower = url.to_lowercase();
lower.starts_with("http://") || lower.starts_with("https://")
}
fn said(key: &str, cx: &App) -> SharedString {
text(cx, key, &[])
}
/// Rows with lines only between groups.
#[derive(Default)]
struct Rows {
menu: Menu,
filled: bool,
line: bool,
}
impl Rows {
fn row(self, item: MenuItem) -> Self {
self.with(|menu| menu.item(item))
}
fn buttons(self, items: Vec<MenuItem>) -> Self {
self.with(|menu| menu.buttons(items))
}
fn with(mut self, add: impl FnOnce(Menu) -> Menu) -> Self {
if self.line && self.filled {
self.menu = self.menu.separator();
}
self.menu = add(self.menu);
(self.filled, self.line) = (true, false);
self
}
fn line(mut self) -> Self {
self.line = true;
self
}
fn menu(self) -> Menu {
self.menu
}
}
/// A row that runs `action`, its keys shown.
fn run(label: SharedString, action: Box<dyn Action>, window: &Window) -> MenuItem {
let keys = (window.highest_precedence_binding_for_action(action.as_ref())).map(|binding| {
let strokes: Vec<String> = binding.keystrokes().iter().map(|k| k.unparse()).collect();
strokes.join(" ")
});
let action: Rc<Box<dyn Action>> = Rc::new(action);
let row = MenuItem::new(label)
.on_click(move |window, cx| window.dispatch_action(action.boxed_clone(), cx));
match keys {
Some(keys) => row.keys(keys),
None => row,
}
}
/// A button that presses `stroke` where focus went back.
fn press(label: SharedString, icon: IconName, stroke: &str, shown: bool) -> MenuItem {
let keystroke = Keystroke::parse(stroke).expect("a fixed keystroke");
let button = MenuItem::new(label).icon(icon);
let button = match shown {
true => button.keys(keystroke.unparse()),
false => button,
};
button.on_click(move |window, cx| {
let keystroke = keystroke.clone();
window.defer(cx, move |window, cx| {
window.dispatch_keystroke(keystroke, cx);
});
})
}
fn clipboard(selected: bool, cx: &App) -> Vec<MenuItem> {
vec![
press(
said("mark.edit.cut", cx),
IconName::Scissors,
"secondary-x",
true,
)
.disabled(!selected),
press(
said("mark.edit.copy", cx),
IconName::Copy,
"secondary-c",
true,
)
.disabled(!selected),
press(
said("mark.edit.paste", cx),
IconName::Clipboard,
"secondary-v",
true,
),
press(
said("mark.edit.delete", cx),
IconName::Trash2,
"backspace",
false,
)
.disabled(!selected),
]
}
fn copy_text(label: SharedString, copied: &str) -> MenuItem {
let copied = copied.to_string();
MenuItem::new(label).on_click(move |_, cx| {
log::info!("mark: {} bytes copied from the menu", copied.len());
cx.write_to_clipboard(ClipboardItem::new_string(copied.clone()));
})
}
/// Typora's Copy / Paste As rows.
fn copies(window: &Window, cx: &App) -> Vec<MenuItem> {
vec![
run(
said("mark.copy.plain", cx),
Box::new(export::CopyPlain),
window,
),
run(
said("mark.copy.markdown", cx),
Box::new(clip::CopyMarkdown),
window,
),
run(
said("mark.copy.html", cx),
Box::new(export::CopyHtml),
window,
),
run(
said("mark.copy.rich", cx),
Box::new(export::CopyRich),
window,
),
]
}
fn copy_as(window: &Window, cx: &App) -> Menu {
let paste = run(
said("mark.paste.plain", cx),
Box::new(clip::PastePlain),
window,
);
copies(window, cx)
.into_iter()
.fold(Menu::new(), Menu::item)
.separator()
.item(paste)
}
fn formats(window: &Window, cx: &App) -> Vec<MenuItem> {
let row = |key, action: Box<dyn Action>, name| run(said(key, cx), action, window).icon(name);
vec![
row("mark.format.strong", Box::new(b::Strong), IconName::Bold),
row(
"mark.format.emphasis",
Box::new(b::Emphasis),
IconName::Italic,
),
row("mark.format.code", Box::new(b::InlineCode), IconName::Code),
row("mark.format.link", Box::new(b::Hyperlink), IconName::Link),
]
}
fn wraps(window: &Window, cx: &App) -> Vec<MenuItem> {
let row = |key, action: Box<dyn Action>, name| run(said(key, cx), action, window).icon(name);
vec![
row("mark.block.quote", Box::new(b::Quote), IconName::Quote),
row(
"mark.block.ordered",
Box::new(b::OrderedList),
IconName::ListOrdered,
),
row("mark.block.bullet", Box::new(b::BulletList), IconName::List),
row(
"mark.block.task",
Box::new(b::TaskList),
IconName::ListChecks,
),
]
}
fn paragraph(window: &Window, cx: &App) -> Menu {
let row = |key, action: Box<dyn Action>| run(said(key, cx), action, window);
Menu::new()
.item(row("mark.block.h1", Box::new(b::Heading1)))
.item(row("mark.block.h2", Box::new(b::Heading2)))
.item(row("mark.block.h3", Box::new(b::Heading3)))
.item(row("mark.block.h4", Box::new(b::Heading4)))
.item(row("mark.block.h5", Box::new(b::Heading5)))
.item(row("mark.block.h6", Box::new(b::Heading6)))
.separator()
.item(row("mark.block.paragraph", Box::new(b::Paragraph)))
}
fn table(window: &Window, cx: &App) -> Menu {
let row = |key, action: Box<dyn Action>| run(said(key, cx), action, window);
Menu::new()
.item(row("mark.table.row_above", Box::new(tools::RowAbove)))
.item(row("mark.table.row_below", Box::new(tools::RowBelow)))
.item(row("mark.table.column_left", Box::new(tools::ColumnLeft)))
.item(row("mark.table.column_right", Box::new(tools::ColumnRight)))
.separator()
.item(row("mark.table.move_row_up", Box::new(tools::MoveRowUp)))
.item(row(
"mark.table.move_row_down",
Box::new(tools::MoveRowDown),
))
.item(row(
"mark.table.move_column_left",
Box::new(tools::MoveColumnLeft),
))
.item(row(
"mark.table.move_column_right",
Box::new(tools::MoveColumnRight),
))
.separator()
.item(row("mark.table.delete_row", Box::new(tools::DeleteRow)))
.item(row(
"mark.table.delete_column",
Box::new(tools::DeleteColumn),
))
.separator()
.item(row("mark.table.tidy", Box::new(tools::TidyTable)))
.separator()
.item(row("mark.table.delete", Box::new(tools::DeleteTable)))
}
fn insert(inline: bool, window: &Window, cx: &App) -> Menu {
let row = |key, action: Box<dyn Action>| run(said(key, cx), action, window);
let menu = match inline {
true => Menu::new()
.item(row("mark.insert.image", Box::new(b::InsertImage)))
.separator(),
false => Menu::new(),
};
menu.item(row("mark.block.footnote", Box::new(b::Footnote)))
.item(row("mark.block.link_reference", Box::new(b::LinkReference)))
.item(row("mark.block.rule", Box::new(b::Rule)))
.item(row("mark.menu.table", Box::new(tools::InsertTable)))
.item(row("mark.block.code", Box::new(b::CodeFences)))
.item(row("mark.block.math", Box::new(b::MathBlock)))
.item(row("mark.block.toc", Box::new(b::Toc)))
.item(row("mark.block.front_matter", Box::new(b::FrontMatter)))
.separator()
.item(row("mark.insert.before", Box::new(b::ParagraphBefore)))
.item(row("mark.insert.after", Box::new(b::ParagraphAfter)))
}
/// A block kind's name, as Typora's menus say it.
fn kind(block: Option<TargetBlock>, cx: &App) -> SharedString {
use TargetBlock as K;
let key = match block {
None | Some(K::Paragraph) => "mark.block.paragraph",
Some(K::Heading(level)) => {
return said(&format!("mark.block.h{}", level.clamp(1, 6)), cx);
}
Some(K::Quote) => "mark.block.quote",
Some(K::Alert) => "mark.kind.alert",
Some(K::List) => "mark.kind.list",
Some(K::Code) => "mark.block.code",
Some(K::Math) => "mark.block.math",
Some(K::Table) => "mark.menu.table",
Some(K::Rule) => "mark.block.rule",
Some(K::Html) => "mark.kind.html",
Some(K::Footnote) => "mark.block.footnote",
Some(K::Definition) => "mark.block.link_reference",
Some(K::FrontMatter) => "mark.block.front_matter",
Some(K::Toc) => "mark.block.toc",
};
said(key, cx)
}