npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@e-llm-studio/citation

v0.0.216

Published

## Table of Contents

Readme

📚 e-llm-studio/citation

Table of Contents

  1. Project Overview
  2. Installation
  3. Available Components
  4. Common Use Cases
  5. Development & Contribution
  6. License

Project Overview

The @e-llm-studio/citation library is a comprehensive React component library designed to render various types of citations and related UI elements within the e-LLM Studio ecosystem. It provides a robust set of reusable, production-ready components that enable developers to display citations, reasoning chains, code snippets, PDFs, and other content types with rich interactive features and highly customizable styling.

This library serves as a foundational building block for applications that need to present complex information in an organized, user-friendly manner. Whether you're displaying book citations with highlighted passages, rendering AI reasoning with confidence scores, showcasing code with syntax highlighting, or managing large datasets with pagination, the citation library offers flexible, well-documented components that integrate seamlessly into modern React applications.

The library emphasizes developer experience through comprehensive documentation, TypeScript support, and extensive customization options. Each component is designed with accessibility and performance in mind, ensuring that applications built with these components provide excellent user experiences across different devices and use cases.


Installation

Prerequisites

Before you begin, ensure you have the following installed on your system:

  • Node.js & npm - Required for package management and running build scripts
  • Git - Required for cloning the repository
  • Basic familiarity with Git and the command line

Installation Steps

1. Clone the Repository

Start by cloning the citation library repository to your local machine:

git clone https://github.com/e-llm-studio/citation.git

cd citation

2. Install Dependencies

Install all required dependencies using npm:

npm install

Alternatively, you can use yarn if you prefer:

yarn install

3. Link the Library Locally (Optional)

If you want to test the library in another project before publishing, you can link it locally:

# In the citation library folder
npm link

# In your test project folder
cd ../your-project
npm link @e-llm-studio/citation

This allows you to test changes in your local library without publishing to npm.

4. Build the Library

Build the library to compile TypeScript and prepare distribution files:

npm run build

5. Test Locally

After building, you can test the library in your project:

# In your test project
npm start
# or
npm run build

Import the library components and verify that your changes work as expected.

Quick Installation for End Users

If you're installing the published package from npm:

# Using npm
npm install @e-llm-studio/citation

# Using yarn
yarn add @e-llm-studio/citation

# Using pnpm
pnpm add @e-llm-studio/citation

Citation Components

BookCitation

Overview

The BookCitation component is designed to display book citations with an interactive and expandable interface. It provides a rich, user-friendly way to present quoted text from books with support for highlighting, citation details management, and book cover images. The component enables readers to explore citations in context while maintaining a clean, organized presentation.

Features

  • Text highlighting with partial and full match support - Highlights specific text passages within citations using flexible matching algorithms
  • Automatic cleaning of scanned text to remove artifacts - Intelligently removes OCR artifacts, page numbers, headers, and footers
  • Expandable/collapsible view of citation details - Toggle between collapsed citation button and expanded view
  • Blur effect for non-highlighted text - Applies visual blur to non-highlighted portions to focus reader attention
  • Scroll-to-highlight functionality - Automatically scrolls to and centers highlighted text when expanded
  • Support for book cover images and external links - Displays book cover images and provides clickable external links
  • Customizable styling through the customStyle prop - Allows fine-grained control over component appearance

Usage:

import BookCitation from '@e-llm-studio/citation/BookCitation'

<BookCitation
 citationTitle="Sample Book"
 paragraphs={['<p>Highlighted text example</p>']}
 textToHighlight={['example']}
 partialMatch={true}
/>

Props:

| Prop Name | Type | Description | |-----------|------|-------------| | title | string | Optional title of the book or publication being cited | | author | string \| string[] | Optional author name(s) of the book or publication | | pageNumber | string | Optional current page number where the citation is located | | totalPageNumber | string | Optional total number of pages in the book or publication | | paragraphs | string[] | Required array of HTML strings containing the text content | | citationTitle | string | Required title or label for the citation | | textToHighlight | string[] | Required array of text strings to highlight within the paragraphs | | bookCoverImage | string | Optional URL or path to the book cover image | | handleExternalLinkClick | () => void | Optional callback function triggered when external link is clicked | | externalLinkComponent | React.ReactNode | Optional React component to render as an external link button | | citationNumber | number | Optional citation number displayed in the citation button | | partialMatch | boolean | Optional flag to enable partial text matching when highlighting | | defaultState | boolean | Optional flag to set the initial expanded/collapsed state | | isNonHighlightedBlur | boolean | Optional flag to enable blur effect on non-highlighted text | | customStyle | object | Optional object for overriding default styles | | useDropdown | boolean | Optional flag to render the citation as a dropdown (default: true) |



CognitiveCompare (Main Component)

A side-by-side document comparison component with cognitive analysis, deviation badges, citation-linked PDF previews, and two layout modes (Standard and Relative Order). For full documentation see the dedicated README.

Props

| Prop | Type | Default | Description | | --------------------- | ----------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | treeData | Record<string, any> \| null | — | Required. Backend tree structure powering both columns. | | displayConfig | IDisplayConfig | — | Required. Controls header/toggle visibility and initial layout mode. | | componentHeaderText | string | "Contract Comparison" | Text shown in the top header bar. | | deviationData | Record<string, any> | {} | Per-node deviation analysis results keyed by node ID. Populates the Deviation Analysis tab in the cognitive popup and drives inline text highlights within section content. |


IDisplayConfig

| Property | Type | Default | Description | | ----------------------- | --------- | ------- | ---------------------------------------------------------------------- | | isHeaderVisible | boolean | true | Show or hide the top header bar. | | isToggleVisible | boolean | true | Show or hide the Standard / Relative Order toggle switch. | | maintainRelativeOrder | boolean | false | Initial layout mode — true for Relative Order, false for Standard. |


treeData Shape

treeData is the primary data contract. It must be a flat object where every key is a node ID, plus four reserved keys.

