Last active
April 9, 2022 21:43
-
-
Save mattvague/961ad897f2e6b9777668abe43bca4a45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @typedef {import('mdast').Root} Root | |
* @typedef {import('mdast-util-math')} DoNotTouchAsThisImportIncludesMathInTree | |
* @typedef Options | |
* @property {string} [startDelimiter=string] | |
* @property {string} [endDelimiter=string] | |
*/ | |
import {visit, CONTINUE} from 'unist-util-visit' | |
import * as acorn from 'acorn' | |
/** | |
* WIP!!! | |
* Plugin to support parsing JS expressions in math (for use in MDX) | |
* e.g. | |
* ``` | |
* export const myVar = "x" | |
* $$ | |
* What is the derivative of $f(\eval{myVar}) = \eval{myVar}^2 + \eval{1 + 2 + 3}$? | |
* $$ | |
* ``` | |
* | |
* @type {import('unified').Plugin<[Options?] | void[], Root, Root>} | |
*/ | |
export default function casPlugin(options = {}) { | |
return (tree) => { | |
visit(tree, "math", (node, index, parent) => { | |
const expression = `String.raw\`${node.value}\`` | |
const estree = acorn.parse(expression, { ecmaVersion: 2020 }) | |
parent.children.splice(index, 1, { | |
type: 'mdxJsxFlowElement', | |
name: 'Katex', | |
attributes: [], | |
children: [{ | |
type: 'mdxTextExpression', | |
value: expression, | |
data: { | |
estree | |
} | |
}] | |
}) | |
return [CONTINUE, index] | |
}); | |
visit(tree, "inlineMath", (node, index, parent) => { | |
const expression = `String.raw\`${node.value}\`` | |
const estree = acorn.parse(expression, { ecmaVersion: 2020 }) | |
parent.children.splice(index, 1, { | |
type: 'mdxJsxTextElement', | |
name: 'Katex', | |
children: [{ | |
type: 'mdxTextExpression', | |
value: expression, | |
data: { | |
estree | |
} | |
}] | |
}) | |
return [CONTINUE, index] | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment