You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.5 KiB

  1. const EventEmitter = require('events')
  2. module.exports = class Window extends EventEmitter {
  3. constructor (options) {
  4. super()
  5. this.visible = false
  6. this.dom = document.createElement('div')
  7. this.dom.className = 'Window'
  8. this.header = document.createElement('div')
  9. this.header.className = 'header'
  10. this.header.innerHTML = options.title
  11. this.dom.appendChild(this.header)
  12. this.closeBtn = document.createElement('div')
  13. this.closeBtn.className = 'closeBtn'
  14. this.closeBtn.onclick = (e) => {
  15. this.close()
  16. e.stopImmediatePropagation()
  17. }
  18. this.header.appendChild(this.closeBtn)
  19. this.content = document.createElement('div')
  20. this.content.className = 'content'
  21. this.dom.appendChild(this.content)
  22. dragElement(this.dom)
  23. this.dom.onclick = () => {
  24. if (!this.visible) { return }
  25. const activeEl = document.activeElement
  26. if (document.body.lastElementChild !== this.dom) {
  27. document.body.appendChild(this.dom)
  28. activeEl.focus()
  29. }
  30. }
  31. }
  32. show () {
  33. this.visible = true
  34. document.body.appendChild(this.dom)
  35. this.emit('show')
  36. }
  37. close () {
  38. this.visible = false
  39. document.body.removeChild(this.dom)
  40. this.emit('close')
  41. }
  42. }
  43. // copied from https://www.w3schools.com/HOWTO/howto_js_draggable.asp
  44. // Make the DIV element draggable:
  45. function dragElement(elmnt) {
  46. var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  47. if (elmnt.firstChild) {
  48. // if present, the header is where you move the DIV from:
  49. elmnt.firstChild.onmousedown = dragMouseDown;
  50. } else {
  51. // otherwise, move the DIV from anywhere inside the DIV:
  52. elmnt.onmousedown = dragMouseDown;
  53. }
  54. function dragMouseDown(e) {
  55. e = e || window.event;
  56. e.preventDefault();
  57. // get the mouse cursor position at startup:
  58. pos3 = e.clientX;
  59. pos4 = e.clientY;
  60. document.onmouseup = closeDragElement;
  61. // call a function whenever the cursor moves:
  62. document.onmousemove = elementDrag;
  63. }
  64. function elementDrag(e) {
  65. e = e || window.event;
  66. e.preventDefault();
  67. // calculate the new cursor position:
  68. pos1 = pos3 - e.clientX;
  69. pos2 = pos4 - e.clientY;
  70. pos3 = e.clientX;
  71. pos4 = e.clientY;
  72. // set the element's new position:
  73. elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  74. elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  75. }
  76. function closeDragElement() {
  77. // stop moving when mouse button is released:
  78. document.onmouseup = null;
  79. document.onmousemove = null;
  80. }
  81. }