domConsole.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import $ from 'jquery';
  2. export class DOMConsole {
  3. static get USER () {
  4. return 0;
  5. }
  6. static get INFO () {
  7. return 1;
  8. }
  9. static get ERR () {
  10. return 2;
  11. }
  12. constructor (elementID) {
  13. this.input = null;
  14. this.needInput = true;
  15. this.parent = $(elementID);
  16. this.setup();
  17. this.inputListeners = [];
  18. }
  19. setup () {
  20. this._setupDom();
  21. this._setupEvents();
  22. }
  23. _setupEvents () {
  24. this.input.on("keydown", (event) => {
  25. if (!this.needInput) {
  26. event.preventDefault();
  27. return;
  28. }
  29. const keyCode = event.which;
  30. if (keyCode === 13) {
  31. let text = this.input.val();
  32. text = text.replace('[\n\r]+', '');
  33. this.notifyListeners(text);
  34. this.write(text);
  35. this.input.val("");
  36. }
  37. });
  38. }
  39. _setupDom () {
  40. const termDiv = $("<div></div>");
  41. termDiv.addClass("ivprog-term-div");
  42. this.input = $('<input text="type">')
  43. this.input.addClass("ivprog-term-input");
  44. termDiv.append(this.input);
  45. this.parent.append(termDiv);
  46. }
  47. notifyListeners (text) {
  48. this.inputListeners.forEach(resolve => resolve(text));
  49. this.inputListeners.splice(0, this.inputListeners.length);
  50. this.needInput = false;
  51. }
  52. write (text) {
  53. this._appendText(text, DOMConsole.USER);
  54. }
  55. info (text) {
  56. this._appendText(text, DOMConsole.INFO);
  57. }
  58. err (text) {
  59. this._appendText(text, DOMConsole.ERR);
  60. }
  61. _appendText (text, type) {
  62. const divClass = this.getClassForType(type);
  63. const textDiv = $("<div></div>");
  64. textDiv.addClass(divClass);
  65. textDiv.append(text);
  66. textDiv.insertBefore(this.input);
  67. }
  68. getClassForType (type) {
  69. switch (type) {
  70. case DOMConsole.USER:
  71. return "ivprog-term-userText";
  72. case DOMConsole.INFO:
  73. return "ivprog-term-info";
  74. case DOMConsole.ERR:
  75. return "ivprog-term-error";
  76. }
  77. }
  78. dispose () {
  79. this.parent.off();
  80. this.input.off();
  81. this.input = null;
  82. this.parent.empty();
  83. }
  84. requestInput (callback) {
  85. this.inputListeners.push(callback);
  86. this.input.focus();
  87. this.needInput = true;
  88. }
  89. sendOutput (text) {
  90. text.split("\n").forEach(t => {
  91. t = t.replace(/\t/g,'&#9;');
  92. this.write(t)
  93. });
  94. }
  95. clear () {
  96. this.input.parent().children().not(this.input).remove();
  97. this.input.val("");
  98. }
  99. }