ConditionalNode.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { RendererNode } from "../../../model/vdom/RendererNode";
  2. import { PupperNode } from "../../../model/vdom/PupperNode";
  3. import { Renderer } from "../Renderer";
  4. export class ConditionalNode extends PupperNode {
  5. /**
  6. * The consequence if the condition is met.
  7. */
  8. declare private consequent: RendererNode[] | undefined;
  9. /**
  10. * The alternative consequence if the condition is not met.
  11. */
  12. declare private alternate: RendererNode[] | undefined;
  13. constructor(
  14. node: VirtualDOM.VNode,
  15. parent: RendererNode | null = null,
  16. renderer: Renderer
  17. ) {
  18. super(node, parent, renderer);
  19. }
  20. protected initNode() {
  21. super.initNode();
  22. this.consequent = this.children
  23. .find((child) => child.getAttribute("x-if-cond") === "consequent")
  24. ?.delete()
  25. .children;
  26. this.alternate = this.children
  27. .find((child) => child.getAttribute("x-if-cond") === "alternate")
  28. ?.delete()
  29. .children;
  30. // If has no consequent
  31. if (!this.consequent) {
  32. throw new Error("Found a conditional node without consequence.");
  33. }
  34. }
  35. public clone() {
  36. const clone = new ConditionalNode(this.node, this.parent, this.renderer);
  37. clone.consequent = this.cloneConsequent();
  38. clone.alternate = this.cloneAlternate();
  39. return clone;
  40. }
  41. /**
  42. * Determines if has the conditional has a consequence (then).
  43. * @returns
  44. */
  45. public hasConsequent() {
  46. return this.consequent !== undefined;
  47. }
  48. /**
  49. * Determines if has the conditional has an alternative (else).
  50. * @returns
  51. */
  52. public hasAlternate() {
  53. return this.alternate !== undefined;
  54. }
  55. /**
  56. * Clone the consequent nodes.
  57. * @returns
  58. */
  59. public cloneConsequent() {
  60. return this.consequent.map((child) => child.clone().setParent(this));
  61. }
  62. /**
  63. * Clone the alternate nodes.
  64. * @returns
  65. */
  66. public cloneAlternate() {
  67. return this.alternate?.map((child) => child.clone().setParent(this));
  68. }
  69. }