{
  // Top-level metadata keys
  base_root_id: string,           // ID of the root node (looked up inside nodes)
  input_index_map: {              // Maps side index to document UUID
    "0": string,                  // left side UUID
    "1": string,                  // right side UUID
  },
  documents: {                    // Document metadata keyed by UUID
    [uuid: string]: {
      title: string,
      signed_url: string,         // PDF URL used by CitationAnchor / PdfViewer
    }
  },

  // All node data lives under the `nodes` key
  nodes: {
    // Root node (identified by base_root_id)
    [rootId: string]: {
      display_node?: boolean,
      comparison_inputs: {
        [uuid: string]: { title: string }   // column titles
      },
      decision_scope_description?: string,
      next?: Record<string, string>,         // child node IDs
    },

    // Section nodes
    [nodeId: string]: {
      display_node?: boolean,        // set false to hide the node
      evaluation_result?: DeviationDataEntry, // deviation result attached directly to node
      comparison_inputs: {
        [uuid: string]: {
          title: string,
          content: string,
          additional_attributes?: {
            display_index?: number,    // used in Relative Order mode for sorting
            display_title?: boolean,   // set false to suppress rendering the title
            display_content?: boolean, // set false to suppress rendering the content
          }
        }
      },
      next?: Record<string, string>, // child node IDs (for subsections)
      mapping_rationale?: {
        decision_strength?: string,  // numeric string, e.g. "72"
        decisioning_factors?: string[],
        gaps_in_decision?: string[],
        citations?: Record<string, Record<string, CitationEntry>>
      }
    }
  }
}

All node data (root and section nodes) lives under the nodes key. The top-level base_root_id, input_index_map, and documents keys remain directly on treeData.

deviationData Shape

// deviationData[nodeId]
{
  evaluation_outputs?: {
    output_value?: string,           // badge label text
    metadata?: { label_color?: string } // hex — drives badge/highlight colors
  },
  cognitive_decisioning?: {
    decisioning_factors?: string[],
    gaps_in_decision?: string[],
    citations?: Record<string, any>,
    decision_strength?: string | null,
  },
  deviations?: Record<string, any>,  // { devKey: { [docUuid]: highlightText } }
}

Usage

import CognitiveCompare from "@e-llm-studio/citation/CognitiveCompare";

<CognitiveCompare
  treeData={myTreeData}
  displayConfig={{
    isHeaderVisible: true,
    isToggleVisible: true,
    maintainRelativeOrder: false,
  }}
  deviationData={myDeviationData}
/>;

Key Behaviours

  • Badge and highlight colors are generated dynamically from evaluation_outputs.metadata.label_color via generateColorPalette(). The static relationStyles map has been removed.
  • Clicking a badge in Standard mode opens CognitivePopup directly. In Relative Order mode it opens MoreFunctionsPopup offering Connect, Side by Side, and Cognitive Decisioning actions.
  • The Deviation Analysis tab is shown first in the popup and displays cognitive_decisioning.decisioning_factors and gaps_in_decision with inline citation anchors that open split PDF viewers.
  • deviations entries drive inline <mark> highlights inside section content, colored using the same label_color-derived palette.

ChatCitation

Overview

ChatCitation is a composable React UI component for rendering chat-based citations, including summarized and detailed chat views alongside a rule book/reference section. The component is designed to be highly customizable via renderers, slot styles, and slot props, making it flexible for various use cases.

Features

  • Composable chat views - Supports both summarized and detailed chat display modes
  • Rule book/reference section - Optional left panel for displaying supporting rules and references
  • Markdown rendering - Rich text support with customizable markdown renderers
  • Customizable styling - Fine-grained control over styles through slot-based customization
  • Relevance scoring - Display AI relevance scores for citations
  • Tab-based navigation - Toggle between summarized and detailed views
  • Flexible content rendering - Support for custom renderers and markdown components

Usage

import ChatCitation from '@e-llm-studio/citation/ChatCitation'

<ChatCitation
 chatContainer={{
 chatData: [
 { role: 'user', message: 'Hello', userName: 'User1', timeStamp: dayjs() }
 ]
 }}
 ruleBookContainer={{
 title: 'References',
 data: { content: 'Rule content', highlighted_texts: ['important'] }
 }}
/>

Props

| Prop Name | Type | Description | |-----------|------|-------------| | rootContainer | RootContainerProps | Optional top-level container configuration | | chatContainer | ChatContainerProps | Required chat container configuration with chat data | | ruleBookContainer | RuleBookContainerProps | Optional rule book/reference section configuration | | renderer | FeatureModMarkdownProps["renderers"] | Optional custom markdown renderers |


ChatDrawer

Overview

ChatDrawer is a generic, resizable drawer component for rendering collapsible panels with a draggable resize handle. All content is consumer-owned — pass any React node as children: forms, file lists, summary cards, tables, or any custom component. The consuming team is fully responsible for styling and rendering the content inside.

Features

  • Collapsible panel — Header is always visible; body and drag handle only render when open
  • Notch toggle — Small tab below the drawer with a chevron arrow; click to expand/collapse, drag to resize
  • Drag to resize — Grab the pill handle at the bottom to resize between minHeight and maxHeight
  • Configurable heightdefaultHeight, minHeight, maxHeight all exposed as props
  • Consumer-owned content — Zero opinion on what goes inside, pass any React node
  • Deep style overrides — Every visual region customizable via the styles prop
  • Inline styles only — No Tailwind or MUI dependency, works in any consuming app

Usage

import ChatDrawer from '@e-llm-studio/citation/ChatDrawer'

<ChatDrawer
  uploadListTopContent="My Panel"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  defaultHeight={300}
  minHeight={150}
  maxHeight="60vh"
>
  {/* Pass any component here — form, file list, summary cards, etc. */}
  <YourComponent />
</ChatDrawer>

With onHeightChange (sibling layout adjustment):

const [drawerHeight, setDrawerHeight] = useState(300);

<ChatDrawer
  uploadListTopContent="Context"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  defaultHeight={300}
  onHeightChange={setDrawerHeight}
>
  <YourComponent />
</ChatDrawer>

With drawer summary

<ChatDrawer
  uploadListTopContent="Custom Notch"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  styles={{
    notch: { backgroundColor: '#6d28d9', border: '1px solid #5b21b6' },
    notchArrowColor: '#fff',
  }}
  drawerSummaryComponent={<RedliningFixesSummaryUI approved={5} rejected={2} pending={3} />}
>
  <YourComponent />
</ChatDrawer>

With drawer countBadge

<ChatDrawer
  uploadListTopContent="Custom Notch"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  styles={{
    notch: { backgroundColor: '#6d28d9', border: '1px solid #5b21b6' },
    notchArrowColor: '#fff',
  }}
  totalCountsBadge={<TotalCountsBadge totalDeviations={10} resolvedDeviations={7} />}
