Spaces:
Sleeping
Sleeping
Download befree-frontend/features/layout/LayoutReviewFeature.tsx from Coeinterns/bank-statement-api: direct link, hf CLI and curl.
- Browser
- Download file 33.1 kB
-
https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/befree-frontend/features/layout/LayoutReviewFeature.tsx
- Command line
-
hf download hf://spaces/Coeinterns/bank-statement-api/befree-frontend/features/layout/LayoutReviewFeature.tsx
-
curl -L -o LayoutReviewFeature.tsx https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/befree-frontend/features/layout/LayoutReviewFeature.tsx
33.1 kB
| 'use client'; | |
| import { useParams as useNextParams, useRouter as useNextRouter } from 'next/navigation'; | |
| import { useState, useEffect, useRef, useCallback } from 'react'; | |
| import { motion, AnimatePresence } from 'framer-motion'; | |
| import { | |
| useReviewSession, | |
| useLayout, | |
| useVerifyLayout, | |
| } from '@/hooks/useStatementAPI'; | |
| import { useToast } from '@/components/ui/use-toast'; | |
| import { Button } from '@/components/ui/button'; | |
| import { api } from '@/lib/api'; | |
| import { LoadingState, ErrorState } from '@/components/shared'; | |
| import { useBeFreeStore } from '@/store/befree-store'; | |
| import { | |
| Columns, | |
| Plus, | |
| Trash2, | |
| FileText, | |
| RefreshCw, | |
| HelpCircle, | |
| AlertCircle, | |
| ArrowRight, | |
| ChevronLeft, | |
| ChevronRight, | |
| ZoomIn, | |
| ZoomOut, | |
| Maximize2, | |
| } from 'lucide-react'; | |
| interface ColumnLayout { | |
| name: string; | |
| header_label: string; | |
| x_min: number; | |
| x_max: number; | |
| col_type: string; | |
| confidence: number; | |
| } | |
| // βββ Color tokens per column type ββββββββββββββββββββββββββββββββββββββββββββ | |
| const colConfig: Record<string, { bg: string; border: string; text: string; pill: string }> = { | |
| date: { bg: 'rgba(22,163,74,0.10)', border: '#16a34a', text: '#15803d', pill: '#dcfce7' }, | |
| description: { bg: 'rgba(37,99,235,0.10)', border: '#2563eb', text: '#1d4ed8', pill: '#dbeafe' }, | |
| debit: { bg: 'rgba(220,38,38,0.10)', border: '#dc2626', text: '#b91c1c', pill: '#fee2e2' }, | |
| credit: { bg: 'rgba(5,150,105,0.10)', border: '#059669', text: '#047857', pill: '#d1fae5' }, | |
| balance: { bg: 'rgba(217,119,6,0.10)', border: '#d97706', text: '#b45309', pill: '#fef3c7' }, | |
| amount: { bg: 'rgba(124,58,237,0.10)', border: '#7c3aed', text: '#6d28d9', pill: '#ede9fe' }, | |
| other: { bg: 'rgba(100,116,139,0.10)', border: '#64748b', text: '#475569', pill: '#f1f5f9' }, | |
| }; | |
| const getColConfig = (name: string) => colConfig[name] ?? colConfig.other; | |
| function FieldLabel({ children }: { children: React.ReactNode }) { | |
| return ( | |
| <label className="block text-[10px] font-semibold text-slate-400 uppercase tracking-widest mb-1.5"> | |
| {children} | |
| </label> | |
| ); | |
| } | |
| // βββ Dual-handle range slider for x_min / x_max ββββββββββββββββββββββββββββββ | |
| function BoundarySlider({ | |
| xMin, | |
| xMax, | |
| pageWidth, | |
| color, | |
| onChange, | |
| }: { | |
| xMin: number; | |
| xMax: number; | |
| pageWidth: number; | |
| color: string; | |
| onChange: (xMin: number, xMax: number) => void; | |
| }) { | |
| const trackRef = useRef<HTMLDivElement>(null); | |
| const dragging = useRef<'min' | 'max' | null>(null); | |
| const pct = (v: number) => Math.max(0, Math.min(100, (v / pageWidth) * 100)); | |
| const fromPct = (p: number) => Math.round(Math.max(0, Math.min(pageWidth, (p / 100) * pageWidth))); | |
| const getEventPct = (e: MouseEvent | TouchEvent) => { | |
| if (!trackRef.current) return 0; | |
| const rect = trackRef.current.getBoundingClientRect(); | |
| const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX; | |
| return Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100)); | |
| }; | |
| const startDrag = (handle: 'min' | 'max') => (e: React.MouseEvent | React.TouchEvent) => { | |
| e.preventDefault(); | |
| dragging.current = handle; | |
| const onMove = (ev: MouseEvent | TouchEvent) => { | |
| if (!dragging.current) return; | |
| const p = getEventPct(ev); | |
| const val = fromPct(p); | |
| if (dragging.current === 'min') { | |
| onChange(Math.min(val, xMax - 1), xMax); | |
| } else { | |
| onChange(xMin, Math.max(val, xMin + 1)); | |
| } | |
| }; | |
| const onUp = () => { | |
| dragging.current = null; | |
| window.removeEventListener('mousemove', onMove); | |
| window.removeEventListener('mouseup', onUp); | |
| window.removeEventListener('touchmove', onMove); | |
| window.removeEventListener('touchend', onUp); | |
| }; | |
| window.addEventListener('mousemove', onMove); | |
| window.addEventListener('mouseup', onUp); | |
| window.addEventListener('touchmove', onMove, { passive: false }); | |
| window.addEventListener('touchend', onUp); | |
| }; | |
| const leftPct = pct(xMin); | |
| const rightPct = pct(xMax); | |
| return ( | |
| <div className="space-y-1.5"> | |
| {/* Track */} | |
| <div | |
| ref={trackRef} | |
| className="relative h-5 flex items-center select-none" | |
| style={{ cursor: 'default' }} | |
| > | |
| {/* Rail */} | |
| <div className="absolute inset-x-0 h-2 bg-slate-100 rounded-full" /> | |
| {/* Active fill */} | |
| <div | |
| className="absolute h-2 rounded-full opacity-80" | |
| style={{ | |
| left: `${leftPct}%`, | |
| width: `${rightPct - leftPct}%`, | |
| backgroundColor: color, | |
| }} | |
| /> | |
| {/* Min handle */} | |
| <div | |
| onMouseDown={startDrag('min')} | |
| onTouchStart={startDrag('min')} | |
| className="absolute w-4 h-4 rounded-full border-2 border-white shadow-md cursor-ew-resize | |
| hover:scale-110 transition-transform z-10" | |
| style={{ | |
| left: `${leftPct}%`, | |
| transform: 'translateX(-50%)', | |
| backgroundColor: color, | |
| }} | |
| /> | |
| {/* Max handle */} | |
| <div | |
| onMouseDown={startDrag('max')} | |
| onTouchStart={startDrag('max')} | |
| className="absolute w-4 h-4 rounded-full border-2 border-white shadow-md cursor-ew-resize | |
| hover:scale-110 transition-transform z-10" | |
| style={{ | |
| left: `${rightPct}%`, | |
| transform: 'translateX(-50%)', | |
| backgroundColor: color, | |
| }} | |
| /> | |
| </div> | |
| {/* Numeric readout */} | |
| <div className="flex items-center justify-between text-[10px] text-slate-400 font-mono px-0.5"> | |
| <span className="text-slate-600 font-semibold">{xMin} pt</span> | |
| <span className="text-slate-300">ββββββββ</span> | |
| <span className="text-slate-600 font-semibold">{xMax} pt</span> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| // βββ Page navigator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| function PageNavigator({ | |
| page, | |
| totalPages, | |
| onChange, | |
| }: { | |
| page: number; | |
| totalPages: number; | |
| onChange: (p: number) => void; | |
| }) { | |
| const [editing, setEditing] = useState(false); | |
| const [draft, setDraft] = useState(String(page)); | |
| const clamp = (v: number) => Math.max(1, Math.min(totalPages, v)); | |
| const commit = () => { | |
| const n = parseInt(draft, 10); | |
| onChange(isNaN(n) ? page : clamp(n)); | |
| setEditing(false); | |
| }; | |
| return ( | |
| <div className="flex items-center gap-1"> | |
| <button | |
| disabled={page <= 1} | |
| onClick={() => onChange(page - 1)} | |
| className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 | |
| disabled:opacity-30 disabled:cursor-not-allowed transition" | |
| > | |
| <ChevronLeft className="w-3.5 h-3.5" /> | |
| </button> | |
| {editing ? ( | |
| <input | |
| autoFocus | |
| value={draft} | |
| onChange={(e) => setDraft(e.target.value)} | |
| onBlur={commit} | |
| onKeyDown={(e) => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') setEditing(false); }} | |
| className="w-10 text-center text-xs border border-indigo-400 rounded-lg py-1 focus:outline-none | |
| focus:ring-2 focus:ring-indigo-300 font-mono text-slate-800" | |
| /> | |
| ) : ( | |
| <button | |
| onClick={() => { setDraft(String(page)); setEditing(true); }} | |
| className="px-2.5 py-1 text-xs font-semibold text-slate-700 border border-slate-200 | |
| rounded-lg hover:border-indigo-300 hover:bg-indigo-50 transition font-mono min-w-[3rem] text-center" | |
| title="Click to type a page number" | |
| > | |
| {page} / {totalPages} | |
| </button> | |
| )} | |
| <button | |
| disabled={page >= totalPages} | |
| onClick={() => onChange(page + 1)} | |
| className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 | |
| disabled:opacity-30 disabled:cursor-not-allowed transition" | |
| > | |
| <ChevronRight className="w-3.5 h-3.5" /> | |
| </button> | |
| </div> | |
| ); | |
| } | |
| // βββ Main Feature βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export function LayoutReviewFeature() { | |
| const params = useNextParams(); | |
| const router = useNextRouter(); | |
| const statementId = params.statementId as string; | |
| const { toast } = useToast(); | |
| const { data: sessionData, isLoading: isSessionLoading } = useReviewSession(statementId); | |
| const { | |
| data: layoutData, | |
| isLoading: isLayoutLoading, | |
| refetch: refetchLayout, | |
| isError, | |
| } = useLayout(statementId); | |
| const verifyMutation = useVerifyLayout(statementId); | |
| const totalPdfPages = useBeFreeStore((s) => s.totalPdfPages); | |
| const setTotalPdfPages = useBeFreeStore((s) => s.setTotalPdfPages); | |
| const [columns, setColumns] = useState<ColumnLayout[]>([]); | |
| const [headerPage, setHeaderPage] = useState<number>(1); | |
| const [isVerifying, setIsVerifying] = useState(false); | |
| const [imageSrc, setImageSrc] = useState<string | null>(null); | |
| const [imageLoading, setImageLoading] = useState(true); | |
| const [imageError, setImageError] = useState(false); | |
| // zoom: 1 = fit-to-container (default), >1 = user zoomed in | |
| const [zoom, setZoom] = useState(1); | |
| const imgContainerRef = useRef<HTMLDivElement>(null); | |
| const initializedRef = useRef(false); | |
| const pageWidth = layoutData?.page_width || 612; | |
| const pageHeight = layoutData?.page_height || 792; | |
| const totalPages = totalPdfPages > 1 ? totalPdfPages : 1; | |
| // ββ Probe page count via GET ββββββββββββββββββββββββββββββββββββββββββββββ | |
| useEffect(() => { | |
| if (!statementId) return; | |
| if (totalPdfPages > 1) return; | |
| let cancelled = false; | |
| const probeExists = async (page: number): Promise<boolean> => { | |
| try { | |
| const res = await api.head(`/api/v1/statements/${statementId}/page-image/${page}`); | |
| return res.status === 200; | |
| } catch { | |
| return false; | |
| } | |
| }; | |
| const discoverPageCount = async () => { | |
| let hi = 1; | |
| while (!cancelled && (await probeExists(hi))) { | |
| hi *= 2; | |
| } | |
| if (cancelled) return; | |
| let lo = Math.max(1, hi / 2); | |
| while (!cancelled && lo < hi - 1) { | |
| const mid = Math.floor((lo + hi) / 2); | |
| if (await probeExists(mid)) { | |
| lo = mid; | |
| } else { | |
| hi = mid; | |
| } | |
| } | |
| if (!cancelled) { | |
| const discovered = lo; | |
| if (discovered > 1) setTotalPdfPages(discovered); | |
| } | |
| }; | |
| discoverPageCount(); | |
| return () => { cancelled = true; }; | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| }, [statementId]); | |
| // ββ Seed columns from layoutData ββββββββββββββββββββββββββββββββββββββββββ | |
| useEffect(() => { | |
| if (!layoutData) return; | |
| setColumns( | |
| (layoutData.columns || []).map((c: any) => ({ | |
| name: c.name || 'other', | |
| header_label: c.header_label || '', | |
| x_min: Math.round(c.x_min ?? 0), | |
| x_max: Math.round(c.x_max ?? 0), | |
| col_type: c.col_type || 'text', | |
| confidence: c.confidence ?? 1.0, | |
| })) | |
| ); | |
| setHeaderPage((layoutData.page_num ?? 0) + 1); | |
| if (layoutData.total_pages) setTotalPdfPages(layoutData.total_pages); | |
| initializedRef.current = true; | |
| }, [layoutData]); | |
| const handleRedetect = useCallback(() => { | |
| initializedRef.current = false; | |
| refetchLayout(); | |
| }, [refetchLayout]); | |
| // ββ Fetch page image βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| useEffect(() => { | |
| if (!statementId || !headerPage) return; | |
| let cancelled = false; | |
| const fetchImage = async () => { | |
| setImageLoading(true); | |
| setImageError(false); | |
| try { | |
| const res = await api.get<Blob>( | |
| `/api/v1/statements/${statementId}/page-image/${headerPage}`, | |
| { responseType: 'blob' } | |
| ); | |
| const objectUrl = URL.createObjectURL(res.data); | |
| if (!cancelled) { | |
| setImageSrc((prev) => { if (prev) URL.revokeObjectURL(prev); return objectUrl; }); | |
| setZoom(1); | |
| } | |
| } catch (err) { | |
| console.error('Page image fetch failed:', err); | |
| if (!cancelled) setImageError(true); | |
| } finally { | |
| if (!cancelled) setImageLoading(false); | |
| } | |
| }; | |
| fetchImage(); | |
| return () => { cancelled = true; }; | |
| }, [statementId, headerPage]); | |
| useEffect(() => { | |
| return () => { setImageSrc((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); }; | |
| }, []); | |
| // ββ Guards ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if (isSessionLoading || isLayoutLoading) { | |
| return <LoadingState message="Analyzing statement layout and coordinatesβ¦" />; | |
| } | |
| if (isError || !layoutData) { | |
| return ( | |
| <ErrorState | |
| title="Failed to load layout detection" | |
| message="Could not analyze the layout for this statement. Please retry." | |
| onRetry={handleRedetect} | |
| /> | |
| ); | |
| } | |
| // ββ Column helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const handleAddColumn = () => { | |
| setColumns((prev) => [ | |
| ...prev, | |
| { name: 'other', header_label: 'New Column', x_min: 0, x_max: 100, col_type: 'text', confidence: 1.0 }, | |
| ]); | |
| }; | |
| const handleRemoveColumn = (index: number) => { | |
| setColumns((prev) => prev.filter((_, i) => i !== index)); | |
| }; | |
| const handleColumnChange = (index: number, fields: Partial<ColumnLayout>) => { | |
| setColumns((prev) => { | |
| const next = [...prev]; | |
| next[index] = { ...next[index], ...fields }; | |
| return next; | |
| }); | |
| }; | |
| // ββ Verify ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const handleVerify = async () => { | |
| if (columns.length === 0) { | |
| toast({ title: 'Validation Error', description: 'Configure at least one column.', variant: 'destructive' }); | |
| return; | |
| } | |
| if (columns.some((c) => c.x_min >= c.x_max)) { | |
| toast({ title: 'Invalid Boundaries', description: 'Each column must have x_min < x_max.', variant: 'destructive' }); | |
| return; | |
| } | |
| try { | |
| setIsVerifying(true); | |
| await verifyMutation.mutateAsync({ | |
| columns: columns.map((c) => ({ | |
| name: c.name, header_label: c.header_label, | |
| x_min: Number(c.x_min), x_max: Number(c.x_max), | |
| col_type: c.col_type, confidence: c.confidence, | |
| })), | |
| header_page: Number(headerPage) - 1, | |
| }); | |
| toast({ title: 'Re-extraction started', description: 'Processing with updated column layoutβ¦', variant: 'success' }); | |
| router.push(`/processing/${statementId}`); | |
| } catch (err: any) { | |
| setIsVerifying(false); | |
| toast({ title: 'Re-extraction Failed', description: err?.message || 'Could not start re-extraction.', variant: 'destructive' }); | |
| } | |
| }; | |
| const zoomStep = 0.25; | |
| const minZoom = 0.5; | |
| const maxZoom = 3; | |
| // ββ Render βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| return ( | |
| <div className="h-full w-full flex flex-col bg-slate-50 font-sans overflow-hidden text-slate-800" style={{ minWidth: 0 }}> | |
| {/* ββ Header βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */} | |
| <header className="bg-white border-b border-slate-200 px-6 py-3 flex items-center justify-between z-20 shadow-sm"> | |
| <div className="flex items-center gap-3"> | |
| <div className="bg-indigo-50 p-2 rounded-lg border border-indigo-100"> | |
| <Columns className="w-4 h-4 text-indigo-600" /> | |
| </div> | |
| <div> | |
| <h1 className="text-sm font-bold text-slate-900 tracking-tight leading-tight"> | |
| Re-extract with Custom Layout | |
| </h1> | |
| <p className="text-xs text-slate-400 truncate max-w-sm mt-0.5"> | |
| Adjust column boundaries then re-run extraction Β· {sessionData?.fileName || 'Loadingβ¦'} | |
| </p> | |
| </div> | |
| </div> | |
| <div className="flex items-center gap-2"> | |
| <Button | |
| variant="outline" size="sm" | |
| onClick={() => router.back()} | |
| className="border-slate-200 text-slate-600 hover:bg-slate-50 flex items-center gap-1.5 text-xs font-medium" | |
| > | |
| <ChevronLeft className="w-3.5 h-3.5" /> Back to Review | |
| </Button> | |
| <Button | |
| variant="outline" size="sm" onClick={handleRedetect} | |
| className="border-slate-200 text-slate-600 hover:bg-slate-50 flex items-center gap-1.5 text-xs font-medium" | |
| > | |
| <RefreshCw className="w-3.5 h-3.5" /> Re-detect | |
| </Button> | |
| <Button | |
| onClick={handleVerify} disabled={isVerifying} | |
| className="bg-indigo-600 hover:bg-indigo-700 text-white flex items-center gap-1.5 | |
| text-xs font-semibold px-4 shadow-sm shadow-indigo-200 disabled:opacity-60" | |
| > | |
| <RefreshCw className="w-3.5 h-3.5" /> Re-extract <ArrowRight className="w-3 h-3" /> | |
| </Button> | |
| </div> | |
| </header> | |
| {/* ββ Workspace ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */} | |
| <div className="flex-1 flex overflow-hidden relative"> | |
| {/* Full-screen verifying overlay */} | |
| <AnimatePresence> | |
| {isVerifying && ( | |
| <motion.div | |
| initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} | |
| className="absolute inset-0 bg-white/80 z-30 flex items-center justify-center backdrop-blur-sm" | |
| > | |
| <div className="flex flex-col items-center gap-4 bg-white rounded-2xl border border-slate-200 | |
| shadow-xl px-10 py-8"> | |
| <div className="w-9 h-9 rounded-full border-4 border-indigo-100 border-t-indigo-500 animate-spin" /> | |
| <div className="text-center"> | |
| <h3 className="font-bold text-slate-900 text-sm">Re-extractingβ¦</h3> | |
| <p className="text-xs text-slate-400 mt-1">Processing with updated column boundaries</p> | |
| </div> | |
| </div> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| {/* ββ LEFT: PDF viewer βββββββββββββββββββββββββββββββββββββββββββββββ */} | |
| <div className="w-[48%] min-w-0 h-full flex flex-col border-r border-slate-200 bg-slate-100"> | |
| {/* Viewer toolbar */} | |
| <div className="flex items-center justify-between px-4 py-2 bg-white border-b border-slate-200 shrink-0"> | |
| {/* Page navigation */} | |
| <PageNavigator | |
| page={headerPage} | |
| totalPages={totalPages} | |
| onChange={(p) => setHeaderPage(p)} | |
| /> | |
| {/* Zoom controls */} | |
| <div className="flex items-center gap-1"> | |
| <button | |
| onClick={() => setZoom((z) => Math.max(minZoom, +(z - zoomStep).toFixed(2)))} | |
| disabled={zoom <= minZoom} | |
| className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 | |
| disabled:opacity-30 disabled:cursor-not-allowed transition" | |
| title="Zoom out" | |
| > | |
| <ZoomOut className="w-3.5 h-3.5" /> | |
| </button> | |
| <button | |
| onClick={() => setZoom(1)} | |
| className="px-2 py-1 text-[11px] font-semibold text-slate-600 border border-slate-200 | |
| rounded-lg hover:bg-slate-50 transition min-w-[3rem] text-center font-mono" | |
| title="Reset zoom" | |
| > | |
| {Math.round(zoom * 100)}% | |
| </button> | |
| <button | |
| onClick={() => setZoom((z) => Math.min(maxZoom, +(z + zoomStep).toFixed(2)))} | |
| disabled={zoom >= maxZoom} | |
| className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 | |
| disabled:opacity-30 disabled:cursor-not-allowed transition" | |
| title="Zoom in" | |
| > | |
| <ZoomIn className="w-3.5 h-3.5" /> | |
| </button> | |
| <button | |
| onClick={() => setZoom(1)} | |
| className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 transition ml-0.5" | |
| title="Fit to view" | |
| > | |
| <Maximize2 className="w-3.5 h-3.5" /> | |
| </button> | |
| </div> | |
| </div> | |
| {/* Scrollable image area */} | |
| <div | |
| ref={imgContainerRef} | |
| className="flex-1 overflow-auto" | |
| style={{ cursor: zoom > 1 ? 'grab' : 'default' }} | |
| > | |
| {imageLoading ? ( | |
| <div className="flex flex-col items-center gap-3 text-slate-400 mt-20"> | |
| <div className="w-7 h-7 rounded-full border-2 border-indigo-400 border-t-transparent animate-spin" /> | |
| <span className="text-xs">Rendering pageβ¦</span> | |
| </div> | |
| ) : imageError || !imageSrc ? ( | |
| <div className="flex flex-col items-center gap-2 text-slate-400 mt-20"> | |
| <AlertCircle className="w-8 h-8 text-rose-400" /> | |
| <span className="text-xs text-slate-500">Failed to load page image.</span> | |
| <button | |
| onClick={() => setHeaderPage((p) => { const cur = p; setHeaderPage(0); setTimeout(() => setHeaderPage(cur), 50); return p; })} | |
| className="text-xs text-indigo-600 hover:underline mt-1" | |
| > | |
| Retry | |
| </button> | |
| </div> | |
| ) : ( | |
| <div className="p-4 flex flex-col items-center" style={{ minWidth: 0 }}> | |
| <div style={{ | |
| width: '100%', | |
| height: 0, | |
| paddingBottom: `${(zoom - 1) * 50}%`, | |
| }} /> | |
| <div | |
| style={{ | |
| transform: `scale(${zoom})`, | |
| transformOrigin: 'top center', | |
| width: '100%', | |
| maxWidth: `${pageWidth}px`, | |
| }} | |
| > | |
| <div | |
| className="relative shadow-xl border border-slate-200 rounded-lg bg-white overflow-hidden" | |
| style={{ | |
| aspectRatio: `${pageWidth} / ${pageHeight}`, | |
| width: '100%', | |
| }} | |
| > | |
| <img | |
| src={imageSrc} | |
| alt={`Page ${headerPage}`} | |
| className="w-full h-full object-contain select-none pointer-events-none block" | |
| draggable={false} | |
| /> | |
| {/* Column overlays */} | |
| {columns.map((col, idx) => { | |
| const leftPct = Math.max(0, (col.x_min / pageWidth) * 100); | |
| const widthPct = Math.max(0.3, ((col.x_max - col.x_min) / pageWidth) * 100); | |
| const cfg = getColConfig(col.name); | |
| return ( | |
| <div | |
| key={idx} | |
| className="absolute top-0 bottom-0 border-l border-r pointer-events-none | |
| flex flex-col justify-start pt-1.5 px-0.5" | |
| style={{ | |
| left: `${leftPct}%`, | |
| width: `${widthPct}%`, | |
| backgroundColor: cfg.bg, | |
| borderColor: cfg.border, | |
| }} | |
| > | |
| <div | |
| className="text-[7px] font-bold px-1 py-0.5 rounded text-white shadow truncate | |
| max-w-full text-center leading-tight" | |
| style={{ backgroundColor: cfg.border }} | |
| > | |
| {col.name} | |
| </div> | |
| </div> | |
| ); | |
| })} | |
| </div> | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| </div> | |
| {/* ββ RIGHT: Editor βββββββββββββββββββββββββββββββββββββββββββββββββββ */} | |
| <div className="w-[52%] min-w-0 h-full flex flex-col overflow-y-auto bg-white"> | |
| <div className="max-w-2xl w-full mx-auto px-7 py-6 space-y-6 pb-16"> | |
| {/* Guide */} | |
| <div className="bg-indigo-50 border border-indigo-100 rounded-xl p-4 flex gap-3"> | |
| <HelpCircle className="w-4 h-4 text-indigo-500 shrink-0 mt-0.5" /> | |
| <p className="text-xs text-indigo-700 leading-relaxed"> | |
| Drag the <strong>handles</strong> on each column's range slider to adjust boundaries, | |
| then click <strong>Re-extract</strong> to re-run extraction with the updated layout. | |
| Column highlights on the page update in real-time. | |
| </p> | |
| </div> | |
| {/* Columns */} | |
| <section className="space-y-3"> | |
| <div className="flex items-center justify-between"> | |
| <div className="flex items-center gap-2"> | |
| <FileText className="w-3.5 h-3.5 text-indigo-500" /> | |
| <h3 className="text-[11px] font-bold text-slate-500 uppercase tracking-widest"> | |
| Column Ranges | |
| <span className="ml-2 text-indigo-600 font-semibold normal-case tracking-normal"> | |
| ({columns.length}) | |
| </span> | |
| </h3> | |
| </div> | |
| <Button | |
| onClick={handleAddColumn} size="sm" variant="outline" | |
| className="border-indigo-200 text-indigo-600 hover:bg-indigo-50 flex items-center gap-1 text-xs font-semibold" | |
| > | |
| <Plus className="w-3.5 h-3.5" /> Add Column | |
| </Button> | |
| </div> | |
| {columns.length === 0 && ( | |
| <div className="text-center py-10 text-slate-400 bg-slate-50 rounded-xl border | |
| border-dashed border-slate-200 text-xs"> | |
| No columns yet β click <strong>Add Column</strong> to begin. | |
| </div> | |
| )} | |
| <div className="space-y-3"> | |
| {columns.map((col, idx) => { | |
| const cfg = getColConfig(col.name); | |
| const hasError = col.x_min >= col.x_max; | |
| return ( | |
| <motion.div | |
| key={idx} | |
| initial={{ opacity: 0, y: 6 }} | |
| animate={{ opacity: 1, y: 0 }} | |
| exit={{ opacity: 0, y: -4 }} | |
| transition={{ duration: 0.15 }} | |
| className={`bg-white border rounded-xl p-4 shadow-sm transition-colors | |
| ${hasError ? 'border-rose-300 bg-rose-50/40' : 'border-slate-200 hover:border-slate-300'}`} | |
| > | |
| {/* Row 1: type + label + delete */} | |
| <div className="flex items-end gap-3 mb-3"> | |
| <div className="w-[22%]"> | |
| <FieldLabel>Type</FieldLabel> | |
| <select | |
| value={col.name} | |
| onChange={(e) => handleColumnChange(idx, { name: e.target.value })} | |
| className="w-full bg-white border border-slate-200 rounded-lg px-2 py-1.5 | |
| text-xs text-slate-800 font-semibold focus:outline-none focus:ring-2 | |
| focus:ring-indigo-400 cursor-pointer transition" | |
| style={{ borderLeft: `3px solid ${cfg.border}` }} | |
| > | |
| {Object.keys(colConfig).map((k) => ( | |
| <option key={k} value={k}>{k}</option> | |
| ))} | |
| </select> | |
| </div> | |
| <div className="flex-1"> | |
| <FieldLabel>Header Label</FieldLabel> | |
| <input | |
| type="text" | |
| value={col.header_label} | |
| onChange={(e) => handleColumnChange(idx, { header_label: e.target.value })} | |
| className="w-full bg-white border border-slate-200 rounded-lg px-2.5 py-1.5 | |
| text-xs text-slate-800 focus:outline-none focus:ring-2 | |
| focus:ring-indigo-400 transition hover:border-slate-300" | |
| /> | |
| </div> | |
| <div className="pb-0.5"> | |
| <button | |
| onClick={() => handleRemoveColumn(idx)} | |
| className="p-1.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 rounded-lg transition-colors" | |
| > | |
| <Trash2 className="w-4 h-4" /> | |
| </button> | |
| </div> | |
| </div> | |
| {/* Row 2: boundary slider */} | |
| <div> | |
| <FieldLabel>Column Boundaries (drag handles)</FieldLabel> | |
| {hasError && ( | |
| <p className="text-[10px] text-rose-500 font-medium mb-1.5 flex items-center gap-1"> | |
| <AlertCircle className="w-3 h-3" /> x_min must be less than x_max | |
| </p> | |
| )} | |
| <BoundarySlider | |
| xMin={col.x_min} | |
| xMax={col.x_max} | |
| pageWidth={pageWidth} | |
| color={hasError ? '#f87171' : cfg.border} | |
| onChange={(xMin, xMax) => handleColumnChange(idx, { x_min: xMin, x_max: xMax })} | |
| /> | |
| </div> | |
| {/* Row 3: pill badge */} | |
| <div className="mt-3"> | |
| <span | |
| className="inline-flex items-center text-[10px] font-semibold px-2 py-0.5 rounded-full" | |
| style={{ backgroundColor: cfg.pill, color: cfg.text }} | |
| > | |
| {col.name} | |
| </span> | |
| </div> | |
| </motion.div> | |
| ); | |
| })} | |
| </div> | |
| </section> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| } |