main.ts (2887B)
1 import init, { WebRegex } from "../pkg/automaton" 2 import { Graphviz } from "@hpcc-js/wasm"; 3 import svgPanZoom from "svg-pan-zoom"; 4 5 function updateAcceptance(acceptanceDisplay: HTMLElement | null, regex: WebRegex, input: string) { 6 if (!acceptanceDisplay) { 7 return; 8 } 9 acceptanceDisplay.innerText = regex.accepts(input).toString(); 10 } 11 12 function updateError(errorDisplay: HTMLElement | null, error: string) { 13 if (!errorDisplay) { 14 return; 15 } 16 errorDisplay.innerText = error; 17 } 18 19 function clearError(errorDisplay: HTMLElement | null) { 20 if (!errorDisplay) { 21 return; 22 } 23 errorDisplay.innerText = ""; 24 } 25 26 function updateAutomatonGraph(svgElement: HTMLElement | null, dot: string) { 27 if (!svgElement) { return; } 28 Graphviz.load().then((graphviz) => { 29 const dfaSVGString = graphviz.dot(dot); 30 svgElement.innerHTML = dfaSVGString; 31 let svg = svgPanZoom(svgElement); 32 svg.destroy(); 33 svg = svgPanZoom(svgElement); 34 svg.enablePan(); 35 svg.enableZoom(); 36 }); 37 } 38 39 function main() { 40 let regex = new WebRegex(""); 41 42 let acceptanceDisplay = document.getElementById("acceptance"); 43 const regexField = <HTMLInputElement | null>document.getElementById("regex"); 44 const submitRegexButton = document.getElementById("submitRegex"); 45 const inputField = <HTMLInputElement | null>document.getElementById("inputString"); 46 const regexError = document.getElementById("regexError"); 47 48 const enfaSVG = document.getElementById("enfaSVGElement"); 49 const nfaSVG = document.getElementById("nfaSVGElement"); 50 const dfaSVG = document.getElementById("dfaSVGElement"); 51 52 try { 53 updateAutomatonGraph(enfaSVG, regex.enfa_dot()); 54 updateAutomatonGraph(nfaSVG, regex.nfa_dot()); 55 updateAutomatonGraph(dfaSVG, regex.dfa_dot()); 56 } catch (e) { 57 console.error("Unable to get dot!\n", e.to_string()); 58 updateError(regexError, e.to_string()); 59 } 60 61 submitRegexButton?.addEventListener("click", () => { 62 try { 63 regex = new WebRegex(regexField?.value ?? ""); 64 clearError(regexError); 65 } catch (e) { 66 console.error("Unable to make regex!\n", e.to_string()); 67 updateError(regexError, e.to_string()); 68 } 69 updateAcceptance(acceptanceDisplay, regex, inputField?.value ?? ""); 70 try { 71 updateAutomatonGraph(enfaSVG, regex.enfa_dot()); 72 updateAutomatonGraph(nfaSVG, regex.nfa_dot()); 73 updateAutomatonGraph(dfaSVG, regex.dfa_dot()); 74 } catch (e) { 75 console.error("Unable to get dot!\n", e.to_string()); 76 updateError(regexError, e.to_string()); 77 } 78 }); 79 80 inputField?.addEventListener("input", () => { 81 updateAcceptance(acceptanceDisplay, regex, inputField?.value ?? ""); 82 }); 83 } 84 85 86 init().then(main); 87