index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import init, {matzo_run} from '../pkg/matzo_web.js';
  2. import {EditorView, basicSetup} from "codemirror"
  3. window.onload = () => {
  4. const run = document.getElementById('run');
  5. const src = document.getElementById('src');
  6. const output = document.getElementById('output');
  7. const examples = document.getElementById('examples');
  8. const seed = document.getElementById('seed');
  9. let timer = null;
  10. init()
  11. .then(() => {
  12. const updateCode = () => {
  13. const code = editor.state.doc.toString();
  14. // update the URL hash
  15. location.hash = '#' + encodeURIComponent(code);
  16. // run the code
  17. updateOutput(code);
  18. clearTimeout(timer);
  19. timer = null;
  20. };
  21. const updateOutput = (code) => {
  22. let result = matzo_run(code, BigInt(seed.value));
  23. output.innerHTML = result;
  24. };
  25. const editListener = EditorView.updateListener.of(_ => {
  26. if (timer !== null) {
  27. clearTimeout(timer);
  28. timer = null;
  29. }
  30. timer = setTimeout(updateCode, 500);
  31. });
  32. const editor = new EditorView({
  33. extensions: [basicSetup, editListener],
  34. parent: src,
  35. });
  36. if (location.hash) {
  37. const encoded = location.hash.substring(1);
  38. editor.dispatch({
  39. changes: {from: 0, insert: decodeURIComponent(encoded)}
  40. });
  41. } else {
  42. editor.dispatch({
  43. changes: {from: 0, insert: sources['simple']}
  44. });
  45. }
  46. examples.onchange = () => {
  47. const stuff = sources[examples.value]
  48. editor.dispatch({changes: {from: 0, to: editor.state.doc.length, insert: stuff}});
  49. };
  50. seed.onchange = () => {
  51. updateOutput(editor.state.doc.toString());
  52. }
  53. run.onclick = () => {
  54. seed.value = Math.floor(Math.random() * 0xffffffff);
  55. updateOutput(editor.state.doc.toString());
  56. }
  57. });
  58. };