Remove KaTeX CSS includes if we don't need them.

Signed-off-by: Danila Fedorin <danila.fedorin@gmail.com>
This commit is contained in:
Danila Fedorin 2025-02-23 14:35:31 -08:00
parent 36e4feb668
commit 647f47a5f3

View File

@ -25,13 +25,16 @@ class KatexRenderer
end
def substitute(content)
found_any = false
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
found_any = true
render(false, $~[1])
end
rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match|
found_any = true
render(true, $~[1])
end
return rendered
return rendered, found_any
end
end
@ -58,8 +61,17 @@ renderer = KatexRenderer.new(katex)
files.each do |file|
puts "Rendering file: #{file}"
document = Nokogiri::HTML.parse(File.open(file))
found_any = false
document.search('//*[not(ancestor-or-self::code or ancestor-or-self::script)]/text()').each do |t|
t.replace(renderer.substitute(t.content))
rendered, found_any_in_text = renderer.substitute(t.content)
found_any ||= found_any_in_text
t.replace(rendered)
end
# If we didn't find any mathematical equations, no need to include KaTeX CSS.
unless found_any
document.css('link[href$="katex.css"], link[href$="katex.min.css"]').each(&:remove)
end
File.write(file, document.to_html(encoding: 'UTF-8'))
end