NodeModel.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import Plugin, { PugNodes, PugAST } from "../../core/Plugin";
  2. export interface IParserNode extends Record<string, any> {
  3. type: string;
  4. attributes?: Record<string, string | boolean | number>;
  5. children?: IParserNode[] | NodeModel[];
  6. }
  7. export abstract class NodeModel<TChildren = any> {
  8. /**
  9. * The children nodes to this node.
  10. */
  11. public children: TChildren[] = [];
  12. constructor(
  13. /**
  14. * The parent array that contains this node.
  15. */
  16. public parent?: NodeModel
  17. ) {
  18. }
  19. /**
  20. * Checks if the node has children nodes.
  21. * @returns
  22. */
  23. public hasChildren() {
  24. return this.children && this.children.length > 0;
  25. }
  26. /**
  27. * Retrieves the node children nodes.
  28. * @returns
  29. */
  30. public getChildren() {
  31. return this.children;
  32. }
  33. /**
  34. * Sets the node children nodes.
  35. * @param children The children nodes.
  36. */
  37. public setChildren(children: TChildren[]) {
  38. this.children = children;
  39. }
  40. /**
  41. * Retrieves the index inside the parent children for this node.
  42. * @returns
  43. */
  44. public getIndex() {
  45. return this.parent.getChildren().indexOf(this);
  46. }
  47. /**
  48. * Checks if has a previous node.
  49. * @returns
  50. */
  51. public hasPrev(): boolean {
  52. return this.getPrevNode() !== null;
  53. }
  54. /**
  55. * Retrieves the previous node to this node.
  56. * @returns
  57. */
  58. public getPrevNode(): NodeModel | null {
  59. return this.parent.children[this.parent.children.indexOf(this) - 1] || null;
  60. }
  61. /**
  62. * Checks if has a next node.
  63. * @returns
  64. */
  65. public hasNext(): boolean {
  66. return this.getNextNode() !== null;
  67. }
  68. /**
  69. * Retrieves the next node to this node.
  70. * @returns
  71. */
  72. public getNextNode() {
  73. return this.parent.children[this.parent.children.indexOf(this) + 1] || null;
  74. }
  75. /**
  76. * Removes the current node from the parent.
  77. */
  78. public delete() {
  79. this.parent.children.splice(this.getIndex(), 1);
  80. }
  81. /**
  82. * Retrieves all the containers that can have children nodes.
  83. * @returns
  84. */
  85. public getChildrenContainers() {
  86. return [this.children];
  87. }
  88. /**
  89. * Converts the node back into a pug node.
  90. * @returns
  91. */
  92. abstract toPugNode(): PugNodes | PugAST;
  93. }