import React, { useState } from "react"; import katex from "katex"; import "./App.css"; import { AST, compile, toLatex } from "ulm-js"; const useCompiler = ( initialCode: string ): [ string, { ast?: AST; error?: string }, { html?: string; error?: string }, (newCode: string) => void ] => { const render = ( newCode: string ): [{ ast?: AST; error?: string }, { html?: string; error?: string }] => { let newAst, newHtml; try { newAst = { ast: compile(newCode) }; try { newHtml = { html: katex.renderToString(toLatex(newAst.ast), { throwOnError: false }) }; } catch (error) { newHtml = { error: error.toString() }; } } catch (error) { newAst = { error: error.toString() }; newHtml = { html: "" }; } return [newAst, newHtml]; }; const [initialAst, initialHtml] = render(initialCode); const [code, setCode] = useState(initialCode); const [ast, setAst] = useState(initialAst); const [html, setHtml] = useState(initialHtml); return [ code, ast, html, (newCode: string): void => { const [newAst, newHtml] = render(newCode); setCode(newCode); setAst(newAst); setHtml(newHtml); } ]; }; const App: React.FC = () => { const [ code, { ast, error: astError }, { html, error: htmlError }, update ] = useCompiler( "NumericEqualRelation(\n NumericAdditionOperation(\n NumericAdditionOperation(0.1, 0.3),\n 0.2\n ),\n 3/5\n)" ); return (
{astError ? astError : JSON.stringify(ast, null, 2)}