You hook up your vector database, spin up an LLM, wire your Retrieval-Augmented Generation (RAG) pipeline into a slick Vue 3 composition-API interface, and everything looks pristine. Users type questions, the model responds with coherent, grounded answers, and appended at the bottom of each message is a neat list of citation badges: [1] contract_v2.pdf, [2] architecture_spec.docx.
Then, your product manager tests it with an internal audit document containing 142 pages.
They click citation [2]. The application scrolls them to the top of a 50-megabyte PDF viewer component. They stare at a wall of text, squinting, trying to find where in those dense paragraphs the AI actually derived the sentence: “The indemnification clause caps liability at five million dollars.”
They turn around from their desk and ask the question that haunts every frontend RAG engineer: "Which exact paragraph on which exact page did this come from, and can you highlight it automatically when I click the badge?"
Providing basic file names is no longer enough for production-grade AI systems. Modern enterprise users expect Google-Docs-style precise highlighting that jumps directly from a chat message bubble down to the exact paragraph, line, and page of the source document.
In this architectural walkthrough, we are going to build file-level and page-level citation highlighting in a modern Vue RAG application using Vue 3, TypeScript, Pinia, and Tailwind CSS, backed by a precise PDF and text chunking strategy.
📋 Table of Contents
- The Anatomy of a Citation Pipeline
- 1. Structuring the Vector Chunks for Precision Metadata
- 2. Building the Pinia Citation Store for Reactive State Management
- 3. Crafting the Vue Chat Message Component with Clickable Citation Badges
- 4. Rendering and Highlighting Text at the File Level
- 5. Implementing Page-Level PDF Navigation and DOM Scroll Synchronization
- 6. Handling Edge Cases: Multi-Paragraph Spans and Fuzzy Text Matching
- Production Architecture Decisions and Performance Trade-offs
The Anatomy of a Citation Pipeline
To achieve seamless client-side highlighting, data must flow cleanly from your ingestion pipeline all the way to the browser's Document Object Model (DOM). Most developers make the mistake of storing only the raw text chunk in the vector database. When the LLM answers, it only knows it used "Chunk #412."
To bridge the gap between a chat bubble and a document viewer, your metadata payload must look like a precise mapping index.
[ Ingestion Pipeline ]
│ (PDF / Docs)
▼
[ Chunking Engine ] ──► Extracts: file_id, page_number, paragraph_index, exact_string_hash
│
▼
[ Vector DB ] ────────► Stores Embeddings + Rich Metadata
│
▼
[ LLM Generation ] ───► Returns Answer + Citation Markers ([1], [2])
│
▼
[ Vue Frontend ] ─────► Maps Markers to Pinia Store ──► Triggers DOM Scroll & Highlight
Let's break down how to implement each piece of this pipeline cleanly in a Vue application.
1. Structuring the Vector Chunks for Precision Metadata
Scenario: Your ingestion script splits a 200-page enterprise handbook into 1,000 character chunks. When a user asks about PTO policies, the vector search returns 3 chunks. But Chunk #3 starts halfway through a sentence about parental leave and ends on vacation carryover rules.
Why it matters:
If your metadata only tracks page_number: 14, highlighting the entire page forces the user to hunt manually. You need intra-page positioning coordinates or exact string matches to target the precise span.
Solution: Ensure your backend embedding pipeline injects structured metadata into every vector point. Below is a TypeScript interface representing the payload your Vue frontend expects when receiving a RAG completion chunk.
// types/citation.ts
export interface SourceMetadata {
chunkId: string;
fileId: string;
fileName: string;
fileType: 'pdf' | 'markdown' | 'docx';
pageNumber: number;
paragraphIndex: number;
exactText: string;
startOffset: number;
endOffset: number;
score: number;
}
export interface RagMessage {
id: string;
role: 'user' | 'assistant';
content: string;
citations: SourceMetadata[];
createdAt: string;
}
Why this works:
By carrying startOffset, endOffset, and exactText alongside the pageNumber, your frontend doesn't have to guess where the referenced text lives inside the document viewer. It can query the DOM or the PDF renderer with exact coordinates.
💡 Practical note: Always store a cryptographic hash (like SHA-256) of the
exactTextin your metadata. If your document store updates and text shifts slightly, the hash allows your frontend to gracefully fall back to fuzzy string matching instead of failing to highlight entirely.
2. Building the Pinia Citation Store for Reactive State Management
Scenario: Your Vue layout features a split-screen interface: the RAG chat interface lives on the left, and the interactive document viewer (or Markdown previewer) lives on the right. When a user clicks a citation badge in message #4, the right pane needs to react instantly, switch files if necessary, flip to page 12, and pulse-highlight the target paragraph.
Why it matters: Passing props up and down through deeply nested chat trees, message lists, and markdown renderers quickly turns into prop-drilling hell. Global chat state combined with citation navigation requires a dedicated, reactive store.
Solution: Implement a Pinia store designed specifically to track active navigation targets, highlighted citation IDs, and open document viewers.
// stores/citationStore.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { SourceMetadata } from '@/types/citation';
export const useCitationStore = defineStore('citation', () => {
// Currently active citation being highlighted in the viewer
const activeCitation = ref<SourceMetadata | null>(null);
// State to control visibility of the document preview drawer/pane
const isViewerOpen = ref<boolean>(false);
// The file currently loaded in the viewer pane
const activeFileId = ref<string | null>(null);
function jumpToCitation(citation: SourceMetadata) {
activeCitation.value = citation;
activeFileId.value = citation.fileId;
isViewerOpen.value = true;
// Optional: Reset highlight after animation completes so it can be re-triggered
setTimeout(() => {
// Keep activeCitation for reference, but clear transient triggers if needed
}, 3000);
}
function closeViewer() {
isViewerOpen.value = false;
activeCitation.value = null;
}
return {
activeCitation,
isViewerOpen,
activeFileId,
jumpToCitation,
closeViewer
};
});
Why this works:
Separating citation navigation from local component state means any component—whether it's a chat bubble, a header toolbar, or a keyboard shortcut listener—can trigger a document jump by simply calling citationStore.jumpToCitation(targetCitation).
3. Crafting the Vue Chat Message Component with Clickable Citation Badges
Scenario:
The LLM returns an answer containing inline markers like [1] or names them explicitly. You need a clean way to parse these markers in the rendered message text and transform them into interactive Vue components or styled DOM elements.
Why it matters:
Using standard markdown parsers like marked or markdown-it will render [1] as plain text. You need a custom renderer or a post-processing step to convert citation references into clickable badges that are styled consistently and bound to your Pinia store.
Solution: Build a Vue component that takes the raw assistant response, extracts or matches citation tags, and renders interactive badge components inline.
<!-- components/ChatMessage.vue -->
<script setup lang="ts">
import { computed } from 'vue';
import { useCitationStore } from '@/stores/citationStore';
import type { RagMessage } from '@/types/citation';
const props = defineProps<{
message: RagMessage;
}>();
const citationStore = useCitationStore();
/**
* Transforms text containing [1], [2] into structured tokens
* for rendering interactive citation chips.
*/
const parsedContent = computed(() => {
if (props.message.role !== 'assistant' || !props.message.citations?.length) {
return [{ type: 'text', value: props.message.content }];
}
const content = props.message.content;
// Regex to match citation brackets like [1], [2], etc.
const citationRegex = /\[(\d+)\]/g;
let lastIndex = 0;
let match;
const tokens = [];
while ((match = citationRegex.exec(content)) !== null) {
// Push preceding text
if (match.index > lastIndex) {
tokens.push({
type: 'text',
value: content.slice(lastIndex, match.index)
});
}
const citationIndex = parseInt(match[1], 10) - 1;
const citationData = props.message.citations[citationIndex];
if (citationData) {
tokens.push({
type: 'citation',
index: match[1],
data: citationData
});
} else {
// Fallback if index is out of bounds
tokens.push({ type: 'text', value: match[0] });
}
lastIndex = citationRegex.lastIndex;
}
if (lastIndex < content.length) {
tokens.push({
type: 'text',
value: content.slice(lastIndex)
});
}
return tokens;
});
</script>
<template>
<div class="p-4 rounded-xl mb-4 transition-colors" :class="message.role === 'assistant' ? 'bg-slate-800 text-slate-100' : 'bg-indigo-950 text-indigo-100'">
<div class="font-semibold text-xs text-slate-400 mb-1 uppercase tracking-wider">
{{ message.role }}
</div>
<div class="prose prose-invert max-w-none text-sm leading-relaxed">
<template v-for="(token, i) in parsedContent" :key="i">
<span v-if="token.type === 'text'">{{ token.value }}</span>
<button
v-else-if="token.type === 'citation'"
@click="citationStore.jumpToCitation(token.data)"
class="inline-flex items-center mx-1 px-1.5 py-0.5 rounded text-xs font-medium bg-indigo-600/40 text-indigo-300 border border-indigo-500/30 hover:bg-indigo-600 hover:text-white transition-all cursor-pointer"
:title="`Jump to ${token.data.fileName} (Page ${token.data.pageNumber})`"
>
[{{ token.index }}]
</button>
</template>
</div>
</div>
</template>
Why this works: Instead of relying on heavy regex replacement pipelines that break HTML injection safeguards, this tokenization approach breaks the response into clean reactive blocks, ensuring maximum security against XSS while providing native click handlers for each citation badge.
4. Rendering and Highlighting Text at the File Level
Scenario:
The user clicks citation [1], which points to an internal Markdown policy document rather than a PDF. The document viewer opens on the right side of your screen.
Why it matters: Opening the document is only half the battle. If the file is 4,000 words long, the user still has to find the exact paragraph. We need programmatic DOM element targeting and CSS pulse animations to draw the user's eye instantly.
Solution: Create a document viewer component that renders paragraphs with unique data attributes corresponding to their chunk or paragraph index, then watches the Pinia store for active navigation triggers.
<!-- components/MarkdownViewer.vue -->
<script setup lang="ts">
import { watch, nextTick, ref } from 'vue';
import { useCitationStore } from '@/stores/citationStore';
const props = defineProps<{
fileId: string;
fileName: string;
contentBlocks: Array<{ id: string; text: string; pageNumber: number }>;
}>();
const citationStore = useCitationStore();
const containerRef = ref<HTMLElement | null>(null);
// Watch for store changes to highlight and scroll to specific paragraphs
watch(
() => citationStore.activeCitation,
async (newCitation) => {
if (!newCitation || newCitation.fileId !== props.fileId) return;
await nextTick();
const targetElement = containerRef.value?.querySelector(
`[data-chunk-id="${newCitation.chunkId}"]`
);
if (targetElement) {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Apply temporary pulse highlight class
targetElement.classList.add('highlight-pulse');
setTimeout(() => {
targetElement.classList.remove('highlight-pulse');
}, 3000);
}
},
{ deep: true }
);
</script>
<template>
<div class="h-full flex flex-col bg-slate-900 border-l border-slate-700">
<div class="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-950">
<h3 class="font-medium text-sm text-slate-200 truncate">{{ fileName }}</h3>
<button @click="citationStore.closeViewer()" class="text-slate-400 hover:text-slate-200 text-xs">
Close ✕
</button>
</div>
<div ref="containerRef" class="flex-1 overflow-y-auto p-6 space-y-4">
<div
v-for="block in contentBlocks"
:key="block.id"
:data-chunk-id="block.id"
class="p-4 rounded-lg bg-slate-800/50 border border-slate-700/50 text-slate-300 text-sm leading-relaxed transition-all duration-500"
>
<div class="flex justify-between items-center mb-1">
<span class="text-[10px] text-slate-500 font-mono">Page {{ block.pageNumber }}</span>
</div>
<p>{{ block.text }}</p>
</div>
</div>
</div>
</template>
<style scoped>
@keyframes pulse-highlight {
0% { background-color: rgba(99, 102, 241, 0.4); border-color: rgba(99, 102, 241, 0.8); }
50% { background-color: rgba(99, 102, 241, 0.2); }
100% { background-color: rgba(30, 41, 59, 0.5); border-color: rgba(51, 65, 85, 0.5); }
}
.highlight-pulse {
animation: pulse-highlight 2.5s ease-in-out;
}
</style>
Why this works:
By attaching data-chunk-id attributes directly to the rendered elements, we avoid fragile CSS selectors or manual node traversals. The browser's native scrollIntoView({ behavior: 'smooth', block: 'center' }) handles the viewport adjustment with zero external dependencies.
5. Implementing Page-Level PDF Navigation and DOM Scroll Synchronization
Scenario: Enterprise documents are almost universally PDFs. Markdown or HTML views don't cut it when legal teams demand audit trails tied to official PDF layouts. You integrate PDF.js into your Vue application to render pages natively in the browser.
Why it matters: PDF rendering libraries virtualize pages for performance. If page 45 hasn't been scrolled into view yet, its DOM nodes do not exist. Telling the application to "scroll to paragraph on page 45" will fail because the element hasn't been mounted yet.
Solution: Combine PDF.js page rendering control with text-layer searching so your viewer explicitly commands the PDF renderer to flip to the target page before attempting to highlight coordinates.
<!-- components.PdfViewer.vue -->
<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from 'vue';
import { useCitationStore } from '@/stores/citationStore';
import * as pdfjsLib from 'pdfjs-dist';
// Configure worker for PDF.js
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`;
const props = defineProps<{
pdfUrl: string;
fileId: string;
}>();
const citationStore = useCitationStore();
const pdfDoc = ref<pdfjsLib.PDFDocumentProxy | null>(null);
const totalPages = ref(0);
const currentPage = ref(1);
const canvasContainer = ref<HTMLElement | null>(null);
onMounted(async () => {
try {
const loadingTask = pdfjsLib.getDocument(props.pdfUrl);
pdfDoc.value = await loadingTask.promise;
totalPages.value = pdfDoc.value.numPages;
await renderPage(currentPage.value);
} catch (err) {
console.error('Failed to load PDF:', err);
}
});
async function renderPage(pageNum: number) {
if (!pdfDoc.value) return;
const page = await pdfDoc.value.getPage(pageNum);
const viewport = page.getViewport({ scale: 1.5 });
const canvas = document.getElementById(`pdf-canvas-${pageNum}`) as HTMLCanvasElement;
if (!canvas) return;
const context = canvas.getContext('2d');
if (!context) return;
canvas.height = viewport.height;
canvas.width = viewport.width;
await page.render({
canvasContext: context,
viewport: viewport
}).promise;
}
// Watch citation store for page navigation requests
watch(
() => citationStore.activeCitation,
async (newCitation) => {
if (!newCitation || newCitation.fileId !== props.fileId) return;
// 1. Force viewer to the target page if different
if (newCitation.pageNumber !== currentPage.value) {
currentPage.value = newCitation.pageNumber;
await nextTick();
await renderPage(currentPage.value);
}
// 2. Highlight specific text coordinates or bounding boxes on the rendered page layer
await highlightPdfTextSpan(newCitation);
},
{ deep: true }
);
async function highlightPdfTextSpan(citation: any) {
// Implementation for applying absolute positioned bounding box
// overlays over the PDF text layer using citation.startOffset / endOffset
const textLayer = document.getElementById(`text-layer-${citation.pageNumber}`);
if (!textLayer) return;
// Example: Find matching text span and apply pulse style
const spans = textLayer.querySelectorAll('span');
spans.forEach(span => {
if (span.textContent?.includes(citation.exactText.slice(0, 20))) {
span.classList.add('pdf-highlight-active');
span.scrollIntoView({ behavior: 'smooth', block: 'center' });
setTimeout(() => span.classList.remove('pdf-highlight-active'), 3000);
}
});
}
</script>
<template>
<div class="h-full flex flex-col bg-slate-900 border-l border-slate-700">
<div class="p-3 bg-slate-950 border-b border-slate-800 flex justify-between items-center text-xs text-slate-300">
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="citationStore.closeViewer()" class="text-slate-400 hover:text-white">Close ✕</button>
</div>
<div ref="canvasContainer" class="flex-1 overflow-y-auto p-4 flex flex-col items-center">
<div v-for="p in totalPages" :key="p" class="mb-4 relative shadow-lg">
<canvas :id="`pdf-canvas-${p}`" class="rounded border border-slate-700"></canvas>
<div :id="`text-layer-${p}`" class="absolute inset-0 pointer-events-none"></div>
</div>
</div>
</div>
</template>
<style>
.pdf-highlight-active {
background-color: rgba(234, 179, 8, 0.4) !important;
outline: 2px solid rgba(234, 179, 8, 0.8);
border-radius: 2px;
}
</style>
Why this works: Directly managing PDF.js canvas rendering cycles alongside DOM text-layer overlays gives you pixel-accurate highlighting without needing expensive third-party enterprise PDF viewing licenses.
6. Handling Edge Cases: Multi-Paragraph Spans and Fuzzy Text Matching
Scenario: The LLM generates a synthesized answer that combines two distinct sentences: one from page 4, paragraph 2, and another from page 4, paragraph 5. The citation badge points to a multi-paragraph chunk. When clicked, only the first sentence gets highlighted because your DOM selector stops at the first newline.
Why it matters: Real-world RAG outputs rarely map cleanly to single, isolated paragraphs. Users will encounter truncation, hyphenation differences between PDF text extractors and embedding models, and slight whitespace discrepancies.
Solution: Implement a client-side normalization and fuzzy matching utility that strips punctuation, collapses whitespaces, and scans neighboring DOM nodes if an exact string match fails.
// utils/fuzzyMatch.ts
export function normalizeText(text: string): string {
return text
.toLowerCase()
.replace(/[\s\n\r]+/g, ' ')
.replace(/[^\w\s]/gi, '')
.trim();
}
export function findMatchingElement(container: HTMLElement, targetText: string): HTMLElement | null {
const normalizedTarget = normalizeText(targetText);
const candidateElements = container.querySelectorAll('[data-chunk-id], p, span');
let bestMatch: HTMLElement | null = null;
let highestScore = 0;
for (const el of Array.from(candidateElements)) {
const elText = normalizeText(el.textContent || '');
if (elText.includes(normalizedTarget) || normalizedTarget.includes(elText)) {
const score = elText.length / Math.abs(elText.length - normalizedTarget.length + 1);
if (score > highestScore) {
highestScore = score;
bestMatch = el as HTMLElement;
}
}
}
return bestMatch;
}
Why this works:
PDF extraction introduces subtle character encoding artifacts (such as ligature transformations like fi becoming a single character or missing soft hyphens). Fuzzy normalization ensures your frontend doesn't fail silently when encountering minor string variations.
Production Architecture Decisions and Performance Trade-offs
When scaling file-level and page-level citation highlighting to thousands of concurrent users across massive repositories, architectural choices matter. The table below outlines the trade-offs between different highlighting implementation strategies:
| Strategy | Complexity | Memory Footprint | Scroll Precision | Best Use Case |
|---|---|---|---|---|
| File-Level Markdown Chunking | Low | Low | Paragraph level | Internal wikis, knowledge bases, README docs |
| PDF.js Canvas + Text Layer Overlay | High | High | Character / Word level | Legal contracts, financial statements, audited compliance reports |
| Server-Side Rendered HTML Previews | Medium | Medium | Exact CSS Selector | Enterprise document management systems with pre-parsed HTML |
What I Would Choose in a Real Project
If I am building an internal developer tool or product documentation assistant, I use Markdown Chunking with Pinia State (Approaches 1 through 3). It requires zero external commercial licensing, runs blazingly fast in Vue 3, and fits standard LLM vector stores without complex coordinate mapping.
If I am building a fintech or legal compliance copilot where auditors inspect every single claim down to the line number, I invest the engineering hours into PDF.js with precise character offset mapping and bounding box overlays (Approach 5). The initial implementation complexity is higher, but the auditability it provides is non-negotiable for enterprise procurement.