1 import {EditorFormModal, EditorFormModalDefinition} from "./modals";
2 import {EditorContainerUiElement, EditorUiContext, EditorUiElement, EditorUiStateUpdate} from "./core";
3 import {EditorDecorator, EditorDecoratorAdapter} from "./decorator";
4 import {$getSelection, BaseSelection, COMMAND_PRIORITY_LOW, LexicalEditor, SELECTION_CHANGE_COMMAND} from "lexical";
5 import {DecoratorListener} from "lexical/LexicalEditor";
6 import type {NodeKey} from "lexical/LexicalNode";
7 import {EditorContextToolbar, EditorContextToolbarDefinition} from "./toolbars";
9 export type SelectionChangeHandler = (selection: BaseSelection|null) => void;
11 export class EditorUIManager {
13 protected modalDefinitionsByKey: Record<string, EditorFormModalDefinition> = {};
14 protected activeModalsByKey: Record<string, EditorFormModal> = {};
15 protected decoratorConstructorsByType: Record<string, typeof EditorDecorator> = {};
16 protected decoratorInstancesByNodeKey: Record<string, EditorDecorator> = {};
17 protected context: EditorUiContext|null = null;
18 protected toolbar: EditorContainerUiElement|null = null;
19 protected contextToolbarDefinitionsByKey: Record<string, EditorContextToolbarDefinition> = {};
20 protected activeContextToolbars: EditorContextToolbar[] = [];
21 protected selectionChangeHandlers: Set<SelectionChangeHandler> = new Set();
23 setContext(context: EditorUiContext) {
24 this.context = context;
25 this.setupEventListeners(context);
26 this.setupEditor(context.editor);
29 getContext(): EditorUiContext {
30 if (this.context === null) {
31 throw new Error(`Context attempted to be used without being set`);
37 triggerStateUpdateForElement(element: EditorUiElement) {
40 editor: this.getContext().editor
44 registerModal(key: string, modalDefinition: EditorFormModalDefinition) {
45 this.modalDefinitionsByKey[key] = modalDefinition;
48 createModal(key: string): EditorFormModal {
49 const modalDefinition = this.modalDefinitionsByKey[key];
50 if (!modalDefinition) {
51 throw new Error(`Attempted to show modal of key [${key}] but no modal registered for that key`);
54 const modal = new EditorFormModal(modalDefinition, key);
55 modal.setContext(this.getContext());
60 setModalActive(key: string, modal: EditorFormModal): void {
61 this.activeModalsByKey[key] = modal;
64 setModalInactive(key: string): void {
65 delete this.activeModalsByKey[key];
68 getActiveModal(key: string): EditorFormModal|null {
69 return this.activeModalsByKey[key];
72 registerDecoratorType(type: string, decorator: typeof EditorDecorator) {
73 this.decoratorConstructorsByType[type] = decorator;
76 protected getDecorator(decoratorType: string, nodeKey: string): EditorDecorator {
77 if (this.decoratorInstancesByNodeKey[nodeKey]) {
78 return this.decoratorInstancesByNodeKey[nodeKey];
81 const decoratorClass = this.decoratorConstructorsByType[decoratorType];
82 if (!decoratorClass) {
83 throw new Error(`Attempted to use decorator of type [${decoratorType}] but not decorator registered for that type`);
87 const decorator = new decoratorClass(nodeKey);
88 this.decoratorInstancesByNodeKey[nodeKey] = decorator;
92 getDecoratorByNodeKey(nodeKey: string): EditorDecorator|null {
93 return this.decoratorInstancesByNodeKey[nodeKey] || null;
96 setToolbar(toolbar: EditorContainerUiElement) {
98 this.toolbar.getDOMElement().remove();
101 this.toolbar = toolbar;
102 toolbar.setContext(this.getContext());
103 this.getContext().containerDOM.prepend(toolbar.getDOMElement());
106 registerContextToolbar(key: string, definition: EditorContextToolbarDefinition) {
107 this.contextToolbarDefinitionsByKey[key] = definition;
110 protected triggerStateUpdate(update: EditorUiStateUpdate): void {
111 const context = this.getContext();
112 context.lastSelection = update.selection;
113 this.toolbar?.updateState(update);
114 this.updateContextToolbars(update);
115 for (const toolbar of this.activeContextToolbars) {
116 toolbar.updateState(update);
118 this.triggerSelectionChange(update.selection);
121 triggerStateRefresh(): void {
122 this.triggerStateUpdate({
123 editor: this.getContext().editor,
124 selection: this.getContext().lastSelection,
128 protected triggerSelectionChange(selection: BaseSelection|null): void {
133 for (const handler of this.selectionChangeHandlers) {
138 onSelectionChange(handler: SelectionChangeHandler): void {
139 this.selectionChangeHandlers.add(handler);
142 offSelectionChange(handler: SelectionChangeHandler): void {
143 this.selectionChangeHandlers.delete(handler);
146 protected updateContextToolbars(update: EditorUiStateUpdate): void {
147 for (let i = this.activeContextToolbars.length - 1; i >= 0; i--) {
148 const toolbar = this.activeContextToolbars[i];
150 this.activeContextToolbars.splice(i, 1);
153 const node = (update.selection?.getNodes() || [])[0] || null;
158 const element = update.editor.getElementByKey(node.getKey());
163 const toolbarKeys = Object.keys(this.contextToolbarDefinitionsByKey);
164 const contentByTarget = new Map<HTMLElement, EditorUiElement[]>();
165 for (const key of toolbarKeys) {
166 const definition = this.contextToolbarDefinitionsByKey[key];
167 const matchingElem = ((element.closest(definition.selector)) || (element.querySelector(definition.selector))) as HTMLElement|null;
169 const targetEl = definition.displayTargetLocator ? definition.displayTargetLocator(matchingElem) : matchingElem;
170 if (!contentByTarget.has(targetEl)) {
171 contentByTarget.set(targetEl, [])
174 contentByTarget.get(targetEl).push(...definition.content);
178 for (const [target, contents] of contentByTarget) {
179 const toolbar = new EditorContextToolbar(target, contents);
180 toolbar.setContext(this.getContext());
181 this.activeContextToolbars.push(toolbar);
183 this.getContext().containerDOM.append(toolbar.getDOMElement());
184 toolbar.updatePosition();
188 protected setupEditor(editor: LexicalEditor) {
189 // Update button states on editor selection change
190 editor.registerCommand(SELECTION_CHANGE_COMMAND, () => {
191 this.triggerStateUpdate({
193 selection: $getSelection(),
196 }, COMMAND_PRIORITY_LOW);
198 // Register our DOM decorate listener with the editor
199 const domDecorateListener: DecoratorListener<EditorDecoratorAdapter> = (decorators: Record<NodeKey, EditorDecoratorAdapter>) => {
200 editor.getEditorState().read(() => {
201 const keys = Object.keys(decorators);
202 for (const key of keys) {
203 const decoratedEl = editor.getElementByKey(key);
208 const adapter = decorators[key];
209 const decorator = this.getDecorator(adapter.type, key);
210 decorator.setNode(adapter.getNode());
211 const decoratorEl = decorator.render(this.getContext(), decoratedEl);
213 decoratedEl.append(decoratorEl);
218 editor.registerDecoratorListener(domDecorateListener);
221 protected setupEventListeners(context: EditorUiContext) {
222 const updateToolbars = (event: Event) => {
223 for (const toolbar of this.activeContextToolbars) {
224 toolbar.updatePosition();
228 window.addEventListener('scroll', updateToolbars, {capture: true, passive: true});
229 window.addEventListener('resize', updateToolbars, {passive: true});