1 import {BaseSelection} from "lexical";
2 import {EditorUiContext, EditorUiElement, EditorUiStateUpdate} from "./core";
3 import {el} from "../../helpers";
5 export interface EditorBasicButtonDefinition {
7 icon?: string|undefined;
8 format?: 'small' | 'long';
11 export interface EditorButtonDefinition extends EditorBasicButtonDefinition {
12 action: (context: EditorUiContext, button: EditorButton) => void;
13 isActive: (selection: BaseSelection|null, context: EditorUiContext) => boolean;
14 isDisabled?: (selection: BaseSelection|null, context: EditorUiContext) => boolean;
15 setup?: (context: EditorUiContext, button: EditorButton) => void;
18 export class EditorButton extends EditorUiElement {
19 protected definition: EditorButtonDefinition;
20 protected active: boolean = false;
21 protected completedSetup: boolean = false;
22 protected disabled: boolean = false;
24 constructor(definition: EditorButtonDefinition|EditorBasicButtonDefinition) {
27 if ((definition as EditorButtonDefinition).action !== undefined) {
28 this.definition = definition as EditorButtonDefinition;
42 setContext(context: EditorUiContext) {
43 super.setContext(context);
45 if (this.definition.setup && !this.completedSetup) {
46 this.definition.setup(context, this);
47 this.completedSetup = true;
51 protected buildDOM(): HTMLButtonElement {
52 const label = this.getLabel();
53 const format = this.definition.format || 'small';
54 const children: (string|HTMLElement)[] = [];
56 if (this.definition.icon || format === 'long') {
57 const icon = el('div', {class: 'editor-button-icon'});
58 icon.innerHTML = this.definition.icon || '';
62 if (!this.definition.icon ||format === 'long') {
63 const text = el('div', {class: 'editor-button-text'}, [label]);
67 const button = el('button', {
69 class: `editor-button editor-button-${format}`,
70 title: this.definition.icon ? label : null,
71 disabled: this.disabled ? 'true' : null,
72 }, children) as HTMLButtonElement;
74 button.addEventListener('click', this.onClick.bind(this));
80 this.definition.action(this.getContext(), this);
83 protected updateActiveState(selection: BaseSelection|null) {
84 const isActive = this.definition.isActive(selection, this.getContext());
85 this.setActiveState(isActive);
88 protected updateDisabledState(selection: BaseSelection|null) {
89 if (this.definition.isDisabled) {
90 const isDisabled = this.definition.isDisabled(selection, this.getContext());
91 this.toggleDisabled(isDisabled);
95 setActiveState(active: boolean) {
97 this.dom?.classList.toggle('editor-button-active', this.active);
100 updateState(state: EditorUiStateUpdate): void {
101 this.updateActiveState(state.selection);
102 this.updateDisabledState(state.selection);
105 isActive(): boolean {
110 return this.trans(this.definition.label);
113 toggleDisabled(disabled: boolean) {
114 this.disabled = disabled;
116 this.dom?.setAttribute('disabled', 'true');
118 this.dom?.removeAttribute('disabled');