done base code for frontend

This commit is contained in:
azeeee05
2026-05-20 15:39:50 +05:30
parent d230c66e0d
commit bce334fb33
29 changed files with 5335 additions and 17 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+66 -17
View File
@@ -1,24 +1,73 @@
# Frontend (React + TypeScript) — placeholder
# React + TypeScript + Vite
Phase 0 task **"React + TypeScript frontend scaffolding"** (Dev 2) and all later
viewer/editor UI lives here. Not implemented yet — this session scaffolds the
C++ build pipeline only.
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Planned responsibilities (see the engine blueprint §9):
Currently, two official plugins are available:
- Layered viewer: canvas layer, selection layer, annotation layer, overlay layer.
- PDF <-> canvas <-> zoomed coordinate mapping.
- Virtualized page rendering (only visible pages).
- Talks to the gateway over HTTP; later, to the engine directly via WASM.
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
Setup when implemented: Vite + React + **TypeScript strict mode** from day one.
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
frontend/
package.json
tsconfig.json # "strict": true
src/
components/
viewer/
lib/
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+22
View File
@@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2735
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.6",
"react-dom": "^19.2.6"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+184
View File
@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
+172
View File
@@ -0,0 +1,172 @@
import { useState, useEffect } from 'react';
import { Toolbar } from './components/Toolbar';
import { Sidebar } from './components/Sidebar';
import { PDFViewer } from './viewer/PDFViewer';
import type { Annotation } from './viewer/AnnotationLayer';
import { gatewayService } from './lib/gatewayService';
import type { DocumentInfo } from './lib/gatewayService';
import { wasmLoader } from './lib/wasmLoader';
import './App.css';
function App() {
const [documents, setDocuments] = useState<DocumentInfo[]>([]);
const [selectedDocId, setSelectedDocId] = useState<string>('sample-doc-1');
const [activeDoc, setActiveDoc] = useState<DocumentInfo | null>(null);
// Settings
const [zoom, setZoom] = useState<number>(1.0);
const [rotation, setRotation] = useState<number>(0);
const [activeTool, setActiveTool] = useState<string>('select');
const [currentPage, setCurrentPage] = useState<number>(0);
// States
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [backendHealthy, setBackendHealthy] = useState<boolean | null>(null);
const [sidebarTab, setSidebarTab] = useState<'documents' | 'annotations' | 'outline'>('documents');
const [isLoading, setIsLoading] = useState<boolean>(true);
// Check Gateway Health on mount
useEffect(() => {
const checkHealth = async () => {
try {
const health = await gatewayService.getHealth();
setBackendHealthy(health.engine_available || true);
} catch (err) {
setBackendHealthy(false);
}
};
checkHealth();
}, []);
// Fetch Documents list
useEffect(() => {
const fetchDocs = async () => {
try {
setIsLoading(true);
const docs = await gatewayService.listDocuments();
setDocuments(docs);
if (docs.length > 0) {
const defaultDoc = docs[0];
setSelectedDocId(defaultDoc.id);
setActiveDoc(defaultDoc);
}
} catch (err) {
console.error('Failed to load documents list', err);
} finally {
setIsLoading(false);
}
};
fetchDocs();
}, []);
// Load selected document metadata
useEffect(() => {
const loadDocMetadata = async () => {
if (!selectedDocId) return;
try {
setIsLoading(true);
const doc = await gatewayService.getDocument(selectedDocId);
setActiveDoc(doc);
setCurrentPage(0);
setAnnotations([]); // Reset highlights for new document
} catch (err) {
console.error('Failed to load document metadata', err);
} finally {
setIsLoading(false);
}
};
loadDocMetadata();
}, [selectedDocId]);
// Load WASM Engine (Simulated Phase 0 loading)
useEffect(() => {
const loadWasm = async () => {
console.log('[WASM] Initializing Emscripten compiler context...');
const instance = await wasmLoader.loadEngine();
console.log(`[WASM] C++ Core initialized: version ${instance.version}`);
};
loadWasm();
}, []);
const handleUploadStart = async (file: File) => {
try {
setIsLoading(true);
const newDoc = await gatewayService.uploadDocument(file);
setDocuments((prev) => [newDoc, ...prev]);
setSelectedDocId(newDoc.id);
setActiveDoc(newDoc);
} catch (err) {
console.error('File upload failed', err);
} finally {
setIsLoading(false);
}
};
const handleAnnotationAdded = (newAnno: Annotation) => {
setAnnotations((prev) => [...prev, newAnno]);
// Switch to annotations list tab automatically so the user sees the note
setSidebarTab('annotations');
};
return (
<div className="w-screen h-screen flex flex-col overflow-hidden bg-slate-950 font-sans text-slate-100 antialiased">
{/* Top Navigation / Toolbar */}
<Toolbar
zoom={zoom}
onZoomChange={setZoom}
rotation={rotation}
onRotationChange={setRotation}
activeTool={activeTool}
onActiveToolChange={setActiveTool}
currentPage={currentPage}
totalPages={activeDoc?.totalPages || 1}
onUploadStart={handleUploadStart}
backendHealthy={backendHealthy}
/>
<div className="flex-1 w-full flex overflow-hidden">
{/* Left Interactive Sidebar */}
<Sidebar
documents={documents}
selectedDocumentId={selectedDocId}
onSelectDocument={setSelectedDocId}
annotations={annotations}
totalPages={activeDoc?.totalPages || 0}
activeTab={sidebarTab}
setActiveTab={setSidebarTab}
/>
{/* Main PDF Scroll Viewer Area */}
{isLoading ? (
<div className="flex-1 h-full flex flex-col items-center justify-center bg-slate-900 gap-4">
<div className="relative w-14 h-14 flex items-center justify-center">
<div className="absolute w-full h-full border-4 border-indigo-500/20 rounded-full" />
<div className="absolute w-full h-full border-4 border-indigo-500 border-t-transparent rounded-full animate-spin" />
</div>
<p className="text-sm font-bold tracking-widest uppercase text-indigo-400 animate-pulse">Loading Document Canvas...</p>
</div>
) : activeDoc ? (
<PDFViewer
documentId={activeDoc.id}
totalPages={activeDoc.totalPages}
zoom={zoom}
rotation={rotation}
activeTool={activeTool}
annotations={annotations}
onAnnotationAdded={handleAnnotationAdded}
onPageVisible={setCurrentPage}
/>
) : (
<div className="flex-1 h-full flex flex-col items-center justify-center bg-slate-900 gap-3 text-slate-400">
<svg xmlns="http://www.w3.org/2000/svg" className="w-12 h-12 text-slate-650" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414-5.414a1 1 0 01.707.707V19a2 2 0 01-2 2z" />
</svg>
<p className="text-sm font-bold">No active document. Please upload a PDF file.</p>
</div>
)}
</div>
</div>
);
}
export default App;
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

