diff --git a/legacy/App.tsx b/legacy/App.tsx deleted file mode 100644 index b6f3853..0000000 --- a/legacy/App.tsx +++ /dev/null @@ -1,573 +0,0 @@ -import React, { useState, useEffect, useMemo, useRef } from 'react'; -import { parseMarkdownToBlocks, exportDiff } from './utils/parser'; -import { Viewer, ViewerHandle } from './components/Viewer'; -import { AnnotationPanel } from './components/AnnotationPanel'; -import { Landing } from './components/Landing'; -import { ExportModal } from './components/ExportModal'; -import { Annotation, Block, AnnotationType, EditorMode } from './types'; -import { ThemeProvider } from './components/ThemeProvider'; -import { ModeToggle } from './components/ModeToggle'; -import { ModeSwitcher } from './components/ModeSwitcher'; -import { TaterSpriteRunning } from './components/TaterSpriteRunning'; -import { TaterSpritePullup } from './components/TaterSpritePullup'; -import { Settings } from './components/Settings'; -import { useSharing } from './hooks/useSharing'; - -const PLAN_CONTENT = `# Implementation Plan: Real-time Collaboration - -## Overview -Add real-time collaboration features to the editor using WebSocket connections and operational transforms. - -## Phase 1: Infrastructure - -### WebSocket Server -Set up a WebSocket server to handle concurrent connections: - -\`\`\`typescript -const server = new WebSocketServer({ port: 8080 }); - -server.on('connection', (socket, request) => { - const sessionId = generateSessionId(); - sessions.set(sessionId, socket); - - socket.on('message', (data) => { - broadcast(sessionId, data); - }); -}); -\`\`\` - -### Client Connection -- Establish persistent connection on document load -- Implement reconnection logic with exponential backoff -- Handle offline state gracefully - -### Database Schema - -\`\`\`sql -CREATE TABLE documents ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - title VARCHAR(255) NOT NULL, - content JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); - -CREATE TABLE collaborators ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - document_id UUID REFERENCES documents(id) ON DELETE CASCADE, - user_id UUID NOT NULL, - role VARCHAR(50) DEFAULT 'editor', - cursor_position JSONB, - last_seen_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() -); - -CREATE INDEX idx_collaborators_document ON collaborators(document_id); -\`\`\` - -## Phase 2: Operational Transforms - -> The key insight is that we need to transform operations against concurrent operations to maintain consistency. - -Key requirements: -- Transform insert against insert -- Transform insert against delete -- Transform delete against delete -- Maintain cursor positions across transforms - -### Transform Implementation - -\`\`\`typescript -interface Operation { - type: 'insert' | 'delete'; - position: number; - content?: string; - length?: number; - userId: string; - timestamp: number; -} - -class OperationalTransform { - private pendingOps: Operation[] = []; - private history: Operation[] = []; - - transform(op1: Operation, op2: Operation): [Operation, Operation] { - if (op1.type === 'insert' && op2.type === 'insert') { - if (op1.position <= op2.position) { - return [op1, { ...op2, position: op2.position + (op1.content?.length || 0) }]; - } else { - return [{ ...op1, position: op1.position + (op2.content?.length || 0) }, op2]; - } - } - - if (op1.type === 'delete' && op2.type === 'delete') { - // Complex delete vs delete transformation - const op1End = op1.position + (op1.length || 0); - const op2End = op2.position + (op2.length || 0); - - if (op1End <= op2.position) { - return [op1, { ...op2, position: op2.position - (op1.length || 0) }]; - } - // ... more cases - } - - return [op1, op2]; - } - - apply(doc: string, op: Operation): string { - if (op.type === 'insert') { - return doc.slice(0, op.position) + op.content + doc.slice(op.position); - } else { - return doc.slice(0, op.position) + doc.slice(op.position + (op.length || 0)); - } - } -} -\`\`\` - -## Phase 3: UI Updates - -1. Show collaborator cursors in real-time -2. Display presence indicators -3. Add conflict resolution UI -4. Implement undo/redo stack per user - -### React Component for Cursors - -\`\`\`tsx -import React, { useEffect, useState } from 'react'; -import { useCollaboration } from '../hooks/useCollaboration'; - -interface CursorOverlayProps { - documentId: string; - containerRef: React.RefObject; -} - -export const CursorOverlay: React.FC = ({ - documentId, - containerRef -}) => { - const { collaborators, currentUser } = useCollaboration(documentId); - const [positions, setPositions] = useState>(new Map()); - - useEffect(() => { - const updatePositions = () => { - const newPositions = new Map(); - collaborators.forEach(collab => { - if (collab.userId !== currentUser.id && collab.cursorPosition) { - const rect = getCursorRect(containerRef.current, collab.cursorPosition); - if (rect) newPositions.set(collab.userId, rect); - } - }); - setPositions(newPositions); - }; - - const interval = setInterval(updatePositions, 50); - return () => clearInterval(interval); - }, [collaborators, currentUser, containerRef]); - - return ( - <> - {Array.from(positions.entries()).map(([userId, rect]) => ( -
-
-
- {collaborators.find(c => c.userId === userId)?.userName} -
-
- ))} - - ); -}; -\`\`\` - -### Configuration - -\`\`\`json -{ - "collaboration": { - "enabled": true, - "maxCollaborators": 10, - "cursorColors": ["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6"], - "syncInterval": 100, - "reconnect": { - "maxAttempts": 5, - "backoffMultiplier": 1.5, - "initialDelay": 1000 - } - } -} -\`\`\` - ---- - -**Target:** Ship MVP in next sprint -`; - -const App: React.FC = () => { - const [page, setPage] = useState<'landing' | 'editor'>(() => { - const path = window.location.pathname; - const hasShareHash = window.location.hash.length > 1; - // Go directly to editor if path indicates or if we have a share hash - return path === '/editor' || path === '/app' || hasShareHash ? 'editor' : 'landing'; - }); - const [markdown, setMarkdown] = useState(PLAN_CONTENT); - const [annotations, setAnnotations] = useState([]); - const [selectedAnnotationId, setSelectedAnnotationId] = useState(null); - const [blocks, setBlocks] = useState([]); - const [showExport, setShowExport] = useState(false); - const [showFeedbackPrompt, setShowFeedbackPrompt] = useState(false); - const [isPanelOpen, setIsPanelOpen] = useState(true); - const [editorMode, setEditorMode] = useState('selection'); - const [taterMode, setTaterMode] = useState(() => { - const stored = localStorage.getItem('plannotator-tater-mode'); - return stored === 'true'; - }); - const [isApiMode, setIsApiMode] = useState(false); - const [isLoading, setIsLoading] = useState(true); - const [isSubmitting, setIsSubmitting] = useState(false); - const [submitted, setSubmitted] = useState<'approved' | 'denied' | null>(null); - const viewerRef = useRef(null); - - // URL-based sharing - const { - isSharedSession, - isLoadingShared, - shareUrl, - shareUrlSize, - pendingSharedAnnotations, - clearPendingSharedAnnotations, - } = useSharing( - markdown, - annotations, - setMarkdown, - setAnnotations, - () => { - // When loaded from share, go directly to editor - setPage('editor'); - setIsLoading(false); - } - ); - - // Apply shared annotations to DOM after they're loaded - useEffect(() => { - if (pendingSharedAnnotations && pendingSharedAnnotations.length > 0) { - // Small delay to ensure DOM is rendered - const timer = setTimeout(() => { - // Clear existing highlights first (important when loading new share URL) - viewerRef.current?.clearAllHighlights(); - viewerRef.current?.applySharedAnnotations(pendingSharedAnnotations); - clearPendingSharedAnnotations(); - }, 100); - return () => clearTimeout(timer); - } - }, [pendingSharedAnnotations, clearPendingSharedAnnotations]); - - const goToEditor = () => { - window.history.pushState({}, '', '/editor'); - setPage('editor'); - }; - - const handleTaterModeChange = (enabled: boolean) => { - setTaterMode(enabled); - localStorage.setItem('plannotator-tater-mode', String(enabled)); - }; - - // Check if we're in API mode (served from Bun hook server) - // Skip if we loaded from a shared URL - useEffect(() => { - if (isLoadingShared) return; // Wait for share check to complete - if (isSharedSession) return; // Already loaded from share - - fetch('/api/plan') - .then(res => { - if (!res.ok) throw new Error('Not in API mode'); - return res.json(); - }) - .then((data: { plan: string }) => { - setMarkdown(data.plan); - setIsApiMode(true); - setPage('editor'); // Skip landing page in API mode - }) - .catch(() => { - // Not in API mode - use default content - setIsApiMode(false); - }) - .finally(() => setIsLoading(false)); - }, [isLoadingShared, isSharedSession]); - - useEffect(() => { - setBlocks(parseMarkdownToBlocks(markdown)); - }, [markdown]); - - // API mode handlers - const handleApprove = async () => { - setIsSubmitting(true); - try { - await fetch('/api/approve', { method: 'POST' }); - setSubmitted('approved'); - } catch { - setIsSubmitting(false); - } - }; - - const handleDeny = async () => { - setIsSubmitting(true); - try { - await fetch('/api/deny', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ feedback: diffOutput }) - }); - setSubmitted('denied'); - } catch { - setIsSubmitting(false); - } - }; - - const handleAddAnnotation = (ann: Annotation) => { - setAnnotations(prev => [...prev, ann]); - setSelectedAnnotationId(ann.id); - setIsPanelOpen(true); - }; - - const handleDeleteAnnotation = (id: string) => { - viewerRef.current?.removeHighlight(id); - setAnnotations(prev => prev.filter(a => a.id !== id)); - if (selectedAnnotationId === id) setSelectedAnnotationId(null); - }; - - const handleIdentityChange = (oldIdentity: string, newIdentity: string) => { - setAnnotations(prev => prev.map(ann => - ann.author === oldIdentity ? { ...ann, author: newIdentity } : ann - )); - }; - - const diffOutput = useMemo(() => exportDiff(blocks, annotations), [blocks, annotations]); - - if (page === 'landing') { - return ( - - - - ); - } - - return ( - -
- {/* Tater sprites */} - {taterMode && } - {/* Minimal Header */} -
-
- - v0.1 -
- -
- {isApiMode && ( - <> - - - - -
- - )} - - - - - - - -
-
- - {/* Main Content */} -
- {/* Document Area */} -
-
- {/* Mode Switcher */} -
- -
- - -
-
- - {/* Annotation Panel */} - -
- - {/* Export Modal */} - setShowExport(false)} - shareUrl={shareUrl} - shareUrlSize={shareUrlSize} - diffOutput={diffOutput} - annotationCount={annotations.length} - taterSprite={taterMode ? : undefined} - /> - - {/* Feedback prompt dialog */} - {showFeedbackPrompt && ( -
-
-
-
- - - -
-

Add Annotations First

-
-

- To provide feedback, select text in the plan and add annotations. Claude will use your annotations to revise the plan. -

-
- -
-
-
- )} - - {/* Completion overlay - shown after approve/deny */} - {submitted && ( -
-
-
- {submitted === 'approved' ? ( - - - - ) : ( - - - - )} -
- -
-

- {submitted === 'approved' ? 'Plan Approved' : 'Feedback Sent'} -

-

- {submitted === 'approved' - ? 'Claude will proceed with the implementation.' - : 'Claude will revise the plan based on your annotations.'} -

-
- -
-

- Return to your Claude Code terminal to continue. -

-
-
-
- )} -
-
- ); -}; - -export default App; diff --git a/legacy/components/AnnotationPanel.tsx b/legacy/components/AnnotationPanel.tsx deleted file mode 100644 index 67dbcce..0000000 --- a/legacy/components/AnnotationPanel.tsx +++ /dev/null @@ -1,235 +0,0 @@ -import React, { useState } from 'react'; -import { Annotation, AnnotationType, Block } from '../types'; -import { isCurrentUser } from '../utils/identity'; - -interface PanelProps { - isOpen: boolean; - annotations: Annotation[]; - blocks: Block[]; - onSelect: (id: string) => void; - onDelete: (id: string) => void; - selectedId: string | null; - shareUrl?: string; -} - -export const AnnotationPanel: React.FC = ({ - isOpen, - annotations, - blocks, - onSelect, - onDelete, - selectedId, - shareUrl -}) => { - const [copied, setCopied] = useState(false); - const sortedAnnotations = [...annotations].sort((a, b) => a.createdA - b.createdA); - - const handleQuickShare = async () => { - if (!shareUrl) return; - try { - await navigator.clipboard.writeText(shareUrl); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (e) { - console.error('Failed to copy:', e); - } - }; - - if (!isOpen) return null; - - return ( - - ); -}; - -function formatTimestamp(ts: number): string { - const now = Date.now(); - const diff = now - ts; - const seconds = Math.floor(diff / 1000); - const minutes = Math.floor(seconds / 60); - const hours = Math.floor(minutes / 60); - const days = Math.floor(hours / 24); - - if (seconds < 60) return 'now'; - if (minutes < 60) return `${minutes}m`; - if (hours < 24) return `${hours}h`; - if (days < 7) return `${days}d`; - - return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); -} - -const AnnotationCard: React.FC<{ - annotation: Annotation; - isSelected: boolean; - onSelect: () => void; - onDelete: () => void; -}> = ({ annotation, isSelected, onSelect, onDelete }) => { - const typeConfig = { - [AnnotationType.DELETION]: { - label: 'Delete', - color: 'text-destructive', - bg: 'bg-destructive/10', - icon: ( - - - - ) - }, - [AnnotationType.INSERTION]: { - label: 'Insert', - color: 'text-secondary', - bg: 'bg-secondary/10', - icon: ( - - - - ) - }, - [AnnotationType.REPLACEMENT]: { - label: 'Replace', - color: 'text-primary', - bg: 'bg-primary/10', - icon: ( - - - - ) - }, - [AnnotationType.COMMENT]: { - label: 'Comment', - color: 'text-accent', - bg: 'bg-accent/10', - icon: ( - - - - ) - } - }; - - const config = typeConfig[annotation.type]; - - return ( -
- {/* Author */} - {annotation.author && ( -
- - - - {annotation.author}{isCurrentUser(annotation.author) && ' (me)'} -
- )} - - {/* Type Badge + Timestamp + Delete */} -
-
-
- - {config.icon} - - - {config.label} - -
- - {formatTimestamp(annotation.createdA)} - -
- -
- - {/* Original Text */} -
- "{annotation.originalText}" -
- - {/* Comment/Replacement Text */} - {annotation.text && annotation.type !== AnnotationType.DELETION && ( -
- {annotation.text} -
- )} -
- ); -}; diff --git a/legacy/components/AnnotationSidebar.tsx b/legacy/components/AnnotationSidebar.tsx deleted file mode 100644 index bd1b565..0000000 --- a/legacy/components/AnnotationSidebar.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import React from 'react'; -import { Annotation, AnnotationType, Block } from '../types'; - -interface SidebarProps { - annotations: Annotation[]; - blocks: Block[]; - onSelect: (id: string) => void; - onDelete: (id: string) => void; - selectedId: string | null; -} - -export const AnnotationSidebar: React.FC = ({ - annotations, - blocks, - onSelect, - onDelete, - selectedId -}) => { - const sortedAnnotations = [...annotations].sort((a, b) => { - const blockA = blocks.findIndex(blk => blk.id === a.blockId); - const blockB = blocks.findIndex(blk => blk.id === b.blockId); - if (blockA !== blockB) return blockA - blockB; - return a.startOffset - b.startOffset; - }); - - return ( -
-
-

Review Changes

- - {annotations.length} - -
- -
- {sortedAnnotations.length === 0 ? ( -
-

No annotations yet.

-

Select text in the document to add comments or suggest changes.

-
- ) : ( - sortedAnnotations.map(ann => ( -
onSelect(ann.id)} - className={` - group relative p-3 rounded-lg border transition-all cursor-pointer - ${selectedId === ann.id - ? 'bg-accent/20 border-accent shadow-sm' - : 'bg-card border-border hover:border-accent hover:shadow-sm' - } - `} - > -
- - {ann.type} - - -
- -
- "{ann.originalText}" -
- - {(ann.text && ann.type !== AnnotationType.DELETION) && ( -
- {ann.type === AnnotationType.REPLACEMENT ? '→ ' : ''}{ann.text} -
- )} -
- )) - )} -
-
- ); -}; diff --git a/legacy/components/DecisionBar.tsx b/legacy/components/DecisionBar.tsx deleted file mode 100644 index fd89509..0000000 --- a/legacy/components/DecisionBar.tsx +++ /dev/null @@ -1,131 +0,0 @@ -import React, { useState } from 'react'; - -interface DecisionBarProps { - onApprove: () => Promise; - onDeny: (feedback: string) => Promise; - annotationCount: number; - getFeedback: () => string; -} - -export const DecisionBar: React.FC = ({ - onApprove, - onDeny, - annotationCount, - getFeedback -}) => { - const [isSubmitting, setIsSubmitting] = useState(false); - const [submitted, setSubmitted] = useState<'approved' | 'denied' | null>(null); - - const handleApprove = async () => { - setIsSubmitting(true); - try { - await onApprove(); - setSubmitted('approved'); - } catch (error) { - console.error('Failed to approve:', error); - setIsSubmitting(false); - } - }; - - const handleDeny = async () => { - const feedback = getFeedback(); - setIsSubmitting(true); - try { - await onDeny(feedback); - setSubmitted('denied'); - } catch (error) { - console.error('Failed to deny:', error); - setIsSubmitting(false); - } - }; - - if (submitted) { - return ( -
-
- {/* Icon */} -
- {submitted === 'approved' ? ( - - - - ) : ( - - - - )} -
- - {/* Message */} -
-

- {submitted === 'approved' ? 'Plan Approved' : 'Feedback Sent'} -

-

- {submitted === 'approved' - ? 'Claude will proceed with the implementation.' - : 'Claude will revise the plan based on your annotations.'} -

-
- - {/* Instruction */} -
-

- Return to your Claude Code terminal to continue. -

-
-
-
- ); - } - - return ( -
-
- {/* Status info */} -
- {annotationCount > 0 ? ( - {annotationCount} annotation{annotationCount !== 1 ? 's' : ''} to send as feedback - ) : ( - Review the plan, then approve or request changes - )} -
- - {/* Action buttons */} -
- - - -
-
-
- ); -}; diff --git a/legacy/components/ExportModal.tsx b/legacy/components/ExportModal.tsx deleted file mode 100644 index 4b5e760..0000000 --- a/legacy/components/ExportModal.tsx +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Export Modal with tabs for Share and Raw Diff - * - * Share tab (default): Shows shareable URL with copy button - * Raw Diff tab: Shows human-readable diff output with copy/download - */ - -import React, { useState } from 'react'; - -interface ExportModalProps { - isOpen: boolean; - onClose: () => void; - shareUrl: string; - shareUrlSize: string; - diffOutput: string; - annotationCount: number; - taterSprite?: React.ReactNode; -} - -type Tab = 'share' | 'diff'; - -export const ExportModal: React.FC = ({ - isOpen, - onClose, - shareUrl, - shareUrlSize, - diffOutput, - annotationCount, - taterSprite, -}) => { - const [activeTab, setActiveTab] = useState('share'); - const [copied, setCopied] = useState(false); - - if (!isOpen) return null; - - const handleCopyUrl = async () => { - try { - await navigator.clipboard.writeText(shareUrl); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (e) { - console.error('Failed to copy:', e); - } - }; - - const handleCopyDiff = async () => { - try { - await navigator.clipboard.writeText(diffOutput); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (e) { - console.error('Failed to copy:', e); - } - }; - - const handleDownloadDiff = () => { - const blob = new Blob([diffOutput], { type: 'text/plain' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'annotations.diff'; - a.click(); - URL.revokeObjectURL(url); - }; - - return ( -
-
e.stopPropagation()} - > - {taterSprite} - - {/* Header with tabs */} -
-
-

Export

-
- - {annotationCount} annotation{annotationCount !== 1 ? 's' : ''} - - -
-
- - {/* Tabs */} -
- - -
-
- - {/* Tab content */} -
- {activeTab === 'share' ? ( -
-
- -
-