1 import {BaseSelection} from "lexical";
2 import {EditorUiContext, EditorUiElement, EditorUiStateUpdate} from "./core";
4 import {el} from "../../utils/dom";
6 export interface EditorBasicButtonDefinition {
8 icon?: string|undefined;
9 format?: 'small' | 'long';
12 export interface EditorButtonDefinition extends EditorBasicButtonDefinition {
13 action: (context: EditorUiContext, button: EditorButton) => void;
14 isActive: (selection: BaseSelection|null, context: EditorUiContext) => boolean;
15 isDisabled?: (selection: BaseSelection|null, context: EditorUiContext) => boolean;
16 setup?: (context: EditorUiContext, button: EditorButton) => void;
19 export class EditorButton extends EditorUiElement {
20 protected definition: EditorButtonDefinition;
21 protected active: boolean = false;
22 protected completedSetup: boolean = false;
23 protected disabled: boolean = false;
25 constructor(definition: EditorButtonDefinition|EditorBasicButtonDefinition) {
28 if ((definition as EditorButtonDefinition).action !== undefined) {
29 this.definition = definition as EditorButtonDefinition;
43 setContext(context: EditorUiContext) {
44 super.setContext(context);
46 if (this.definition.setup && !this.completedSetup) {
47 this.definition.setup(context, this);
48 this.completedSetup = true;
52 protected buildDOM(): HTMLButtonElement {
53 const label = this.getLabel();
54 const format = this.definition.format || 'small';
55 const children: (string|HTMLElement)[] = [];
57 if (this.definition.icon || format === 'long') {
58 const icon = el('div', {class: 'editor-button-icon'});
59 icon.innerHTML = this.definition.icon || '';
63 if (!this.definition.icon ||format === 'long') {
64 const text = el('div', {class: 'editor-button-text'}, [label]);
68 const button = el('button', {
70 class: `editor-button editor-button-${format}`,
71 title: this.definition.icon ? label : null,
72 disabled: this.disabled ? 'true' : null,
73 }, children) as HTMLButtonElement;
75 button.addEventListener('click', this.onClick.bind(this));
81 this.definition.action(this.getContext(), this);
84 protected updateActiveState(selection: BaseSelection|null) {
85 const isActive = this.definition.isActive(selection, this.getContext());
86 this.setActiveState(isActive);
89 protected updateDisabledState(selection: BaseSelection|null) {
90 if (this.definition.isDisabled) {
91 const isDisabled = this.definition.isDisabled(selection, this.getContext());
92 this.toggleDisabled(isDisabled);
96 setActiveState(active: boolean) {
98 this.dom?.classList.toggle('editor-button-active', this.active);
101 updateState(state: EditorUiStateUpdate): void {
102 this.updateActiveState(state.selection);
103 this.updateDisabledState(state.selection);
106 isActive(): boolean {
111 return this.trans(this.definition.label);
114 toggleDisabled(disabled: boolean) {
115 this.disabled = disabled;
117 this.dom?.setAttribute('disabled', 'true');
119 this.dom?.removeAttribute('disabled');