From 8583520baf01323c9de87514ca240bdbe09da80a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 31 Mar 2024 18:05:31 +0200 Subject: [PATCH] fix math integration --- src/misc/markdown.rs | 24 +++++++++++++++++++++--- static/js/libs/katex.js | 18 +++++++++--------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/misc/markdown.rs b/src/misc/markdown.rs index e02916a..7e3228a 100644 --- a/src/misc/markdown.rs +++ b/src/misc/markdown.rs @@ -1,10 +1,12 @@ use crate::misc::date::Date; use comrak::nodes::{AstNode, NodeValue}; use comrak::{format_html, parse_document, Arena, ComrakOptions, ListStyleType}; -use lol_html::{element, rewrite_str, RewriteStrSettings}; +use lol_html::{element, rewrite_str, HtmlRewriter, RewriteStrSettings, Settings}; use ramhorns::Content; use serde::{Deserialize, Deserializer}; use std::fs; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; /// Metadata for blog posts #[derive(Content, Debug, Default, Deserialize)] @@ -322,9 +324,25 @@ fn check_code<'a>(root: &'a AstNode<'a>, blacklist: &[String]) -> bool { }) } -/// Check if html can contains maths +/// Check if html contains maths fn check_math(html: &str) -> bool { - html.contains('$') + let math_detected = Arc::new(AtomicBool::new(false)); + + let mut output = vec![]; + let _ = HtmlRewriter::new( + Settings { + element_content_handlers: vec![element!("span[data-math-style]", |_| { + math_detected.store(true, Ordering::SeqCst); + + Ok(()) + })], + ..Settings::default() + }, + |c: &[u8]| output.extend_from_slice(c), + ) + .write(html.as_bytes()); + + math_detected.load(Ordering::SeqCst) } /// Change class of languages for hljs detection diff --git a/static/js/libs/katex.js b/static/js/libs/katex.js index 8c06455..bb220db 100644 --- a/static/js/libs/katex.js +++ b/static/js/libs/katex.js @@ -16,13 +16,13 @@ window.addEventListener("load", () => { macros[`\\${item[0]}`] = `\\${item[1]}`; } - renderMathInElement(document.body, { - delimiters: [ - { left: "$$", right: "$$", display: true }, - { left: "$", right: "$", display: false }, - ], - throwOnError: false, - macros, - output: "mathml", - }); + const attribute = "data-math-style"; + for (let element of document.querySelectorAll(`span[${attribute}]`)) { + katex.render(element.textContent, element, { + throwOnError: false, + displayMode: element.getAttribute(attribute) === "display", + macros, + output: "mathml", + }); + } });