Move from mathjax to katex

This commit is contained in:
cuom1999 2024-02-05 17:02:49 -06:00
parent b2c9be7bda
commit 08d2437d49
35 changed files with 64 additions and 214 deletions

View file

@ -43,7 +43,6 @@ from judge.models import (
from judge.widgets import ( from judge.widgets import (
HeavyPreviewPageDownWidget, HeavyPreviewPageDownWidget,
MathJaxPagedownWidget,
PagedownWidget, PagedownWidget,
Select2MultipleWidget, Select2MultipleWidget,
Select2Widget, Select2Widget,
@ -412,7 +411,7 @@ class NewMessageForm(ModelForm):
fields = ["title", "content"] fields = ["title", "content"]
widgets = {} widgets = {}
if PagedownWidget is not None: if PagedownWidget is not None:
widgets["content"] = MathJaxPagedownWidget() widgets["content"] = PagedownWidget()
class CustomAuthenticationForm(AuthenticationForm): class CustomAuthenticationForm(AuthenticationForm):

View file

@ -96,7 +96,7 @@ class Command(BaseCommand):
.replace("'//", "'https://") .replace("'//", "'https://")
) )
maker.title = problem_name maker.title = problem_name
for file in ("style.css", "mathjax3_config.js"): for file in "style.css":
maker.load(file, os.path.join(settings.DMOJ_RESOURCES, file)) maker.load(file, os.path.join(settings.DMOJ_RESOURCES, file))
maker.make(debug=True) maker.make(debug=True)
if not maker.success: if not maker.success:

View file

@ -6,7 +6,7 @@ from pymdownx import superfences
EXTENSIONS = [ EXTENSIONS = [
"pymdownx.arithmatex", # "pymdownx.arithmatex",
"pymdownx.magiclink", "pymdownx.magiclink",
"pymdownx.betterem", "pymdownx.betterem",
"pymdownx.details", "pymdownx.details",
@ -83,24 +83,9 @@ def markdown(value, lazy_load=False):
value, extensions=extensions, extension_configs=EXTENSION_CONFIGS value, extensions=extensions, extension_configs=EXTENSION_CONFIGS
) )
# Don't clean mathjax
hash_script_tag = {}
soup = BeautifulSoup(html, "html.parser") soup = BeautifulSoup(html, "html.parser")
for script_tag in soup.find_all("script"):
allow_math_types = ["math/tex", "math/tex; mode=display"]
if script_tag.attrs.get("type", False) in allow_math_types:
hash_script_tag[str(hash(str(script_tag)))] = str(script_tag)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(tag, hashed_tag)
html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS) html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(hashed_tag, tag)
if not html: if not html:
html = escape(value) html = escape(value)
if lazy_load: if lazy_load:

View file

@ -27,7 +27,7 @@ from django_ratelimit.decorators import ratelimit
from judge.models import Comment, CommentVote, Notification, BlogPost from judge.models import Comment, CommentVote, Notification, BlogPost
from judge.utils.views import TitleMixin from judge.utils.views import TitleMixin
from judge.widgets import MathJaxPagedownWidget, HeavyPreviewPageDownWidget from judge.widgets import HeavyPreviewPageDownWidget
from judge.comments import add_mention_notifications from judge.comments import add_mention_notifications
import json import json

View file

@ -407,8 +407,6 @@ class ProblemPdfView(ProblemMixin, SingleObjectMixin, View):
) )
maker.title = problem_name maker.title = problem_name
assets = ["style.css"] assets = ["style.css"]
if maker.math_engine == "jax":
assets.append("mathjax3_config.js")
for file in assets: for file in assets:
maker.load(file, os.path.join(settings.DMOJ_RESOURCES, file)) maker.load(file, os.path.join(settings.DMOJ_RESOURCES, file))
maker.make() maker.make()

View file

