Display RAG Sources as Expandable Citations in Vue 3

Retrieval-Augmented Generation (RAG) applications have evolved from brittle proof-of-concept scripts into core enterprise features. Yet, the frontend user experience around grounding—showing why an LLM generated a specific response—remains an afterthought in many web applications.

You’ve likely seen the result: a chat interface spews out a wall of generated text accompanied by an unhelpful list of raw UUIDs, truncated database keys, or sterile inline numbers like [1][4][7] that lead to nowhere when clicked.

If you are building production-grade AI interfaces in Vue 3, displaying sources isn't just about rendering text; it’s about establishing user trust through transparent, interactive UI patterns. Users want to hover over a citation or click a reference tag to inspect the exact chunk of text retrieved from a vector store, verify the cosine similarity score, and confirm that the model didn't hallucinate an enterprise policy.

This guide explores how to build a production-ready, highly polished expandable citation system in Vue 3 using Composition API, <script setup>, Tailwind CSS, and headless accessibility patterns.


📋 Table of Contents


The UX Gap in Standard RAG Interfaces

When developers first wire up a vector database like Pinecone, pgvector, or Milvus with an LLM backend, they focus heavily on chunking strategies, embedding models, and rerankers. The frontend usually gets a basic markdown renderer where citations are appended as static text at the bottom of the response block.

<!-- The anti-pattern: Dead-end citations -->
<div class="message-body">
  Acme Corp's remote work policy allows up to 10 days of international work per year [1].
</div>
<div class="sources-footer text-xs text-gray-500">
  Sources: [1] internal_wiki_v4_chunk_8812.md
</div>

This approach breaks down for three reasons:

  1. Context Switching: Users have to scan back and forth between the bottom footer and the body text to map [1] to its reference.
  2. Opaque Metadata: Filenames like internal_wiki_v4_chunk_8812.md tell the user nothing about why the snippet was retrieved or what its relevance score was.
  3. Lack of Interactivity: Users cannot inspect the surrounding text of the chunk to verify if the LLM misinterpreted a conditional statement.

To bridge this gap, modern AI interfaces (like Perplexity or ChatGPT Enterprise) embed interactive citation badges directly into the text flow. Clicking a badge expands a preview card showing the document title, snippet excerpt, similarity score, and a link to the original source. Let's build this in Vue 3.


1. Structuring and Sanitizing the Backend Source Payload

Scenario: Your Python/Node.js backend streams an LLM response via Server-Sent Events (SSE). Along with the text tokens, it pushes a metadata payload containing the chunks retrieved from your vector store.

Why it matters: Raw vector search payloads are messy. They contain high-dimensional vectors, internal database primary keys, and raw HTML or markdown formatting that can break your frontend layout if rendered carelessly.

Solution: Normalize your backend payload into a strict TypeScript interface before it hits your Vue component tree.

// types/citations.ts
export interface SourceMetadata {
  id: string;
  title: string;
  url?: string;
  pageNumber?: number;
  similarityScore: number;
  snippet: string;
  collection: string;
}

export interface CitationMarker {
  index: number;
  sourceId: string;
  startOffset: number;
  endOffset: number;
}

export interface AssistantMessage {
  id: string;
  content: string;
  sources: SourceMetadata[];
  citations: CitationMarker[];
}

When designing your SSE event stream, ensure the backend emits the text stream first, followed by a final metadata packet containing the resolved citation indices mapped to specific character offsets in the generated text string.

