domConsole.js 2.4 KB

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