All files / src/views confirm-modal.ts

100% Statements 23/23
100% Branches 2/2
100% Functions 7/7
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51            6x 6x       6x 6x 6x 6x   6x       5x 5x 5x   5x   5x 5x 5x   5x 5x       6x       9x 4x             4x      
import { App, Modal } from "obsidian";
import { MESSAGES } from "../locales/en";
import { bindEscapeToClose } from "../utils";
 
export class ConfirmModal extends Modal {
    private message: string;
    private _resolve: ((value: boolean) => void) | null = null;
    private decided = false;
    readonly result: Promise<boolean>;
 
    constructor(app: App, message: string) {
        super(app);
        this.message = message;
        this.result = new Promise<boolean>((resolve) => {
            this._resolve = resolve;
        });
        bindEscapeToClose(this);
    }
 
    onOpen(): void {
        const { contentEl } = this;
        contentEl.empty();
        contentEl.addClass("lilbee-confirm-modal");
 
        contentEl.createEl("p", { text: this.message });
 
        const actions = contentEl.createDiv({ cls: "lilbee-confirm-actions" });
        const continueBtn = actions.createEl("button", { text: MESSAGES.BUTTON_CONTINUE, cls: "mod-cta" });
        continueBtn.addEventListener("click", () => this.decide(true));
 
        const cancelBtn = actions.createEl("button", { text: MESSAGES.BUTTON_CANCEL });
        cancelBtn.addEventListener("click", () => this.decide(false));
    }
 
    onClose(): void {
        this.decide(false);
    }
 
    private decide(confirmed: boolean): void {
        if (this.decided) return;
        this.decided = true;
        /* v8 ignore next -- `decided` guards re-entry, so `_resolve` is always set here */
        if (this._resolve) {
            const resolve = this._resolve;
            this._resolve = null;
            resolve(confirmed);
        }
        this.close();
    }
}