// Example SSE final payload structure
{
  "type": "message_complete",
  "content": "Our security framework mandates SOC2 compliance for all third-party vendors handling PII [1]. Exceptions require VP approval [2].",
  "sources": [
    {
      "id": "doc_sec_01",
      "title": "Information Security Policy 2026",
      "url": "https://internal.acme.co/docs/sec-01",
      "similarityScore": 0.89,
      "snippet": "All third-party vendors handling Personally Identifiable Information (PII) must maintain an active SOC2 Type II certification...",
      "collection": "policy-docs"
    },
    {
      "id": "doc_sec_04",
      "title": "Executive Exception Workflow",
      "url": "https://internal.acme.co/docs/sec-04",
      "similarityScore": 0.84,
      "snippet": "Bypassing standard vendor security reviews requires explicit written sign-off from the Vice President of Engineering...",
      "collection": "workflows"
    }
  ],
  "citations": [
    { "index": 1, "sourceId": "doc_sec_01", "startOffset": 93, "endOffset": 96 },
    { "index": 2, "sourceId": "doc_sec_04", "startOffset": 124, "endOffset": 127 }
  ]
}

💡 Practical note: Never trust raw snippets from vector databases without sanitization. If your documents contain unescaped HTML or malicious markdown, rendering them inside expandable popovers exposes your application to XSS vulnerabilities. Always sanitize text snippets using a trusted library like DOMPurify before binding them to v-html.


2. Building the Reactive Citation Parser and Tokenizer

Scenario: Your LLM outputs inline markers like [1] or [doc_sec_01] directly within the text stream. Relying on regular expressions inside template bindings during streaming causes severe layout thrashing and broken HTML tags.

Why it matters: During a live SSE stream, text chunks arrive every few milliseconds. If you attempt to dynamically parse and replace citation strings on every single token emission without a stable tokenization strategy, your DOM nodes will constantly re-render, causing cursor jumps and high CPU utilization.

Solution: Create a dedicated composable (useCitations.ts) that transforms a raw message string and its citation index table into an array of renderable tokens (text blocks vs. citation nodes).

// composables/useCitations.ts
import { computed, type Ref } from 'computed-ref' // or standard Vue computed
import type { SourceMetadata, CitationMarker } from '@/types/citations'

export type TokenType = 'text' | 'citation'

export interface TextToken {
  type: 'text'
  content: string
}

export interface CitationToken {
  type: 'citation'
  index: number
  source: SourceMetadata
}

export type MessageToken = TextToken | CitationToken

export function useCitations(
  content: Ref<string>,
  sources: Ref<SourceMetadata[]>,
  citations: Ref<CitationMarker[]>
) {
  const tokens = computed<MessageToken[]>(() => {
    const rawText = content.value
    const sourceMap = new Map(sources.value.map(s => [s.id, s]))
    
    if (!citations.value || citations.value.length === 0) {
      return [{ type: 'text', content: rawText }]
    }

    // Sort citations by start offset to ensure sequential processing
    const sortedCitations = [...citations.value].sort((a, b) => a.startOffset - b.startOffset)
    
    const result: MessageToken[] = []
    let lastIndex = 0

    for (const citation of sortedCitations) {
      // Push text leading up to the citation
      if (citation.startOffset > lastIndex) {
        result.push({
          type: 'text',
          content: rawText.slice(lastIndex, citation.startOffset)
        })
      }

      // Resolve source metadata
      // Assuming citation points to a source via sourceId or index matching
      const source = sources.value.find(s => s.id === citation.sourceId) || sources.value[citation.index - 1]

      if (source) {
        result.push({
          type: 'citation',
          index: citation.index,
          source
        })
      }

      lastIndex = citation.endOffset
    }

    // Push remaining trailing text
    if (lastIndex < rawText.length) {
      result.push({
        type: 'text',
        content: rawText.slice(lastIndex)
      })
    }

    return result
  })

  return { tokens }
}

Why this works: By decoupling the raw string parsing from the UI rendering layer, Vue's virtual DOM only updates the specific token segments that change during streaming. Text tokens are appended cleanly, while citation tokens mount as self-contained interactive Vue components.


3. Crafting the Expandable Inline Citation Component

Scenario: When a user clicks citation [1], you need an interactive popover or drawer that displays the source metadata without shifting the surrounding paragraph layout.

