]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/framework/decorator.ts
570b8222b9c8e1fed5cb8b08db28382d859d9fa8
[bookstack] / resources / js / wysiwyg / ui / framework / decorator.ts
1 import {EditorUiContext} from "./core";
2 import {LexicalNode} from "lexical";
3
4 export interface EditorDecoratorAdapter {
5     type: string;
6     getNode(): LexicalNode;
7 }
8
9 export abstract class EditorDecorator {
10
11     protected node: LexicalNode | null = null;
12     protected context: EditorUiContext;
13
14     private onDestroyCallbacks: (() => void)[] = [];
15
16     constructor(context: EditorUiContext) {
17         this.context = context;
18     }
19
20     protected getNode(): LexicalNode {
21         if (!this.node) {
22             throw new Error('Attempted to get use node without it being set');
23         }
24
25         return this.node;
26     }
27
28     setNode(node: LexicalNode) {
29         this.node = node;
30     }
31
32     /**
33      * Register a callback to be ran on destroy of this decorator's node.
34      */
35     protected onDestroy(callback: () => void) {
36         this.onDestroyCallbacks.push(callback);
37     }
38
39     /**
40      * Render the decorator.
41      * Can run on both creation and update for a node decorator.
42      * If an element is returned, this will be appended to the element
43      * that is being decorated.
44      */
45     abstract render(context: EditorUiContext, decorated: HTMLElement): HTMLElement|void;
46
47     /**
48      * Destroy this decorator. Used for tear-down operations upon destruction
49      * of the underlying node this decorator is attached to.
50      */
51     destroy(context: EditorUiContext): void {
52         for (const callback of this.onDestroyCallbacks) {
53             callback();
54         }
55     }
56
57 }