All files / src/views source-preview-modal.ts

100% Statements 175/175
100% Branches 46/46
100% Functions 14/14
100% Lines 175/175

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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2391x                     1x 1x 1x 1x 1x 1x 1x                             1x 33x 33x   33x 33x 33x 33x 33x 33x   33x 33x 33x 33x 33x           33x 33x 33x 33x 33x 33x   33x 33x   33x   33x 1x 1x 1x 1x 1x   32x 32x 32x   32x 33x   33x 4x 4x 1x 1x 1x 4x 1x 1x 1x 4x   33x 33x             33x 33x 33x 5x 4x 5x 2x 2x 2x 2x 2x 2x 2x   2x 1x 1x 1x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 33x 33x   33x 33x 33x 33x 33x 33x 33x 33x 4x 4x 33x   33x 33x         33x 33x 3x 3x 3x 3x 3x 1x 1x 3x 33x 30x 30x 30x 30x 30x 30x 30x   33x 33x 33x 33x 33x 33x   33x 33x 33x 33x 1x 1x 33x 2x 2x 30x 33x   33x 32x 32x 30x 30x 32x 1x 1x 1x 1x 1x 32x   33x 30x 30x 30x 8x 8x 8x         22x 30x 16x 16x 16x 16x 6x 6x 6x 6x 30x   33x 8x 8x 8x 8x 8x   33x     8x 8x 8x 8x 8x 33x  
import { App, MarkdownRenderer, Modal, Notice } from "obsidian";
import type { LilbeeClient } from "../api";
import type { Source, SourceContent } from "../types";
import { CONTENT_TYPE, isPdfContentType } from "../types";
import { MESSAGES } from "../locales/en";
import { bindEscapeToClose, errorMessage } from "../utils";
import { formatLocation } from "./results";
 
// Text/* mime types that should NOT render inline through MarkdownRenderer
// even though they pass the broad text/* category. Keep narrow and explicit;
// broadening this set requires a security review.
const TEXT_INLINE_RENDER_DENY = new Set([
    "text/html",
    "text/javascript",
    "application/javascript",
    "application/xhtml+xml",
    "text/css",
]);
 
/**
 * Read-only preview for sources that aren't in the local vault (external
 * server mode, or a vault-bound source whose file was removed). Fetches
 * content via `/api/source` and renders markdown inline. For PDFs the modal
 * embeds an `<object type="application/pdf">` pointing at the `raw=1`
 * endpoint with a `#page=N` fragment — Chromium's built-in PDFium viewer
 * honours that fragment, which lets the preview jump directly to the
 * chunk's page. The type-locked `<object>` tag narrows the rendering
 * surface for any non-PDF bytes the server might return.
 *
 * A future "Save to vault" button will push the content into `<vault>/lilbee/`
 * once the server exposes the write path — disabled for now with a tooltip.
 */
export class SourcePreviewModal extends Modal {
    private api: LilbeeClient;
    private source: Source;
 
    constructor(app: App, api: LilbeeClient, source: Source) {
        super(app);
        this.api = api;
        this.source = source;
        bindEscapeToClose(this);
    }
 
    onOpen(): void {
        const { contentEl, modalEl } = this;
        contentEl.empty();
        contentEl.addClass("lilbee-modal");
        contentEl.addClass("lilbee-preview-modal");
        // Apply resize handling to the outer modal frame that Obsidian creates;
        // CSS ``resize: both`` on the inner content element is clipped by the
        // frame's default ``overflow: hidden``. Setting dimensions inline
        // beats Obsidian's default ``width: fit-content`` without relying on
        // CSS specificity escalations.
        modalEl.addClass("lilbee-preview-modal-frame");
        modalEl.style.width = "min(880px, 92vw)";
        modalEl.style.height = "min(640px, 85vh)";
        modalEl.style.resize = "both";
        modalEl.style.overflow = "hidden";
        modalEl.style.position = "fixed";
 
        contentEl.createEl("h2", { text: MESSAGES.TITLE_SOURCE_PREVIEW });
        this.makeDraggable(contentEl);
 
        this.renderHeader(contentEl);
 
        if (!this.source.source) {
            new Notice(MESSAGES.ERROR_PREVIEW_INVALID_SOURCE);
            contentEl.createEl("p", { text: MESSAGES.ERROR_PREVIEW_INVALID_SOURCE, cls: "lilbee-preview-error" });
            this.renderFooter(contentEl);
            return;
        }
 
        const bodyHost = contentEl.createDiv({ cls: "lilbee-preview-host" });
        bodyHost.createDiv({ cls: "lilbee-preview-loading" });
        this.renderFooter(contentEl);
 
        void this.loadContent(bodyHost);
    }
 
    onClose(): void {
        this.contentEl.empty();
        if (this.dragMoveHandler) {
            window.removeEventListener("pointermove", this.dragMoveHandler);
            this.dragMoveHandler = null;
        }
        if (this.dragUpHandler) {
            window.removeEventListener("pointerup", this.dragUpHandler);
            this.dragUpHandler = null;
        }
    }
 
    private dragMoveHandler: ((e: PointerEvent) => void) | null = null;
    private dragUpHandler: ((e: PointerEvent) => void) | null = null;
 
