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;
10 export interface EditorButtonDefinition extends EditorBasicButtonDefinition {
11 action: (context: EditorUiContext, button: EditorButton) => void;
12 isActive: (selection: BaseSelection|null, context: EditorUiContext) => boolean;
13 setup?: (context: EditorUiContext, button: EditorButton) => void;
16 export class EditorButton extends EditorUiElement {
17 protected definition: EditorButtonDefinition;
18 protected active: boolean = false;
19 protected completedSetup: boolean = false;
20 protected disabled: boolean = false;
22 constructor(definition: EditorButtonDefinition|EditorBasicButtonDefinition) {
25 if ((definition as EditorButtonDefinition).action !== undefined) {
26 this.definition = definition as EditorButtonDefinition;
40 setContext(context: EditorUiContext) {
41 super.setContext(context);
43 if (this.definition.setup && !this.completedSetup) {
44 this.definition.setup(context, this);
45 this.completedSetup = true;
49 protected buildDOM(): HTMLButtonElement {
51 const label = this.getLabel();
52 let child: string|HTMLElement = label;
53 if (this.definition.icon) {
54 child = el('span', {class: 'editor-button-icon'});
55 child.innerHTML = this.definition.icon;
58 const button = el('button', {
60 class: 'editor-button',
61 title: this.definition.icon ? label : null,
62 disabled: this.disabled ? 'true' : null,
63 }, [child]) as HTMLButtonElement;
65 button.addEventListener('click', this.onClick.bind(this));
71 this.definition.action(this.getContext(), this);
74 updateActiveState(selection: BaseSelection|null) {
75 const isActive = this.definition.isActive(selection, this.getContext());
76 this.setActiveState(isActive);
79 setActiveState(active: boolean) {
81 this.dom?.classList.toggle('editor-button-active', this.active);
84 updateState(state: EditorUiStateUpdate): void {
85 this.updateActiveState(state.selection);
93 return this.trans(this.definition.label);
96 toggleDisabled(disabled: boolean) {
97 this.disabled = disabled;
99 this.dom?.setAttribute('disabled', 'true');
101 this.dom?.removeAttribute('disabled');