Why it matters: Standard CSS tooltips (hover states) fail on mobile devices and make it impossible for users to copy text out of the source snippet. Click-to-expand popovers provide a much better experience, but they require careful management of positioning, focus trapping, and click-outside listeners.

Solution: Build a robust Vue 3 component (CitationBadge.vue) that handles toggle states, similarity score badges, and truncation for long document snippets.

<!-- components/CitationBadge.vue -->
<script setup lang="ts">
emits: ['select']
import { ref, onMounted, onUnmounted } from 'vue'
import type { SourceMetadata } from '@/types/citations'

const props = defineProps<{
  index: number
  source: SourceMetadata
}>()

const isOpen = ref(false)
const popoverRef = ref<HTMLElement | null>(null)

const togglePopover = () => {
  isOpen.value = !isOpen.value
}

const handleClickOutside = (event: MouseEvent) => {
  if (popoverRef.value && !popoverRef.value.contains(event.target as Node)) {
    isOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside, true)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside, true)
})
</script>

<template>
  <span class="relative inline-block mx-0.5" ref="popoverRef">
    <button
      @click.stop="togglePopover"
      type="button"
      :aria-expanded="isOpen"
      :aria-label="`Source ${index}: ${source.title}`"
      class="inline-flex items-center justify-center px-1.5 py-0.5 text-xs font-semibold text-indigo-700 dark:text-indigo-300 bg-indigo-50 dark:bg-indigo-950/60 border border-indigo-200 dark:border-indigo-800 rounded hover:bg-indigo-100 dark:hover:bg-indigo-900 transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500"
    >
      {{ index }}
    </button>

    <!-- Expandable Popover Card -->
    <Transition
      enter-active-class="transition duration-150 ease-out"
      enter-from-class="transform scale-95 opacity-0"
      enter-to-class="transform scale-100 opacity-100"
      leave-active-class="transition duration-100 ease-in"
      leave-from-class="transform scale-100 opacity-100"
      leave-to-class="transform scale-95 opacity-0"
    >
      <div
        v-if="isOpen"
        class="absolute z-50 w-80 p-3 mt-2 text-left bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg shadow-xl left-1/2 -translate-x-1/2 sm:left-0 sm:translate-x-0"
      >
        <div class="flex items-start justify-between gap-2 mb-2">
          <span class="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
            {{ source.collection }}
          </span>
          <span class="inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono bg-emerald-50 dark:bg-emerald-950 text-emerald-700 dark:text-emerald-300 rounded">
            {{ Math.round(source.similarityScore * 100) }}% match
          </span>
        </div>

        <h4 class="text-sm font-semibold text-slate-900 dark:text-slate-100 mb-1 leading-snug">
          <a 
            v-if="source.url" 
            :href="source.url" 
            target="_blank" 
            rel="noopener noreferrer"
            class="hover:underline flex items-center gap-1 text-indigo-600 dark:text-indigo-400"
          >
            {{ source.title }}
            <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round-width" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
            </svg>
          </a>
          <span v-else>{{ source.title }}</span>
        </h4>

        <p class="text-xs text-slate-600 dark:text-slate-300 font-serif leading-relaxed bg-slate-50 dark:bg-slate-800/50 p-2 rounded border border-slate-100 dark:border-slate-800 line-clamp-4">
          "{{ source.snippet }}"
        </p>
      </div>
    </Transition>
  </span>
</template>

⚠️ Gotcha: Using left-1/2 -translate-x-1/2 is great for centering popovers on mobile viewports, but on desktop screens near the right edge of your chat window, the popover will overflow the viewport boundary. In production, consider adding simple bounding logic or using floating positioning libraries like Floating UI (@floating-ui/vue) to dynamically flip popovers when they hit screen edges.


4. Managing Global Citation State with Provide/Inject