>
  <YourComponent />
</ChatDrawer>

With drawer header component prop

<ChatDrawer
  uploadListTopContent="Custom Notch"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  styles={{
    notch: { backgroundColor: '#6d28d9', border: '1px solid #5b21b6' },
    notchArrowColor: '#fff',
  }}
  headerComponent={<AutopilotIndicator />}
>
  <YourComponent />
</ChatDrawer>

With styles (theme customization):

<ChatDrawer
  uploadListTopContent="Dark Panel"
  isExpanded={isOpen}
  onToggle={() => setIsOpen(v => !v)}
  styles={{
    container: { backgroundColor: '#1a1a2e', border: '1px solid #444' },
    header: { backgroundColor: '#1a1a2e' },
    title: { color: '#fff' },
    body: { backgroundColor: '#1a1a2e' },
    notch: { backgroundColor: '#1a1a2e', border: '1px solid #444' },
    notchArrowColor: '#fff',
  }}
>
  <YourComponent />
</ChatDrawer>

Props

| Prop | Type | Required | Description | |------|------|----------|-------------| | children | ReactNode | ❌ | Scrollable body — fully consumer owned. Pass any React node. | | uploadListTopContent | string | ❌ | Header title shown in the always-visible top bar. Defaults to "Data uploaded for your context". | | isExpanded | boolean | ❌ | Controlled open/close state. Defaults to false. | | onToggle | () => void | ❌ | Called when the notch is clicked. Wire your open/close state here. | | defaultHeight | number | ❌ | Initial height of the panel in px when expanded. Defaults to 300. | | minHeight | number | ❌ | Minimum height in px when drag-resizing. Defaults to 150. | | maxHeight | number \| string | ❌ | Maximum height when drag-resizing. Accepts a px number or a CSS string like "70vh". Defaults to 40vh. | | onHeightChange | (height: number) => void | ❌ | Fired on every drag tick with the current height in px. Useful when a sibling layout needs to react to height changes. | | styles | ChatDrawerStyles | ❌ | Style overrides for each visual region. Keys: container, header, title, body, dragPill, notch, notchArrowColor. Each accepts any valid CSSProperties except notchArrowColor which is a string. |


CitationRenderer

Overview

CitationRenderer is a versatile, interactive "Pill" component designed to display a compact reference citation that expands into detailed content. It provides a space-efficient toggle mechanism, perfect for displaying source material, footnotes, or reasoning chains without cluttering the main UI. It works seamlessly with MarkdownRenderer to display rich, interactive text content.

Features

  • Expandable pill button - Compact display that expands on click
  • Customizable icons - Support for custom icons for chevron and citation indicators
  • Markdown content support - Render rich text content using MarkdownRenderer
  • Controlled and uncontrolled modes - Manage state internally or externally
  • Flexible styling - Customize appearance through style props
  • Callback support - Optional callbacks for side effects on toggle

Usage

import CitationRenderer from '@e-llm-studio/citation/CitationRenderer'

<CitationRenderer
 inLineCitation={true}
 citationTitle="Reference 1"
 citationComponent={<div>Detailed content here</div>}
 chevronDownComponent={<ChevronDownIcon />}
 chevronUpComponent={<ChevronUpIcon />}
/>

Props

| Prop Name | Type | Description | |-----------|------|-------------| | inLineCitation | boolean | Must be true to enable expand/collapse behavior | | citationTitle | string | The text displayed inside the pill button | | citationComponent | ReactNode | The content to render when expanded | | citationIcon | ReactNode | Icon displayed to the left of the title | | chevronUpComponent | ReactNode | Icon shown when the citation is expanded | | chevronDownComponent | ReactNode | Icon shown when the citation is collapsed | | additionalCallbackForPillButton | func | Hook to trigger side effects on click | | styles | Object | CSS overrides for styling | | isOpen | boolean | Forces the expanded state (controlled mode) | | onToggle | func | Callback fired when the pill is clicked |


CognitiveDecisioningCard

Overview

CognitiveDecisioningCard is a specialized React UI component designed to provide transparency into AI workflows. It renders a toggleable "Pill" that expands into a detailed card, displaying the AI's Reasoning, identified Gaps, and a confidence Score. It features a nested accordion design, robust Markdown rendering for content, and full styling customization.

Features

  • Toggleable pill button - Click to expand/collapse the detailed card
  • Reasoning and gap sections - Display AI reasoning and identified gaps with markdown support
  • Confidence score badge - Show confidence percentage in the header
  • Nested accordion design - Collapsible sections for organized content
  • Custom markdown rendering - Support for custom markdown components
  • Icon customization - Replace default icons with custom components
  • Advanced section customization - Override default sections with custom data structures

Usage

import CognitiveDecisioningCard from '@e-llm-studio/citation/CognitiveDecisioningCard'

<CognitiveDecisioningCard
 isOpen={isOpen}
 onToggle={() => setIsOpen(!isOpen)}
 score="92"
 reasoning="**Analysis:** Based on document review..."
 gap="Missing date information in section 3."
 title="AI Analysis Report"
/>

Advanced Customization:

const customSections = [
 {
 id: 'step1',
 title: 'Data Retrieval',
 subtitle: '3 sources processed',
 icon: <CheckIcon />,
 content: 'Data retrieved successfully'
 }
]

<CognitiveDecisioningCard
 isOpen={true}
 sections={customSections}
 score="100"
 mdComponents={{
 a: ({ node, ...props }) => <a {...props} target="_blank" />
 }}
/>

Props

| Prop Name | Type | Description | |-----------|------|-------------| | reasoning | string | Markdown text explaining the AI's logic | | gap | string | Markdown text explaining missing info or uncertainties | | score | string | Confidence score percentage (e.g., "92") | | isOpen | boolean | Controls the visibility of the expanded card | | onToggle | () => void | Callback handler for the pill trigger click | | title | string | Header title. Default: "Cognitive Decisioning AI" | | hideTrigger | boolean | If true, hides the pill button | | sections | SectionContent[] | Advanced: Overrides default Reasoning/Gap sections | | mdComponents | Object | Custom renderers for react-markdown | | headerIcon | ReactNode | Replaces the default brain icon | | reasoningIcon | ReactNode | Replaces the icon for the reasoning section | | gapIcon | ReactNode | Replaces the icon for the gap section | | scoreIcon | ReactNode | Replaces the sparkle icon in the score badge | | reasoningTitle | string | Title for the reasoning section. Default: "Decision Making Factors" | | reasoningSubtitle | string | Subtitle for the reasoning section. Default: "Why this was picked" | | gapTitle | string | Title for the gap section. Default: "Gaps in Decision" | | gapSubtitle | string | Subtitle for the gap section. Default: "What's missing or unclear" | | scoreLabel | string | Label prefix shown before the score percentage. Default: "Decision Strength: " |


