index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import init, {matzo_run} from '../pkg/matzo_web.js';
  2. import {EditorView, basicSetup} from "codemirror";
  3. import {StreamLanguage} from "@codemirror/language";
  4. import {matzoLang} from "./language.js";
  5. window.onload = () => {
  6. const run = document.getElementById('run');
  7. const src = document.getElementById('src');
  8. const output = document.getElementById('output');
  9. const examples = document.getElementById('examples');
  10. const seed = document.getElementById('seed');
  11. let timer = null;
  12. init()
  13. .then(() => {
  14. const updateCode = () => {
  15. const code = editor.state.doc.toString();
  16. const data = JSON.stringify({
  17. 'source': code,
  18. 'seed': Number(seed.value),
  19. });
  20. // update the URL hash
  21. location.hash = '#' + encodeURIComponent(data);
  22. // run the code
  23. updateOutput(code);
  24. clearTimeout(timer);
  25. timer = null;
  26. };
  27. const updateOutput = (code) => {
  28. let result = matzo_run(code, BigInt(seed.value));
  29. output.innerHTML = result;
  30. };
  31. const editListener = EditorView.updateListener.of(_ => {
  32. if (timer !== null) {
  33. clearTimeout(timer);
  34. timer = null;
  35. }
  36. timer = setTimeout(updateCode, 500);
  37. });
  38. console.log(`Lang: ${matzoLang}`);
  39. const editor = new EditorView({
  40. extensions: [basicSetup, editListener, StreamLanguage.define(matzoLang)],
  41. parent: src,
  42. });
  43. if (location.hash) {
  44. const encoded = location.hash.substring(1);
  45. try {
  46. const data = JSON.parse(decodeURIComponent(encoded));
  47. editor.dispatch({
  48. changes: {from: 0, insert: data.source}
  49. });
  50. seed.value = Number(data.seed);
  51. console.log(`Setting seed value to ${seed.value}`);
  52. } catch (exn) {
  53. editor.dispatch({
  54. changes: {from: 0, insert: sources['simple']}
  55. });
  56. seed.value = 12345;
  57. }
  58. } else {
  59. editor.dispatch({
  60. changes: {from: 0, insert: sources['simple']}
  61. });
  62. }
  63. examples.onchange = () => {
  64. const stuff = sources[examples.value]
  65. editor.dispatch({changes: {from: 0, to: editor.state.doc.length, insert: stuff}});
  66. };
  67. seed.onchange = () => {
  68. updateCode();
  69. }
  70. run.onclick = () => {
  71. seed.value = Math.floor(Math.random() * 0xffffffff);
  72. updateCode();
  73. }
  74. });
  75. };