@ -10,8 +10,8 @@ from judge.widgets.mixins import CompressorWidgetMixin
__all__ = [ __all__ = [
"PagedownWidget", "PagedownWidget",
"AdminPagedownWidget", "AdminPagedownWidget",
"MathJaxPagedownWidget", "KatexPagedownWidget",
"MathJaxAdminPagedownWidget", "KatexAdminPagedownWidget",
"HeavyPreviewPageDownWidget", "HeavyPreviewPageDownWidget",
"HeavyPreviewAdminPageDownWidget", "HeavyPreviewAdminPageDownWidget",
] ]
@ -21,8 +21,8 @@ try:
except ImportError: except ImportError:
PagedownWidget = None PagedownWidget = None
AdminPagedownWidget = None AdminPagedownWidget = None
MathJaxPagedownWidget = None KatexPagedownWidget = None
MathJaxAdminPagedownWidget = None KatexAdminPagedownWidget = None
HeavyPreviewPageDownWidget = None HeavyPreviewPageDownWidget = None
HeavyPreviewAdminPageDownWidget = None HeavyPreviewAdminPageDownWidget = None
else: else:
@ -61,15 +61,19 @@ else:
} }
js = ["admin/js/pagedown.js"] js = ["admin/js/pagedown.js"]
class MathJaxPagedownWidget(PagedownWidget): class KatexPagedownWidget(PagedownWidget):
class Media: class Media:
css = {
"all": ["https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css"]
}
js = [ js = [
"mathjax3_config.js", "katex_config.js",
"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js", "https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js",
"https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js",
"pagedown_math.js", "pagedown_math.js",
] ]
class MathJaxAdminPagedownWidget(AdminPagedownWidget, MathJaxPagedownWidget): class KatexAdminPagedownWidget(AdminPagedownWidget, KatexPagedownWidget):
pass pass
class HeavyPreviewPageDownWidget(PagedownWidget): class HeavyPreviewPageDownWidget(PagedownWidget):
@ -112,7 +116,7 @@ else:
js = ["dmmd-preview.js"] js = ["dmmd-preview.js"]
class HeavyPreviewAdminPageDownWidget( class HeavyPreviewAdminPageDownWidget(
AdminPagedownWidget, HeavyPreviewPageDownWidget KatexPagedownWidget, AdminPagedownWidget, HeavyPreviewPageDownWidget
): ):
class Media: class Media:
css = { css = {

View file

@ -521,16 +521,6 @@ noscript #noscript {
margin-top: 1.2em; margin-top: 1.2em;
} }
math {
font-size: 1.155em;
}
.MathJax {
&:focus {
outline: none;
}
}
@media(max-width: 1498px) { @media(max-width: 1498px) {
#page-container { #page-container {
border-left: none; border-left: none;

View file

@ -30,31 +30,7 @@ $(function () {
$(this).attr("src", $(this).attr("data-src")); $(this).attr("src", $(this).attr("data-src"));
}) })
$preview.addClass('dmmd-preview-has-content').removeClass('dmmd-preview-stale'); $preview.addClass('dmmd-preview-has-content').removeClass('dmmd-preview-stale');
renderKatex($content[0]);
var $jax = $content.find('.require-mathjax-support');
if ($jax.length) {
if (!('MathJax' in window)) {
$.ajax({
type: 'GET',
url: $jax.attr('data-config'),
dataType: 'script',
cache: true,
success: function () {
$.ajax({
type: 'GET',
url: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js',
dataType: 'script',
cache: true,
success: function () {
MathJax.typeset();
}
});
}
});
} else {
MathJax.typeset($content[0]);
}
}
}); });
} else { } else {
$content.empty(); $content.empty();

17
resources/katex_config.js Normal file
View file

@ -0,0 +1,17 @@
window.KatexOptions = {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\[', right: '\\]', display: true},
{left: "\\(", right: "\\)", display: false},
{left: "\\begin{equation}", right: "\\end{equation}", display: true},
{left: "\\begin{align}", right: "\\end{align}", display: true},
{left: "\\begin{alignat}", right: "\\end{alignat}", display: true},
{left: "\\begin{gather}", right: "\\end{gather}", display: true},
{left: "\\begin{CD}", right: "\\end{CD}", display: true},
],
throwOnError : false
};
window.renderKatex = (elem=document.body) => {
renderMathInElement(elem, window.KatexOptions);
}

