All files / src/views results.ts

100% Statements 95/95
100% Branches 62/62
100% Functions 15/15
100% Lines 90/90

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            5x 5x       2x 2x                           15x 1x                                                 112x 112x 21x 21x   91x 112x 13x 13x   78x       24x 1x                 32x     32x 32x       32x 2x 2x 2x     32x           32x 32x 32x 32x     32x 32x 24x 24x 24x 24x 10x           3x 3x 3x 3x 3x 2x                                   22x 3x 3x   19x 19x 22x   22x 1x 18x 1x     19x 19x 19x 7x     19x 6x 6x   13x     19x 19x 1x   18x 3x                                   11x 11x 14x 14x 3x 2x   12x 12x 12x 17x 17x 17x 17x 17x 1x 1x             11x 11x 11x 20x 20x 14x 14x   20x   14x    
import { App } from "obsidian";
import type { LilbeeClient } from "../api";
import { CLAIM_TYPE, MEMORY_SOURCE_PREFIX, SEARCH_CHUNK_TYPE, type DocumentResult, type Source } from "../types";
import { MESSAGES } from "../locales/en";
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,
    };
}
 
/** A persisted source path names a memory when it has the server's `memory:<id>` form. */
export function memorySourceFromPath(path: string): Source | null {
    if (!path.startsWith(MEMORY_SOURCE_PREFIX)) return null;
    return {
        source: path,
        content_type: "",
        distance: 0,
        chunk: "",
        page_start: null,
        page_end: null,
        line_start: null,
        line_end: null,
        memory_id: path.slice(MEMORY_SOURCE_PREFIX.length),
    };
}
 
/**
 * 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.createSpan({
        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.createSpan({ text: loc, cls: "lilbee-location" });
        }
    }
}
 
function renderMemoryChip(container: HTMLElement, source: Source, app: App, api: LilbeeClient): void {
    const chip = container.createSpan({ cls: "lilbee-source-chip lilbee-source-chip-memory" });
    chip.createSpan({ text: "M", cls: "lilbee-memory-type-badge" });
    chip.createSpan({ text: MESSAGES.LABEL_MEMORY_SOURCE });
    chip.addClass("lilbee-clickable");
    chip.addEventListener("click", () => {
        void executeSourceClick(app, api, sourceClickAction(source, app.vault));
    });
}
 
/**
 * 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 {
    if (source.memory_id) {
        renderMemoryChip(container, source, app, api);
        return;
    }
    const isWiki = source.chunk_type === SEARCH_CHUNK_TYPE.WIKI;
    const cls = isWiki ? "lilbee-source-chip lilbee-source-chip-wiki" : "lilbee-source-chip";
    const chip = container.createSpan({ cls });
 
    if (source.claim_type === CLAIM_TYPE.FACT) {
        chip.addClass("lilbee-claim-fact");
    } else if (source.claim_type === CLAIM_TYPE.INFERENCE) {
        chip.addClass("lilbee-claim-inference");
    }
 
    let label = source.source;
    const loc = formatLocation(source);
    if (loc) {
        label += ` (${loc})`;
    }
 
    if (isWiki) {
        chip.createSpan({ text: "W", cls: "lilbee-wiki-type-badge" });
        chip.createSpan({ 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 === SEARCH_CHUNK_TYPE.WIKI || first.memory_id) {
            for (const s of group) renderSourceChip(container, s, app, api);
            continue;
        }
        const chip = container.createSpan({ cls: "lilbee-source-chip lilbee-source-chip-grouped" });
        chip.createSpan({ text: first.source, cls: "lilbee-source-chip-file" });
        for (const source of group) {
            const loc = formatLocation(source);
            const label = loc ?? "open";
            const tag = chip.createSpan({ 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 ?? SEARCH_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)!);
}