Element.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import EventEmitter from 'node:events'
  2. import exception from 'tui-lib/util/exception'
  3. export default class Element extends EventEmitter {
  4. // The basic class containing methods for working with an element hierarchy.
  5. // Generally speaking, you usually want to extend DisplayElement instead of
  6. // this class.
  7. constructor() {
  8. super()
  9. this.children = []
  10. this.parent = null
  11. }
  12. eachDescendant(fn) {
  13. // Run a function on this element, all of its children, all of their
  14. // children, etc.
  15. fn(this)
  16. for (const child of this.children) {
  17. child.eachDescendant(fn)
  18. }
  19. }
  20. addChild(child, afterIndex = this.children.length, {fixLayout = true} = {}) {
  21. // TODO Don't let a direct ancestor of this be added as a child. Don't
  22. // let itself be one of its childs either!
  23. if (child === this) {
  24. throw exception(
  25. 'EINVALIDHIERARCHY', 'An element cannot be a child of itself')
  26. }
  27. child.parent = this
  28. if (afterIndex === this.children.length) {
  29. this.children.push(child)
  30. } else {
  31. this.children.splice(afterIndex, 0, child)
  32. }
  33. if (fixLayout) {
  34. child.fixLayout()
  35. }
  36. }
  37. removeChild(child, {fixLayout = true} = {}) {
  38. // Removes the given child element from the children list of this
  39. // element. It won't be rendered in the future. If the given element
  40. // isn't a direct child of this element, nothing will happen.
  41. if (child.parent !== this) {
  42. return
  43. }
  44. child.parent = null
  45. this.children.splice(this.children.indexOf(child), 1)
  46. if (fixLayout) {
  47. this.fixLayout()
  48. }
  49. }
  50. get root() {
  51. let el = this
  52. while (el.parent) {
  53. el = el.parent
  54. }
  55. return el
  56. }
  57. get directAncestors() {
  58. const ancestors = []
  59. let el = this
  60. while (el.parent) {
  61. el = el.parent
  62. ancestors.push(el)
  63. }
  64. return ancestors
  65. }
  66. }