65 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-05-30 16:50:55 +01:00
import {BaseSelection} from "lexical";
import {EditorUiContext, EditorUiElement, EditorUiStateUpdate} from "./core";
import {el} from "../../helpers";
2024-06-12 19:51:42 +01:00
export interface EditorBasicButtonDefinition {
label: string;
icon?: string|undefined;
2024-06-12 19:51:42 +01:00
}
export interface EditorButtonDefinition extends EditorBasicButtonDefinition {
2024-05-30 16:50:55 +01:00
action: (context: EditorUiContext) => void;
isActive: (selection: BaseSelection|null) => boolean;
}
export class EditorButton extends EditorUiElement {
protected definition: EditorButtonDefinition;
2024-05-30 16:50:55 +01:00
protected active: boolean = false;
constructor(definition: EditorButtonDefinition) {
super();
this.definition = definition;
}
protected buildDOM(): HTMLButtonElement {
const label = this.getLabel();
let child: string|HTMLElement = label;
if (this.definition.icon) {
child = el('span', {class: 'editor-button-icon'});
child.innerHTML = this.definition.icon;
}
const button = el('button', {
type: 'button',
class: 'editor-button',
title: this.definition.icon ? label : null,
}, [child]) as HTMLButtonElement;
button.addEventListener('click', this.onClick.bind(this));
return button;
}
protected onClick() {
2024-05-30 16:50:55 +01:00
this.definition.action(this.getContext());
}
updateActiveState(selection: BaseSelection|null) {
2024-05-30 16:50:55 +01:00
this.active = this.definition.isActive(selection);
this.dom?.classList.toggle('editor-button-active', this.active);
}
updateState(state: EditorUiStateUpdate): void {
this.updateActiveState(state.selection);
}
2024-05-30 16:50:55 +01:00
isActive(): boolean {
return this.active;
}
getLabel(): string {
return this.trans(this.definition.label);
}
}