CognitiveInternalGPTReasoning

Overview

The CognitiveInternalgptReasoningComponent is a React component designed to render non-web search reasoning citations with advanced interactive features. It provides a comprehensive display of reasoning data with support for expandable content, highlight navigation, and modal fullscreen viewing. This component is particularly useful for displaying AI-generated reasoning, training data citations, and confidence scores in a user-friendly format.

Features

  • Expandable Content - Display a paraphrase text that expands to show the full data source content
  • Highlight Navigation - Automatically extract and navigate between highlighted sections within the content
  • Confidence Score Display - Show confidence percentage in both expanded view and modal
  • Fullscreen Modal View - Open a fullscreen modal for detailed examination of reasoning data
  • Text Formatting Support - Handle bold text, list items, headers, and special highlight tags
  • Custom Icon Support - Replace default icons with custom React components

Usage

import NonWebReasoningComponent from '@e-llm-studio/citation/CognitiveInternalgptReasoningComponent'

const reasoningData = {
 text: "Reasoning text here",
 dataSource: "Source with <highlight>highlighted text</highlight>",
 confidence_score: 95,
 paraphrase: "Brief summary",
 previewCallback?:callback
 DocumentTitle?: "title";
}

<NonWebReasoningComponent
 item={reasoningData}
 index={1}
 headerTitle="GPT Reasoning"
/>

Highlight Navigation:

  • Extracts <highlight> tags from dataSource
  • Provides navigation between highlighted sections
  • Shows current position (e.g., "2/5 highlights")
  • Auto-scrolls to active highlight
  • previewCallback we can use this to pass a callback for external link opening or pdf opening
  • DocumentTitle : pdf title or document title

GptWebCitation

Overview

GptWebCitation is a composite React component that wraps the GPT reasoning citation (CognitiveInternalgptCoreComponent) and adds an optional Web Citation view. Users can toggle between GPT and web-based citations without modifying the underlying GPT citation code.

In GPT view, the component renders the standard GPT citation panel with a View Web Citation button on the left and the document source link on the right (inside the GPT citation footer). In Web Citation view, it shows a screenshot snapshot of the source page (when available), a relevance score badge, visit links, and a View GPT Citation toggle to switch back.

The component is presentational — it does not fetch web citations. The parent owns webCitationData, webCitationStatus, and view toggling.

Features

  • Dual citation views — Toggle between GPT reasoning and web-based citation
  • Non-invasive GPT integration — Wraps CognitiveInternalgptCoreComponent via props; no changes to GPT citation code required
  • Screenshot web citations — Renders imageMetadata.signed_url when the API returns a snapshot
  • Status-driven skeleton UI"pending" loading skeleton and "error" fallback with Visit Link
  • defaultCitationUrl — Immediate visit link while fetch is in progress (before highlightedUrl arrives)
  • Visit link priorityhighlightedUrl from API response wins over defaultCitationUrl in pending/error states
  • Relevance score badge — Auto-extracted from web citation content (e.g. "decision strength is 85%")
  • Expand screenshot button — Optional full-screen image view (showExpandImageButton)
  • Custom icons — Override expand and external-link icons via iconsConfig
  • Fixed height mode — Optional isFixedHeight keeps GPT and web panels the same size with contained screenshots
  • Style overrides — Customize layout via the styles prop without editing component internals

Installation / Import

import GptWebCitation from '@e-llm-studio/citation/GptWebCitation';

// Optional utilities and types
import {
  mapCitationDataToDisplay,
  getWebCitationImageUrl,
  resolveSkeletonVisitUrl,
  type GptWebCitationStatus,
  type IWebCitationApiResponse,
  type IGptWebCitationStyleOverrides,
  type IGptWebCitationImageStyles,
  type IGptWebCitationSkeletonStyles,
  type IGptWebCitationVisitLinkStyles,
  type IGptWebCitationFullScreenStyles,
} from '@e-llm-studio/citation';

Usage 1: Basic GPT + Web Citation Toggle

import { useState } from 'react';
import { ChevronDown, ChevronUp, ExternalLink, Maximize2, X } from 'lucide-react';
import GptWebCitation from '@e-llm-studio/citation/GptWebCitation';
import type { GptWebCitationStatus } from '@e-llm-studio/citation';

const gptCitation = {
  item: {
    confidence_score: 100,
    text: 'Standard financial data interpretation patterns.',
    dataSource:
      'Title: Commodity Market Analysis\n\n- <highlight>Verify the most recent timestamp in search results.</highlight>\n- Analyze safe-haven asset demand and geopolitical triggers.',
    paraphrase: 'Market interpretation patterns for commodity price reporting.',
  },
  headerTitle: 'Summary Citations',
  index: 0,
  iconsConfig: {
    ChevronDownIcon: ChevronDown,
    ChevronUpIcon: ChevronUp,
    MaximizeIcon: Maximize2,
    CloseIcon: X,
  },
  DocumentTitle: 'Source : Employee Handbook - Code of Conduct Section.pdf',
  previewCallback: () => window.open('/preview/document'),
};

const webCitationIcons = {
  MaximizeIcon: Maximize2,
  ExternalLinkIcon: ExternalLink,
};

function CitationPanel() {
  const [showWebCitation, setShowWebCitation] = useState(false);
  const [webCitationData, setWebCitationData] = useState(undefined);
  const [webCitationStatus, setWebCitationStatus] =
    useState<GptWebCitationStatus>('pending');

  const handleGenerateWebCitation = async () => {
    setShowWebCitation(true);
    setWebCitationStatus('pending');

    try {
      const response = await fetch('/api/web-citation/generate');
      const data = await response.json();
      setWebCitationData(data);
      setWebCitationStatus('success');
    } catch {
      setWebCitationStatus('error');
    }
  };

  return (
    <GptWebCitation
      gptCitation={gptCitation}
      defaultCitationUrl="https://example.com/article"
      isWebCitation={true}
      webCitationData={webCitationData}
      webCitationStatus={webCitationStatus}
      showWebCitation={showWebCitation}
      onGenerateWebCitation={handleGenerateWebCitation}
      onToggleCitationView={() => setShowWebCitation((prev) => !prev)}
      iconsConfig={webCitationIcons}
    />
  );
}

