]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/framework/core.ts
d437b36bd0936d47f1be92507592fb220ae72619
[bookstack] / resources / js / wysiwyg / ui / framework / core.ts
1 import {BaseSelection, LexicalEditor} from "lexical";
2 import {EditorUIManager} from "./manager";
3 import {el} from "../../helpers";
4
5 export type EditorUiStateUpdate = {
6     editor: LexicalEditor,
7     selection: BaseSelection|null,
8 };
9
10 export type EditorUiContext = {
11     editor: LexicalEditor,
12     translate: (text: string) => string,
13     manager: EditorUIManager,
14     lastSelection: BaseSelection|null,
15 };
16
17 export abstract class EditorUiElement {
18     protected dom: HTMLElement|null = null;
19     private context: EditorUiContext|null = null;
20
21     protected abstract buildDOM(): HTMLElement;
22
23     setContext(context: EditorUiContext): void {
24         this.context = context;
25     }
26
27     getContext(): EditorUiContext {
28         if (this.context === null) {
29             throw new Error('Attempted to use EditorUIContext before it has been set');
30         }
31
32         return this.context;
33     }
34
35     getDOMElement(): HTMLElement {
36         if (!this.dom) {
37             this.dom = this.buildDOM();
38         }
39
40         return this.dom;
41     }
42
43     trans(text: string) {
44         return this.getContext().translate(text);
45     }
46
47     updateState(state: EditorUiStateUpdate): void {
48         return;
49     }
50 }
51
52 export class EditorContainerUiElement extends EditorUiElement {
53     protected children : EditorUiElement[];
54
55     constructor(children: EditorUiElement[]) {
56         super();
57         this.children = children;
58     }
59
60     protected buildDOM(): HTMLElement {
61         return el('div', {}, this.getChildren().map(child => child.getDOMElement()));
62     }
63
64     getChildren(): EditorUiElement[] {
65         return this.children;
66     }
67
68     updateState(state: EditorUiStateUpdate): void {
69         for (const child of this.children) {
70             child.updateState(state);
71         }
72     }
73
74     setContext(context: EditorUiContext) {
75         super.setContext(context);
76         for (const child of this.getChildren()) {
77             child.setContext(context);
78         }
79     }
80 }
81
82 export class EditorSimpleClassContainer extends EditorContainerUiElement {
83     protected className;
84
85     constructor(className: string, children: EditorUiElement[]) {
86         super(children);
87         this.className = className;
88     }
89
90     protected buildDOM(): HTMLElement {
91         return el('div', {
92             class: this.className,
93         }, this.getChildren().map(child => child.getDOMElement()));
94     }
95 }
96