Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active July 9, 2020 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/8a2a225355942afa0705be4a468d70eb to your computer and use it in GitHub Desktop.
Save baweaver/8a2a225355942afa0705be4a468d70eb to your computer and use it in GitHub Desktop.
const ROOT = document.getElementById("root");
const PREFIX = '::';
const GRAY = '#CCC';
const KATEX_OPTIONS = {
throwOnError: false
};
function slicePrefix(str) {
return str.slice(PREFIX.length);
}
function textColorTag(str) {
return String.raw`\textcolor{${str}}`;
}
function interpolateKatex(template, labels) {
const replaceKeys = Object.keys(labels).map(k => `${PREFIX}${k}`)
const replaceRegex = new RegExp(replaceKeys.join('|'), 'g');
const replaceMap = Object.fromEntries(
replaceKeys.map(k => [
k, textColorTag(labels[slicePrefix(k)])]
)
);
return template.replace(replaceRegex, s => replaceMap[s]);
}
function greyExcept(labels, highlightedLabel) {
return Object.fromEntries(
Object.keys(labels).map(k => k === highlightedLabel ? labels[k] : GRAY)
)
}
function renderInterpolatedKatex(template, labels) {
return katex.render(interpolateKatex(template, labels), ROOT, KATEX_OPTIONS)
}
function renderKatex(template) {
return katex.render(template, ROOT, KATEX_OPTIONS);
}
const baseTemplate = String.raw`
::energy{X}_{::freq{k}} =
::path{
\frac{1}{N}
\sum_{n=0}^{N-1}
}
::signal{x_n}
::spin{e}^{
::signal{i}
::circle{2 \pi}
::freq{k}
::path{
\frac{n}{N}
}
}
`;
const baseColor = {
freq: '#228B22',
energy: '#7200AC',
signal: '#FD6B7B',
spin: '#FD6B7B',
circle: '#FFA97B',
path: '#DD56A2',
};
const colorKeys = Object.keys(baseColors);
const defaultFormula = interpolateKatex(baseTemplate, baseColor);
colorKeys.forEach(k => {
const nonHighlightedKeys = colorKeys
.filter(ck => ck !== k)
.map(ck => `.${ck}`)
.join(', ');
const $nonHighlightedElements = $(nonHighlightedKeys);
$(`.${k}`).hover(() => {
renderInterpolatedKatex(baseTemplate, greyExcept(baseColors, k));
$nonHighlightedElements.addClass('greyed');
}, () => {
renderKatex(defaultFormula);
$nonHighlightedElements.removeClass('greyed');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment