obsidian-book-tracker/src/commands/Command.ts

100 lines
2.1 KiB
TypeScript

import type {
Editor,
Hotkey,
MarkdownFileInfo,
MarkdownView,
Command as ObsidianCommand,
} from "obsidian";
export abstract class Command implements ObsidianCommand {
private _icon?: string;
public get icon(): string | undefined {
return this._icon;
}
protected setIcon(icon: string) {
this._icon = icon;
}
private _mobileOnly?: boolean;
public get mobileOnly(): boolean | undefined {
return this._mobileOnly;
}
protected setMobileOnly(mobileOnly: boolean) {
this._mobileOnly = mobileOnly;
}
private _repeatable?: boolean;
public get repeatable(): boolean | undefined {
return this._repeatable;
}
protected setRepeatable(repeatable: boolean) {
this._repeatable = repeatable;
}
private _hotkeys: Hotkey[] = [];
public get hotkeys(): Hotkey[] {
return this._hotkeys;
}
protected addHotkey(hotkey: Hotkey) {
this._hotkeys.push(hotkey);
}
protected removeHotkey(hotkey: Hotkey) {
this._hotkeys = this._hotkeys.filter(
(h) => h.key !== hotkey.key && h.modifiers !== h.modifiers
);
}
protected clearHotkeys() {
this._hotkeys = [];
}
constructor(public id: string, public name: string) {}
callback?(): any;
checkCallback?(checking: boolean): boolean;
editorCallback?(
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo
): boolean;
editorCheckCallback?(
checking: boolean,
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo
): boolean | void;
}
export abstract class CheckCommand extends Command {
checkCallback(checking: boolean): boolean {
if (!this.check()) return false;
if (!checking) {
this.run();
}
return true;
}
protected abstract check(): boolean;
protected abstract run(): void | Promise<void>;
}
export abstract class EditorCheckCommand extends Command {
editorCheckCallback(
checking: boolean,
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo
): boolean | void {
if (!this.check(editor, ctx)) return false;
if (!checking) {
this.run(editor, ctx);
}
return true;
}
protected abstract check(
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo
): boolean;
protected abstract run(
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo
): void | Promise<void>;
}