View file

@ -1,26 +0,0 @@
window.MathJax = {
chtml: {
adaptiveCSS: false,
},
options: {
ignoreHtmlClass: 'tex2jax_ignore',
processHtmlClass: 'tex2jax_process',
renderActions: {
find: [10, function (doc) {
for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
const display = !!node.type.match(/; *mode=display/);
const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
const text = document.createTextNode('');
const sibling = node.previousElementSibling;
node.parentNode.replaceChild(text, node);
math.start = {node: text, delim: '', n: 0};
math.end = {node: text, delim: '', n: 0};
doc.math.push(math);
if (sibling && sibling.matches('.MathJax_Preview')) {
sibling.parentNode.removeChild(sibling);
}
}
}, '']
}
}
};

View file

@ -1,13 +1,12 @@
function mathjax_pagedown($) { function mathjax_pagedown($) {
if ('MathJax' in window) {
$.each(window.editors, function (id, editor) { $.each(window.editors, function (id, editor) {
console.log(id);
var preview = $('div.wmd-preview#' + id + '_wmd_preview')[0]; var preview = $('div.wmd-preview#' + id + '_wmd_preview')[0];
editor.hooks.chain('onPreviewRefresh', function () { editor.hooks.chain('onPreviewRefresh', function () {
MathJax.typeset(preview); renderKatex(preview);
}); });
MathJax.typeset(preview); renderKatex(preview);
}); });
}
} }
window.mathjax_pagedown = mathjax_pagedown; window.mathjax_pagedown = mathjax_pagedown;

View file

@ -376,6 +376,8 @@
{% block extra_js %}{% endblock %} {% block extra_js %}{% endblock %}
</div> </div>
{% block bodyend %}{% endblock %} {% block bodyend %}{% endblock %}
<script src="{{ static('katex_config.js') }}"></script>
{% include "katex-load.html" %}
{% block footer %} {% block footer %}
<footer> <footer>
<span id="footer-content"> <span id="footer-content">

View file

@ -49,8 +49,5 @@
{% block bodyend %} {% block bodyend %}
{{ super() }} {{ super() }}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% include "comments/math.html" %} {% include "comments/math.html" %}
{% endblock %} {% endblock %}

View file

@ -5,9 +5,6 @@
{% block title %} {{_('Chat Box')}} {% endblock %} {% block title %} {{_('Chat Box')}} {% endblock %}
{% block js_media %} {% block js_media %}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% include "comments/math.html" %} {% include "comments/math.html" %}
<script type="text/javascript" src="{{ static('event.js') }}"></script> <script type="text/javascript" src="{{ static('event.js') }}"></script>
<script type="module" src="https://unpkg.com/emoji-picker-element@1"></script> <script type="module" src="https://unpkg.com/emoji-picker-element@1"></script>

View file

@ -52,7 +52,7 @@
function postProcessMessages() { function postProcessMessages() {
register_time($('.time-with-rel')); register_time($('.time-with-rel'));
MathJax.typeset(); renderKatex();
populateCopyButton(); populateCopyButton();
merge_authors(); merge_authors();
} }

View file

