From bad116eaeea5978c68789f878a910031c2d1bdff Mon Sep 17 00:00:00 2001 From: alexcss Date: Tue, 12 Nov 2024 17:22:54 +0200 Subject: [PATCH] Render Equation script --- docusaurus.config.js | 3 +++ package.json | 1 + src/clientModules/renderEquations.js | 34 ++++++++++++++++++++++++++++ yarn.lock | 7 ++++++ 4 files changed, 45 insertions(+) create mode 100644 src/clientModules/renderEquations.js diff --git a/docusaurus.config.js b/docusaurus.config.js index 9e5d38e2..41fac199 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -61,6 +61,9 @@ const config = { defaultLocale: 'en', locales: ['en'], }, + clientModules:[ + '/src/clientModules/renderEquations.js' + ], plugins: [ 'docusaurus-plugin-sass', [ diff --git a/package.json b/package.json index fcd2a910..2f146d46 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "bootstrap": "5.3.3", "clsx": "^2.0.0", "docusaurus-plugin-sass": "^0.2.5", + "katex": "^0.16.11", "prism-react-renderer": "^2.3.0", "react": "^18.0.0", "react-bootstrap": "^2.10.2", diff --git a/src/clientModules/renderEquations.js b/src/clientModules/renderEquations.js new file mode 100644 index 00000000..7b629e5e --- /dev/null +++ b/src/clientModules/renderEquations.js @@ -0,0 +1,34 @@ +import katex from 'katex' +import 'katex/dist/katex.min.css' + +function renderEquation (el) { + if (!el) return + + let equation = el.getAttribute('title').slice('tex-render '.length) + + if (!equation) return + + let equationEl = document.createElement('span') + + katex.render(equation, equationEl, { + throwOnError: false, + }) + equationEl.setAttribute('title', equation) + equationEl.classList.add('tex-rendered') + el.replaceWith(equationEl) +} + +function initRenderEquation () { + const elements = document.querySelectorAll('a[title^="tex-render "]') + if (elements.length === 0) return + + elements.forEach(renderEquation) +} + +export function onRouteDidUpdate ({ location, previousLocation }) { + // Don't execute if we are still on the same page; the lifecycle may be fired + // because the hash changes (e.g. when navigating between headings) + if (location.pathname !== previousLocation?.pathname) { + initRenderEquation() + } +} diff --git a/yarn.lock b/yarn.lock index 9ccac9c5..ab6a69db 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5259,6 +5259,13 @@ jsonfile@^6.0.1: optionalDependencies: graceful-fs "^4.1.6" +katex@^0.16.11: + version "0.16.11" + resolved "https://registry.yarnpkg.com/katex/-/katex-0.16.11.tgz#4bc84d5584f996abece5f01c6ad11304276a33f5" + integrity sha512-RQrI8rlHY92OLf3rho/Ts8i/XvjgguEjOkO1BEXcU3N8BqPpSzBNwV/G0Ukr+P/l3ivvJUE/Fa/CwbS6HesGNQ== + dependencies: + commander "^8.3.0" + keyv@^4.5.3: version "4.5.4" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93"