Usage 2: Web Citation API Response Shape

Pass the API response from your web citation service as webCitationData:

const webCitationData = {
  citationId: '550e8400-e29b-41d4-a716-446655440061',
  content:
    'The decision strength is 85% because:<ol><li>The exact <a href="https://example.com/article">valuation of SpaceX</a> fluctuates between sources.</li></ol>',
  citationType: 'web',
  citationUrl: 'https://example.com/article',
  highlightedUrl: 'https://example.com/article#highlight',
  message: 'Citation processed successfully',
  imageMetadata: {
    signed_url: 'https://storage.example.com/image_citations/screenshot.png',
    blob_path: 'image_citations/screenshot.png',
    gs_uri: 'gs://bucket/image_citations/screenshot.png',
  },
};

<GptWebCitation
  gptCitation={gptCitation}
  defaultCitationUrl="https://example.com/article"
  isWebCitation={true}
  webCitationData={webCitationData}
  webCitationStatus="success"
  showWebCitation={true}
/>

When imageMetadata.signed_url is present and webCitationStatus is "success", the component renders a screenshot snapshot. If the image is unavailable or the fetch fails, an error skeleton is shown with a Visit Link (using highlightedUrl or defaultCitationUrl).

Visit link resolution

| UI state | Visit link source | | --- | --- | | Pending / error skeleton | highlightedUrl from webCitationData → else defaultCitationUrl prop | | Screenshot footer (success) | citationUrl from webCitationData |

Use resolveSkeletonVisitUrl(highlightedUrl, defaultCitationUrl) from @e-llm-studio/citation if you need the same logic outside the component.

Usage 3: GPT-Only Mode (No Web Citation)

Set isWebCitation={false} to render only the GPT citation with no toggle button. defaultCitationUrl is still required by the prop contract but is unused in GPT-only mode:

<GptWebCitation
  gptCitation={gptCitation}
  defaultCitationUrl="https://example.com/article"
  isWebCitation={false}
/>

Usage 4: Hide Expand Buttons

Hide the web citation screenshot expand button:

<GptWebCitation
  gptCitation={gptCitation}
  defaultCitationUrl="https://example.com/article"
  isWebCitation={true}
  webCitationData={webCitationData}
  webCitationStatus="success"
  showWebCitation={true}
  showExpandImageButton={false}
/>

Hide the GPT citation header maximize/expand icon:

<GptWebCitation
  gptCitation={gptCitation}
  defaultCitationUrl="https://example.com/article"
  isWebCitation={true}
  showGptMaximizeButton={false}
/>

You can also use gptCitation.disableMaximize: true directly on the GPT config.

Usage 5: Custom Styling via Props (matched heights)

Layout, borders, and heights for both GPT and web views can be controlled from the parent without modifying component internals. Prefer isFixedHeight (Usage 6) when you only need equal panel size + contained screenshots; use styles when you need granular control over skeleton, image, visit-link, or full-screen elements:

const sharedPanelHeight = '520px';
const sharedContentHeight = '384px';

<GptWebCitation
  gptCitation={{
    ...gptCitation,
    bodyHeight: sharedContentHeight,
  }}
  defaultCitationUrl="https://example.com/article"
  isWebCitation={true}
  webCitationData={webCitationData}
  webCitationStatus="success"
  showGptMaximizeButton={true}
  iconsConfig={{
    MaximizeIcon: Maximize2,
    ExternalLinkIcon: ExternalLink,
  }}
  styles={{
    container: { maxWidth: 900 },
    gptCitation: {
      wrapper: {
        minHeight: sharedPanelHeight,
        border: '1px solid #e5e7eb',
        borderRadius: 8,
      },
      footerAction: { left: '1.5rem' },
      toggleButton: { minWidth: 180, fontSize: 14 },
    },
    webCitation: {
      panel: {
        minHeight: sharedPanelHeight,
        border: '1px solid #e5e7eb',
        borderRadius: 8,
      },
      header: { padding: '8px 16px' },
      content: {
        minHeight: sharedContentHeight,
        maxHeight: sharedContentHeight,
        overflowY: 'auto',
      },
      footer: { padding: '8px 16px' },
      toggleButton: { minWidth: 180, fontSize: 14 },
      learnedFrom: { fontSize: 13 },
    },
  }}
/>

Style keys

| Key | Applies to | Description | |-----|------------|-------------| | container | Both views | Shared outer wrapper (overlay in GPT view, merged into web panel) | | gptCitation.wrapper | GPT view | Border card around GPT citation (left/right borders restored here) | | gptCitation.footerAction | GPT view | View Web Citation button row in footer | | gptCitation.toggleButton | GPT view | View Web Citation button styles | | webCitation.panel | Web view | Outer web citation card | | webCitation.header | Web view | Source label + relevance score badge row | | webCitation.content | Web view | Screenshot or loading/error skeleton | | webCitation.footer | Web view | View GPT Citation + Learned From row | | webCitation.toggleButton | Web view | View GPT Citation button styles | | webCitation.learnedFrom | Web view | "Learned From …" text styles | | webCitation.visitLink.row | Image + skeleton | Shared visit link row (merged with scoped overrides below) | | webCitation.visitLink.hint | Image + skeleton | Shared visit link hint text | | webCitation.visitLink.link | Image + skeleton | Shared visit link anchor styles | | webCitation.image.wrapper | Screenshot view | Outer image citation wrapper | | webCitation.image.center | Screenshot view | Center column (viewport or inline skeleton) | | webCitation.image.viewport | Screenshot view | Viewport around scroll container | | webCitation.image.scrollContainer | Screenshot view | Scrollable screenshot container | | webCitation.image.image | Screenshot view | Screenshot <img> element | | webCitation.image.expandButton | Screenshot view | Full-screen expand button | | webCitation.image.visitLink.* | Screenshot footer | Image-specific visit link overrides (merged on top of webCitation.visitLink) | | webCitation.image.fullScreen.overlay | Full-screen viewer | Portal overlay backdrop | | webCitation.image.fullScreen.content | Full-screen viewer | Modal content card | | webCitation.image.fullScreen.closeButton | Full-screen viewer | Close button | | webCitation.image.fullScreen.imageWrapper | Full-screen viewer | Scrollable image wrapper | | webCitation.image.fullScreen.image | Full-screen viewer | Full-screen <img> | | webCitation.skeleton.container | Pending/error | Outer skeleton column | | webCitation.skeleton.frame | Pending/error | Gray skeleton frame | | webCitation.skeleton.shimmer | Pending | Shimmer animation overlay | | webCitation.skeleton.pending.content | Pending | Centered pending content block | | webCitation.skeleton.pending.text | Pending | Loading message text | | webCitation.skeleton.pending.actionRow | Pending | Visit link row | | webCitation.skeleton.pending.actionHint | Pending | "to view details" hint | | webCitation.skeleton.error.content | Error | Error content block | | webCitation.skeleton.error.title | Error | "No preview available" title | | webCitation.skeleton.error.message | Error | Restriction message | | webCitation.skeleton.error.actionGroup | Error | Action row wrapper | | webCitation.skeleton.error.detailsToggle | Error | Error details expand button | | webCitation.skeleton.error.detailsMessage | Error | Expanded error details text | | webCitation.skeleton.error.visitLinkGlow | Error | Glowing visit link (merged on top of visit link styles) | | webCitation.skeleton.visitLink.* | Pending/error | Skeleton-specific visit link overrides (merged on top of webCitation.visitLink) |