@ -1,33 +1,6 @@
<script src="{{ static('libs/featherlight/featherlight.min.js') }}" type="text/javascript"></script> <script src="{{ static('libs/featherlight/featherlight.min.js') }}" type="text/javascript"></script>
{% compress js %} {% compress js %}
{{ comment_form.media.js }} {{ comment_form.media.js }}
{% if not REQUIRE_JAX %}
<script type="text/javascript">
$(function () {
$('#id_body').keypress(function () {
if (!("MathJax" in window)) {
$.ajax({
type: "GET",
url: '{{ static('mathjax3_config.js') }}',
dataType: "script",
cache: true,
success: function () {
$.ajax({
type: "GET",
url: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js',
dataType: "script",
cache: true,
success: function () {
mathjax_pagedown($);
}
});
}
});
}
});
});
</script>
{% endif %}
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function () { $(document).ready(function () {
let loading_gif = "<img src=\"{{static('loading.gif')}}\" style=\"height: 3em; margin-bottom: 3px\" class=\"loading\">"; let loading_gif = "<img src=\"{{static('loading.gif')}}\" style=\"height: 3em; margin-bottom: 3px\" class=\"loading\">";
@ -61,10 +34,8 @@
}); });
function update_math($comment) { function update_math($comment) {
if ('MathJax' in window) {
var $body = $comment.find('.comment-body'); var $body = $comment.find('.comment-body');
MathJax.typeset($body[0]); renderKatex($body[0]);
}
} }
window.show_revision = function (comment_id, offset) { window.show_revision = function (comment_id, offset) {
@ -145,7 +116,7 @@
$comment_loading.hide(); $comment_loading.hide();
var $comment = $("#comment-" + id + "-children"); var $comment = $("#comment-" + id + "-children");
$comment.append(data); $comment.append(data);
MathJax.typeset($('#comments')[0]); renderKatex($('#comments')[0]);
register_time($('.time-with-rel')); register_time($('.time-with-rel'));
} }
}) })
@ -188,7 +159,7 @@
var $comment = $("#comment-" + id + "-children"); var $comment = $("#comment-" + id + "-children");
$comment.append(data); $comment.append(data);
} }
MathJax.typeset($('#comments')[0]); renderKatex($('#comments')[0]);
register_time($('.time-with-rel')); register_time($('.time-with-rel'));
} }
}) })
@ -246,7 +217,7 @@
window.DjangoPagedown.createEditor($wmd.get(0)); window.DjangoPagedown.createEditor($wmd.get(0));
if ('MathJax' in window) { if ('MathJax' in window) {
var preview = $('.featherlight div.wmd-preview')[0]; var preview = $('.featherlight div.wmd-preview')[0];
MathJax.typeset(preview); renderKatex(preview);
} }
} }
} }

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -44,9 +44,3 @@
</div> </div>
</div> </div>
{% endblock %} {% endblock %}
{% block bodyend %}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% endblock %}

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -30,7 +30,7 @@
window.loading_page = false; window.loading_page = false;
window.has_next_page = parseInt($(".has_next").attr("value")); window.has_next_page = parseInt($(".has_next").attr("value"));
window.page++; window.page++;
MathJax.typeset($('.middle-content')[0]); renderKatex($('.middle-content')[0]);
onWindowReady(); onWindowReady();
activateBlogBoxOnClick(); activateBlogBoxOnClick();
}) })

View file

@ -3,7 +3,3 @@
{% block body %} {% block body %}
<div class="content-description">{{ flatpage.content|markdown|reference }}</div> <div class="content-description">{{ flatpage.content|markdown|reference }}</div>
{% endblock %} {% endblock %}
{% block bodyend %}
{% if REQUIRE_JAX %}{% include "mathjax-load.html" %}{% endif %}
{% endblock %}

View file

@ -0,0 +1,4 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"
onload="renderMathInElement(document.body, window.KatexOptions);"></script>

View file

