1 import {BaseSelection} from "lexical";
2 import {EditorUiContext, EditorUiElement, EditorUiStateUpdate} from "./core";
3 import {el} from "../../helpers";
4 import {context} from "esbuild";
6 export interface EditorBasicButtonDefinition {
8 icon?: string|undefined;
11 export interface EditorButtonDefinition extends EditorBasicButtonDefinition {
12 action: (context: EditorUiContext) => void;
13 isActive: (selection: BaseSelection|null) => boolean;
14 setup?: (context: EditorUiContext, button: EditorButton) => void;
17 export class EditorButton extends EditorUiElement {
18 protected definition: EditorButtonDefinition;
19 protected active: boolean = false;
20 protected completedSetup: boolean = false;
21 protected disabled: boolean = false;
23 constructor(definition: EditorButtonDefinition) {
25 this.definition = definition;
28 setContext(context: EditorUiContext) {
29 super.setContext(context);
31 if (this.definition.setup && !this.completedSetup) {
32 this.definition.setup(context, this);
33 this.completedSetup = true;
37 protected buildDOM(): HTMLButtonElement {
39 const label = this.getLabel();
40 let child: string|HTMLElement = label;
41 if (this.definition.icon) {
42 child = el('span', {class: 'editor-button-icon'});
43 child.innerHTML = this.definition.icon;
46 const button = el('button', {
48 class: 'editor-button',
49 title: this.definition.icon ? label : null,
50 disabled: this.disabled ? 'true' : null,
51 }, [child]) as HTMLButtonElement;
53 button.addEventListener('click', this.onClick.bind(this));
59 this.definition.action(this.getContext());
62 updateActiveState(selection: BaseSelection|null) {
63 this.active = this.definition.isActive(selection);
64 this.dom?.classList.toggle('editor-button-active', this.active);
67 updateState(state: EditorUiStateUpdate): void {
68 this.updateActiveState(state.selection);
76 return this.trans(this.definition.label);
79 toggleDisabled(disabled: boolean) {
80 this.disabled = disabled;
82 this.dom?.setAttribute('disabled', 'true');
84 this.dom?.removeAttribute('disabled');