Legacy flat keys (gptCitationWrapper, footerAction, webCitationButton) still work for backward compatibility.

Example: customize screenshot and pending skeleton

<GptWebCitation
  gptCitation={gptCitation}
  defaultCitationUrl="https://example.com/article"
  isWebCitation
  webCitationData={data}
  webCitationStatus={status}
  styles={{
    webCitation: {
      visitLink: {
        link: { backgroundColor: 'rgba(37, 99, 235, 0.08)', borderRadius: 8 },
      },
      image: {
        scrollContainer: { borderRadius: 16, borderColor: '#d1d5db' },
        image: { objectFit: 'contain', maxHeight: 360 },
        expandButton: { backgroundColor: '#111827' },
      },
      skeleton: {
        frame: { minHeight: 320, backgroundColor: '#f8fafc' },
        pending: {
          text: { fontSize: 14, color: '#374151' },
        },
        error: {
          title: { color: '#dc2626' },
          visitLinkGlow: { borderColor: '#dc2626' },
        },
      },
    },
  }}
/>

Usage 6: Fixed height mode (matched GPT + web panels)

Set isFixedHeight={true} when you want GPT and web citation views to share the same panel dimensions. Screenshots use object-fit: contain so tall pages stay inside the box without layout shift when toggling views.

<GptWebCitation
  gptCitation={{
    ...gptCitation,
    bodyHeight: '384px', // optional — customizes inner content height
  }}
  defaultCitationUrl="https://example.com/article"
  isWebCitation
  isFixedHeight
  webCitationData={webCitationData}
  webCitationStatus="success"
  showWebCitation={showWebCitation}
  onToggleCitationView={() => setShowWeb((v) => !v)}
/>

| Scenario | Panel height | | --- | --- | | isFixedHeight + isWebCitation (toggle footer present) | 520px default, or calc(bodyHeight + 3.25rem) when gptCitation.bodyHeight is set | | isFixedHeight + isWebCitation={false} (GPT only) | 520px default, or gptCitation.bodyHeight when set |

isFixedHeight applies flex layout and contained images automatically. For manual per-element styling without fixed dimensions, use styles (Usage 5) instead.

Props

| Prop | Type | Default | Description | |------|------|---------|-------------| | gptCitation | IGptCitationConfig | required | GPT citation config passed to CognitiveInternalgptCoreComponent | | defaultCitationUrl | string | required | Fallback source URL for Visit Link in pending/error skeletons. Used when webCitationData.highlightedUrl is not yet available | | isWebCitation | boolean | false | When true, enables web citation toggle and web view | | webCitationData | IWebCitationApiResponse | — | Web citation API response (screenshot metadata, URLs, optional message) | | webCitationStatus | "pending" | "success" | "error" | inferred | Lifecycle status from parent API call. Inferred from webCitationData when omitted | | showWebCitation | boolean | true (uncontrolled) | false = GPT view, true = web view. Omit for uncontrolled internal state | | onGenerateWebCitation | () => void | — | Called when web view opens and no cached screenshot exists. Parent should fetch and update status/data. Also invoked once on mount when isWebCitation + showWebCitation are true and no image is cached | | onToggleCitationView | () => void | — | Called when user toggles between GPT and web views | | showExpandImageButton | boolean | true | Show/hide full-screen expand on screenshot | | showGptMaximizeButton | boolean | true | Show/hide GPT header maximize icon (gptCitation.disableMaximize: true when false) | | iconsConfig | IGptWebCitationImageIconsConfig | — | MaximizeIcon and ExternalLinkIcon overrides for web view | | topic | string | auto | Override topic label in web header | | sourceLabel | string | auto | Override header source label in web view | | relevanceScore | number | auto | Override relevance/decision strength badge (%) | | learnedFrom | string | auto | Site name in web footer (auto-derived from citationUrl) | | sourceModel | string | — | Deprecated. Use sourceLabel instead | | isFixedHeight | boolean | false | When true, GPT and web panels share the same fixed height/width; screenshot uses object-fit: contain | | styles | IGptWebCitationStyleOverrides | — | Style overrides for GPT and web citation views (see Usage 5) |

When isFixedHeight is true, both views use the same panel height (520px by default, or gptCitation.bodyHeight + toggle footer). Pair with gptCitation.bodyHeight to customize the content area (e.g. "384px").

webCitationStatus inference

When webCitationStatus is omitted, the component derives it in this order:

| Priority | Condition | Status | | --- | --- | --- | | 1 | Valid screenshot URL in webCitationData (signed_url or gs_uri) | "success" (always — image wins over explicit status) | | 2 | Explicit webCitationStatus prop | uses prop value | | 3 | webCitationData present but no image URL | "error" | | 4 | No webCitationData | "pending" |

Pass webCitationStatus="pending" explicitly while your fetch is in flight (before the image URL is available).

IGptCitationConfig (gptCitation prop)

