index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const term = new Terminal();
  2. var command = "";
  3. var need_more_lines = false;
  4. var stopped = false;
  5. var repl = 0;
  6. var Module = {
  7. 'print': function(text) {
  8. term.write(text + "\r\n");
  9. },
  10. 'printErr': function(text) {
  11. term.write(text + "\r\n");
  12. },
  13. 'onRuntimeInitialized': function(text) {
  14. var vm = Module.ccall('pkpy_new_vm', 'number', ['boolean'], [true]);
  15. repl = Module.ccall('pkpy_new_repl', 'number', ['number'], [vm]);
  16. term.write(need_more_lines ? "... " : ">>> ");
  17. },
  18. 'onAbort': function(text) {
  19. stopped = true;
  20. },
  21. };
  22. function term_init() {
  23. term.open(document.getElementById('terminal'));
  24. term.onData(e => {
  25. if (stopped) return;
  26. switch (e) {
  27. case '\r': // Enter
  28. term.write("\r\n");
  29. if(command == 'exit()'){
  30. stopped = true;
  31. term.write("Bye!\r\n");
  32. break;
  33. }
  34. need_more_lines = Module.ccall('pkpy_repl_input', 'number', ['number', 'string'], [repl, command]) == 0;
  35. command = '';
  36. term.write(need_more_lines ? "... " : ">>> ");
  37. break;
  38. case '\u007F': // Backspace (DEL)
  39. // Do not delete the prompt
  40. if (term._core.buffer.x > 4) { // '>>> ' or '... '
  41. term.write('\b \b');
  42. if (command.length > 0) {
  43. command = command.substr(0, command.length - 1);
  44. }
  45. }
  46. break;
  47. default: // Print all other characters for demo
  48. if (e >= String.fromCharCode(0x20) && e <= String.fromCharCode(0x7E) || e >= '\u00a0') {
  49. command += e;
  50. term.write(e);
  51. }
  52. }
  53. });
  54. }