feat(katex): added KaTeX support to sequence diagrams

This commit is contained in:
NicolasNewman
2023-05-06 17:19:31 +09:00
parent f8a4488050
commit 4202488da0
4 changed files with 284 additions and 146 deletions

View File

@@ -144,6 +144,39 @@
>
<hr />
<pre class="mermaid">
sequenceDiagram
participant 1 as $$\frac{\lim_{x\rightarrow0}{\frac{1}{x}}}{\frac{-b\pm\sqrt{b^2-4ac}}{2a}}$$
participant 2 as $$\beta$$
participant 3 as $$\delta$$
participant 4 as $$\frac{\frac{\lim_{x\rightarrow0}{\frac{1}{x}}}{\frac{-b\pm\sqrt{b^2-4ac}}{2a}}}{\frac{\text{d}}{\text{d}x}{x^2}}$$
1->>2: $$\sqrt{2}$$
note right of 2: $$\frac{1+\frac{1+\frac{1+\frac{1}{2}}{2}}{2}}{2}+\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$
2->>3: $$\frac{\lim_{x\rightarrow0}{\frac{1}{x}}}{\frac{-b\pm\sqrt{b^2-4ac}}{2a}}$$
note right of 3: $$\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$
3->>4: $$\lim_{x\rightarrow0}{\frac{1}{x}}$$;
note right of 4: multiline
4->>1: multiline<br />using #lt;br /#gt;
note right of 1: multiline<br />$$\frac{1}{2}$$<br />3rd line
</pre>
<hr />
<pre class="mermaid">
sequenceDiagram
autonumber
participant 1 as $$\alpha$$lex
participant 2 as $$\beta$$ob
participant 3 as $$\theta$$iffany
1->>2: Hello John, does&nbsp; $$\frac{1}{2}+1=2$$?
loop $$\frac{1}{2}+1=2$$
2->>2: $$\frac{1}{2}+1=\frac{3}{2}$$
end
Note right of 2: $$x = \begin{cases} 1 &\text{if } \frac{1}{2}+1=2 \\ 0 &\text{if } \frac{1}{2}+1\ne2 \end{cases}$$
2-->>1: $$\frac{1}{2}+1\ne2\implies 1$$
2->>3: $$\frac{\text{d}}{\text{d}x}{3x^2+2x+1}$$
3-->>2: $$6x+2$$
</pre>
<hr />
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({

View File

@@ -195,7 +195,8 @@ export const hasKatex = (text: string): boolean => (text.match(katexRegex)?.leng
* @returns Object containing {width, height}
*/
export const calculateMathMLDimensions = (text: string, config: MermaidConfig) => {
text = renderKatex(text, config).split(lineBreakRegex).map((text) => hasKatex(text) ? renderKatex(text, config) : `<div>${text}</div>`).join('');
text = renderKatex(text, config);
const divElem = document.createElement('div')
divElem.innerHTML = text;
divElem.id = 'katex-temp';
@@ -209,6 +210,13 @@ export const calculateMathMLDimensions = (text: string, config: MermaidConfig) =
return dim;
}
// export const temp = (text: string, config: MermaidConfig) => {
// return renderKatex(text, config).split(lineBreakRegex).map((text) =>
// hasKatex(text) ?
// `<div style="display: flex;">${text}</div>` :
// `<div>${text}</div>`).join('');
// }
/**
* Attempts to render and return the KaTeX portion of a string with MathML
*
@@ -218,14 +226,25 @@ export const calculateMathMLDimensions = (text: string, config: MermaidConfig) =
*/
export const renderKatex = (text: string, config: MermaidConfig): string => {
if (isMathMLSupported || (!isMathMLSupported && config.legacyMathML)) {
return text.replace(/\$\$(.*)\$\$/g, (r, c) =>
return text
.split(lineBreakRegex)
.map((line) => hasKatex(line) ?
`
<div style="display: flex; align-items: center; justify-content: center; white-space: nowrap;">
${line}
</div>
` :
`<div>${line}</div>`
)
.join('')
.replace(katexRegex, (r, c) =>
katex
.renderToString(c, { throwOnError: true, displayMode: true, output: isMathMLSupported ? 'mathml' : 'htmlAndMathml' })
.replace(/\n/g, ' ')
.replace(/<annotation.*<\/annotation>/g, '')
);
)
}
return text.replace(/\$\$(.*)\$\$/g, (r, c) => 'MathML is unsupported in this environment.');
return text.replace(katexRegex, 'MathML is unsupported in this environment.');
};
export default {

View File

@@ -1,8 +1,8 @@
// @ts-nocheck TODO: fix file
import { select, selectAll } from 'd3';
import svgDraw, { drawText, fixLifeLineHeights } from './svgDraw.js';
import svgDraw, { drawKatex, drawText, fixLifeLineHeights } from './svgDraw.js';
import { log } from '../../logger.js';
import common from '../common/common.js';
import common, { calculateMathMLDimensions, hasKatex } from '../common/common.js';
import * as configApi from '../../config.js';
import assignWithDepth from '../../assignWithDepth.js';
import utils from '../../utils.js';
@@ -247,7 +247,7 @@ const drawNote = function (elem: any, noteModel: NoteModel) {
textObj.textMargin = conf.noteMargin;
textObj.valign = 'center';
const textElem = drawText(g, textObj);
const textElem = hasKatex(textObj.text) ? drawKatex(g, textObj) : drawText(g, textObj);
const textHeight = Math.round(
textElem
@@ -299,11 +299,16 @@ function boundMessage(_diagram, msgModel): number {
bounds.bumpVerticalPos(10);
const { startx, stopx, message } = msgModel;
const lines = common.splitBreaks(message).length;
const textDims = utils.calculateTextDimensions(message, messageFont(conf));
const isKatexMsg = hasKatex(message);
const textDims = isKatexMsg ?
calculateMathMLDimensions(message, configApi.getConfig()) :
utils.calculateTextDimensions(message, messageFont(conf));
if (!isKatexMsg) {
const lineHeight = textDims.height / lines;
msgModel.height += lineHeight;
bounds.bumpVerticalPos(lineHeight);
}
let lineStartY;
let totalOffset = textDims.height - 10;
@@ -362,7 +367,7 @@ const drawMessage = function (diagram, msgModel, lineStartY: number, diagObj: Di
textObj.textMargin = conf.wrapPadding;
textObj.tspan = false;
drawText(diagram, textObj);
hasKatex(textObj.text) ? drawKatex(diagram, textObj, {startx, stopx, starty: lineStartY}) : drawText(diagram, textObj);
const textWidth = textDims.width;
@@ -1005,7 +1010,9 @@ function getMaxMessageWidthPerActor(
const wrappedMessage = msg.wrap
? utils.wrapLabel(msg.message, conf.width - 2 * conf.wrapPadding, textFont)
: msg.message;
const messageDimensions = utils.calculateTextDimensions(wrappedMessage, textFont);
const messageDimensions = hasKatex(wrappedMessage) ?
calculateMathMLDimensions(msg.message, configApi.getConfig()) :
utils.calculateTextDimensions(wrappedMessage, textFont);
const messageWidth = messageDimensions.width + 2 * conf.wrapPadding;
/*
@@ -1116,7 +1123,10 @@ function calculateActorMargins(
actorFont(conf)
);
}
const actDims = utils.calculateTextDimensions(actor.description, actorFont(conf));
const actDims = hasKatex(actor.description) ?
calculateMathMLDimensions(actor.description, configApi.getConfig()) :
utils.calculateTextDimensions(actor.description, actorFont(conf));
actor.width = actor.wrap
? conf.width
: Math.max(conf.width, actDims.width + 2 * conf.wrapPadding);
@@ -1179,7 +1189,9 @@ const buildNoteModel = function (msg, actors, diagObj) {
const stopx = actors[msg.to].x;
const shouldWrap = msg.wrap && msg.message;
let textDimensions = utils.calculateTextDimensions(
let textDimensions: {width: number, height: number, lineHeight?: number} = hasKatex(msg.message) ?
calculateMathMLDimensions(msg.message, configApi.getConfig()) :
utils.calculateTextDimensions(
shouldWrap ? utils.wrapLabel(msg.message, conf.width, noteFont(conf)) : msg.message,
noteFont(conf)
);

View File

@@ -1,7 +1,8 @@
import common from '../common/common.js';
import common, { calculateMathMLDimensions, hasKatex, renderKatex } from '../common/common.js';
import { addFunction } from '../../interactionDb.js';
import { parseFontSize } from '../../utils.js';
import { sanitizeUrl } from '@braintree/sanitize-url';
import * as configApi from '../../config.js';
export const drawRect = function (elem, rectData) {
const rectElem = elem.append('rect');
@@ -152,6 +153,48 @@ const popupMenuDownFunc = function (popupId) {
pu.style.display = 'none';
}
};
export const drawKatex = function (elem, textData, msgModel = null) {
let textElem = elem.append('foreignObject');
const lines = renderKatex(textData.text, configApi.getConfig());
const divElem = textElem
.append('xhtml:div')
.attr('style', 'width: fit-content;')
.attr('xmlns', 'http://www.w3.org/1999/xhtml')
.html(lines);
const dim = divElem.node().getBoundingClientRect();
textElem.attr('height', Math.round(dim.height)).attr('width', Math.round(dim.width));
if (textData.class === 'noteText') {
const rectElem = elem.node().firstChild;
rectElem.setAttribute('height', dim.height + 2 * textData.textMargin);
const rectDim = rectElem.getBBox();
textElem
.attr('x', Math.round(rectDim.x + rectDim.width / 2 - dim.width / 2))
.attr('y', Math.round(rectDim.y + rectDim.height / 2 - dim.height / 2));
} else if (msgModel) {
let { startx, stopx, starty } = msgModel;
if (startx > stopx) {
const temp = startx;
startx = stopx;
stopx = temp;
}
textElem.attr('x', Math.round(startx + Math.abs(startx - stopx) / 2 - dim.width / 2))
if (textData.class === 'loopText') {
textElem.attr('y', Math.round(starty));
} else {
textElem.attr('y', Math.round(starty - dim.height));
}
}
return [textElem];
};
export const drawText = function (elem, textData) {
let prevTextHeight = 0,
textHeight = 0;
@@ -397,7 +440,7 @@ const drawActorTypeParticipant = function (elem, actor, conf, isFooter) {
}
}
_drawTextCandidateFunc(conf)(
_drawTextCandidateFunc(conf, hasKatex(actor.description))(
actor.description,
g,
rect.x,
@@ -487,7 +530,7 @@ const drawActorTypeActor = function (elem, actor, conf, isFooter) {
const bounds = actElem.node().getBBox();
actor.height = bounds.height;
_drawTextCandidateFunc(conf)(
_drawTextCandidateFunc(conf, hasKatex(actor.description))(
actor.description,
actElem,
rect.x,
@@ -623,7 +666,8 @@ export const drawLoop = function (elem, loopModel, labelText, conf) {
txt.fontWeight = fontWeight;
txt.wrap = true;
let textElem = drawText(g, txt);
let textElem = hasKatex(txt.text) ? drawKatex(g, txt, loopModel) : drawText(g, txt);
if (loopModel.sectionTitles !== undefined) {
loopModel.sectionTitles.forEach(function (item, idx) {
@@ -639,7 +683,13 @@ export const drawLoop = function (elem, loopModel, labelText, conf) {
txt.fontSize = fontSize;
txt.fontWeight = fontWeight;
txt.wrap = loopModel.wrap;
textElem = drawText(g, txt);
if (hasKatex(txt.text)) {
loopModel.starty = loopModel.sections[idx].y;
drawKatex(g, txt, loopModel);
} else {
drawText(g, txt);
}
let sectionHeight = Math.round(
textElem
.map((te) => (te._groups || te)[0][0].getBBox().height)
@@ -930,6 +980,29 @@ const _drawTextCandidateFunc = (function () {
_setTextAttrs(text, textAttrs);
}
function byKatex(content, g, x, y, width, height, textAttrs, conf) {
// TODO duplicate render calls, optimize
const dim = calculateMathMLDimensions(content, configApi.getConfig());
const s = g.append('switch');
const f = s
.append('foreignObject')
.attr('x', x + width / 2 - dim.width / 2)
.attr('y', y + height / 2 - dim.height / 2)
.attr('width', dim.width)
.attr('height', dim.height);
const text = f.append('xhtml:div').style('height', '100%').style('width', '100%');
text
.append('div')
.style('text-align', 'center')
.style('vertical-align', 'middle')
.html(renderKatex(content, configApi.getConfig()));
byTspan(content, s, x, y, width, height, textAttrs, conf);
_setTextAttrs(text, textAttrs);
}
/**
* @param {any} toText
* @param {any} fromTextAttrsDict
@@ -942,7 +1015,8 @@ const _drawTextCandidateFunc = (function () {
}
}
return function (conf) {
return function (conf, hasKatex = false) {
if (hasKatex) return byKatex;
return conf.textPlacement === 'fo' ? byFo : conf.textPlacement === 'old' ? byText : byTspan;
};
})();