Scenario: Your application layout features a split-pane view: the conversation stream sits on the left, and a dedicated "Reference Inspector Drawer" sits on the right. When a user clicks citation [1] anywhere in the chat, the right drawer should automatically open and highlight source doc_sec_01.

Why it matters: Passing callback functions or event emitters up and down through multi-layered chat components (MessageList.vue -> MessageItem.vue -> MessageBody.vue -> CitationBadge.vue) leads to prop drilling and tightly coupled components.

Solution: Use Vue 3’s provide and inject API with a reactive state store to manage the currently active citation drawer across the component tree.

// symbols/citationContext.ts
import { injectionKey, type InjectionKey, type Ref } from 'vue'
import type { SourceMetadata } from '@/types/citations'

export interface CitationContextType {
  activeSource: Ref<SourceMetadata | null>
  isDrawerOpen: Ref<boolean>
  inspectSource: (source: SourceMetadata) => void
  closeDrawer: () => void
}

export const CitationKey: InjectionKey<CitationContextType> = Symbol('CitationContext')

Implement the provider in your parent chat container:

<!-- components/ChatContainer.vue -->
<script setup lang="ts">
import { ref, provide } from 'vue'
import { CitationKey } from '@/symbols/citationContext'
import type { SourceMetadata } from '@/types/citations'

const activeSource = ref<SourceMetadata | null>(null)
const isDrawerOpen = ref(false)

const inspectSource = (source: SourceMetadata) => {
  activeSource.value = source
  isDrawerOpen.value = true
}

const closeDrawer = () => {
  isDrawerOpen.value = false
}

provide(CitationKey, {
  activeSource,
  isDrawerOpen,
  inspectSource,
  closeDrawer
})
</script>

<template>
  <div class="flex h-screen overflow-hidden bg-slate-50 dark:bg-slate-950">
    <!-- Main chat stream -->
    <div class="flex-1 overflow-y-auto">
      <slot />
    </div>

    <!-- Side inspection drawer -->
    <aside v-if="isDrawerOpen" class="w-96 border-l border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-4">
      <!-- Drawer Header & Snippet view -->
    </aside>
  </div>
</template>

Then consume it inside your badge component to allow dual-mode interaction (popover on click, plus syncing with the side drawer):

// Inside CitationBadge.vue script setup
import { inject } from 'vue'
import { CitationKey } from '@/symbols/citationContext'

const citationContext = inject(CitationKey)

const handleBadgeClick = () => {
  togglePopover()
  if (citationContext) {
    citationContext.inspectSource(props.source)
  }
}

5. Designing Keyboard Navigation and Accessibility (A11y)

Scenario: Enterprise applications undergo rigorous accessibility audits (WCAG 2.1 AA/AAA). Standard clickable spans and non-semantic divs break screen readers and keyboard traversal for users who cannot rely on a mouse.

Why it matters: AI interfaces are frequently used in enterprise legal, medical, and financial tools where keyboard navigation and screen reader support are strict regulatory requirements.

Solution: Ensure that every citation badge acts as a true interactive button with proper ARIA attributes, focus rings, and keyboard event handlers (Enter and Space).

<!-- Accessibility-hardened badge template snippet -->
<button
  @click.stop="togglePopover"
  @keydown.esc="isOpen = false"
  type="button"
  :aria-expanded="isOpen"
  :aria-controls="`popover-${index}`"
  class="inline-flex items-center justify-center px-1.5 py-0.5 text-xs font-semibold text-indigo-700 bg-indigo-50 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:ring-offset-2"
>
  <span class="sr-only">Reference {{ index }}:</span>
  {{ index }}
</button>

When the popover opens, manage focus containment so that pressing Tab cycles through links inside the popover card rather than escaping into the background DOM tree.


6. Handling Edge Cases: Overlapping Ranges and Missing Metadata

Scenario: What happens when your vector database returns duplicate chunks, or when two adjacent sentences draw from the exact same source document, resulting in markers [1][2] pointing to the same file? Even worse, what if a citation index [99] arrives from the LLM, but the vector chunk payload was dropped due to network timeouts?