    // Promotes Obsidian's auto-centered modal to explicit top/left on the
    // first drag so the modal stays where the user puts it across resize.
    // The whole chrome (title, header, footer, padding) is the drag surface,
    // but pointer events that land inside the embedded body or on an
    // interactive element (button/input/link) pass through.
    private makeDraggable(handle: HTMLElement): void {
        handle.addClass("lilbee-preview-drag-handle");
        handle.addEventListener("pointerdown", (down: PointerEvent) => {
            if (down.button !== 0) return;
            const target = down.target as HTMLElement | null;
            if (target?.closest(".lilbee-preview-host, button, input, textarea, select, a")) return;
            down.preventDefault();
            const rect = this.modalEl.getBoundingClientRect();
            const offsetX = down.clientX - rect.left;
            const offsetY = down.clientY - rect.top;
            this.modalEl.style.margin = "0";
            this.modalEl.style.left = `${rect.left}px`;
            this.modalEl.style.top = `${rect.top}px`;
 
            const move = (e: PointerEvent): void => {
                this.modalEl.style.left = `${e.clientX - offsetX}px`;
                this.modalEl.style.top = `${e.clientY - offsetY}px`;
            };
            const up = (): void => {
                window.removeEventListener("pointermove", move);
                window.removeEventListener("pointerup", up);
                this.dragMoveHandler = null;
                this.dragUpHandler = null;
            };
            this.dragMoveHandler = move;
            this.dragUpHandler = up;
            window.addEventListener("pointermove", move);
            window.addEventListener("pointerup", up);
        });
    }
 
    private renderHeader(container: HTMLElement): void {
        const header = container.createDiv({ cls: "lilbee-preview-header" });
        header.createEl("span", {
            text: this.source.vault_path ?? this.source.source,
            cls: "lilbee-preview-path",
        });
        const loc = formatLocation(this.source);
        if (loc) {
            container.createEl("span", { text: loc, cls: "lilbee-preview-meta" });
        }
    }
 
    private renderFooter(container: HTMLElement): void {
        const footer = container.createDiv({ cls: "lilbee-preview-footer" });
        // When the source resolves to a vault file, swap the disabled
        // "Save to vault" stub for an "Open in vault" affordance — clicking
        // it dismisses the preview and opens the original file in the main
        // pane via Obsidian's standard link routing.
        const inVaultPath = this.resolveVaultPath();
        if (inVaultPath !== null) {
            const openBtn = footer.createEl("button", {
                text: MESSAGES.LABEL_PREVIEW_OPEN_IN_VAULT,
                cls: "lilbee-preview-open-vault",
            });
            openBtn.addEventListener("click", () => {
                this.app.workspace.openLinkText(inVaultPath, "");
                this.close();
            });
        } else {
            const save = footer.createEl("button", {
                text: MESSAGES.LABEL_PREVIEW_SAVE_TO_VAULT,
                cls: "lilbee-preview-save",
            }) as HTMLButtonElement;
            save.disabled = true;
            save.setAttribute("title", MESSAGES.TOOLTIP_PREVIEW_SAVE_SOON);
        }
 
        const close = footer.createEl("button", {
            text: MESSAGES.LABEL_PREVIEW_CLOSE,
            cls: "lilbee-preview-close mod-cta",
        });
        close.addEventListener("click", () => this.close());
    }
 
    private resolveVaultPath(): string | null {
        const vault = this.app.vault;
        const vaultPath = this.source.vault_path;
        if (vaultPath && vault.getAbstractFileByPath(vaultPath)) {
            return vaultPath;
        }
        if (this.source.source && vault.getAbstractFileByPath(this.source.source)) {
            return this.source.source;
        }
        return null;
    }
 
    private async loadContent(host: HTMLElement): Promise<void> {
        try {
            const content = await this.api.getSource(this.source.source);
            host.empty();
            this.renderBody(host, content);
        } catch (err) {
            const reason = errorMessage(err, String(err));
            host.empty();
            host.createEl("p", { text: MESSAGES.ERROR_PREVIEW_LOAD(reason), cls: "lilbee-preview-error" });
            new Notice(MESSAGES.ERROR_PREVIEW_LOAD(reason));
        }
    }
 
    private renderBody(host: HTMLElement, content: SourceContent): void {
        const ct = content.content_type;
        const isPdf = isPdfContentType(this.source.content_type) || isPdfContentType(ct);
        if (isPdf) {
            this.renderPdf(host);
            return;
        }
        // Mirror the server's raw-content allowlist: any text/* may render through
        // MarkdownRenderer, except formats that can carry script (text/html,
        // text/javascript, application/xhtml+xml) or styling (text/css). The
        // <object> tag protects the PDF path; this gate protects the JSON path.
        const textBlocked = TEXT_INLINE_RENDER_DENY.has(ct);
        if (!textBlocked && ct.startsWith("text/")) {
            const body = host.createDiv({ cls: "lilbee-preview-body" });
            void MarkdownRenderer.render(this.app, content.markdown, body, "", this);
            return;
        }
        host.createEl("p", {
            text: MESSAGES.ERROR_PREVIEW_UNSUPPORTED(ct),
            cls: "lilbee-preview-error",
        });
    }
 
    private renderPdf(host: HTMLElement): void {
        const body = host.createDiv({ cls: "lilbee-preview-body" });
        const frame = body.createEl("object", { cls: "lilbee-preview-pdf-frame" });
        frame.setAttribute("type", CONTENT_TYPE.PDF);
        frame.setAttribute("data", this.rawSourceUrl(this.source.page_start));
    }
 
    private rawSourceUrl(page: number | null): string {
        // Direct URL to the raw PDF bytes for the embedded viewer to fetch.
        // Appending `#page=N` makes Chromium's PDFium viewer open at that page.
        const params = new URLSearchParams({ source: this.source.source, raw: "1" });
        const base = (this.api as unknown as { baseUrl?: string }).baseUrl ?? "";
        const fragment = page && page > 0 ? `#page=${page}` : "";
        return `${base}/api/source?${params.toString()}${fragment}`;
    }
}