agentleFS
Open-Source-LegalOpen-Source-Legal/OpenContracts/.cursor/rules/pdf-viewer-and-annotator-architecture.mdc

OpenContracts / rules

Cursor rule1.5k starsChanged 14 months agoMITView on GitHub

When working on pdf annotations or pdf rendering, consult this high level overview

Trending

Quiet since April.thin dataabout the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 2 mentionsMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 0 mentionsSep 2026: 0 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the Open-Source-Legal/OpenContracts repository that our weekly crawl found: only 2 in all, so this is a hint, not a trend. There is no adoption data for this file yet.
  • Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.

    Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository4 other files it gives its agents.

The file

Show its rules and text

We split this pdf-viewer-and-annotator-architecture.mdc into the rules it gives an agent

19 rules. About 0 are common, 17 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈17

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When working on document knowledge base and pdf-related frontend functionality, ensure you update our cursor rule here …

    line 9
  2. Very specific:

    When modifying filtering logic, ensure changes are applied consistently to both useVisibleAnnotations and useVisibleRelationships hooks to …

    line 10
  3. Distinctive:

    Ensure smooth scrolling and navigation even with hundreds of pages

    line 27
  4. Distinctive:

    Search functionality with highlighting

    line 39
  5. Distinctive:

    Document summary viewing and editing

    line 45
  6. Distinctive:

    Only mounts when page is in visible range

    line 103
  7. Distinctive:

    All settings stored in shared Jotai atoms

    line 184
  8. Distinctive:

    Only shows relationships with at least one visible annotation

    line 202
  9. Very specific:

    PDFPage/TxtAnnotator: Use useVisibleAnnotations() for rendering

    line 206
  10. Distinctive:

    All components react to the same atom state changes

    line 209
  11. Distinctive:

    Check if page owns the pending annotation

    line 225
  12. Distinctive:

    When annotations or relationships are updated (added, modified, or filtered):

    line 234
  13. Distinctive:

    All updates create new immutable instances

    line 238
  14. Distinctive:

    All components consuming these hooks automatically re-render with filtered data

    line 250
  15. Distinctive:

    No prop drilling or manual synchronization needed

    line 252
  16. Distinctive:

    Virtualization: Only visible PDF pages (+overscan) are rendered, providing dramatic performance improvements for large documents.

    line 271
  17. Distinctive:

    All content when specific items are being highlighted

    line 284
  18. Distinctive:

    Absolute Positioning: All pages are absolutely positioned based on cumulative heights, with a spacer div maintaining correct total scroll …

    line 288
  19. Distinctive:

    Unified State Management: All major state is managed through Jotai atoms, providing a single source of truth and automatic reactivity.

    line 292

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
pdf-viewer-and-annotator-architecture.mdc
---
description: When working on pdf annotations or pdf rendering, consult this high level overview
globs: *DocumentKnowledgeBase*,**/knowledge_base/**/*,**/annotator/**/*
alwaysApply: false
---
# Understanding the PDF Annotation System Architecture

## Admin Tasks if you Edit PDF-related frontend code
1. When working on document knowledge base and pdf-related frontend functionality, ensure you update our cursor rule here [pdf-viewer-and-annotator-architecture.mdc](mdc:.cursor/rules/pdf-viewer-and-annotator-architecture.mdc) such that it captures any material changes to our existing setup.
2. When modifying filtering logic, ensure changes are applied consistently to both `useVisibleAnnotations` and `useVisibleRelationships` hooks to maintain unified behavior.

## Context: Document Knowledge Base

The `DocumentKnowledgeBase` component serves as the main container for viewing and interacting with documents, particularly PDFs. It provides a comprehensive interface that combines document viewing with annotation capabilities, search functionality, knowledge extraction features, and a sophisticated dual-layer architecture for both document annotation and knowledge synthesis.

The system uses a sophisticated virtualized rendering approach for PDFs, where only visible pages (plus a small overscan buffer) are rendered to dramatically improve performance with large documents. This is coupled with an advanced annotation management system that allows users to view, filter, and interact with annotations overlaid on the document.

## Intent: High-Performance Document System with Dual-Layer Architecture

The architecture aims to:

1. Efficiently render large PDF documents using virtualization (only visible pages are rendered)
2. Provide a flexible annotation system that can display/hide annotations based on user preferences
3. Support various annotation types (spans, tokens, structural elements)
4. Enable real-time filtering and selection of annotations
5. Maintain consistent state across the entire application using Jotai atoms
6. Ensure smooth scrolling and navigation even with hundreds of pages
7. Offer dual-layer architecture for document viewing and knowledge synthesis
8. Provide unified content feeds combining notes, annotations, and relationships
9. Support version-controlled document summaries with version history
10. Enable flexible, resizable panel layouts with auto-minimize capabilities

## Dual-Layer Architecture

The system implements two distinct viewing layers:

### Document Layer
- Traditional PDF/text viewing with annotations
- Search functionality with highlighting
- Annotation creation and editing
- Extract and analysis results
- Real-time collaboration features

### Knowledge Layer
- Document summary viewing and editing
- Version history with author tracking
- Markdown-based content editing
- Clean reading experience
- Knowledge synthesis tools

