anki/ts/editable/mathjax.ts

52 lines
1.5 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 05:46:52 +02:00
function getStyle(): HTMLStyleElement {
const style = document.createElement("style") as HTMLStyleElement;
/* color is set for Maths, fill for the empty icon */
const css = `svg { color: white; fill: white; font-size: 20px; }`;
2021-08-07 05:46:52 +02:00
style.appendChild(document.createTextNode(css));
return style;
}
2021-08-04 01:55:39 +02:00
2021-08-07 19:33:01 +02:00
function getEmptyIcon(): [string, string] {
2021-08-07 05:46:52 +02:00
const style = getStyle();
2021-08-04 01:55:39 +02:00
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 19:33:01 +02:00
return [svg.outerHTML, ""];
2021-08-04 01:55:39 +02:00
}
2021-08-07 05:46:52 +02:00
2021-08-07 19:33:01 +02:00
export function convertMathjax(input: string): [string, string] {
2021-08-07 05:46:52 +02:00
if (input.trim().length === 0) {
return getEmptyIcon();
}
const output = globalThis.MathJax.tex2svg(input);
const svg = output.children[0];
if (svg.viewBox.baseVal.height === 16) {
return getEmptyIcon();
}
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
const style = getStyle();
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
}