@ -60,7 +60,7 @@
}, },
success: function(data) { success: function(data) {
$('#display').html(data); $('#display').html(data);
MathJax.typeset(); renderKatex();
populateCopyButton(); populateCopyButton();
}, },
error: function(error) { error: function(error) {
@ -82,8 +82,6 @@
<script src="{{ static('pagedown/Markdown.Editor.js') }}"></script> <script src="{{ static('pagedown/Markdown.Editor.js') }}"></script>
<script src="{{ static('pagedown-extra/Markdown.Extra.js') }}"></script> <script src="{{ static('pagedown-extra/Markdown.Extra.js') }}"></script>
<script src="{{ static('pagedown_init.js') }}"></script> <script src="{{ static('pagedown_init.js') }}"></script>
<script src="{{ static('mathjax3_config.js') }}"></script>
<script src="http://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<script src="{{ static('pagedown_math.js') }}"></script> <script src="{{ static('pagedown_math.js') }}"></script>
{% endblock %} {% endblock %}

View file

@ -1,5 +0,0 @@
<script type="text/javascript" src="{{ static('mathjax3_config.js') }}?v=1"></script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3.0.0/es5/tex-chtml.js">
</script>

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -36,8 +36,5 @@
{% endblock %} {% endblock %}
{% block bodyend %} {% block bodyend %}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% include "comments/math.html" %} {% include "comments/math.html" %}
{% endblock %} {% endblock %}

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -92,16 +92,7 @@
<div class="content-description printing"> <div class="content-description printing">
{{ description|markdown|reference|absolutify(url)|str|safe }} {{ description|markdown|reference|absolutify(url)|str|safe }}
</div> </div>
<script src="{{ static('katex_config.js') }}"></script>
<script type="text/javascript" src="{{ static('mathjax3_config.js') }}"></script> {% include "katex-load.html" %}
<script type="text/javascript" src="mathjax3_config.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS_HTML"></script>
<script type="text/javascript">
MathJax.Hub.Register.StartupHook("End", function () {
if (typeof window.callPhantom === 'function')
window.callPhantom({'action': 'snapshot'});
document.body.classList.add('math-loaded');
});
</script>
</body> </body>
</html> </html>

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -88,9 +88,6 @@
}); });
}); });
</script> </script>
<script src="{{ static('mathjax3_config.js') }}"></script>
<script src="http://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<script src="{{ static('pagedown_math.js') }}"></script>
{% endblock %} {% endblock %}

View file

@ -83,7 +83,7 @@
$('.middle-right-content').removeClass("wrapper"); $('.middle-right-content').removeClass("wrapper");
} }
$(document).prop('title', $(data).filter('title').text()); $(document).prop('title', $(data).filter('title').text());
MathJax.typeset($('.middle-right-content')[0]); renderKatex($('.middle-right-content')[0]);
onWindowReady(); onWindowReady();
activateBlogBoxOnClick(); activateBlogBoxOnClick();
$('.xdsoft_datetimepicker').hide(); $('.xdsoft_datetimepicker').hide();
@ -152,8 +152,5 @@
{% block bodyend %} {% block bodyend %}
{{ super() }} {{ super() }}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% include "comments/math.html" %} {% include "comments/math.html" %}
{% endblock %} {% endblock %}

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -227,8 +227,5 @@
{% block bodyend %} {% block bodyend %}
{{ super() }} {{ super() }}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
{% include "comments/math.html" %} {% include "comments/math.html" %}
{% endblock %} {% endblock %}

View file

@ -1,4 +1 @@
{{ preview_data|markdown|reference|str|safe }} {{ preview_data|markdown|reference|str|safe }}
{% if REQUIRE_JAX %}
<div data-config="{{ static('mathjax3_config.js') }}" class="require-mathjax-support"></div>
{% endif %}

View file

@ -185,10 +185,6 @@
{% endblock %} {% endblock %}
{% block bodyend %} {% block bodyend %}
{% if REQUIRE_JAX %}
{% include "mathjax-load.html" %}
{% endif %}
<script type="text/javascript"> <script type="text/javascript">
var submission_activity = {{ submission_data }}; var submission_activity = {{ submission_data }};
var metadata = {{ submission_metadata }}; var metadata = {{ submission_metadata }};