| Field | Type | Description | |-------|------|-------------| | item | INonReasoningSource | GPT reasoning data (dataSource, confidence_score, highlights, etc.) | | headerTitle | string | Panel header title | | index | number | Citation index | | iconsConfig | object | Icon components (ChevronDownIcon, ChevronUpIcon, MaximizeIcon, CloseIcon) | | DocumentTitle | string | Source document label shown in the GPT footer (right side). Hidden when isWebCitation is true | | previewCallback | () => void | Called when the source link is clicked | | bodyHeight | string | Optional fixed GPT content body height (pair with styles.webCitation.content) | | disableMaximize | boolean | Disable GPT header fullscreen maximize button (or use showGptMaximizeButton={false}) |

IGptWebCitationImageIconsConfig (iconsConfig prop)

| Field | Type | Fallback | |-------|------|----------| | MaximizeIcon | ElementType | gptCitation.iconsConfig.MaximizeIcon, then Maximize2 | | ExternalLinkIcon | ElementType | ExternalLink |

Style override types (styles prop)

Nested under styles.webCitation:

| Type | Keys | Purpose | | --- | --- | --- | | IGptWebCitationVisitLinkStyles | row, hint, link | Visit link row shared by image footer and skeletons | | IGptWebCitationImageStyles | wrapper, center, viewport, scrollContainer, image, expandButton, visitLink, fullScreen | Screenshot view + inline loading skeleton while image decodes | | IGptWebCitationSkeletonStyles | container, frame, shimmer, pending.*, error.*, visitLink | Pending/error skeleton UI | | IGptWebCitationFullScreenStyles | overlay, content, closeButton, imageWrapper, image | Full-screen screenshot modal |

webCitation.visitLink merges with scoped image.visitLink or skeleton.visitLink overrides (scoped wins on conflict).

IWebCitationApiResponse (webCitationData prop)

| Field | Type | Description | |-------|------|-------------| | citationId | string | Unique citation identifier | | content | string | HTML/markdown explanation (used for topic/score extraction) | | citationType | string | Citation type (e.g. "web") | | citationUrl | string | Original source URL (screenshot footer Visit Link) | | highlightedUrl | string | Highlighted URL from API (preferred for skeleton Visit Link) | | message | string | API status or error message | | imageMetadata | object | Image snapshot metadata | | imageMetadata.signed_url | string | Signed URL for screenshot (preferred) | | imageMetadata.gs_uri | string | GCS URI fallback for image | | db | object | Database metadata (citation_id, blob_path) |

Utility helpers

Exported from @e-llm-studio/citation:

| Function | Purpose | | --- | --- | | mapCitationDataToDisplay(data) | Normalizes API response → display fields (topic, highlightedUrl, relevanceScore, etc.) | | getWebCitationImageUrl(data) | Resolves screenshot URL from imageMetadata | | resolveSkeletonVisitUrl(highlightedUrl, defaultCitationUrl) | Visit link for pending/error skeletons | | extractTopicFromContent(content) | First anchor text from content | | extractRelevanceScoreFromContent(content) | Parses decision strength / confidence % | | extractLearnedFromUrl(citationUrl) | Hostname → site name for footer | | sanitizeExternalUrl(url) | Safe http(s) URL for links |

View Behavior

| State | What renders | |-------|--------------| | isWebCitation={false} | GPT citation only | | isWebCitation={true}, showWebCitation={false} | GPT citation + View Web Citation button | | isWebCitation={true}, showWebCitation={true}, webCitationStatus="pending" | Shimmer skeleton + optional Visit Link (highlightedUrldefaultCitationUrl) | | isWebCitation={true}, showWebCitation={true}, webCitationStatus="success" | Screenshot (pending skeleton while image loads) + footer Visit Link | | isWebCitation={true}, showWebCitation={true}, webCitationStatus="error" | Error skeleton ("No preview available") + inline Visit Link | | isFixedHeight={true} | GPT and web outer panels share height; screenshot object-fit: contain; skeleton fills content area |

Auto-fetch

When isWebCitation is true and the web view is open with no cached screenshot, onGenerateWebCitation is called:

  1. Once on mount (per webCitationData.citationId)
  2. Again when the user clicks View Web Citation and no image is cached

The parent should set webCitationStatus="pending", fetch, then update webCitationData and status.

Error skeleton

The error state shows a fixed title ("No preview available"), a restriction message ("This website restricts external previews"), and an inline Visit Link when a source URL is available.

Local Test Component

A test harness is available at src/features/GptWebCitation/GptWebCitationTest.tsx. Run the citation dev server with GptWebCitationTest mounted in src/index.tsx to preview the component interactively. The harness uses sampleWebCitationApiResponse from WebCitationSampleResponse.ts, simulates a 2s fetch delay when View Web Citation is clicked, and accepts isFixedHeight, webCitationStatus, iconsConfig, and styles props for local experimentation.


CodeCitation

Overview

CodeCitation is a composable React UI component for rendering code citations with interactive features, syntax highlighting, and customizable display modes. It provides developers with a powerful tool for displaying code snippets with syntax highlighting, diagnostics, and theme support.

Features

  • Inline and popup citation views - Flexible display modes for different use cases
  • Syntax highlighting - Support for multiple programming languages
  • Dark/Light mode theme toggling - Accessibility and user preference support
  • Code highlighting - Highlight specific lines or variables
  • Displaying diagnostics - Show errors and warnings with customizable styling
  • Fetching code from backend - Support for dynamic code retrieval
  • Customizable UI - Extensive customization through props and inline styles
  • Fullscreen view support - View code in fullscreen modal
  • Responsive design - Works well on various screen sizes

Usage

import { CodeCitation } from '@e-llm-studio/citation/CodeCitation'

<CodeCitation
 citationTitle="Example Code"
 filename="example.js"
 filepath="/src/example.js"
 customCode={`function hello() { return "world"; }`}
 inLineCitation={true}
 isDarkModeEnabled={false}
 showThemeToggle={true}
 editorHeight={400}
/>

Advanced Features:

const diagnostics = [
 {
 range: { lineStart: 2, lineEnd: 2, columnStart: 6, columnEnd: 11 },
 severity: 1 
 }
]

const highlightRanges = [
 {
 startIndex: 2,
 endIndex: 5,
 color: 'rgba(255, 255, 0, 0.3)',
 lightModeColor: 'rgba(255, 255, 0, 0.2)'
 }
]