Users can seamlessly switch between layers based on their current task, with intelligent context-aware switching.

## Component Interactions

### State Management with Jotai

The system uses Jotai atoms to manage global state:

```
AnnotationAtoms.tsx
├── pdfAnnotationsAtom - Core state (annotations, relations, docTypes)
├── structuralAnnotationsAtom - Structural annotations
├── allAnnotationsAtom - Computed, de-duplicated annotation list
└── perPageAnnotationsAtom - Page-indexed annotation map

UISettingsAtom.tsx
├── activeLayerAtom - Current layer (knowledge/document)
├── chatPanelWidthAtom - Panel width management
├── sidebarViewModeAtom - Chat vs feed mode
├── showStructuralAtom - Show/hide structural content
├── showSelectedOnlyAtom - Filter to selected items only
├── showBoundingBoxesAtom - Visual display setting
└── showLabelsAtom - Label display behavior

DocumentAtom.tsx
├── scrollContainerRefAtom - Scroll container reference
├── pendingScrollAnnotationIdAtom - Annotation to scroll to
└── textSearchStateAtom - Search state management
```

This approach provides:
- Centralized state management
- Computed derivations that automatically update
- Efficient re-rendering when only relevant state changes
- Layer-aware state transitions

### PDF Rendering Pipeline

1. **DocumentKnowledgeBase** initializes the document view and loads annotation data via GraphQL
   - Loads PDF document using pdfjs-dist
   - Fetches PAWLS token data for precise text selection
   - Initializes Jotai atoms with annotation data
   - Manages layer switching and tab navigation

2. **PDF** component manages the virtualized rendering of pages:
   - Calculates page heights at current zoom level (cached per zoom)
   - Uses binary search to determine visible page range
   - Adds overscan buffer (2 pages above/below) for smooth scrolling
   - Ensures selected annotation/search result pages are always rendered
   - Absolutely positions all pages based on cumulative heights

3. **PDFPage** renders individual pages with their annotations:
   - Only mounts when page is in visible range
   - Creates and manages its own PDF canvas
   - Overlays annotation components on top of the canvas
   - Handles user interactions for creating/selecting annotations
   - Implements two-phase scroll-to-annotation system

### Advanced Features

#### Unified Content Feed
The `UnifiedContentFeed` component provides a consolidated view of all document content:
- Combines notes, annotations, relationships, and search results
- Sortable by page order or chronologically
- Filterable by content type and properties
- Real-time updates as content changes
- Consistent interaction patterns across content types

#### Summary Version History
Version control for document summaries:
- Each edit creates a new numbered version
- Full content snapshots for each version
- Author and timestamp tracking
- Diff generation between versions
- Visual version browser with one-click switching

#### Resizable Panel System
Sophisticated chat panel width management:
- Preset sizes: quarter (25%), half (50%), full (90%)
- Custom width via drag handle
- Auto-minimize when hovering over document
- Smooth animations and transitions
- Persistent width preferences

#### Floating UI Components
- **FloatingSummaryPreview**: Picture-in-picture summary view
- **FloatingDocumentControls**: Contextual action buttons
- **FloatingDocumentInput**: Unified chat/search input
- **ZoomControls**: Simple zoom interface with keyboard shortcuts

### Virtualization Implementation Details

The PDF component implements sophisticated virtualization:

```typescript
// Page height calculation (cached per zoom level)
useEffect(() => {
  const heights = await calculatePageHeights(pdfDoc, zoomLevel);
  setPageHeights(heights);
}, [pdfDoc, zoomLevel]);

// Visible range calculation using binary search
const calcRange = useCallback(() => {
  const scroll = getScrollPosition();
  const viewHeight = getViewportHeight();

  // Binary search for first/last visible pages
  const firstVisible = binarySearchFirstVisible(cumulative, scroll);
  const lastVisible = binarySearchLastVisible(cumulative, scroll + viewHeight);

  // Add overscan and ensure selected items are visible
  let start = Math.max(0, firstVisible - OVERSCAN);
  let end = Math.min(pageCount - 1, lastVisible + OVERSCAN);

  // Force selected annotation's page to be visible
  if (selectedPageIdx !== undefined) {
    start = Math.min(start, selectedPageIdx);
    end = Math.max(end, selectedPageIdx);
  }

  setRange([start, end]);
}, [/* dependencies */]);
```

### Unified Annotation and Relationship Visibility System

The system implements a unified, atom-based filtering architecture that ensures consistency between annotations and relationships across all components:

1. **AnnotationControls** component (used in FloatingDocumentControls and sidebars):
   - Toggle for showing only selected annotations/relationships
   - Toggle for showing structural annotations/relationships
   - Toggle for showing bounding boxes
   - Label filter selection
   - All settings stored in shared Jotai atoms

2. **useAnnotationDisplay** hook manages display preferences:
   - `showStructural` - controls both structural annotations AND relationships
   - `showSelectedOnly` - filters to selected items and their connections
   - `showBoundingBoxes` - visual display option
   - `showLabels` - label display behavior (always/hover/hide)
   - Single source of truth for all filtering preferences

