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.

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