<CodeCitation
 customCode={sampleCode}
 diagnostics={diagnostics}
 diagnosticStylesBySeverity={{
 1: { style: { backgroundColor: 'rgba(255,0,0,0.2)' } }
 }}
 startIndex={2}
 endIndex={5}
 isHighlightingEnabled={true}
/>

Props

| Prop Name | Type | Description | |-----------|------|-------------| | citationTitle | string | Display name for the citation | | filename | string | Filename with extension to identify the language | | filepath | string | File path for reference | | customCode | string | The code string to display in the editor | | inLineCitation | boolean | Set to true for inline display or false for popup modal | | isDarkModeEnabled | boolean | Enable dark theme by default | | showThemeToggle | boolean | Display theme toggle button | | editorHeight | number | Height of the code editor in pixels | | editorWidth | string \| number | Width of the code editor | | baseUrlForCodeRetrieval | string | Base URL for fetching code from backend | | assistantName | string | Name of the assistant for context | | organizationName | string | Name of the organization | | userId | string | User ID for tracking | | taskId | string | Task ID for context | | repoUrl | string | Repository URL for reference | | showFullscreenIcon | boolean | Display fullscreen toggle button | | showFileSummaryIButton | boolean | Display file summary info button | | isHighlightingEnabled | boolean | Enable code highlighting |


CitationsViewer

Overview

The Citation Viewer is a rich, interactive React component designed to display AI-generated audio citations. It features a synchronized audio waveform player, a transcript view that highlights active segments, and a summary of key takeaways. This component is ideal for displaying RAG (Retrieval-Augmented Generation) results where the source material is audio or video, allowing users to listen to the specific segment referenced by the AI.

Features

  • Interactive Waveform - Visualizes audio using wavesurfer.js with playback controls
  • Smart Highlighting - Automatically highlights the specific time range referenced in the citation on the waveform
  • Synchronized Transcript - Displays chat history and highlights the active message segment
  • Key Takeaways - Renders extracted insights with bold text formatting and keyword tags
  • GCS Integration - Built-in hook to resolve Google Cloud Storage (gs://) URLs to signed URLs via a backend endpoint
  • Themable - Fully customizable colors and typography via a theme config object

Usage

import CitationsViewer from '@e-llm-studio/citation/CitationsViewer'

<CitationsViewer
 artifact={{
 baseUrl: "https://api.example.com",
 artifactTitle: "Quarterly Earnings Call",
 fileUrl: "gs://bucket/audio.mp3",
 chatHistory: [
 {
 role: "Speaker 1",
 message: "Revenue increased by 20%",
 timestamp: "10:30",
 timestamp_start: 120.5,
 timestamp_end: 125.0
 }
 ],
 keyTakeaways: [
 {
 takeawayId: "1",
 name: "Revenue Growth",
 content: "**20% year-over-year growth**",
 keywords: ["Revenue", "Growth"]
 }
 ]
 }}
 onCloseHandler={() => console.log('Closed')}
/>

Props

| Prop Name | Type | Required | Description | |-----------|------|----------|-------------| | artifact | ArtifactData | ✅ | The main data object containing audio, transcript, and metadata | | onCloseHandler | () => void | ❌ | Callback function triggered when the close (X) button is clicked | | theme | ThemeConfig | ❌ | Object to override default colors and fonts | | iconsConfig | IconsConfig | ❌ | Object to inject custom React icons (Play, Pause, Close) |


PdfEditorCitation

Overview

PdfEditorCitation is a core component for the Advanced Document Management and Citation System. It provides a user-friendly interface for viewing, editing, and citing PDF documents directly within the application. It combines interactive PDF viewing capabilities with a collapsible UI pattern, allowing users to manage document space efficiently while maintaining full access to PDF editing and annotation features.

Features

  • Collapsible PDF viewer functionality - Users can expand and collapse the PDF editor section
  • Interactive PDF editing capabilities - Full support for PDF editing, annotations, and collaborative features
  • Sentence highlighting support - Ability to highlight specific sentences within PDF documents
  • Customizable UI through CSS classes - Flexible styling options for seamless integration

Usage

import { PdfEditorCitation } from '@e-llm-studio/citation/PdfEditorCitation'

<PdfEditorCitation
 citationTitleElement={<div>Research Paper.pdf</div>}
 pdfUrl="https://example.com/document.pdf"
 pdfEditorBackendBaseUrl="https://pdf-backend.example.com"
 sentenceHighlightDetails={{
 pdfPageNumber: 5,
 sentenceToHighlight: "key finding in the research"
 }}
 currentUserId="user-123"
/>

Props

| Prop Name | Type | Description | |-----------|------|-------------| | citationTitleElement | ReactElement | A React element to display as the clickable title | | pdfUrl | string | The URL of the PDF file to be displayed and edited | | pdfEditorBackendBaseUrl | string | The base URL of the PDF editor backend service | | citationRootClassName | string | Optional CSS class name for the root container | | citationBodyClassName | string | Optional CSS class name for the body section | | citationBodyWhenCollapsedClassName | string | Optional CSS class name for collapsed state | | citationTitleClassName | string | Optional CSS class name for the title section | | rlefEventServiceBaseUrl | string | Optional base URL for the RLEF event service | | currentUserId | string | Optional user ID of the current user | | sentenceHighlightDetails | object | Optional sentence highlighting configuration |


RequirementAICitation

Overview

RequirementAICitation is a comprehensive React module for displaying AI-generated insights and rich media evidence. It serves two primary purposes: displaying an AI Reasoning Card with expandable sections for logic, gaps, and confidence scores with embedded citations, and providing standalone media citations for Files, Images, and Web Links.

Features

  • AI Reasoning Card - Complex, expandable card displaying AI logic, gaps, and confidence scores with embedded, clickable citations
  • Standalone Media Citations - Individual, stylized citation pills for Files, Images, and Web Links
  • Multiple Citation Types - Support for file citations (PDFs), image citations, and web citations
  • Relevance Scoring - Display AI relevance scores for all citation types
  • Rich Media Preview - Integrated viewers for PDFs, images, and web content
  • Customizable Styling - Deep CSS injection for all components

Usage 1: AI Reasoning Card (Composite Component)

Use this when you want to display AI analysis with embedded, clickable citations that open in a preview panel.

import { AiReasoningCitation } from '@e-llm-studio/citation/AiReasoningCitation'

<AiReasoningCitation
  title="AI Analysis"