Why it matters: LLMs are probabilistic. They frequently hallucinate indices or output malformed bracket patterns ([[1]], [1, 2], [ref_missing]). If your parser crashes on invalid offsets, the entire chat message fails to render, showing a blank screen to the user.

Solution: Build defensive fallback handlers directly into your tokenization composable.

// Safe fallback handling in useCitations.ts
const resolveSource = (sourceId: string | undefined, index: number, allSources: SourceMetadata[]) => {
  if (sourceId) {
    const found = allSources.find(s => s.id === sourceId)
    if (found) return found
  }
  // Fallback to index-based lookup (1-indexed)
  if (allSources[index - 1]) {
    return allSources[index - 1]
  }
  // Ultimate fallback stub for missing metadata
  return {
    id: `missing-${index}`,
    title: `Source [${index}] (Metadata unavailable)`,
    similarityScore: 0,
    snippet: 'The retrieval payload for this citation was not returned by the server.',
    collection: 'unknown'
  }
}

By substituting a graceful placeholder card when metadata is missing, you ensure that the application remains functional even when backend ingestion pipelines drop a chunk.


7. Optimizing Rendering Performance for Long Conversations

Scenario: A user has an active chat history spanning 50 messages, with hundreds of inline citations rendered across the DOM. Scrolling up and down causes noticeable frame drops.

Why it matters: Each interactive citation badge is a Vue component with event listeners (click outside). Rendering thousands of independent interactive components inside long chat logs bloats memory consumption and slows down DOM reconciliation.

Solution: Combine Vue's built-in component caching with virtualization or conditional rendering strategies for historical messages.

  1. Virtualize Long Chat Lists: Use libraries like @tanstack/vue-virtual to render only the messages currently visible in the scroll viewport.
  2. Memoize Static Text Tokens: Ensure text token segments are rendered as plain static strings rather than complex reactive template expressions.
<!-- MessageBody.vue -->
<script setup lang="ts">
import { toRefs } from 'vue'
import { useCitations } from '@/composables/useCitations'
import CitationBadge from './CitationBadge.vue'
import type { SourceMetadata, CitationMarker } from '@/types/citations'

const props = defineProps<{
  content: string
  sources: SourceMetadata[]
  citations: CitationMarker[]
}>()

const { content, sources, citations } = toRefs(props)
const { tokens } = useCitations(content, sources, citations)
</script>

<template>
  <div class="prose dark:prose-invert max-w-none text-slate-800 dark:text-slate-200">
    <template v-for="(token, idx) in tokens" :key="idx">
      <span v-if="token.type === 'text'">{{ token.content }}</span>
      <CitationBadge 
        v-else-if="token.type === 'citation'" 
        :index="token.index" 
        :source="token.source" 
      />
    </template>
  </div>
</template>

Production Architecture Perspective

When deciding how to implement expandable citations in your Vue 3 application, consider the following architectural tradeoffs:

Approach Complexity Performance Mobile UX Best Use Case
Static Footer Links Low High Poor Simple internal wikis or low-traffic bots
Hover Tooltips (CSS only) Medium High Terrible Quick prototyping, read-only desktop apps
Click-to-Expand Popovers Medium-High High Excellent Standard production RAG chat interfaces
Dual-Mode (Popover + Side Drawer) High Optimized Excellent Enterprise document analysis, legal research tools

In production environments handling sensitive documents, I lean toward the Dual-Mode pattern. It gives users instant gratification via inline popovers while providing power users with a dedicated inspection drawer to cross-reference multiple document chunks simultaneously.

By combining Vue 3’s performant Composition API, rigorous type safety, and thoughtful accessibility patterns, you transform raw vector search outputs into an intuitive, trustworthy user experience.

Post a Comment

Previous Post Next Post