All files / src/views documents-modal.ts

100% Statements 94/94
100% Branches 25/25
100% Functions 13/13
100% Lines 84/84

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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157              2x 2x       33x 33x 33x 33x 33x 33x 33x 33x 33x         33x 33x 33x 33x 33x 33x       28x 28x 28x   28x   28x         28x 5x 5x     28x       28x 28x   28x 28x   28x       5x 5x     7x 7x 3x 3x 2x         33x 33x 33x 33x 33x 33x 33x       36x 35x 35x 35x         34x 34x 34x 34x   34x 100x     1x   35x         40x 38x       101x 100x   100x       100x 6x 6x 5x   1x   6x     100x 100x 100x 100x 100x       4x 3x 3x 3x 3x 3x 2x 2x 1x 1x   1x        
import { App, Modal, Notice } from "obsidian";
import type LilbeePlugin from "../main";
import type { DocumentEntry, DocumentsResponse } from "../types";
import { ConfirmModal } from "./confirm-modal";
import { MESSAGES } from "../locales/en";
import { bindEscapeToClose, debounce, DEBOUNCE_MS, relativeTimeFromIso } from "../utils";
 
const PAGE_SIZE = 20;
const SCROLL_BOTTOM_THRESHOLD_PX = 200;
 
export class DocumentsModal extends Modal {
    private plugin: LilbeePlugin;
    private offset = 0;
    private total = 0;
    private hasMore = true;
    private isFetching = false;
    private documents: DocumentEntry[] = [];
    private selected = new Set<string>();
    private resultsEl: HTMLElement | null = null;
    private removeBtn: HTMLElement | null = null;
    private searchQuery = "";
    private debouncedSearch: () => void;
    private cancelDebouncedSearch: () => void;
 
    constructor(app: App, plugin: LilbeePlugin) {
        super(app);
        this.plugin = plugin;
        const searchDebounced = debounce(() => this.resetAndFetch(), DEBOUNCE_MS);
        this.debouncedSearch = searchDebounced.run;
        this.cancelDebouncedSearch = searchDebounced.cancel;
        bindEscapeToClose(this);
    }
 
    onOpen(): void {
        const { contentEl } = this;
        contentEl.empty();
        contentEl.addClass("lilbee-documents-modal");
 
        contentEl.createEl("h2", { text: MESSAGES.TITLE_DOCUMENTS });
 
        const searchInput = contentEl.createEl("input", {
            cls: "lilbee-documents-search",
            placeholder: MESSAGES.PLACEHOLDER_SEARCH_DOCUMENTS,
            attr: { type: "text" },
        });
        searchInput.addEventListener("input", () => {
            this.searchQuery = searchInput.value;
            this.debouncedSearch();
        });
 
        this.removeBtn = contentEl.createEl("button", {
            text: MESSAGES.BUTTON_DELETE_SELECTED,
            cls: "lilbee-documents-remove",
        });
        (this.removeBtn as HTMLButtonElement).disabled = true;
        this.removeBtn.addEventListener("click", () => void this.removeSelected());
 
        this.resultsEl = contentEl.createDiv({ cls: "lilbee-documents-results" });
        this.resultsEl.addEventListener("scroll", this.onScroll);
 
        this.resetAndFetch();
    }
 
    onClose(): void {
        this.cancelDebouncedSearch();
        this.resultsEl?.removeEventListener("scroll", this.onScroll);
    }
 
    private onScroll = (): void => {
        if (!this.resultsEl || this.isFetching || !this.hasMore) return;
        const { scrollTop, clientHeight, scrollHeight } = this.resultsEl;
        if (scrollTop + clientHeight >= scrollHeight - SCROLL_BOTTOM_THRESHOLD_PX) {
            void this.fetchPage();
        }
    };
 
    private resetAndFetch(): void {
        this.offset = 0;
        this.hasMore = true;
        this.documents = [];
        this.selected.clear();
        if (this.resultsEl) this.resultsEl.empty();
        this.updateRemoveBtn();
        void this.fetchPage();
    }
 
    private async fetchPage(): Promise<void> {
        if (this.isFetching) return;
        this.isFetching = true;
        try {
            const response: DocumentsResponse = await this.plugin.api.listDocuments(
                this.searchQuery || undefined,
                PAGE_SIZE,
                this.offset,
            );
            this.total = response.total;
            this.documents.push(...response.documents);
            this.offset += response.documents.length;
            this.hasMore = response.has_more;
 
            for (const doc of response.documents) {
                this.renderRow(doc);
            }
        } catch {
            new Notice(MESSAGES.ERROR_LOAD_DOCUMENTS);
        } finally {
            this.isFetching = false;
        }
    }
 
    private updateRemoveBtn(): void {
        if (!this.removeBtn) return;
        (this.removeBtn as HTMLButtonElement).disabled = this.selected.size === 0;
    }
 
    private renderRow(doc: DocumentEntry): void {
        if (!this.resultsEl) return;
        const row = this.resultsEl.createDiv({ cls: "lilbee-documents-row" });
 
        const checkbox = row.createEl("input", {
            cls: "lilbee-documents-checkbox",
            attr: { type: "checkbox" },
        });
        checkbox.addEventListener("change", () => {
            const checked = checkbox.checked;
            if (checked) {
                this.selected.add(doc.filename);
            } else {
                this.selected.delete(doc.filename);
            }
            this.updateRemoveBtn();
        });
 
        const nameEl = row.createDiv({ cls: "lilbee-documents-row-name", text: doc.filename });
        nameEl.setAttribute("title", doc.filename);
        row.createDiv({ cls: "lilbee-documents-row-chunks", text: `${doc.chunk_count} chunks` });
        const dateEl = row.createDiv({ cls: "lilbee-documents-row-date", text: relativeTimeFromIso(doc.ingested_at) });
        if (doc.ingested_at) dateEl.setAttribute("title", doc.ingested_at);
    }
 
    private async removeSelected(): Promise<void> {
        if (this.selected.size === 0) return;
        const names = Array.from(this.selected);
        const confirm = new ConfirmModal(this.app, MESSAGES.NOTICE_CONFIRM_DELETE_DOCS(names.length));
        confirm.open();
        const confirmed = await confirm.result;
        if (!confirmed) return;
        try {
            const result = await this.plugin.api.removeDocuments(names, true);
            new Notice(MESSAGES.NOTICE_DELETED(result.removed));
            this.resetAndFetch();
        } catch {
            new Notice(MESSAGES.ERROR_DELETE_DOCUMENTS);
        }
    }
}