3. **useVisibleAnnotations** hook applies filtering logic for annotations:
   - Takes the complete annotation list from `useAllAnnotations`
   - Applies filters based on settings from `useAnnotationDisplay`
   - Returns only the annotations that should be visible
   - Handles forced visibility (selected, relationship-connected)

4. **useVisibleRelationships** hook applies parallel filtering for relationships:
   - Filters relationships based on same `useAnnotationDisplay` settings
   - Ensures consistency with annotation filtering
   - Only shows relationships with at least one visible annotation
   - Respects selected-only and structural toggles

5. **Components consume filtered data consistently**:
   - **PDFPage/TxtAnnotator**: Use `useVisibleAnnotations()` for rendering
   - **UnifiedContentFeed**: Uses both `useVisibleAnnotations()` and `useVisibleRelationships()`
   - **RelationshipList**: Uses `useVisibleRelationships()` for display
   - All components react to the same atom state changes

### Scroll-to-Annotation System

The system uses a two-phase approach for scrolling to annotations, triggered by:
- URL parameters (`?ann=id1,id2`)
- Direct props (`initialAnnotationIds`)
- Programmatic selection

1. **Phase 1 (PDF.tsx)**: Scroll to make the page visible
   - Calculate which page contains the annotation
   - Expand virtualization range to include the page
   - Scroll container so page is in viewport
   - Set pendingScrollAnnotationIdAtom

2. **Phase 2 (PDFPage.tsx)**: Center the specific annotation
   - Check if page owns the pending annotation
   - Find the annotation element once rendered
   - Scroll it into view with centering
   - Retry with requestAnimationFrame if element not yet rendered

See [scroll-to-annotation-flow.md](mdc:docs/architecture/components/annotator/current-state/scroll-to-annotation-flow.md) for complete details.

### Data Flow for Annotation and Relationship Updates

When annotations or relationships are updated (added, modified, or filtered):

1. **State Updates**: Changes are made to `pdfAnnotationsAtom` via `usePdfAnnotations().setPdfAnnotations`
   - Contains three arrays: `annotations`, `relations`, and `docTypes`
   - All updates create new immutable instances

2. **Automatic Recomputation**:
   - `allAnnotationsAtom` automatically recomputes to include annotation changes
   - Both `useVisibleAnnotations` and `useVisibleRelationships` recompute based on current filters

3. **Filter Application**:
   - `useVisibleAnnotations` applies filters from `useAnnotationDisplay` to annotations
   - `useVisibleRelationships` applies the SAME filters to relationships
   - Both hooks ensure consistency by reading from the same atom state

4. **Component Re-rendering**:
   - All components consuming these hooks automatically re-render with filtered data
   - Changes in filter settings immediately propagate to all consumers
   - No prop drilling or manual synchronization needed

## Tab Navigation System

The sidebar implements a sophisticated tab system with layer awareness:
- **Summary** (knowledge layer): Document summary view
- **Chat** (both layers): AI-powered chat interface
- **Notes** (both layers): Document notes management
- **Relationships** (both layers): Document connections
- **Annotations** (document layer): Annotation list
- **Relations** (document layer): Annotation relationships
- **Search** (document layer): Text search
- **Analyses** (document layer): Document analysis
- **Extracts** (document layer): Data extraction

Each tab knows which layer(s) it belongs to and can trigger layer switches when activated.

## Key Technical Aspects

1. **Virtualization**: Only visible PDF pages (+overscan) are rendered, providing dramatic performance improvements for large documents. Binary search algorithms ensure O(log n) complexity for finding visible pages.

2. **Height Caching**: Page heights are calculated once per zoom level and cached, preventing expensive recalculations during scrolling.

3. **Smart Range Expansion**: The visible range automatically expands to include selected annotations, search results, or chat source highlights, ensuring important content is always rendered.

4. **Computed Derivations**: `allAnnotationsAtom` and `perPageAnnotationsAtom` are derived states that automatically update when their dependencies change, eliminating manual synchronization.

5. **Unified Filtering**: The `useVisibleAnnotations` and `useVisibleRelationships` hooks provide parallel filtering logic that ensures annotations and relationships are filtered consistently using the same atom state.

6. **Forced Visibility**: Some content is always visible regardless of filter settings:
   - Selected annotations and relationships
   - Annotations connected to selected relationships
   - All content when specific items are being highlighted

7. **Efficient Rendering**: Components only re-render when their specific dependencies change, not on every state update. PDFPage components manage their own lifecycle independently.

8. **Absolute Positioning**: All pages are absolutely positioned based on cumulative heights, with a spacer div maintaining correct total scroll height.

9. **Layer-aware Navigation**: The system intelligently manages which features are available in each layer and handles transitions smoothly.

10. **Unified State Management**: All major state is managed through Jotai atoms, providing a single source of truth and automatic reactivity.

This architecture creates a flexible, highly performant system for displaying and interacting with annotations on PDF documents, with centralized state management and consistent filtering logic across the application. The virtualization approach enables smooth handling of documents with hundreds or thousands of pages, while the dual-layer architecture provides both detailed annotation capabilities and high-level knowledge synthesis tools.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.