anki/ts/editable/mathjax.ts

58 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-08-04 01:55:39 +02:00
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
2021-08-07 05:46:52 +02:00
import { mathIcon } from "./icons";
const parser = new DOMParser();
2021-08-07 22:07:57 +02:00
function getCSS(nightMode: boolean, fontSize: number): string {
const color = nightMode ? "white" : "black";
/* color is set for Maths, fill for the empty icon */
2021-08-07 22:07:57 +02:00
return `svg { color: ${color}; fill: ${color}; font-size: ${fontSize}px; }`;
}
2021-08-07 05:46:52 +02:00
2021-08-07 22:07:57 +02:00
function getStyle(css: string): HTMLStyleElement {
const style = document.createElement("style") as HTMLStyleElement;
style.appendChild(document.createTextNode(css));
return style;
}
2021-08-04 01:55:39 +02:00
2021-08-07 22:07:57 +02:00
function getEmptyIcon(style: HTMLStyleElement): [string, string] {
2021-08-07 05:46:52 +02:00
const icon = parser.parseFromString(mathIcon, "image/svg+xml");
const svg = icon.children[0];
svg.insertBefore(style, svg.children[0]);
2021-08-07 05:46:52 +02:00
2021-08-07 22:23:18 +02:00
return [svg.outerHTML, "MathJax"];
2021-08-04 01:55:39 +02:00
}
2021-08-07 05:46:52 +02:00
export function convertMathjax(
input: string,
nightMode: boolean,
fontSize: number
): [string, string] {
2021-08-07 22:07:57 +02:00
const style = getStyle(getCSS(nightMode, fontSize));
2021-08-07 05:46:52 +02:00
if (input.trim().length === 0) {
2021-08-07 22:07:57 +02:00
return getEmptyIcon(style);
2021-08-07 05:46:52 +02:00
}
const output = globalThis.MathJax.tex2svg(input);
const svg = output.children[0];
if (svg.viewBox.baseVal.height === 16) {
2021-08-07 22:07:57 +02:00
return getEmptyIcon(style);
2021-08-07 05:46:52 +02:00
}
2021-08-07 19:33:01 +02:00
let title = "";
2021-08-07 19:13:08 +02:00
if (svg.innerHTML.includes("data-mjx-error")) {
svg.querySelector("rect").setAttribute("fill", "yellow");
svg.querySelector("text").setAttribute("color", "red");
2021-08-07 19:33:01 +02:00
title = svg.querySelector("title").innerHTML;
2021-08-07 19:13:08 +02:00
} else {
2021-08-07 05:46:52 +02:00
svg.insertBefore(style, svg.children[0]);
}
2021-08-07 19:13:08 +02:00
2021-08-07 19:33:01 +02:00
return [svg.outerHTML, title];
2021-08-07 05:46:52 +02:00
}