All files / src/views results.ts

100% Statements 83/83
100% Branches 56/56
100% Functions 12/12
100% Lines 79/79

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          5x 5x       2x 2x                                               103x 103x 21x 21x   82x 103x 13x 13x   69x       24x 1x                 32x     32x 32x       32x 2x 2x 2x     32x           32x 32x 32x 32x     32x 32x 24x 24x 24x 24x 10x                                     19x 19x 19x   19x 1x 18x 1x     19x 19x 19x 7x     19x 6x 6x   13x     19x 19x 1x   18x 3x                                   9x 9x 10x 10x 2x 1x   9x 9x 9x 13x 13x 13x 13x 13x 1x 1x             9x 9x 9x 15x 15x 10x 10x   15x   10x    
import { App } from "obsidian";
import type { LilbeeClient } from "../api";
import type { DocumentResult, Source } from "../types";
import { executeSourceClick, sourceClickAction } from "../utils/source-click";
 
const MAX_EXCERPT_CHARS = 200;
const MAX_EXCERPTS = 3;
 
/** Build a minimal Source from a DocumentResult excerpt so we can dispatch a click action. */
function documentResultToSource(result: DocumentResult): Source {
    const excerpt = result.excerpts[0];
    return {
        source: result.source,
        content_type: result.content_type,
        distance: 0,
        chunk: excerpt?.content ?? "",
        page_start: excerpt?.page_start ?? null,
        page_end: excerpt?.page_end ?? null,
        line_start: excerpt?.line_start ?? null,
        line_end: excerpt?.line_end ?? null,
    };
}
 
/**
 * Format a citation suffix. Prefer `(p. N)` / `(pp. N–M)` when the server
 * reports a real page (>0) — the chat path can deliver PDF sources with an
 * empty content_type, so we don't gate on it. Fall back to `(lines N–M)`
 * for line bounds; treat 0 as the server's null-sentinel and skip it.
 */
export function formatLocation(excerpt: {
    page_start: number | null;
    page_end: number | null;
    line_start: number | null;
    line_end: number | null;
}): string | null {
    const pageStart = excerpt.page_start ?? 0;
    if (pageStart > 0) {
        const pageEnd = excerpt.page_end ?? 0;
        return pageEnd > 0 && pageEnd !== pageStart ? `pp. ${pageStart}–${pageEnd}` : `p. ${pageStart}`;
    }
    const lineStart = excerpt.line_start ?? 0;
    if (lineStart > 0) {
        const lineEnd = excerpt.line_end ?? 0;
        return lineEnd > 0 && lineEnd !== lineStart ? `lines ${lineStart}–${lineEnd}` : `line ${lineStart}`;
    }
    return null;
}
 
function truncate(text: string, maxLen: number): string {
    if (text.length <= maxLen) return text;
    return text.slice(0, maxLen) + "...";
}
 
export function renderDocumentResult(
    container: HTMLElement,
    result: DocumentResult,
    app: App,
    api: LilbeeClient,
): void {
    const card = container.createDiv({ cls: "lilbee-document-card" });
 
    // Header: filename + content type badge
    const header = card.createDiv({ cls: "lilbee-document-card-header" });
    const link = header.createEl("a", {
        text: result.source,
        cls: "lilbee-document-source",
    });
    link.addEventListener("click", (e) => {
        e.preventDefault();
        const source = documentResultToSource(result);
        void executeSourceClick(app, api, sourceClickAction(source, app.vault));
    });
 
    header.createEl("span", {
        text: result.content_type,
        cls: "lilbee-content-badge",
    });
 
    // Relevance bar
    const barContainer = card.createDiv({ cls: "lilbee-relevance-bar-container" });
    const bar = barContainer.createDiv({ cls: "lilbee-relevance-bar" });
    const pct = Math.round(Math.max(0, Math.min(1, result.best_relevance)) * 100);
    bar.style.width = `${pct}%`;
 
    // Excerpts (up to MAX_EXCERPTS)
    const excerpts = result.excerpts.slice(0, MAX_EXCERPTS);
    for (const excerpt of excerpts) {
        const excerptEl = card.createDiv({ cls: "lilbee-excerpt" });
        excerptEl.createEl("p", { text: truncate(excerpt.content, MAX_EXCERPT_CHARS) });
        const loc = formatLocation(excerpt);
        if (loc) {
            excerptEl.createEl("span", { text: loc, cls: "lilbee-location" });
        }
    }
}
 
