index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. const data = JSON.stringify({
  15. 'source': code,
  16. 'seed': Number(seed.value),
  17. });
  18. // update the URL hash
  19. location.hash = '#' + encodeURIComponent(data);
  20. // run the code
  21. updateOutput(code);
  22. clearTimeout(timer);
  23. timer = null;
  24. };
  25. const updateOutput = (code) => {
  26. let result = matzo_run(code, BigInt(seed.value));
  27. output.innerHTML = result;
  28. };
  29. const editListener = EditorView.updateListener.of(_ => {
  30. if (timer !== null) {
  31. clearTimeout(timer);
  32. timer = null;
  33. }
  34. timer = setTimeout(updateCode, 500);
  35. });
  36. const editor = new EditorView({
  37. extensions: [basicSetup, editListener],
  38. parent: src,
  39. });
  40. if (location.hash) {
  41. const encoded = location.hash.substring(1);
  42. try {
  43. const data = JSON.parse(decodeURIComponent(encoded));
  44. editor.dispatch({
  45. changes: {from: 0, insert: data.source}
  46. });
  47. seed.value = Number(data.seed);
  48. console.log(`Setting seed value to ${seed.value}`);
  49. } catch (exn) {
  50. editor.dispatch({
  51. changes: {from: 0, insert: sources['simple']}
  52. });
  53. seed.value = 12345;
  54. }
  55. } else {
  56. editor.dispatch({
  57. changes: {from: 0, insert: sources['simple']}
  58. });
  59. }
  60. examples.onchange = () => {
  61. const stuff = sources[examples.value]
  62. editor.dispatch({changes: {from: 0, to: editor.state.doc.length, insert: stuff}});
  63. };
  64. seed.onchange = () => {
  65. updateCode();
  66. }
  67. run.onclick = () => {
  68. seed.value = Math.floor(Math.random() * 0xffffffff);
  69. updateCode();
  70. }
  71. });
  72. };