]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/framework/manager.ts
Lexical: Added view/edit source code button/form/action
[bookstack] / resources / js / wysiwyg / ui / framework / manager.ts
1 import {EditorFormModal, EditorFormModalDefinition} from "./modals";
2 import {EditorUiContext} from "./core";
3 import {EditorDecorator} from "./decorator";
4
5
6 export class EditorUIManager {
7
8     protected modalDefinitionsByKey: Record<string, EditorFormModalDefinition> = {};
9     protected decoratorConstructorsByType: Record<string, typeof EditorDecorator> = {};
10     protected decoratorInstancesByNodeKey: Record<string, EditorDecorator> = {};
11     protected context: EditorUiContext|null = null;
12
13     setContext(context: EditorUiContext) {
14         this.context = context;
15     }
16
17     getContext(): EditorUiContext {
18         if (this.context === null) {
19             throw new Error(`Context attempted to be used without being set`);
20         }
21
22         return this.context;
23     }
24
25     registerModal(key: string, modalDefinition: EditorFormModalDefinition) {
26         this.modalDefinitionsByKey[key] = modalDefinition;
27     }
28
29     createModal(key: string): EditorFormModal {
30         const modalDefinition = this.modalDefinitionsByKey[key];
31         if (!modalDefinition) {
32             throw new Error(`Attempted to show modal of key [${key}] but no modal registered for that key`);
33         }
34
35         const modal = new EditorFormModal(modalDefinition);
36         modal.setContext(this.getContext());
37
38         return modal;
39     }
40
41     registerDecoratorType(type: string, decorator: typeof EditorDecorator) {
42         this.decoratorConstructorsByType[type] = decorator;
43     }
44
45     getDecorator(decoratorType: string, nodeKey: string): EditorDecorator {
46         if (this.decoratorInstancesByNodeKey[nodeKey]) {
47             return this.decoratorInstancesByNodeKey[nodeKey];
48         }
49
50         const decoratorClass = this.decoratorConstructorsByType[decoratorType];
51         if (!decoratorClass) {
52             throw new Error(`Attempted to use decorator of type [${decoratorType}] but not decorator registered for that type`);
53         }
54
55         // @ts-ignore
56         const decorator = new decoratorClass(nodeKey);
57         this.decoratorInstancesByNodeKey[nodeKey] = decorator;
58         return decorator;
59     }
60 }