diff --git a/crates/formats/src/html.rs b/crates/formats/src/html.rs index 493d1b42..d382ecea 100644 --- a/crates/formats/src/html.rs +++ b/crates/formats/src/html.rs @@ -257,6 +257,18 @@ fn attr(attrs: &str, key: &str) -> Option { attrs.get(start..start + end).map(unescape) } +fn font_size(attrs: &str) -> Option { + let style = attr(attrs, "style")?; + style.split(';').find_map(|declaration| { + let (property, value) = declaration.split_once(':')?; + if !property.trim().eq_ignore_ascii_case("font-size") { + return None; + } + let points = value.trim().strip_suffix("pt")?.trim().parse::().ok()?; + (8..=72).contains(&points).then_some(points) + }) +} + #[derive(Default)] struct Writer { out: String, @@ -267,6 +279,7 @@ struct Writer { div_diagram: bool, in_math: bool, in_math_block: bool, + span_sizes: Vec>, href: Vec>, row: Option>, cell: String, @@ -465,8 +478,23 @@ impl Writer { self.out.push_str("```"); self.block_break(); } - ("span", false) if attrs.to_lowercase().contains("math") => self.in_math = true, - ("span", true) => self.in_math = false, + ("span", false) => { + let size = font_size(attrs); + self.span_sizes.push(size); + if let Some(size) = size { + self.push(&format!("")); + } + if attrs.to_lowercase().contains("math") { + self.in_math = true; + } + } + ("span", true) => { + if self.span_sizes.pop().flatten().is_some() { + self.push(""); + } else { + self.in_math = false; + } + } ("a", false) => { let href = attr(attrs, "href"); self.push("["); diff --git a/crates/formats/src/markdown.rs b/crates/formats/src/markdown.rs index 7365c952..a5b97ce8 100644 --- a/crates/formats/src/markdown.rs +++ b/crates/formats/src/markdown.rs @@ -4,8 +4,9 @@ //! (nested by indentation), block quotes, fenced code (a `mermaid` fence is kept as //! code with its language), math blocks (`$$ ... $$`), tables, rules and standalone //! images. Supported inline: bold, italic, strikethrough, code, links, images and -//! `$math$`. Not supported: reference links, HTML inside Markdown, nested block -//! quotes and lists inside quotes, setext headings, footnotes. +//! `$math$`, and NoteCraft font-size spans. Other HTML is not supported. Also not +//! supported: reference links, nested block quotes and lists inside quotes, setext +//! headings, footnotes. #[derive(Clone, Debug, Default, PartialEq)] pub struct Span { @@ -15,6 +16,8 @@ pub struct Span { pub strike: bool, pub code: bool, pub math: bool, + /// Font size in points, carried by a NoteCraft inline ``. + pub font_size: Option, /// Link target, if this span is part of a link. pub link: Option, /// Image source, if this span is an inline image (the text is the alt text). @@ -53,6 +56,7 @@ struct Style { bold: bool, italic: bool, strike: bool, + font_size: Option, } /// Parses inline Markdown into styled spans. @@ -76,10 +80,61 @@ fn slice(chars: &[char], a: usize, b: usize) -> &[char] { fn push_text(out: &mut Vec, buf: &mut String, st: Style, link: &Option) { if !buf.is_empty() { - out.push(Span { text: std::mem::take(buf), bold: st.bold, italic: st.italic, strike: st.strike, link: link.clone(), ..Span::default() }); + out.push(Span { + text: std::mem::take(buf), + bold: st.bold, + italic: st.italic, + strike: st.strike, + font_size: st.font_size, + link: link.clone(), + ..Span::default() + }); } } +fn span_open_end(chars: &[char], start: usize) -> Option { + let remaining = chars.get(start..)?; + let end = remaining.iter().position(|c| *c == '>')?; + let tag: String = remaining.get(..=end)?.iter().collect(); + tag.to_ascii_lowercase().starts_with(" Option<(u8, usize)> { + let end = span_open_end(chars, start)?; + let tag: String = chars.get(start..end)?.iter().collect(); + let lower = tag.to_ascii_lowercase(); + let style_start = lower.find("style=\"")? + "style=\"".len(); + let style_end = lower.get(style_start..)?.find('"')? + style_start; + let style = lower.get(style_start..style_end)?; + let value = style.split(';').find_map(|declaration| { + let (property, value) = declaration.split_once(':')?; + property.trim().eq("font-size").then(|| value.trim()) + })?; + let points = value.strip_suffix("pt")?.parse::().ok()?; + (8..=72).contains(&points).then_some((points, end)) +} + +fn font_size_close(chars: &[char], start: usize) -> Option { + let close = ['<', '/', 's', 'p', 'a', 'n', '>']; + let mut depth = 1usize; + let mut at = start; + while at < chars.len() { + if chars.get(at..at + close.len()) == Some(close.as_slice()) { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(at); + } + at += close.len(); + } else if let Some(after) = span_open_end(chars, at) { + depth += 1; + at = after; + } else { + at += 1; + } + } + None +} + fn inline(chars: &[char], st: Style, link: Option, depth: usize) -> Vec { let mut out = Vec::new(); let mut buf = String::new(); @@ -87,6 +142,18 @@ fn inline(chars: &[char], st: Style, link: Option, depth: usize) -> Vec< while i < chars.len() { let c = chars.get(i).copied().unwrap_or(' '); let next = chars.get(i + 1).copied(); + if c == '<' + && depth < MAX_DEPTH + && let Some((font_size, content_start)) = font_size_open(chars, i) + && let Some(content_end) = font_size_close(chars, content_start) + { + push_text(&mut out, &mut buf, st, &link); + let mut sized = st; + sized.font_size = Some(font_size); + out.extend(inline(slice(chars, content_start, content_end), sized, link.clone(), depth + 1)); + i = content_end + "".chars().count(); + continue; + } match c { '\\' if next.is_some() => { if let Some(n) = next { @@ -104,6 +171,7 @@ fn inline(chars: &[char], st: Style, link: Option, depth: usize) -> Vec< bold: st.bold, italic: st.italic, strike: st.strike, + font_size: st.font_size, link: link.clone(), ..Span::default() }); @@ -162,7 +230,13 @@ fn inline(chars: &[char], st: Style, link: Option, depth: usize) -> Vec< '$' => match find(chars, i + 1, &['$']) { Some(end) if end > i + 1 && !slice(chars, i + 1, end).contains(&'\n') => { push_text(&mut out, &mut buf, st, &link); - out.push(Span { text: slice(chars, i + 1, end).iter().collect(), math: true, link: link.clone(), ..Span::default() }); + out.push(Span { + text: slice(chars, i + 1, end).iter().collect(), + math: true, + font_size: st.font_size, + link: link.clone(), + ..Span::default() + }); i = end + 1; } _ => { @@ -175,7 +249,7 @@ fn inline(chars: &[char], st: Style, link: Option, depth: usize) -> Vec< push_text(&mut out, &mut buf, st, &link); // Preserve the surrounding link when an image is nested in one. This is // how attachment cards (`[![icon](icon) name](file)`) retain their target. - out.push(Span { text: alt, image: Some(url), link: link.clone(), ..Span::default() }); + out.push(Span { text: alt, image: Some(url), font_size: st.font_size, link: link.clone(), ..Span::default() }); i = after; } None => { @@ -415,6 +489,20 @@ mod tests { assert!(s.iter().any(|x| x.bold && x.italic && x.text == "italic")); } + #[test] + fn font_size_spans_round_trip_and_nest() { + let source = "outer inner outer"; + let spans = parse_inline(source); + assert!(spans.iter().any(|span| span.text == "outer " && span.font_size == Some(18))); + assert!(spans.iter().any(|span| span.text == "inner" && span.font_size == Some(12))); + assert!(spans.iter().any(|span| span.text == " outer" && span.font_size == Some(18))); + assert_eq!(parse_inline(&crate::render::spans_to_markdown(&spans)), spans); + + let invalid = parse_inline("too large"); + assert_eq!(text_of(&invalid), "too large"); + assert!(invalid.iter().all(|span| span.font_size.is_none())); + } + #[test] fn links_images_and_math() { let s = parse_inline("see [the **site**](https://x.test) and ![pic](assets/a.png) with $E=mc^2$"); diff --git a/crates/formats/src/render.rs b/crates/formats/src/render.rs index 082327d8..d85822e2 100644 --- a/crates/formats/src/render.rs +++ b/crates/formats/src/render.rs @@ -214,21 +214,27 @@ fn marked(spans: &[Span], level: usize) -> String { /// One span with nothing but its code, picture, maths or link written round it. fn leaf(s: &Span) -> String { + let sized = |text: String| match s.font_size { + Some(size) => format!("{text}"), + None => text, + }; if let Some(src) = &s.image { let image = format!("![{}]({src})", s.text); - return match &s.link { + let image = match &s.link { Some(target) => format!("[{image}]({target})"), None => image, }; + return sized(image); } if s.math { - return format!("${}$", s.text); + return sized(format!("${}$", s.text)); } let text = if s.code { format!("`{}`", s.text) } else { s.text.clone() }; - match &s.link { + let text = match &s.link { Some(target) => format!("[{text}]({target})"), None => text, - } + }; + sized(text) } /// Blocks as the HTML body of a page: the inside of ``, one block per line. @@ -324,7 +330,10 @@ pub fn spans_to_html(spans: &[Span]) -> String { let mut out = String::new(); for s in spans { if let Some(src) = &s.image { - let image = format!("\"{}\"", escape(src), escape(&s.text)); + let mut image = format!("\"{}\"", escape(src), escape(&s.text)); + if let Some(size) = s.font_size { + image = format!("{image}"); + } match &s.link { Some(target) => out.push_str(&format!("{image}", escape(target))), None => out.push_str(&image), @@ -332,7 +341,11 @@ pub fn spans_to_html(spans: &[Span]) -> String { continue; } if s.math { - out.push_str(&format!("${}$", escape(&s.text))); + let mut math = format!("${}$", escape(&s.text)); + if let Some(size) = s.font_size { + math = format!("{math}"); + } + out.push_str(&math); continue; } let mut text = escape(&s.text); @@ -349,10 +362,15 @@ pub fn spans_to_html(spans: &[Span]) -> String { text = format!("{text}"); } } - match &s.link { - Some(target) => out.push_str(&format!("{text}", escape(target))), - None => out.push_str(&text), - } + let text = match &s.link { + Some(target) => format!("{text}", escape(target)), + None => text, + }; + let text = match s.font_size { + Some(size) => format!("{text}"), + None => text, + }; + out.push_str(&text); } out } @@ -533,4 +551,17 @@ fn b() {}" assert!(html.contains("bold"), "{html}"); assert!(html.contains("a link"), "{html}"); } + + #[test] + fn inline_font_size_round_trips_through_cmgfm_and_html() { + let source = "larger text"; + let blocks = parse(source); + + let markdown = blocks_to_markdown(&blocks); + assert_eq!(parse(&markdown), blocks, "CMGFM retains the size"); + + let html = blocks_to_html(&blocks); + assert!(html.contains("larger text"), "{html}"); + assert_eq!(parse(&html::to_markdown(&html)), blocks, "HTML retains the size"); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a27c2c37..64e1cd26 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -2745,6 +2745,7 @@ impl NoteCraftApp { act, ribbon::Act::Clipboard(_) | ribbon::Act::Mark(_) + | ribbon::Act::FontSize(_) | ribbon::Act::Block(_) | ribbon::Act::ClearFormatting | ribbon::Act::Direction(_) @@ -2763,6 +2764,11 @@ impl NoteCraftApp { crate::containers::ask_clipboard(ctx, *which == "cut"); return true; } + ribbon::Act::FontSize(_) => { + self.status = crate::tl_id!("ui.select_text_before_changing_font_size").into(); + self.status_is_error = false; + return true; + } ribbon::Act::Mark(mark) => { if !pageedit::toggle_mark(&mut ed.blocks, range, mark) { return true; @@ -2855,6 +2861,7 @@ impl NoteCraftApp { ribbon::Act::Equation(tex) => self.insert_in_page(&format!("${tex}$")), ribbon::Act::Tab(name) => self.ribbon_tab = name, ribbon::Act::Mark(mark) => self.apply_mark(mark), + ribbon::Act::FontSize(size) => self.apply_font_size(size), ribbon::Act::Block(kind) => self.apply_block_kind(kind), ribbon::Act::Insert(what) => match what { "space" => { @@ -3621,6 +3628,33 @@ impl NoteCraftApp { Self::mark_dirty_from_blocks(ed); } + fn apply_font_size(&mut self, size: u8) { + if !ribbon::FONT_SIZES.contains(&size) { + log::warn!("ribbon requested unsupported font size {size} pt"); + return; + } + let Some(ed) = self.editor.as_mut() else { return }; + let Some(caret) = ed.caret.as_mut() else { + self.status = crate::tl_id!("ui.click_in_the_page_first_then_use_the_ribbon").into(); + self.status_is_error = false; + return; + }; + if caret.selection.0 == caret.selection.1 { + self.status = crate::tl_id!("ui.select_text_before_changing_font_size").into(); + self.status_is_error = false; + return; + } + let open = format!(""); + let (text, selection) = pageedit::wrap_selection_with(&caret.text, caret.selection, &open, ""); + caret.text = text; + caret.selection = selection; + if let Some(block) = ed.blocks.get_mut(caret.block) { + pageedit::set_block_text(block, &caret.text); + } + ed.rebuild_body(); + Self::mark_dirty_from_blocks(ed); + } + /// The keys Windows users expect for paragraph direction. Alt+Shift remains available /// to Windows for switching the active input language. fn direction_keys(&mut self, ctx: &Context) { diff --git a/crates/ui-egui/src/pageedit.rs b/crates/ui-egui/src/pageedit.rs index 417e6efb..270a23b9 100644 --- a/crates/ui-egui/src/pageedit.rs +++ b/crates/ui-egui/src/pageedit.rs @@ -229,6 +229,20 @@ pub fn wrap_selection(text: &str, selection: (usize, usize), marks: &str) -> (St (format!("{before}{marks}{middle}{marks}{after}"), (a + n, a + n + len)) } +/// Wraps the selected characters with a pair of different delimiters and keeps them selected. +pub fn wrap_selection_with(text: &str, selection: (usize, usize), open: &str, close: &str) -> (String, (usize, usize)) { + let chars: Vec = text.chars().collect(); + let (a, b) = (selection.0.min(selection.1).min(chars.len()), selection.0.max(selection.1).min(chars.len())); + let (before, middle, after): (String, String, String) = ( + chars.get(..a).unwrap_or(&[]).iter().collect(), + chars.get(a..b).unwrap_or(&[]).iter().collect(), + chars.get(b..).unwrap_or(&[]).iter().collect(), + ); + let start = a + open.chars().count(); + let end = start + middle.chars().count(); + (format!("{before}{open}{middle}{close}{after}"), (start, end)) +} + /// Puts `insert` where the caret is, replacing whatever is selected. Returns the new text /// and where the caret ends up. pub fn insert_at_caret(text: &str, selection: (usize, usize), insert: &str) -> (String, usize) { @@ -3130,6 +3144,14 @@ A note to self. assert_eq!(text, "**\u{4e2d}\u{6587}**x"); } + #[test] + fn a_size_wrapper_keeps_its_unicode_selection() { + let open = ""; + let (text, selection) = wrap_selection_with("aمرحبا z", (6, 1), open, ""); + assert_eq!(text, format!("a{open}مرحبا z")); + assert_eq!(text.chars().skip(selection.0).take(selection.1 - selection.0).collect::(), "مرحبا"); + } + /// The two code styles are one block with its lines numbered or not; changing between them keeps the words and the language. #[test] fn code_changes_between_plain_and_numbered_and_keeps_its_words() { diff --git a/crates/ui-egui/src/pagetext.rs b/crates/ui-egui/src/pagetext.rs index ea19497d..d5069a1c 100644 --- a/crates/ui-egui/src/pagetext.rs +++ b/crates/ui-egui/src/pagetext.rs @@ -162,6 +162,18 @@ fn inline(text: &str, from: usize, to: usize, out: &mut Vec<(std::ops::Range').map(|n| n + 1); + if rest.starts_with("") { + out.push((from + i..from + i + "".len(), Style::Marker)); + i += "".len(); + continue; + } // The marks themselves are dimmed and the words inside them carry the style, so the // text reads as formatted text with the marks out of the way. let emphasis = |mark: &str, style: Style, out: &mut Vec<(std::ops::Range, Style)>| -> Option { @@ -229,6 +241,44 @@ fn link_len(s: &str) -> Option { if s.get(..end)?.contains('\n') { None } else { Some(end) } } +fn tag_font_size(tag: &str) -> Option { + let lower = tag.to_ascii_lowercase(); + if !lower.starts_with("().ok()?; + (8..=72).contains(&points).then_some(points) + }) +} + +fn font_size_ranges(text: &str) -> Vec<(std::ops::Range, u8)> { + let mut out = Vec::new(); + let mut spans: Vec> = Vec::new(); + let mut at = 0usize; + while let Some(start) = text.get(at..).and_then(|rest| rest.find('<')).map(|n| at + n) { + let Some(end) = text.get(start..).and_then(|rest| rest.find('>')).map(|n| start + n + 1) else { + break; + }; + let tag = text.get(start..end).unwrap_or(""); + if tag.eq_ignore_ascii_case("") { + if let Some((size, content_start)) = spans.pop().flatten() { + out.push((content_start..start, size)); + } + } else if tag.to_ascii_lowercase().starts_with(", Style)>) { let bytes = text.as_bytes(); @@ -287,9 +337,28 @@ pub fn inline_job(text: &str, base: f32, strong: bool, t: &Tokens, wrap_width: f halign: halign(text, page), ..Default::default() }; + let font_sizes = font_size_ranges(text); for (range, style) in inline_pieces(text) { - if let Some(part) = text.get(range) { + let mut boundaries = vec![range.start, range.end]; + for (size_range, _) in &font_sizes { + if size_range.start > range.start && size_range.start < range.end { + boundaries.push(size_range.start); + } + if size_range.end > range.start && size_range.end < range.end { + boundaries.push(size_range.end); + } + } + boundaries.sort_unstable(); + boundaries.dedup(); + for pair in boundaries.windows(2) { + let (Some(start), Some(end)) = (pair.first(), pair.get(1)) else { continue }; + let Some(part) = text.get(*start..*end) else { continue }; + let font_size = + font_sizes.iter().filter(|(r, _)| r.start <= *start && r.end >= *end).min_by_key(|(r, _)| r.end - r.start).map(|(_, size)| *size); let mut format = style.format(base, t); + if let Some(points) = font_size { + format.font_id.size = base * f32::from(points) / 11.0; + } if strong && style == Style::Body { format.color = t.strong; } @@ -390,6 +459,15 @@ mod tests { covers(PageFormat::Cmgfm, text); } + #[test] + fn a_font_size_span_changes_the_editor_text_size() { + let text = "large"; + let tokens = crate::theme::Theme::DEFAULT.tokens(); + let job = inline_job(text, 11.0, false, &tokens, 1000.0, Some(notecraft_model::Dir::Ltr)); + let section = job.sections.iter().find(|section| section.format.font_id.size > 11.0).expect("sized text section"); + assert_eq!(section.format.font_id.size, 18.0); + } + /// A tag marker is syntax: dimmed, with the words after it reading normally. #[test] fn a_tag_marker_is_dimmed() { diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 5f5515a5..4fd78f21 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -84,6 +84,7 @@ fn pieces(spans: &[Span], size: f32, color: egui::Color32, tokens: &Tokens) -> V /// How one span is drawn. fn format_of(s: &Span, size: f32, color: egui::Color32, tokens: &Tokens) -> TextFormat { let mono = s.code || s.math; + let size = s.font_size.map_or(size, |points| size * f32::from(points) / 11.0); let c = if s.link.is_some() { tokens.link } else if s.bold { @@ -110,6 +111,7 @@ pub fn job(ui: &Ui, spans: &[Span], size: f32, color: egui::Color32, tokens: &To continue; } let mono = s.code || s.math; + let size = s.font_size.map_or(size, |points| size * f32::from(points) / 11.0); let c = if s.link.is_some() { tokens.link } else if s.bold { @@ -810,6 +812,14 @@ fn with_tag(ui: &mut Ui, tag: notecraft_model::Tag, tokens: &Tokens, body: impl mod tests { use super::*; + #[test] + fn inline_font_size_scales_the_span_without_changing_the_base_size() { + let tokens = crate::theme::Theme::DEFAULT.tokens(); + let span = Span { text: "larger".into(), font_size: Some(18), ..Span::default() }; + let format = format_of(&span, 11.0, tokens.text, &tokens); + assert_eq!(format.font_id.size, 18.0); + } + #[test] fn a_blank_line_is_a_line_tall_so_it_can_be_clicked() { use notecraft_formats::markdown::Block; diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 2aff9a39..1d01d2f2 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -18,6 +18,7 @@ use notecraft_model::{PageFormat, Tag}; /// shows a tab for what is selected. pub const TABS: [&str; 5] = ["Home", "Insert", "Draw", "History", "View"]; pub const SOURCE_TAB: &str = "Source"; +pub const FONT_SIZES: [u8; 14] = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36, 48, 72]; /// Shown only while the caret is in a table, the way Office shows a tab for the thing in /// hand. It goes when the caret leaves, and the ribbon falls back to Home. pub const TABLE_TAB: &str = "Table"; @@ -35,6 +36,8 @@ pub enum Act { Symbols, /// Put marks around the selection, or at the caret: bold, italic, strikethrough, code. Mark(&'static str), + /// Apply a point size to the selected text. + FontSize(u8), /// Make the block under the caret this kind: `p`, `h1`, `h2`, `h3`, `quote`, `bullet`, /// `number`, `todo`. Block(&'static str), @@ -829,6 +832,14 @@ fn home_tab(ui: &mut Ui, view: &View<'_>, t: &Tokens, acts: &mut Vec) { group(ui, crate::tl_id!("ui.basic_text"), t, |ui| { rows(ui, |ui| { ui.horizontal(|ui| { + ui.menu_button(crate::tl_id!("ui.font_size"), |ui| { + for size in FONT_SIZES { + if ui.button(format!("{size} pt")).clicked() { + acts.push(Act::FontSize(size)); + ui.close(); + } + } + }); if mark_button(ui, Mark::Bold, crate::tl_id!("ui.bold"), crate::tl_id!("ui.bold_ctrl_b"), false, t).clicked() { acts.push(Act::Mark("bold")); } diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 31bbc1f1..be38b8b3 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -5409,6 +5409,51 @@ fn bold_and_italic_toggle_over_a_line_that_is_partly_marked() { } } +#[test] +fn font_size_applies_to_selected_text_and_survives_reopen_in_both_formats() { + let (_t, app, s) = sample_app("ui-font-size"); + let mut h = sized_harness(app, LIGHT, egui::vec2(2000.0, 900.0)); + + h.state_mut().open_path(&s.md_page.to_string_lossy()); + settle(&mut h); + ask(&mut h, "ui.caret", json!({"block": 1})).expect("caret"); + let unchanged = h.state().body().unwrap_or_default().to_string(); + h.get_by_label("Font Size").click(); + h.run(); + h.get_by_label("18 pt").click(); + settle(&mut h); + let status = + ask(&mut h, "ui.inspect", json!({})).expect("inspect").pointer("/status/text").and_then(Value::as_str).unwrap_or_default().to_string(); + assert!(status.contains("Select text"), "the UI explains that a selection is required: {status}"); + assert_eq!(h.state().body().unwrap_or_default(), unchanged, "a size is not applied at an empty selection"); + + for page in [&s.md_page, &s.html_page] { + let path = page.to_string_lossy().to_string(); + h.state_mut().open_path(&path); + settle(&mut h); + let original = h.state().body().unwrap_or_default().to_string(); + let (selected_text, following_block) = + if original.contains("Kickoff notes") { ("Kickoff notes", "Goals") } else { ("plain files", "Why folders?") }; + ask(&mut h, "ui.caret", json!({"block": 1})).expect("caret"); + ask(&mut h, "ui.key", json!({"key": "A", "ctrl": true})).expect("select block text"); + pump(&mut h); + + h.get_by_label("Font Size").click(); + h.run(); + h.get_by_label("18 pt").click(); + settle(&mut h); + + let body = h.state().body().unwrap_or_default().to_string(); + assert!(body.contains(""), "selected text has a saved font size:\n{body}"); + assert!(body.contains(selected_text) && body.contains(following_block), "the selected text and a following block remain present:\n{body}"); + assert!(!body.contains(&format!("font-size: 18pt\">{following_block}")), "font size stays on the selected block:\n{body}"); + h.state_mut().save(); + h.state_mut().open_path(&path); + settle(&mut h); + assert_eq!(h.state().body().unwrap_or_default().trim_end(), body.trim_end(), "the font size survives save and reopen"); + } +} + /// A code block is drawn the same whether or not the caret is in it: same box, same place for the words. #[test] fn a_code_block_looks_the_same_when_the_caret_arrives() { diff --git a/docs/dom_serialization/page-model.md b/docs/dom_serialization/page-model.md index 9f860498..8e81a453 100644 --- a/docs/dom_serialization/page-model.md +++ b/docs/dom_serialization/page-model.md @@ -53,7 +53,7 @@ rules below; they must not become hidden editor-only state. | `MathBlock` | `$$` display-math fence | `p.math` | | `Table` | GFM table | `table`, rows, header and data cells | | `Image` and inline image `Span` | Markdown image/link syntax | `img` with `src` and `alt` | -| Inline `Span` marks and links | Emphasis, code, strike, math and link syntax | `b`, `i`, `s`, `code`, `span.math`, `a` | +| Inline `Span` marks, links and font size | Emphasis, code, strike, math and links; font size uses `` | `b`, `i`, `s`, `code`, `span.math`, `a`, and a `span` with `font-size` | | `Container` layout | `div.nc-box` with `data-x`, `data-y`, `data-width` | `div.nc-box` with the same data attributes and browser positioning style | The writers are `render::blocks_to_markdown` / `spans_to_markdown` (CMGFM) and diff --git a/docs/folder-format.md b/docs/folder-format.md index c514b605..9b3675dd 100644 --- a/docs/folder-format.md +++ b/docs/folder-format.md @@ -136,8 +136,10 @@ tags: [] - Supported Markdown: headings, paragraphs, bullet, numbered and task lists (nested by indentation), block quotes, fenced code, tables, rules, images, bold, italic, strikethrough, inline code, links. Equations are `$...$` and `$$ ... $$` (TeX). A fenced - block with the language `mermaid` is a diagram. This is a subset of CommonMark and GFM, - not a full implementation. See `crates/formats/src/markdown.rs` for the exact list. + block with the language `mermaid` is a diagram. Font size uses the inline + `text` form, where N is 8 through 72. This is a + subset of CommonMark and GFM, not a full implementation. See `crates/formats/src/markdown.rs` + for the exact list. ### 3.3 Metadata keys diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index 93e43e5a..5a4ae335 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook [[RLI]]$$$Back to the notebook@@@[[PDI]] @id ui.back_to_the_page_before_alt_left [[RLI]]$$$Back to the page before (Alt+Left)@@@[[PDI]] @id ui.basic_text [[RLI]]$$$Basic Text@@@[[PDI]] +@id ui.font_size [[RLI]]$$$Font Size@@@[[PDI]] +@id ui.select_text_before_changing_font_size [[RLI]]$$$Select text before changing font size.@@@[[PDI]] @id ui.black [[RLI]]$$$black@@@[[PDI]] @id ui.blue [[RLI]]$$$blue@@@[[PDI]] @id ui.blue_2 [[RLI]]$$$Blue@@@[[PDI]] diff --git a/i18n/ar.tsv b/i18n/ar.tsv index 55e21040..5e7c9e18 100644 --- a/i18n/ar.tsv +++ b/i18n/ar.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook العودة إلى الدفتر @id ui.back_to_the_page_before_alt_left العودة إلى الصفحة السابقة (Alt+Left) @id ui.basic_text نص أساسي +@id ui.font_size حجم الخط +@id ui.select_text_before_changing_font_size حدد نصًا قبل تغيير حجم الخط. @id ui.black أسود @id ui.blue أزرق @id ui.blue_2 أزرق diff --git a/i18n/de.tsv b/i18n/de.tsv index 63e8fc9c..1be47428 100644 --- a/i18n/de.tsv +++ b/i18n/de.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook Zurück zum Notizbuch @id ui.back_to_the_page_before_alt_left Zurück zur vorherigen Seite (Alt+Links) @id ui.basic_text Basis-Text +@id ui.font_size Schriftgröße +@id ui.select_text_before_changing_font_size Markieren Sie Text, bevor Sie die Schriftgröße ändern. @id ui.black Schwarz @id ui.blue Blau @id ui.blue_2 Blau diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index 5ed8d142..61c04135 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook $$$Back to the notebook@@@ @id ui.back_to_the_page_before_alt_left $$$Back to the page before (Alt+Left)@@@ @id ui.basic_text $$$Basic Text@@@ +@id ui.font_size $$$Font Size@@@ +@id ui.select_text_before_changing_font_size $$$Select text before changing font size.@@@ @id ui.black $$$black@@@ @id ui.blue $$$blue@@@ @id ui.blue_2 $$$Blue@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index a4a2a78e..6b2a2654 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook Back to the notebook @id ui.back_to_the_page_before_alt_left Back to the page before (Alt+Left) @id ui.basic_text Basic Text +@id ui.font_size Font Size +@id ui.select_text_before_changing_font_size Select text before changing font size. @id ui.black black @id ui.blue blue @id ui.blue_2 Blue diff --git a/i18n/es.tsv b/i18n/es.tsv index 37a37350..751e5258 100644 --- a/i18n/es.tsv +++ b/i18n/es.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook Volver al cuaderno @id ui.back_to_the_page_before_alt_left Back to the page before (Alt+Left) @id ui.basic_text Texto básico +@id ui.font_size Tamaño de fuente +@id ui.select_text_before_changing_font_size Selecciona texto antes de cambiar el tamaño de fuente. @id ui.black black @id ui.blue blue @id ui.blue_2 Azul diff --git a/i18n/fa.tsv b/i18n/fa.tsv index a8c9d072..7a23657e 100644 --- a/i18n/fa.tsv +++ b/i18n/fa.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook بازگشت به دفترچه یادداشت @id ui.back_to_the_page_before_alt_left بازگشت به صفحه قبل (Alt+Left) @id ui.basic_text متن ساده +@id ui.font_size اندازه قلم +@id ui.select_text_before_changing_font_size پیش از تغییر اندازه قلم، متنی را انتخاب کنید. @id ui.black سیاه @id ui.blue آبی تیره @id ui.blue_2 آبی diff --git a/i18n/fr.tsv b/i18n/fr.tsv index 37e58b96..8b20dce5 100644 --- a/i18n/fr.tsv +++ b/i18n/fr.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook Retour au bloc-notes @id ui.back_to_the_page_before_alt_left Back to the page before (Alt+Left) @id ui.basic_text Texte de base +@id ui.font_size Taille de police +@id ui.select_text_before_changing_font_size Sélectionnez du texte avant de modifier sa taille. @id ui.black black @id ui.blue blue @id ui.blue_2 Blue diff --git a/i18n/he.tsv b/i18n/he.tsv index fc1dfd6f..0d6c1eef 100644 --- a/i18n/he.tsv +++ b/i18n/he.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook חזרה למחברת @id ui.back_to_the_page_before_alt_left חזרה לדף הקודם (Alt+Left) @id ui.basic_text טקסט בסיסי +@id ui.font_size גודל גופן +@id ui.select_text_before_changing_font_size בחרו טקסט לפני שינוי גודל הגופן. @id ui.black שחור @id ui.blue כחול @id ui.blue_2 כחול diff --git a/i18n/hi.tsv b/i18n/hi.tsv index cecd123b..6f4c2029 100644 --- a/i18n/hi.tsv +++ b/i18n/hi.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook नोटबुक पर वापस जाएं @id ui.back_to_the_page_before_alt_left पिछले पृष्ठ पर वापस (Alt+Left) @id ui.basic_text मूल पाठ +@id ui.font_size फ़ॉन्ट आकार +@id ui.select_text_before_changing_font_size फ़ॉन्ट आकार बदलने से पहले पाठ चुनें। @id ui.black काला @id ui.blue नीला @id ui.blue_2 नीला diff --git a/i18n/ja.tsv b/i18n/ja.tsv index df459c96..e22f1c94 100644 --- a/i18n/ja.tsv +++ b/i18n/ja.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook ノートブックに戻る @id ui.back_to_the_page_before_alt_left 前のページに戻る(Alt+←) @id ui.basic_text 基本テキスト +@id ui.font_size フォント サイズ +@id ui.select_text_before_changing_font_size フォント サイズを変更する前にテキストを選択してください。 @id ui.black 黒 @id ui.blue 青 @id ui.blue_2 青 diff --git a/i18n/ko.tsv b/i18n/ko.tsv index e0f10cc7..cfc831f8 100644 --- a/i18n/ko.tsv +++ b/i18n/ko.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook 노트북으로 돌아가기 @id ui.back_to_the_page_before_alt_left 이전 페이지로 돌아가기 (Alt+Left) @id ui.basic_text 기본 텍스트 +@id ui.font_size 글꼴 크기 +@id ui.select_text_before_changing_font_size 글꼴 크기를 변경하기 전에 텍스트를 선택하세요. @id ui.black 검정 @id ui.blue 파랑 @id ui.blue_2 파란색 diff --git a/i18n/ru.tsv b/i18n/ru.tsv index c37ae528..c4290f4f 100644 --- a/i18n/ru.tsv +++ b/i18n/ru.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook Вернуться к блокноту @id ui.back_to_the_page_before_alt_left Вернуться к предыдущей странице (Alt+Left) @id ui.basic_text Базовый текст +@id ui.font_size Размер шрифта +@id ui.select_text_before_changing_font_size Выберите текст, чтобы изменить размер шрифта. @id ui.black чёрный @id ui.blue синий @id ui.blue_2 Синий diff --git a/i18n/ur.tsv b/i18n/ur.tsv index 9c87e5b0..d41c1d6f 100644 --- a/i18n/ur.tsv +++ b/i18n/ur.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook نات بک پر واپس @id ui.back_to_the_page_before_alt_left پچھلے صفحے پر واپس (Alt+Left) @id ui.basic_text بنیادی متن +@id ui.font_size فونٹ سائز +@id ui.select_text_before_changing_font_size فونٹ سائز تبدیل کرنے سے پہلے متن منتخب کریں۔ @id ui.black کالا @id ui.blue نیلا @id ui.blue_2 نیلا diff --git a/i18n/zh.tsv b/i18n/zh.tsv index f503b0ab..586cdb94 100644 --- a/i18n/zh.tsv +++ b/i18n/zh.tsv @@ -71,6 +71,8 @@ @id ui.back_to_the_notebook 返回笔记本 @id ui.back_to_the_page_before_alt_left 返回上一页(Alt+左箭头) @id ui.basic_text 基本文本 +@id ui.font_size 字体大小 +@id ui.select_text_before_changing_font_size 更改字体大小前,请先选择文本。 @id ui.black 黑色 @id ui.blue 蓝色 @id ui.blue_2 蓝色