+151
View File
@@ -0,0 +1,151 @@
import React from 'react';
import type { DocumentInfo } from '../lib/gatewayService';
import type { Annotation } from '../viewer/AnnotationLayer';
interface SidebarProps {
documents: DocumentInfo[];
selectedDocumentId: string;
onSelectDocument: (id: string) => void;
annotations: Annotation[];
totalPages: number;
activeTab: 'documents' | 'annotations' | 'outline';
setActiveTab: (tab: 'documents' | 'annotations' | 'outline') => void;
}
export const Sidebar: React.FC<SidebarProps> = ({
documents,
selectedDocumentId,
onSelectDocument,
annotations,
totalPages,
activeTab,
setActiveTab,
}) => {
const formatBytes = (bytes: number) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
return (
<div className="sidebar">
{/* Sidebar Tabs */}
<div className="sidebar-tabs">
<button
onClick={() => setActiveTab('documents')}
className={`tab-btn ${activeTab === 'documents' ? 'active' : ''}`}
>
Files
</button>
<button
onClick={() => setActiveTab('outline')}
className={`tab-btn ${activeTab === 'outline' ? 'active' : ''}`}
>
Thumbnails
</button>
<button
onClick={() => setActiveTab('annotations')}
className={`tab-btn ${activeTab === 'annotations' ? 'active' : ''} relative-tab`}
>
Notes
{annotations.length > 0 && (
<span className="badge-notification">
{annotations.length}
</span>
)}
</button>
</div>
{/* Tab Contents */}
<div className="sidebar-content">
{/* DOCUMENTS TAB */}
{activeTab === 'documents' && (
<div className="doc-list-container">
<span className="tab-section-header">
Active Documents
</span>
{documents.map((doc) => {
const isSelected = doc.id === selectedDocumentId;
return (
<div
key={doc.id}
onClick={() => onSelectDocument(doc.id)}
className={`doc-card ${isSelected ? 'active' : ''}`}
>
<div className="doc-card-body">
<div className={`doc-icon-container ${isSelected ? 'active' : ''}`}>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
</svg>
</div>
<div className="doc-details">
<p className="doc-filename">
{doc.filename}
</p>
<div className="doc-metadata">
<span>{formatBytes(doc.sizeBytes)}</span>
<span></span>
<span>{doc.totalPages} Pages</span>
</div>
</div>
</div>
</div>
);
})}
</div>
)}
{/* THUMBNAILS TAB */}
{activeTab === 'outline' && (
<div className="thumbnails-grid">
{Array.from({ length: totalPages }).map((_, idx) => (
<div key={idx} className="thumbnail-card">
<div className="thumbnail-preview">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" className="thumbnail-svg-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span className="thumbnail-label">Page {idx + 1}</span>
</div>
</div>
))}
</div>
)}
{/* ANNOTATIONS TAB */}
{activeTab === 'annotations' && (
<div className="annotations-list">
<span className="tab-section-header">
Active Highlights
</span>
{annotations.length === 0 ? (
<div className="empty-state">
No active highlights yet. Select 'Highlight' tool and drag/select text on pages.
</div>
) : (
annotations.map((anno) => (
<div key={anno.id} className="annotation-card">
<div className="annotation-header">
<span className="annotation-type-badge">
{anno.type}
</span>
<span className="annotation-author">
{anno.author}
</span>
</div>
<p className="annotation-content">
"{anno.content}"
</p>
</div>
))
)}
</div>
)}
</div>
</div>
);
};
+164
View File
@@ -0,0 +1,164 @@
import React from 'react';
interface ToolbarProps {
zoom: number;
onZoomChange: (zoom: number) => void;
rotation: number;
onRotationChange: (rot: number) => void;
activeTool: string;
onActiveToolChange: (tool: string) => void;
currentPage: number;
totalPages: number;
onUploadStart?: (file: File) => void;
backendHealthy: boolean | null;
}
export const Toolbar: React.FC<ToolbarProps> = ({
zoom,
onZoomChange,
rotation,
onRotationChange,
activeTool,
onActiveToolChange,
currentPage,
totalPages,
onUploadStart,
backendHealthy,
}) => {
const handleZoomPercentSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
const val = parseFloat(e.target.value);
onZoomChange(val);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file && onUploadStart) {
onUploadStart(file);
}
};
return (
<div className="toolbar">
{/* Logo & Health */}
<div className="toolbar-section">
<div className="logo-container">
<div className="logo-badge">DQ</div>
<span className="logo-text">
DocQube<span className="logo-sub">PDF</span>
</span>
</div>
<div className={`health-badge status-${backendHealthy === null ? 'checking' : backendHealthy ? 'healthy' : 'unhealthy'}`}>
<span className="health-dot" />
{backendHealthy === null
? 'Checking Gateway...'
: backendHealthy
? 'Gateway Connected'
: 'Gateway Offline'}
</div>
</div>
{/* Center Tools (Zoom, Rotate, Navigate) */}
<div className="toolbar-center">
<div className="page-indicator">
<span>Page</span>
<span className="page-current">{currentPage + 1}</span>
<span className="page-separator">/</span>
<span>{totalPages}</span>
</div>
<div className="divider-vertical" />
<div className="zoom-controls">
<button
onClick={() => onZoomChange(Math.max(0.5, zoom - 0.25))}
className="btn-icon"
title="Zoom Out"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M20 12H4" />
</svg>
</button>
<select
value={zoom}
onChange={handleZoomPercentSelect}
className="zoom-select"
>
<option value="0.5">50%</option>
<option value="0.75">75%</option>
<option value="1.0">100%</option>
<option value="1.25">125%</option>
<option value="1.5">150%</option>
<option value="2.0">200%</option>
</select>
<button
onClick={() => onZoomChange(Math.min(3.0, zoom + 0.25))}
className="btn-icon"
title="Zoom In"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
</svg>
</button>
</div>
<div className="divider-vertical" />
<button
onClick={() => onRotationChange((rotation + 90) % 360)}
className="btn-icon"
title="Rotate Clockwise"
>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 1121.21 7.89M9 11l3-3 3 3m-3-3v12" />
</svg>
</button>
</div>
{/* Right Tools (Active tool highlights, Upload) */}
<div className="toolbar-section gap-3">
<div className="tool-selector">
<button
onClick={() => onActiveToolChange('select')}
className={`tool-btn ${activeTool === 'select' ? 'active' : ''}`}
title="Select Text"
>
Select
</button>
<button
onClick={() => onActiveToolChange('highlight')}
className={`tool-btn highlight ${activeTool === 'highlight' ? 'active' : ''}`}
title="Highlight Ink"
>
Highlight
</button>
<button
onClick={() => onActiveToolChange('signature')}
className={`tool-btn signature ${activeTool === 'signature' ? 'active' : ''}`}
title="Place Digital Signature"
>
Signature
</button>
</div>
<label className="upload-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
</svg>
Upload PDF
<input
type="file"
accept=".pdf"
onChange={handleFileUpload}
className="hidden-file-input"
/>
</label>
</div>
</div>
);
};
+732
View File
@@ -0,0 +1,732 @@
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;700&display=swap');
:root {
--sans: 'Outfit', system-ui, -apple-system, sans-serif;
--mono: 'JetBrains Mono', monospace;
/* Color Palette - Premium Royal/Midnight */
--bg-main: #020617; /* Slate 950 */
--bg-card: #0f172a; /* Slate 900 */
--bg-sidebar: #090d16; /* Deep Midnight */
--bg-accent-indigo: #4f46e5;
--bg-accent-indigo-hover: #4338ca;
--border-main: #1e293b;
--border-glow: rgba(99, 102, 241, 0.25);
--text-main: #f8fafc;
--text-muted: #94a3b8;
--text-dim: #64748b;
/* Status Colors */
--color-success: #10b981;
--color-success-bg: rgba(16, 185, 129, 0.1);
--color-success-border: rgba(16, 185, 129, 0.2);
--color-warning: #f59e0b;
--color-warning-bg: rgba(245, 158, 11, 0.1);
--color-warning-border: rgba(245, 158, 11, 0.2);
--color-error: #f43f5e;
--color-error-bg: rgba(244, 63, 94, 0.1);
--color-error-border: rgba(244, 63, 94, 0.2);
font-family: var(--sans);
color-scheme: dark;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
transition: background-color 0.2s, border-color 0.2s;
}
body {
overflow: hidden;
background-color: var(--bg-main);
color: var(--text-main);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#root {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* Custom Sleek Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-main);
}
::-webkit-scrollbar-thumb {
background: var(--border-main);
border-radius: 9999px;
border: 2px solid var(--bg-main);
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-dim);
}
/* ==========================================================================
TOOLBAR STYLES
========================================================================== */
.toolbar {
height: 64px;
background: var(--bg-card);
border-bottom: 1px solid var(--border-main);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
z-index: 50;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
}
.toolbar-section {
display: flex;
align-items: center;
gap: 16px;
}
.logo-container {
display: flex;
align-items: center;
gap: 10px;
}
.logo-badge {
width: 36px;
height: 36px;
background: var(--bg-accent-indigo);
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
color: white;
font-size: 15px;
box-shadow: 0 8px 16px rgba(79, 70, 229, 0.35);
letter-spacing: 0.5px;
}
.logo-text {
font-weight: 900;
font-size: 18px;
letter-spacing: -0.5px;
display: flex;
align-items: center;
}
.logo-sub {
color: #a5b4fc;
font-weight: 500;
font-size: 11px;
margin-left: 6px;
padding: 2px 8px;
background: rgba(79, 70, 229, 0.15);
border: 1px solid rgba(79, 70, 229, 0.3);
border-radius: 9999px;
letter-spacing: 1px;
text-transform: uppercase;
}
.health-badge {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 12px;
border-radius: 9999px;
font-size: 11px;
font-weight: 600;
border: 1px solid transparent;
}
.health-badge.status-checking {
background: var(--color-warning-bg);
color: var(--color-warning);
border-color: var(--color-warning-border);
}
.health-badge.status-healthy {
background: var(--color-success-bg);
color: var(--color-success);
border-color: var(--color-success-border);
}
.health-badge.status-unhealthy {
background: var(--color-error-bg);
color: var(--color-error);
border-color: var(--color-error-border);
}
.health-dot {
width: 6px;
height: 6px;
border-radius: 9999px;
}
.status-checking .health-dot { background: var(--color-warning); animation: pulse 1.5s infinite; }
.status-healthy .health-dot { background: var(--color-success); }
.status-unhealthy .health-dot { background: var(--color-error); }
.toolbar-center {
display: flex;
align-items: center;
gap: 16px;
background: rgba(2, 6, 23, 0.4);
padding: 6px 12px;
border-radius: 12px;
border: 1px solid rgba(30, 41, 59, 0.7);
}
.page-indicator {
display: flex;
align-items: center;
gap: 6px;
color: var(--text-muted);
font-size: 13px;
font-weight: 600;
padding: 0 8px;
}
.page-current {
color: white;
font-weight: 800;
}
.page-separator {
color: var(--text-dim);
}
.divider-vertical {
width: 1px;
height: 20px;
background: var(--border-main);
}
.zoom-controls {
display: flex;
align-items: center;
gap: 6px;
}
.btn-icon {
background: transparent;
border: none;
color: var(--text-muted);
padding: 6px;
border-radius: 8px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.btn-icon:hover {
color: white;
background: rgba(255, 255, 255, 0.05);
}
.zoom-select {
background: var(--bg-main);
color: var(--text-muted);
font-size: 11px;
font-weight: 700;
padding: 4px 10px;
border-radius: 6px;
border: 1px solid var(--border-main);
outline: none;
cursor: pointer;
appearance: none;
-webkit-appearance: none;
text-align: center;
}
.zoom-select:focus {
border-color: var(--bg-accent-indigo);
}
.tool-selector {
display: flex;
background: rgba(2, 6, 23, 0.4);
padding: 4px;
border-radius: 12px;
border: 1px solid rgba(30, 41, 59, 0.7);
}
.tool-btn {
background: transparent;
border: none;
color: var(--text-muted);
font-weight: 700;
font-size: 12px;
padding: 6px 14px;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.tool-btn:hover {
color: white;
}
.tool-btn.active {
background: var(--border-main);
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.tool-btn.highlight.active {
background: rgba(245, 158, 11, 0.2);
color: #fbbf24;
border: 1px solid rgba(245, 158, 11, 0.4);
}
.tool-btn.signature.active {
background: rgba(79, 70, 229, 0.2);
color: #c7d2fe;
border: 1px solid rgba(79, 70, 229, 0.4);
}
.upload-btn {
display: flex;
align-items: center;
gap: 8px;
background: var(--bg-accent-indigo);
color: white;
font-weight: 600;
font-size: 12px;
padding: 8px 16px;
border-radius: 10px;
cursor: pointer;
box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
border: 1px solid rgba(79, 70, 229, 0.4);
transition: transform 0.2s, background-color 0.2s;
}
.upload-btn:hover {
background: var(--bg-accent-indigo-hover);
transform: translateY(-1px);
}
.hidden-file-input {
display: none;
}
/* ==========================================================================
SIDEBAR STYLES
========================================================================== */
.sidebar {
width: 320px;
background: var(--bg-sidebar);
border-right: 1px solid var(--border-main);
display: flex;
flex-direction: column;
height: 100%;
}
.sidebar-tabs {
display: flex;
border-bottom: 1px solid var(--border-main);
padding: 10px;
gap: 6px;
background: rgba(9, 13, 22, 0.8);
}
.tab-btn {
flex: 1;
background: transparent;
border: none;
color: var(--text-muted);
font-weight: 700;
font-size: 12px;
padding: 8px 0;
border-radius: 8px;
cursor: pointer;
text-align: center;
transition: all 0.2s;
}
.tab-btn:hover {
color: white;
background: rgba(255, 255, 255, 0.03);
}
.tab-btn.active {
background: var(--bg-card);
color: white;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}
.relative-tab {
position: relative;
}
.badge-notification {
position: absolute;
top: 4px;
right: 12px;
background: var(--bg-accent-indigo);
color: white;
font-size: 9px;
font-weight: 900;
width: 16px;
height: 16px;
border-radius: 9999px;
display: flex;
align-items: center;
justify-content: center;
animation: pulse 2s infinite;
}
.sidebar-content {
flex: 1;
overflow-y: auto;
padding: 18px;
}
.doc-list-container, .annotations-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.tab-section-header {
font-size: 10px;
font-weight: 900;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 1.5px;
padding: 0 4px;
}
.doc-card {
background: rgba(15, 23, 42, 0.4);
border: 1px solid var(--border-main);
border-radius: 12px;
padding: 12px;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.doc-card:hover {
background: rgba(15, 23, 42, 0.8);
border-color: rgba(255, 255, 255, 0.1);
}
.doc-card.active {
background: rgba(79, 70, 229, 0.08);
border-color: rgba(79, 70, 229, 0.5);
box-shadow: inset 0 0 12px rgba(79, 70, 229, 0.05);
}
.doc-card-body {
display: flex;
align-items: start;
gap: 12px;
}
.doc-icon-container {
padding: 6px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.03);
color: var(--text-muted);
display: flex;
align-items: center;
}
.doc-icon-container.active {
background: rgba(79, 70, 229, 0.15);
color: #818cf8;
}
.doc-details {
flex: 1;
min-width: 0;
}
.doc-filename {
font-size: 13px;
font-weight: 700;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.doc-card.active .doc-filename {
color: white;
}
.doc-metadata {
display: flex;
gap: 6px;
font-size: 10px;
font-weight: 500;
color: var(--text-dim);
margin-top: 4px;
}
.thumbnails-grid {
display: grid;
grid-template-cols: repeat(2, 1fr);
gap: 14px;
}
.thumbnail-card {
display: flex;
flex-direction: column;
gap: 8px;
cursor: pointer;
}
.thumbnail-preview {
width: 100%;
aspect-ratio: 3 / 4;
background: var(--bg-card);
border: 1px solid var(--border-main);
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--text-muted);
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
.thumbnail-preview:hover {
transform: translateY(-2px);
border-color: rgba(99, 102, 241, 0.4);
}
.thumbnail-svg-icon {
color: var(--text-dim);
margin-bottom: 8px;
}
.thumbnail-label {
font-size: 10px;
font-weight: 600;
color: var(--text-muted);
}
.empty-state {
padding: 32px 16px;
text-align: center;
color: var(--text-dim);
font-size: 12px;
font-weight: 500;
line-height: 1.5;
}
.annotation-card {
padding: 12px;
background: rgba(15, 23, 42, 0.4);
border: 1px solid var(--border-main);
border-radius: 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.annotation-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.annotation-type-badge {
font-size: 9px;
font-weight: 800;
color: #f59e0b;
text-transform: uppercase;
letter-spacing: 1px;
padding: 2px 8px;
background: rgba(245, 158, 11, 0.1);
border: 1px solid rgba(245, 158, 11, 0.2);
border-radius: 9999px;
}
.annotation-author {
font-size: 9px;
font-weight: 700;
color: var(--text-dim);
}
.annotation-content {
font-size: 12px;
color: var(--text-muted);
font-style: italic;
line-height: 1.5;
}
/* ==========================================================================
VIEWER STYLES
========================================================================== */
.viewer-viewport {
flex: 1;
height: 100%;
overflow: auto;
background: #0b0f19; /* Slightly darker midnight */
display: flex;
justify-content: center;
align-items: start;
outline: none;
}
.viewer-content-container {
position: relative;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
padding: 32px 0;
}
.page-container {
position: absolute;
background: white;
border-radius: 8px;
transition: transform 0.2s;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
}
.page-loading-state {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #111827;
color: var(--text-muted);
gap: 12px;
border-radius: 8px;
}
.spinner {
width: 32px;
height: 32px;
border: 4px solid rgba(79, 70, 229, 0.2);
border-top-color: var(--bg-accent-indigo);
border-radius: 9999px;
animation: spin 1s linear infinite;
}
.page-loading-label {
font-size: 13px;
font-weight: 600;
animation: pulse 1.5s infinite;
letter-spacing: 0.5px;
}
/* Layering */
.selection-layer {
position: absolute;
top: 0;
left: 0;
z-index: 20;
cursor: text;
}
.selection-highlight {
position: absolute;
border: 1px solid rgba(99, 102, 241, 0.6);
background: rgba(99, 102, 241, 0.2);
pointer-events: none;
border-radius: 2px;
}
.annotation-layer {
position: absolute;
top: 0;
left: 0;
z-index: 30;
pointer-events: auto;
}
.highlight-box {
position: absolute;
cursor: pointer;
mix-blend-mode: multiply;
opacity: 0.75;
border-radius: 2px;
transition: opacity 0.15s;
}
.highlight-box:hover {
opacity: 0.95;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.highlight-box.type-highlight {
background: #fde047; /* Yellow 300 */
}
.highlight-box.type-comment {
background: #fecdd3; /* Rose 200 */
border-bottom: 2px solid #f43f5e;
}
.overlay-layer {
position: absolute;
top: 0;
left: 0;
z-index: 40;
pointer-events: none;
}
.overlay-signature-alert {
position: absolute;
inset: 0;
background: rgba(79, 70, 229, 0.05);
display: flex;
align-items: center;
justify-content: center;
border: 2px dashed rgba(79, 70, 229, 0.4);
border-radius: 8px;
}
.overlay-badge {
background: var(--bg-accent-indigo);
color: white;
font-size: 11px;
font-weight: 700;
padding: 4px 10px;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.25);
letter-spacing: 0.5px;
}
.overlay-toast {
position: absolute;
top: 16px;
right: 16px;
background: var(--color-success);
color: white;
font-size: 11px;
font-weight: 700;
padding: 4px 12px;
border-radius: 9999px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
/* Animations */
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
+112
View File
@@ -0,0 +1,112 @@
/**
* PDF Coordinate Mapping Utilities
*
* Manages conversions between three coordinate systems:
* 1. PDF Space: Standard points (1/72 inch), (0,0) is usually top-left or bottom-left depending on the engine.
* 2. Canvas Space: Zoomed/scaled pixels on the target canvas, including device pixel ratio (DPR).
* 3. Viewport Space: Client screen coordinates relative to the scroll container / viewer window.
*/
export interface Point {
x: number;
y: number;
}
export interface Rect {
x: number;
y: number;
width: number;
height: number;
}
export interface MappingContext {
zoom: number; // e.g. 1.0 (100%), 1.5 (150%)
dpr: number; // Device Pixel Ratio (window.devicePixelRatio)
rotation: number; // e.g. 0, 90, 180, 270 degrees
scrollX: number;
scrollY: number;
}
export class CoordinateMapper {
private ctx: MappingContext;
constructor(ctx: MappingContext) {
this.ctx = ctx;
}
updateContext(newCtx: Partial<MappingContext>) {
this.ctx = { ...this.ctx, ...newCtx };
}
getContext(): MappingContext {
return { ...this.ctx };
}
/**
* Converts PDF points to zoomed Canvas pixels
*/
pdfToCanvas(pt: Point, pageHeight: number): Point {
// If the PDF library treats (0,0) as bottom-left, we flip Y coordinate.
// For standard screen coordinates we use top-left.
const scaledX = pt.x * this.ctx.zoom * this.ctx.dpr;
const flippedY = pageHeight - pt.y;
const scaledY = flippedY * this.ctx.zoom * this.ctx.dpr;
return this.applyRotation({ x: scaledX, y: scaledY }, pageHeight * this.ctx.zoom * this.ctx.dpr);
}
/**
* Converts zoomed Canvas pixels to PDF points
*/
canvasToPdf(pt: Point, pageHeight: number): Point {
const unrotated = this.undoRotation(pt, pageHeight * this.ctx.zoom * this.ctx.dpr);
const x = unrotated.x / (this.ctx.zoom * this.ctx.dpr);
const y = pageHeight - (unrotated.y / (this.ctx.zoom * this.ctx.dpr));
return { x, y };
}
/**
* Converts Viewport (client screen) coordinates to Canvas pixels
*/
viewportToCanvas(pt: Point, canvasRect: DOMRect): Point {
const canvasX = (pt.x - canvasRect.left + this.ctx.scrollX) * this.ctx.dpr;
const canvasY = (pt.y - canvasRect.top + this.ctx.scrollY) * this.ctx.dpr;
return { x: canvasX, y: canvasY };
}
/**
* Converts Canvas pixels to Viewport coordinates
*/
canvasToViewport(pt: Point, canvasRect: DOMRect): Point {
const viewX = (pt.x / this.ctx.dpr) + canvasRect.left - this.ctx.scrollX;
const viewY = (pt.y / this.ctx.dpr) + canvasRect.top - this.ctx.scrollY;
return { x: viewX, y: viewY };
}
private applyRotation(pt: Point, boundSize: number): Point {
switch (this.ctx.rotation % 360) {
case 90:
return { x: boundSize - pt.y, y: pt.x };
case 180:
return { x: boundSize - pt.x, y: boundSize - pt.y };
case 270:
return { x: pt.y, y: boundSize - pt.x };
default:
return pt;
}
}
private undoRotation(pt: Point, boundSize: number): Point {
switch (this.ctx.rotation % 360) {
case 90:
return { x: pt.y, y: boundSize - pt.x };
case 180:
return { x: boundSize - pt.x, y: boundSize - pt.y };
case 270:
return { x: boundSize - pt.y, y: pt.x };
default:
return pt;
}
}
}
+243
View File
@@ -0,0 +1,243 @@
/**
* Gateway API Service Client
*
* Handles all network requests to the FastAPI gateway backend.
* Provides endpoints for document CRUD, rendering, metadata retrieval, and edits.
*/
export interface DocumentInfo {
id: string;
filename: string;
sizeBytes: number;
totalPages: number;
uploadedAt: string;
status: 'processing' | 'ready' | 'error';
}
export interface RenderParams {
documentId: string;
pageIndex: number;
zoom: number;
rotation: number;
}
export interface EditOperation {
type: 'add_text' | 'delete_text' | 'draw_shape' | 'add_annotation';
pageIndex: number;
data: any;
}
class GatewayService {
private baseUrl: string;
constructor() {
// In dev environment, FastAPI gateway runs on port 8000 by default.
this.baseUrl = import.meta.env.VITE_GATEWAY_URL || 'http://127.0.0.1:8000';
}
async getHealth(): Promise<{ status: string; version: string; engine_available: boolean }> {
const response = await fetch(`${this.baseUrl}/health`);
if (!response.ok) throw new Error(`Health check failed: ${response.statusText}`);
return response.json();
}
async listDocuments(): Promise<DocumentInfo[]> {
const response = await fetch(`${this.baseUrl}/documents`);
if (response.status === 501) {
// Return mocked document list for Phase 0 scaffolding
return this.getMockDocuments();
}
if (!response.ok) throw new Error(`Failed to list documents: ${response.statusText}`);
return response.json();
}
async uploadDocument(file: File): Promise<DocumentInfo> {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${this.baseUrl}/documents`, {
method: 'POST',
body: formData,
});
if (response.status === 501) {
// Simulate upload for Phase 0 scaffolding
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id: `doc_${Math.random().toString(36).substr(2, 9)}`,
filename: file.name,
sizeBytes: file.size,
totalPages: 5, // Mocked total pages
uploadedAt: new Date().toISOString(),
status: 'ready',
});
}, 1000);
});
}
if (!response.ok) throw new Error(`Upload failed: ${response.statusText}`);
return response.json();
}
async getDocument(id: string): Promise<DocumentInfo> {
const response = await fetch(`${this.baseUrl}/documents/${id}`);
if (response.status === 501) {
const mock = this.getMockDocuments().find(d => d.id === id);
if (!mock) throw new Error('Document not found');
return mock;
}
if (!response.ok) throw new Error(`Failed to fetch document metadata: ${response.statusText}`);
return response.json();
}
async deleteDocument(id: string): Promise<{ success: boolean }> {
const response = await fetch(`${this.baseUrl}/documents/${id}`, {
method: 'DELETE',
});
if (response.status === 501) {
return { success: true };
}
if (!response.ok) throw new Error(`Failed to delete document: ${response.statusText}`);
return response.json();
}
async renderPage(params: RenderParams): Promise<string> {
// Returns object URL or base64 data for the rendered page
const query = new URLSearchParams({
page: params.pageIndex.toString(),
zoom: params.zoom.toString(),
rotation: params.rotation.toString(),
}).toString();
const url = `${this.baseUrl}/render/${params.documentId}?${query}`;
const response = await fetch(url);
if (response.status === 501) {
// Fallback: Generate a high-fidelity mock SVG/Canvas data URL for the page
return this.generateMockPage(params.pageIndex);
}
if (!response.ok) throw new Error(`Page render failed: ${response.statusText}`);
const blob = await response.blob();
return URL.createObjectURL(blob);
}
async applyEdits(documentId: string, operations: EditOperation[]): Promise<{ success: boolean; newDocumentId: string }> {
const response = await fetch(`${this.baseUrl}/edits/${documentId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ operations }),
});
if (response.status === 501) {
return { success: true, newDocumentId: `${documentId}_edited` };
}
if (!response.ok) throw new Error(`Failed to apply edits: ${response.statusText}`);
return response.json();
}
private getMockDocuments(): DocumentInfo[] {
return [
{
id: 'sample-doc-1',
filename: 'Quarterly_Financial_Report.pdf',
sizeBytes: 1024 * 1024 * 3.4, // 3.4MB
totalPages: 12,
uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 3).toISOString(),
status: 'ready',
},
{
id: 'sample-doc-2',
filename: 'Engineering_Specification_v4.pdf',
sizeBytes: 1024 * 1024 * 18.2, // 18.2MB
totalPages: 54,
uploadedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 2).toISOString(),
status: 'ready',
},
{
id: 'sample-doc-3',
filename: 'Tenant_Lease_Agreement_Final.pdf',
sizeBytes: 1024 * 245, // 245KB
totalPages: 4,
uploadedAt: new Date(Date.now() - 1000 * 60 * 45).toISOString(),
status: 'ready',
}
];
}
private generateMockPage(pageIndex: number): string {
// Generate a premium vector representation of a mock document page
const width = 800;
const height = 1100;
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">
<rect width="${width}" height="${height}" fill="#fafbfc" />
<!-- Shadow border effect -->
<rect x="5" y="5" width="${width - 10}" height="${height - 10}" fill="white" rx="8" filter="drop-shadow(0 4px 6px rgba(0,0,0,0.05))" />
<!-- Header -->
<text x="60" y="80" font-family="system-ui, sans-serif" font-size="28" font-weight="800" fill="#1e293b">DocQube PDF Engine</text>
<text x="60" y="110" font-family="system-ui, sans-serif" font-size="12" font-weight="500" fill="#64748b" letter-spacing="1">PAGE ${pageIndex + 1} OF THE SPECIFICATION</text>
<line x1="60" y1="130" x2="${width - 60}" y2="130" stroke="#f1f5f9" stroke-width="2" />
<!-- Document Content Simulation -->
<rect x="60" y="160" width="120" height="24" fill="#eff6ff" rx="4" />
<text x="70" y="176" font-family="system-ui, sans-serif" font-size="12" font-weight="700" fill="#3b82f6">SECTION ${pageIndex * 2 + 1}.1</text>
<text x="60" y="210" font-family="system-ui, sans-serif" font-size="20" font-weight="700" fill="#0f172a">High-Performance Rendering Architecture</text>
<!-- Multiline mock text -->
<rect x="60" y="235" width="${width - 120}" height="10" fill="#e2e8f0" rx="3" />
<rect x="60" y="255" width="${width - 160}" height="10" fill="#e2e8f0" rx="3" />
<rect x="60" y="275" width="${width - 120}" height="10" fill="#e2e8f0" rx="3" />
<rect x="60" y="295" width="${width - 240}" height="10" fill="#e2e8f0" rx="3" />
<!-- Draw some abstract blueprints / charts on even pages to make them look distinct -->
${pageIndex % 2 === 0 ? `
<!-- Mock Chart -->
<rect x="60" y="340" width="${width - 120}" height="280" fill="#f8fafc" rx="12" stroke="#e2e8f0" stroke-width="1.5" />
<path d="M 100 580 Q 200 420 300 480 T 500 380 T 700 420" fill="none" stroke="url(#chartGrad)" stroke-width="4" stroke-linecap="round" />
<circle cx="300" cy="480" r="6" fill="#3b82f6" stroke="white" stroke-width="2" />
<circle cx="500" cy="380" r="6" fill="#10b981" stroke="white" stroke-width="2" />
<text x="80" y="375" font-family="system-ui, sans-serif" font-size="14" font-weight="700" fill="#334155">Engine Performance Vectors (Mock Data)</text>
<defs>
<linearGradient id="chartGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#3b82f6" />
<stop offset="100%" stop-color="#10b981" />
</linearGradient>
</defs>
` : `
<!-- Structured List -->
<circle cx="70" cy="360" r="4" fill="#3b82f6" />
<rect x="90" y="355" width="${width - 160}" height="10" fill="#cbd5e1" rx="3" />
<circle cx="70" cy="390" r="4" fill="#3b82f6" />
<rect x="90" y="385" width="${width - 200}" height="10" fill="#cbd5e1" rx="3" />
<circle cx="70" cy="420" r="4" fill="#3b82f6" />
<rect x="90" y="415" width="${width - 140}" height="10" fill="#cbd5e1" rx="3" />
<!-- A block of code/preformatted text -->
<rect x="60" y="470" width="${width - 120}" height="180" fill="#0f172a" rx="12" />
<text x="90" y="510" font-family="monospace" font-size="13" fill="#38bdf8">#include &lt;pdfengine/core.hpp&gt;</text>
<text x="90" y="535" font-family="monospace" font-size="13" fill="#f87171">int main() {</text>
<text x="120" y="560" font-family="monospace" font-size="13" fill="#a7f3d0"> pdf::Engine engine;</text>
<text x="120" y="585" font-family="monospace" font-size="13" fill="#a7f3d0"> engine.load_document("quarterly.pdf");</text>
<text x="120" y="610" font-family="monospace" font-size="13" fill="#fbbf24"> return engine.render_page(1, 2.0);</text>
<text x="90" y="635" font-family="monospace" font-size="13" fill="#f87171">}</text>
`}
<!-- Footer -->
<line x1="60" y1="1020" x2="${width - 60}" y2="1020" stroke="#f1f5f9" stroke-width="1.5" />
<text x="60" y="1045" font-family="system-ui, sans-serif" font-size="11" font-weight="600" fill="#94a3b8">DocQube Core Engine (Gate G0a scaffolding)</text>
<text x="${width - 100}" y="1045" font-family="system-ui, sans-serif" font-size="11" font-weight="700" fill="#94a3b8">PAGE ${pageIndex + 1}</text>
</svg>
`;
return `data:image/svg+xml;utf8,${encodeURIComponent(svg.trim())}`;
}
}
export const gatewayService = new GatewayService();
+76
View File
@@ -0,0 +1,76 @@
/**
* WASM C++ PDF Engine Loader
*
* Manages loading the compiled Emscripten WebAssembly modules.
* Implements fallback mock engines when WASM is not built yet (e.g. in G0a).
*/
export interface WasmEngineInstance {
version: string;
loadDocument: (buffer: ArrayBuffer) => number; // returns doc handle
renderPage: (handle: number, page: number, scale: number) => ImageData;
freeDocument: (handle: number) => void;
}
class WasmLoader {
private isLoaded = false;
private instance: WasmEngineInstance | null = null;
async loadEngine(): Promise<WasmEngineInstance> {
if (this.isLoaded && this.instance) {
return this.instance;
}
try {
// In a real production setup, we load the wasm glue script:
// @ts-ignore
// const Module = await import('@/wasm/pdfengine.js');
// For Phase 0 / Gate G0a, we stub/mock the WASM loading process gracefully:
return new Promise((resolve) => {
setTimeout(() => {
this.isLoaded = true;
this.instance = this.createMockEngineInstance();
resolve(this.instance);
}, 1200); // Simulate network/compilation delay
});
} catch (err) {
console.warn('WASM Loading failed, using JavaScript Canvas Mock rendering.', err);
this.isLoaded = true;
this.instance = this.createMockEngineInstance();
return this.instance;
}
}
private createMockEngineInstance(): WasmEngineInstance {
return {
version: '1.0.0-wasm-g0a-scaffold',
loadDocument: (buffer: ArrayBuffer) => {
console.log(`[WASM Engine] Loaded document of size ${buffer.byteLength} bytes.`);
return Math.floor(Math.random() * 1000) + 1; // handle
},
renderPage: (handle: number, page: number, scale: number) => {
console.log(`[WASM Engine] Render page ${page} with scale ${scale} for handle ${handle}.`);
// Return dummy white/gray pixels (ImageData) representing the mock render
const width = Math.floor(800 * scale);
const height = Math.floor(1100 * scale);
const buffer = new Uint8ClampedArray(width * height * 4);
// Fill image data with off-white and simulated drawing
for (let i = 0; i < buffer.length; i += 4) {
buffer[i] = 250; // R
buffer[i + 1] = 251; // G
buffer[i + 2] = 252; // B
buffer[i + 3] = 255; // A
}
return new ImageData(buffer, width, height);
},
freeDocument: (handle: number) => {
console.log(`[WASM Engine] Released document resources for handle ${handle}.`);
}
};
}
}
export const wasmLoader = new WasmLoader();
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+65
View File
@@ -0,0 +1,65 @@
import React from 'react';
import type { Rect } from '../lib/coordinateMapping';
export interface Annotation {
id: string;
type: 'highlight' | 'signature' | 'strikeout' | 'comment';
bbox: Rect;
color?: string;
author: string;
content?: string;
}
interface AnnotationLayerProps {
pageIndex: number;
width: number;
height: number;
zoom: number;
annotations: Annotation[];
onAnnotationClick?: (annotation: Annotation) => void;
}
export const AnnotationLayer: React.FC<AnnotationLayerProps> = ({
pageIndex: _pageIndex,
width,
height,
zoom,
annotations,
onAnnotationClick,
}) => {
return (
<div
className="annotation-layer"
style={{ width: `${width}px`, height: `${height}px` }}
>
{annotations
.filter((anno) => anno.type === 'highlight' || anno.type === 'comment')
.map((anno) => {
const scaledBbox = {
x: anno.bbox.x * zoom,
y: anno.bbox.y * zoom,
width: anno.bbox.width * zoom,
height: anno.bbox.height * zoom,
};
return (
<div
key={anno.id}
onClick={(e) => {
e.stopPropagation();
onAnnotationClick?.(anno);
}}
className={`highlight-box type-${anno.type}`}
style={{
left: `${scaledBbox.x}px`,
top: `${scaledBbox.y}px`,
width: `${scaledBbox.width}px`,
height: `${scaledBbox.height}px`,
}}
title={`${anno.author}: ${anno.content || ''}`}
/>
);
})}
</div>
);
};
+72
View File
@@ -0,0 +1,72 @@
import React, { useRef, useEffect } from 'react';
interface CanvasLayerProps {
pageIndex: number;
imageUrl: string;
zoom: number;
rotation: number;
width: number;
height: number;
onRenderComplete?: () => void;
}
export const CanvasLayer: React.FC<CanvasLayerProps> = ({
pageIndex,
imageUrl,
zoom,
rotation,
width,
height,
onRenderComplete,
}) => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Apply scaling for High DPI screens
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
ctx.scale(dpr, dpr);
// Simulated asynchronous high-fidelity drawing from loaded image / WASM context
const img = new Image();
img.onload = () => {
ctx.clearRect(0, 0, width, height);
// Save canvas state to handle rotation
ctx.save();
if (rotation !== 0) {
ctx.translate(width / 2, height / 2);
ctx.rotate((rotation * Math.PI) / 180);
ctx.translate(-width / 2, -height / 2);
}
ctx.drawImage(img, 0, 0, width, height);
ctx.restore();
onRenderComplete?.();
};
img.src = imageUrl;
}, [imageUrl, zoom, rotation, width, height, onRenderComplete]);
return (
<canvas
ref={canvasRef}
className="absolute top-0 left-0 w-full h-full pointer-events-none select-none z-10 transition-shadow duration-300"
style={{
boxShadow: '0 4px 20px rgba(15, 23, 42, 0.05)',
}}
data-page-index={pageIndex}
/>
);
};
+38
View File
@@ -0,0 +1,38 @@
import React from 'react';
interface OverlayLayerProps {
pageIndex: number;
width: number;
height: number;
activeTool: string;
onDrawStroke?: (path: string) => void;
}
export const OverlayLayer: React.FC<OverlayLayerProps> = ({
pageIndex,
width,
height,
activeTool,
}) => {
return (
<div
className="overlay-layer"
style={{ width: `${width}px`, height: `${height}px` }}
>
{/* Signature overlay state indicator */}
{activeTool === 'signature' && (
<div className="overlay-signature-alert">
<span className="overlay-badge">
READY TO PLACE SIGNATURE (Page {pageIndex + 1})
</span>
</div>
)}
{activeTool === 'draw' && (
<div className="overlay-toast animate-pulse">
Freehand Ink Pen Enabled
</div>
)}
</div>
);
};
+252
View File
@@ -0,0 +1,252 @@
import React, { useRef, useEffect, useState, useMemo } from 'react';
import { CanvasLayer } from './CanvasLayer';
import { SelectionLayer } from './SelectionLayer';
import { AnnotationLayer } from './AnnotationLayer';
import type { Annotation } from './AnnotationLayer';
import { OverlayLayer } from './OverlayLayer';
import type { Rect } from '../lib/coordinateMapping';
import { gatewayService } from '../lib/gatewayService';
interface PDFViewerProps {
documentId: string;
totalPages: number;
zoom: number;
rotation: number;
activeTool: string;
annotations: Annotation[];
onAnnotationAdded?: (anno: Annotation) => void;
onPageVisible?: (pageIndex: number) => void;
}
interface PageLayout {
index: number;
width: number;
height: number;
top: number;
}
export const PDFViewer: React.FC<PDFViewerProps> = ({
documentId,
totalPages,
zoom,
rotation,
activeTool,
annotations,
onAnnotationAdded,
onPageVisible,
}) => {
const containerRef = useRef<HTMLDivElement | null>(null);
const [scrollPosition, setScrollPosition] = useState({ scrollLeft: 0, scrollTop: 0 });
const [renderedPages, setRenderedPages] = useState<string[]>([]);
const [containerHeight, setContainerHeight] = useState(800);
// Standard Page Dimensions: Letter size is 612x792 pt
const basePageWidth = 612;
const basePageHeight = 792;
const pageGap = 24; // space between pages
// Calculate layout coordinates for all pages sequentially
const pageLayouts = useMemo(() => {
const layouts: PageLayout[] = [];
let currentTop = 0;
for (let i = 0; i < totalPages; i++) {
// Swapped width/height if rotated 90 or 270 degrees
const isSwapped = (rotation / 90) % 2 !== 0;
const w = isSwapped ? basePageHeight : basePageWidth;
const h = isSwapped ? basePageWidth : basePageHeight;
layouts.push({
index: i,
width: w * zoom,
height: h * zoom,
top: currentTop,
});
currentTop += (h * zoom) + pageGap;
}
return layouts;
}, [totalPages, zoom, rotation]);
const totalContentHeight = useMemo(() => {
if (pageLayouts.length === 0) return 0;
const lastPage = pageLayouts[pageLayouts.length - 1];
return lastPage.top + lastPage.height + pageGap;
}, [pageLayouts]);
// Handle scroll events to track viewport and update virtualized window
const handleScroll = () => {
if (!containerRef.current) return;
setScrollPosition({
scrollLeft: containerRef.current.scrollLeft,
scrollTop: containerRef.current.scrollTop,
});
};
useEffect(() => {
const updateSize = () => {
if (containerRef.current) {
setContainerHeight(containerRef.current.clientHeight);
}
};
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
// Compute which pages are currently visible (virtualized rendering)
const visiblePages = useMemo(() => {
const viewportTop = scrollPosition.scrollTop;
const viewportBottom = viewportTop + containerHeight;
// Buffer range: render 1 page before and 1 page after visible bounds
const buffer = 1;
const visible: PageLayout[] = [];
let currentVisiblePageIdx = 0;
let maxVisibleArea = 0;
pageLayouts.forEach((layout) => {
const pageTop = layout.top;
const pageBottom = pageTop + layout.height;
// Overlap calculation
const visibleTop = Math.max(viewportTop, pageTop);
const visibleBottom = Math.min(viewportBottom, pageBottom);
const overlapHeight = Math.max(0, visibleBottom - visibleTop);
if (overlapHeight > maxVisibleArea) {
maxVisibleArea = overlapHeight;
currentVisiblePageIdx = layout.index;
}
const isInside = (pageBottom >= viewportTop - (layout.height * buffer)) &&
(pageTop <= viewportBottom + (layout.height * buffer));
if (isInside) {
visible.push(layout);
}
});
// Notify parent of the primary page visible on screen
onPageVisible?.(currentVisiblePageIdx);
return visible;
}, [pageLayouts, scrollPosition.scrollTop, containerHeight, onPageVisible]);
// Load the rendered SVG/Image URL for each visible page
useEffect(() => {
const fetchPageImages = async () => {
const newUrls = [...renderedPages];
const renderPromises = visiblePages.map(async (page) => {
if (!newUrls[page.index]) {
const url = await gatewayService.renderPage({
documentId,
pageIndex: page.index,
zoom,
rotation,
});
newUrls[page.index] = url;
}
});
await Promise.all(renderPromises);
setRenderedPages(newUrls);
};
fetchPageImages();
}, [visiblePages, documentId, zoom, rotation]);
const handleTextSelection = (text: string, bbox: Rect, _pageIndex: number) => {
if (activeTool === 'highlight') {
const newAnno: Annotation = {
id: `anno_${Math.random().toString(36).substr(2, 9)}`,
type: 'highlight',
bbox: {
x: bbox.x / zoom,
y: bbox.y / zoom,
width: bbox.width / zoom,
height: bbox.height / zoom,
},
author: 'Current User',
content: text,
};
onAnnotationAdded?.(newAnno);
}
};
return (
<div
ref={containerRef}
onScroll={handleScroll}
className="viewer-viewport"
>
<div
className="viewer-content-container"
style={{ height: `${totalContentHeight}px` }}
>
{visiblePages.map((page) => {
const imageUrl = renderedPages[page.index] || '';
return (
<div
key={page.index}
className="page-container shadow-premium"
style={{
top: `${page.top}px`,
width: `${page.width}px`,
height: `${page.height}px`,
}}
>
{imageUrl ? (
<>
{/* Base PDF Canvas Layer */}
<CanvasLayer
pageIndex={page.index}
imageUrl={imageUrl}
zoom={zoom}
rotation={rotation}
width={page.width}
height={page.height}
/>
{/* Highlight/Comment Annotation Layer */}
<AnnotationLayer
pageIndex={page.index}
width={page.width}
height={page.height}
zoom={zoom}
annotations={annotations}
/>
{/* Text Selection Dragging Layer */}
<SelectionLayer
pageIndex={page.index}
width={page.width}
height={page.height}
zoom={zoom}
onTextSelected={(text, bbox) => handleTextSelection(text, bbox, page.index)}
/>
{/* signature/ink overlay tool layer */}
<OverlayLayer
pageIndex={page.index}
width={page.width}
height={page.height}
activeTool={activeTool}
/>
</>
) : (
<div className="page-loading-state">
<div className="spinner" />
<span className="page-loading-label">Loading Page {page.index + 1}...</span>
</div>
)}
</div>
);
})}
</div>
</div>
);
};
+83
View File
@@ -0,0 +1,83 @@
import React, { useState, useRef } from 'react';
import type { Point, Rect } from '../lib/coordinateMapping';
interface SelectionLayerProps {
pageIndex: number;
width: number;
height: number;
zoom: number;
onTextSelected?: (text: string, bbox: Rect) => void;
}
export const SelectionLayer: React.FC<SelectionLayerProps> = ({
pageIndex,
width,
height,
zoom: _zoom,
onTextSelected,
}) => {
const [dragStart, setDragStart] = useState<Point | null>(null);
const [selectionBox, setSelectionBox] = useState<Rect | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
setDragStart({ x, y });
setSelectionBox({ x, y, width: 0, height: 0 });
};
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
if (!dragStart || !selectionBox || !containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const newBox: Rect = {
x: Math.min(dragStart.x, x),
y: Math.min(dragStart.y, y),
width: Math.abs(dragStart.x - x),
height: Math.abs(dragStart.y - y),
};
setSelectionBox(newBox);
};
const handleMouseUp = () => {
if (selectionBox && selectionBox.width > 5 && selectionBox.height > 5) {
// Mock selected text within this box for Phase 0
const mockedText = `[Selected text from Page ${pageIndex + 1} at coordinates x:${Math.floor(selectionBox.x)}, y:${Math.floor(selectionBox.y)}]`;
onTextSelected?.(mockedText, selectionBox);
}
setDragStart(null);
setSelectionBox(null);
};
return (
<div
ref={containerRef}
className="selection-layer"
style={{ width: `${width}px`, height: `${height}px` }}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
>
{/* Selection Box highlight visual */}
{selectionBox && (
<div
className="selection-highlight"
style={{
left: `${selectionBox.x}px`,
top: `${selectionBox.y}px`,
width: `${selectionBox.width}px`,
height: `${selectionBox.height}px`,
}}
/>
)}
</div>
);
};
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
"strict": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})