/**
 * Render a source chip. Chips are always clickable: the default click dispatches
 * through `executeSourceClick` (vault deep-link or server preview modal). When
 * `onWikiClick` is provided, wiki chips use that override instead — preserves
 * the wiki view's custom flow where a click navigates to the wiki page in the
 * sidebar rather than opening the source file.
 */
export function renderSourceChip(
    container: HTMLElement,
    source: Source,
    app: App,
    api: LilbeeClient,
    onWikiClick?: (slug: string) => void,
): void {
    const isWiki = source.chunk_type === "wiki";
    const cls = isWiki ? "lilbee-source-chip lilbee-source-chip-wiki" : "lilbee-source-chip";
    const chip = container.createEl("span", { cls });
 
    if (source.claim_type === "fact") {
        chip.addClass("lilbee-claim-fact");
    } else if (source.claim_type === "inference") {
        chip.addClass("lilbee-claim-inference");
    }
 
    let label = source.source;
    const loc = formatLocation(source);
    if (loc) {
        label += ` (${loc})`;
    }
 
    if (isWiki) {
        chip.createEl("span", { text: "W", cls: "lilbee-wiki-type-badge" });
        chip.createEl("span", { text: label });
    } else {
        chip.setText(label);
    }
 
    chip.addClass("lilbee-clickable");
    if (isWiki && onWikiClick) {
        chip.addEventListener("click", () => onWikiClick(source.source));
    } else {
        chip.addEventListener("click", () => {
            void executeSourceClick(app, api, sourceClickAction(source, app.vault));
        });
    }
}
 
/**
 * Render a chip that groups multiple chunks from the same source under one
 * filename, with each chunk's location surfaced as a small clickable badge.
 * Avoids the "cv-manual.pdf (line 0) × 3" repetition the per-chunk chip path
 * produces when several adjacent chunks share a file. Wiki sources fall
 * through to the per-chip renderer because their click target is per-slug.
 */
export function renderAggregatedSourceChips(
    container: HTMLElement,
    sources: Source[],
    app: App,
    api: LilbeeClient,
): void {
    const groups = groupSourcesByFile(sources);
    for (const group of groups) {
        const first = group[0];
        if (first.chunk_type === "wiki") {
            for (const s of group) renderSourceChip(container, s, app, api);
            continue;
        }
        const chip = container.createEl("span", { cls: "lilbee-source-chip lilbee-source-chip-grouped" });
        chip.createEl("span", { text: first.source, cls: "lilbee-source-chip-file" });
        for (const source of group) {
            const loc = formatLocation(source);
            const label = loc ?? "open";
            const tag = chip.createEl("span", { text: label, cls: "lilbee-source-chip-loc" });
            tag.addClass("lilbee-clickable");
            tag.addEventListener("click", (e: Event) => {
                e.stopPropagation();
                void executeSourceClick(app, api, sourceClickAction(source, app.vault));
            });
        }
    }
}
 
function groupSourcesByFile(sources: Source[]): Source[][] {
    const order: string[] = [];
    const buckets = new Map<string, Source[]>();
    for (const source of sources) {
        const key = `${source.chunk_type ?? "raw"}::${source.source}`;
        if (!buckets.has(key)) {
            buckets.set(key, []);
            order.push(key);
        }
        buckets.get(key)!.push(source);
    }
    return order.map((k) => buckets.get(k)!);
}