Skip to content

Commit

Permalink
Cleanup math setup
Browse files Browse the repository at this point in the history
Remove need for math feature

Move math_fn for documentation ordering
  • Loading branch information
lampsitter committed Jan 13, 2025
1 parent 15de75d commit 14be2b2
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 130 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ First of all thank you for considering it. Check out
You won't be able to run the tests without enabling the `macros` feature
as one of the examples depend on it.

`cargo test --feature macros`
`cargo test --features macros`


### Debugging the proc macros
Expand Down
36 changes: 0 additions & 36 deletions egui_commonmark/examples/book.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
//! Shows a simple way to use the crate to implement a book like view.
use eframe::egui;
use egui::ImageSource;
use egui_commonmark::*;
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};

struct Page {
name: String,
Expand All @@ -20,19 +18,6 @@ struct App {
cache: CommonMarkCache,
curr_tab: Option<usize>,
pages: Vec<Page>,
math_to_svg: Rc<RefCell<HashMap<String, Arc<[u8]>>>>,
}

fn render_math(math: &str, inline: bool) -> Arc<[u8]> {
println!("rendering math: {math}");
// TODO
if inline {
// mathjax_svg::convert_to_svg_inline(math).unwrap()
} else {
// mathjax_svg::convert_to_svg(math).unwrap()
}
.into_bytes()
.into()
}

impl App {
Expand Down Expand Up @@ -62,28 +47,12 @@ impl App {
fn content_panel(&mut self, ui: &mut egui::Ui) {
egui::ScrollArea::vertical().show(ui, |ui| {
// Add a frame with margin to prevent the content from hugging the sidepanel
let math_to_svg = self.math_to_svg.clone();
egui::Frame::none()
.inner_margin(egui::Margin::symmetric(5.0, 0.0))
.show(ui, |ui| {
CommonMarkViewer::new()
.default_width(Some(200))
.max_image_width(Some(512))
.render_math_fn(Some(&move |ui, math, inline| {
let mut map = math_to_svg.borrow_mut();
let svg = map
.entry(math.to_string())
.or_insert_with(|| render_math(math, inline));

let uri = format!("{}.svg", egui::Id::from(math.to_string()).value());
ui.add(
egui::Image::new(ImageSource::Bytes {
uri: uri.into(),
bytes: egui::load::Bytes::Shared(svg.clone()),
})
.fit_to_original_size(1.0),
);
}))
.show(
ui,
&mut self.cache,
Expand Down Expand Up @@ -159,12 +128,7 @@ fn main() -> eframe::Result {
name: "Embedded Image".to_owned(),
content: include_str!("markdown/embedded_image.md").to_owned(),
},
Page {
name: "Math".to_owned(),
content: include_str!("markdown/math.md").to_owned(),
},
],
math_to_svg: Rc::new(RefCell::new(HashMap::new())),
}))
}),
)
Expand Down
57 changes: 0 additions & 57 deletions egui_commonmark/examples/markdown/math.md

This file was deleted.

57 changes: 46 additions & 11 deletions egui_commonmark/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,16 @@ pub use egui_commonmark_backend;

use egui_commonmark_backend::*;

// FIXME: Manual Debug impl
// #[derive(Debug, Default)]
#[derive(Default)]
pub struct CommonMarkViewer<'a> {
options: CommonMarkOptions<'a>,
#[derive(Debug, Default)]
pub struct CommonMarkViewer<'f> {
options: CommonMarkOptions<'f>,
}

impl<'a> CommonMarkViewer<'a> {
impl<'f> CommonMarkViewer<'f> {
pub fn new() -> Self {
Self::default()
}

pub fn render_math_fn(mut self, math_fn: Option<&'a RenderMathFn>) -> Self {
self.options.math_fn = math_fn;
self
}

/// The amount of spaces a bullet point is indented. By default this is 4
/// spaces.
pub fn indentation_spaces(mut self, spaces: usize) -> Self {
Expand Down Expand Up @@ -179,6 +172,48 @@ impl<'a> CommonMarkViewer<'a> {
self
}

/// Allows rendering math. This has to be done manually as you might want a different
/// implementation for the web and native.
///
/// The example is template code for rendering a svg image. Make sure to enable the
/// `egui_extras/svg` feature for the result to show up.
///
/// ## Example
///
/// ```
/// # use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
/// # use egui_commonmark::CommonMarkViewer;
/// let mut math_images = Rc::new(RefCell::new(HashMap::new()));
/// CommonMarkViewer::new()
/// .render_math_fn(Some(&move |ui, math, inline| {
/// let mut map = math_images.borrow_mut();
/// let svg = map
/// .entry(math.to_string())
/// .or_insert_with(|| {
/// if (inline) {
/// // render as inline
/// // dummy data for the example
/// Arc::new([0])
/// } else {
/// Arc::new([0])
/// }
/// });
///
/// let uri = format!("{}.svg", egui::Id::from(math.to_string()).value());
/// ui.add(
/// egui::Image::new(egui::ImageSource::Bytes {
/// uri: uri.into(),
/// bytes: egui::load::Bytes::Shared(svg.clone()),
/// })
/// .fit_to_original_size(1.0),
/// );
/// }));
/// ```
pub fn render_math_fn(mut self, math_fn: Option<&'f RenderMathFn>) -> Self {
self.options.math_fn = math_fn;
self
}

/// Shows rendered markdown
pub fn show(
self,
Expand Down
26 changes: 19 additions & 7 deletions egui_commonmark/src/parsers/pulldown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ impl CommonMarkViewerInternal {
}
}

fn parser_options_math(is_math_enabled: bool) -> pulldown_cmark::Options {
if is_math_enabled {
parser_options() | pulldown_cmark::Options::ENABLE_MATH
} else {
parser_options()
}
}

impl CommonMarkViewerInternal {
/// Be aware that this acquires egui::Context internally.
/// If split Id is provided then split points will be populated
Expand All @@ -122,10 +130,13 @@ impl CommonMarkViewerInternal {
let height = ui.text_style_height(&TextStyle::Body);
ui.set_row_height(height);

let mut events = pulldown_cmark::Parser::new_ext(text, parser_options())
.into_offset_iter()
.enumerate()
.peekable();
let mut events = pulldown_cmark::Parser::new_ext(
text,
parser_options_math(options.math_fn.is_some()),
)
.into_offset_iter()
.enumerate()
.peekable();

while let Some((index, (e, src_span))) = events.next() {
let start_position = ui.next_widget_position();
Expand Down Expand Up @@ -193,9 +204,10 @@ impl CommonMarkViewerInternal {
return;
};

let events = pulldown_cmark::Parser::new_ext(text, parser_options())
.into_offset_iter()
.collect::<Vec<_>>();
let events =
pulldown_cmark::Parser::new_ext(text, parser_options_math(options.math_fn.is_some()))
.into_offset_iter()
.collect::<Vec<_>>();

let num_rows = events.len();

Expand Down
2 changes: 0 additions & 2 deletions egui_commonmark_backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,3 @@ syntect = { version = "5.0.0", optional = true, default-features = false, featur
[features]
better_syntax_highlighting = ["dep:syntect"]
embedded_image = ["dep:data-url"]

math = ["egui_extras/svg"]
26 changes: 24 additions & 2 deletions egui_commonmark_backend/src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ const DEFAULT_THEME_LIGHT: &str = "base16-ocean.light";
#[cfg(feature = "better_syntax_highlighting")]
const DEFAULT_THEME_DARK: &str = "base16-ocean.dark";

// FIXME: Debug
// #[derive(Debug)]
pub struct CommonMarkOptions<'f> {
pub indentation_spaces: usize,
pub max_image_width: Option<usize>,
Expand All @@ -36,6 +34,30 @@ pub struct CommonMarkOptions<'f> {
pub math_fn: Option<&'f crate::RenderMathFn>,
}

impl<'f> std::fmt::Debug for CommonMarkOptions<'f> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = f.debug_struct("CommonMarkOptions");

s.field("indentation_spaces", &self.indentation_spaces)
.field("max_image_width", &self.max_image_width)
.field("show_alt_text_on_hover", &self.show_alt_text_on_hover)
.field("default_width", &self.default_width);

#[cfg(feature = "better_syntax_highlighting")]
s.field("theme_light", &self.theme_light)
.field("theme_light", &self.theme_dark);

s.field("use_explicit_uri_scheme", &self.use_explicit_uri_scheme)
.field(
"default_implicit_uri_scheme",
&self.default_implicit_uri_scheme,
)
.field("alerts", &self.alerts)
.field("mutable", &self.mutable)
.finish()
}
}

impl Default for CommonMarkOptions<'_> {
fn default() -> Self {
Self {
Expand Down
14 changes: 0 additions & 14 deletions egui_commonmark_backend/src/pulldown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,22 +179,8 @@ pub fn parse_alerts<'a>(
}
}

/// Supported pulldown_cmark options
#[inline]
#[cfg(feature = "math")]
pub fn parser_options() -> Options {
Options::ENABLE_TABLES
| Options::ENABLE_TASKLISTS
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_DEFINITION_LIST
| Options::ENABLE_MATH
}

/// Supported pulldown_cmark options
#[inline]
#[cfg(not(feature = "math"))]
pub fn parser_options() -> Options {
Options::ENABLE_TABLES
| Options::ENABLE_TASKLISTS
Expand Down

0 comments on commit 14be2b2

Please sign in to comment.