Compare commits

..
Author SHA1 Message Date
kcar d4a1d29298 chore: preserve app workspace t_61fb4c27_clone 2026-08-09 20:24:44 +01:00
4 changed files with 246 additions and 102 deletions
+60
View File
@@ -0,0 +1,60 @@
const { chromium } = require('playwright');
const fs = require('fs');
const BASE = process.env.PLAYWRIGHT_BASE_URL || 'http://192.168.0.251:13000';
const EMAIL = process.env.VITE_TEST_TEACHER_EMAIL || '[email protected]';
const PASSWORD = process.env.VITE_TEST_TEACHER_PASSWORD || process.env.SEED_TEACHER_PASSWORD;
const TEMPLATE_ID = process.env.TEMPLATE_ID || '31d92cf3-9bbd-4a7e-b2dc-b37f8b69bc34';
const OUT = process.env.OUT || '/out';
async function run(mode) {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ colorScheme: mode, viewport: { width: 1440, height: 980 } });
const page = await context.newPage();
const messages = [];
page.on('console', msg => messages.push(`${msg.type()}: ${msg.text()}`));
page.on('pageerror', err => messages.push(`pageerror: ${err.message}`));
await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' });
if (await page.getByLabel('Email').count()) {
if (!PASSWORD) throw new Error('missing password env');
await page.getByLabel('Email').fill(EMAIL);
await page.getByLabel('Password').fill(PASSWORD);
await page.getByRole('button', { name: 'Login' }).click();
await page.waitForURL(url => /\/dashboard|\/exam-marker|\/node\//.test(url.pathname), { timeout: 20000 });
}
await page.goto(`${BASE}/exam-marker/${TEMPLATE_ID}/setup`, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-testid="exam-template-setup-canvas"]', { timeout: 20000 });
await page.waitForTimeout(3500);
const text = await page.locator('body').innerText();
const checks = {
hasBoundaryTool: text.includes('Boundary'),
hasPartTool: text.includes('Part'),
hasResponseTool: text.includes('Response'),
hasContextTool: text.includes('Context'),
hasQuestionNumberTool: text.includes('Q Number'),
hasMarkAreaTool: text.includes('Mark Area'),
hasReferenceTool: text.includes('Reference'),
hasFurnitureTool: text.includes('Furniture'),
hasHintPanel: text.includes('Setup guide') && text.includes('Boundary pairing preview'),
hasMultiPageCopy: text.includes('later page') || text.includes('multi-page'),
hasPdfStatus: text.includes('PDF backdrop:'),
crashOverlay: text.includes('Template setup canvas crashed'),
};
await page.screenshot({ path: `${OUT}/s4-9c-${mode}.png`, fullPage: true });
await browser.close();
return { mode, url: `${BASE}/exam-marker/${TEMPLATE_ID}/setup`, checks, consoleMessages: messages };
}
(async () => {
fs.mkdirSync(OUT, { recursive: true });
const results = [];
for (const mode of ['light', 'dark']) results.push(await run(mode));
fs.writeFileSync(`${OUT}/s4-9c-smoke.json`, JSON.stringify(results, null, 2));
const failures = results.flatMap(r => Object.entries(r.checks).filter(([k,v]) => k === 'crashOverlay' ? v : !v).map(([k]) => `${r.mode}:${k}`));
const consoleErrors = results.flatMap(r => r.consoleMessages.filter(m => /^(error|pageerror):/i.test(m) && !/Failed to load resource/i.test(m)));
console.log(JSON.stringify({ results, failures, consoleErrors }, null, 2));
if (failures.length || consoleErrors.length) process.exit(1);
})().catch(err => { console.error(err); process.exit(1); });
+159 -45
View File
@@ -5,6 +5,14 @@ import { Alert, Box, Button, Chip, CircularProgress, Divider, Paper, Snackbar, S
import ArrowBackIcon from '@mui/icons-material/ArrowBack'
import SaveIcon from '@mui/icons-material/Save'
import MouseIcon from '@mui/icons-material/Mouse'
import HorizontalRuleIcon from '@mui/icons-material/HorizontalRule'
import CropSquareIcon from '@mui/icons-material/CropSquare'
import EditNoteIcon from '@mui/icons-material/EditNote'
import VisibilityIcon from '@mui/icons-material/Visibility'
import TagIcon from '@mui/icons-material/Tag'
import GradingIcon from '@mui/icons-material/Grading'
import AttachFileIcon from '@mui/icons-material/AttachFile'
import HideSourceIcon from '@mui/icons-material/HideSource'
import '@tldraw/tldraw/tldraw.css'
import { Editor, Tldraw, createShapeId, TLShape } from '@tldraw/tldraw'
import axios from 'axios'
@@ -13,20 +21,20 @@ import { ErrorBoundary } from '../../../components/ErrorBoundary'
import { logger } from '../../../debugConfig'
import { examRepository } from '../../../services/exam/examRepository'
import type { ExamTemplateDetail } from '../../../types/exam.types'
import { CanvasPageGeometry, ExamCanvasShapeModel, PAGE_HEIGHT, PAGE_WIDTH, isUuid, newDomainId, serializeCanvasShapes, shapesFromTemplate } from '../../../utils/exam-canvas/model'
import { PDF_PAGE_SHAPE_TYPE, canvasShapePalette, examCanvasShapeUtils, examCanvasTools, ExamCanvasTLShape, SHAPE_TYPES, isPdfPageShape, shapeTypeToKind } from './examCanvasShapes'
import { CanvasPageGeometry, ExamCanvasShapeModel, PAGE_HEIGHT, PAGE_WIDTH, isUuid, newDomainId, pageForY, serializeCanvasShapes, shapesFromTemplate } from '../../../utils/exam-canvas/model'
import { PDF_PAGE_SHAPE_TYPE, examCanvasShapeUtils, examCanvasTools, ExamCanvasTLShape, SHAPE_TYPES, isPdfPageShape, shapeTypeToKind } from './examCanvasShapes'
import { loadPdfPageImages, PdfPageImage } from './pdfLoader'
const TOOLS = [
{ id: 'select', label: 'Select', icon: '↖', tip: 'Move, resize, delete, or inspect the Attached pill on a region.', color: 'inherit' as const },
{ id: SHAPE_TYPES.boundary, label: 'Boundary', icon: canvasShapePalette.boundary.icon, tip: 'Draw Q start and Q end horizontal rules; an end rule on a later page creates a multi-page question span.', color: 'error' as const },
{ id: SHAPE_TYPES.part, label: 'Part', icon: canvasShapePalette.part.icon, tip: 'Draw the markable sub-question box inside a boundary pair; it becomes the leaf question/part.', color: 'warning' as const },
{ id: SHAPE_TYPES.response, label: 'Response', icon: canvasShapePalette.response.icon, tip: 'Draw around where the student writes; blue regions save as response areas.', color: 'primary' as const },
{ id: SHAPE_TYPES.context, label: 'Context', icon: canvasShapePalette.context.icon, tip: 'Draw stimulus, figures, tables, or prompt text; purple dashed regions save as context.', color: 'secondary' as const },
{ id: SHAPE_TYPES.question_number, label: 'Q Number', icon: canvasShapePalette.question_number.icon, tip: 'Box the printed question number for OCR/structure extraction.', color: 'success' as const },
{ id: SHAPE_TYPES.mark_area, label: 'Mark Area', icon: canvasShapePalette.mark_area.icon, tip: 'Box printed marks such as [2] or Total for Question text.', color: 'success' as const },
{ id: SHAPE_TYPES.reference, label: 'Reference', icon: canvasShapePalette.reference.icon, tip: 'Box formulae, data sheets, appendices, or other resources the student may use.', color: 'info' as const },
{ id: SHAPE_TYPES.furniture, label: 'Furniture', icon: canvasShapePalette.furniture.icon, tip: 'Mark page numbers, margins, blank space, or decoration to exclude from extraction.', color: 'inherit' as const },
{ id: 'select', label: 'Select', tip: 'Move, resize, delete, or inspect attachment pills.', color: 'inherit' as const, icon: <MouseIcon fontSize="small" /> },
{ id: SHAPE_TYPES.boundary, label: 'Boundary', tip: 'Place a top line, then a bottom line; the bottom can be on a later PDF page for multi-page questions.', color: 'error' as const, icon: <HorizontalRuleIcon fontSize="small" /> },
{ id: SHAPE_TYPES.part, label: 'Part', tip: 'Draw the markable sub-question box inside a boundary pair.', color: 'warning' as const, icon: <CropSquareIcon fontSize="small" /> },
{ id: SHAPE_TYPES.response, label: 'Response', tip: 'Draw around where the student writes; saved with response_form=lines.', color: 'primary' as const, icon: <EditNoteIcon fontSize="small" /> },
{ id: SHAPE_TYPES.context, label: 'Context', tip: 'Draw around stimulus/context material; saved with context_type=generic.', color: 'secondary' as const, icon: <VisibilityIcon fontSize="small" /> },
{ id: SHAPE_TYPES.question_number, label: 'Q Number', tip: 'Box the printed question number for OCR and template checking.', color: 'success' as const, icon: <TagIcon fontSize="small" /> },
{ id: SHAPE_TYPES.mark_area, label: 'Mark Area', tip: 'Box printed marks such as [2] or Total for Question X.', color: 'success' as const, icon: <GradingIcon fontSize="small" /> },
{ id: SHAPE_TYPES.reference, label: 'Reference', tip: 'Box formula sheets, data sheets, appendices, or other student resources.', color: 'info' as const, icon: <AttachFileIcon fontSize="small" /> },
{ id: SHAPE_TYPES.furniture, label: 'Furniture', tip: 'Mark margins, page numbers, blank extra space, or decoration to ignore.', color: 'inherit' as const, icon: <HideSourceIcon fontSize="small" /> },
]
const PAGE_START_X = 260
@@ -121,15 +129,35 @@ function syncPdfPages(editor: Editor, pages: PdfPageImage[]) {
try { editor.sendToBack(ids as any) } catch { /* tldraw 3 keeps creation order behind later region shapes */ }
}
type BoundaryPairSummary = { index: number; label: string; startPage: number; endPage: number; multiPage: boolean }
function boundaryPairSummaries(editor: Editor | null, pages: CanvasPageGeometry[]): BoundaryPairSummary[] {
if (!editor) return []
const boundaries = editor.getCurrentPageShapes()
.map(modelFromTLShape)
.filter((shape): shape is ExamCanvasShapeModel => shape?.kind === 'boundary')
.sort((a, b) => (pageForY(a.y + a.h / 2, pages) - pageForY(b.y + b.h / 2, pages)) || (a.y - b.y))
const summaries: BoundaryPairSummary[] = []
for (let i = 0; i < boundaries.length; i += 2) {
const top = boundaries[i]
const bottom = boundaries[i + 1]
if (!top || !bottom) break
const startPage = pageForY(top.y + top.h / 2, pages)
const endPage = pageForY(bottom.y + bottom.h / 2, pages)
const label = top.label?.replace(/\s+(start|end)$/i, '') || bottom.label?.replace(/\s+(start|end)$/i, '') || `Q${summaries.length + 1}`
summaries.push({ index: summaries.length + 1, label, startPage, endPage, multiPage: startPage !== endPage })
}
return summaries
}
function seedGuide(editor: Editor) {
const current = editor.getCurrentPageShapes().filter((s) => shapeTypeToKind(s.type))
if (current.length) return
editor.createShapes([
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.boundary, x: 48, y: 120, props: { w: PAGE_WIDTH - 96, h: 8, kind: 'boundary', label: 'Q1 start', domainId: newDomainId() } },
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.boundary, x: 48, y: PAGE_HEIGHT + 160, props: { w: PAGE_WIDTH - 96, h: 8, kind: 'boundary', label: 'Q1 end (page 2)', domainId: newDomainId() } },
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.boundary, x: 48, y: 520, props: { w: PAGE_WIDTH - 96, h: 8, kind: 'boundary', label: 'Q1 end', domainId: newDomainId() } },
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.part, x: 92, y: 180, props: { w: 520, h: 150, kind: 'part', label: 'Q1(a)', maxMarks: 3, domainId: newDomainId() } },
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.response, x: 116, y: 355, props: { w: 470, h: 120, kind: 'response', label: 'Response', responseForm: 'lines', domainId: newDomainId() } },
{ id: createShapeId(newDomainId()), type: SHAPE_TYPES.context, x: 116, y: 495, props: { w: 470, h: 90, kind: 'context', label: 'Context', contextType: 'generic', domainId: newDomainId() } },
])
}
@@ -148,6 +176,11 @@ const ExamTemplateSetupInner: React.FC = () => {
const [activeTool, setActiveTool] = useState('select')
const [pdfStatus, setPdfStatus] = useState<'loading' | 'ready' | 'missing' | 'error'>('loading')
const [pdfError, setPdfError] = useState<string | null>(null)
const [boundaryPairs, setBoundaryPairs] = useState<BoundaryPairSummary[]>([])
const refreshBoundaryPairs = useCallback(() => {
setBoundaryPairs(boundaryPairSummaries(editorRef.current, pageGeometriesRef.current))
}, [])
const load = useCallback(async () => {
if (!templateId) return
@@ -160,21 +193,7 @@ const ExamTemplateSetupInner: React.FC = () => {
setPdfError(null)
try {
const bytes = await examRepository.getTemplateSourcePdf(templateId)
pages = await loadPdfPageImages(bytes, undefined, (partialPages) => {
const newPage = partialPages[partialPages.length - 1]
const allGeometries = pageGeometryFromImages(partialPages)
pageGeometriesRef.current = allGeometries
const ed = editorRef.current
if (ed) {
const geometry = allGeometries[partialPages.length - 1]
const shapeId = createShapeId(PDF_PAGE_IDS_PREFIX + newPage.pageNumber)
if (!ed.getCurrentPageShapes().find((s) => s.id === shapeId)) {
ed.createShapes([{ id: shapeId, type: PDF_PAGE_SHAPE_TYPE, x: geometry.x, y: geometry.y, isLocked: true, props: { w: geometry.w, h: geometry.h, src: newPage.src, pageNumber: newPage.pageNumber } } as any])
try { ed.sendToBack([shapeId as any]) } catch { /* */ }
}
}
setPdfStatus('ready')
})
pages = await loadPdfPageImages(bytes)
setPdfStatus(pages.length ? 'ready' : 'missing')
} catch (pdfErr) {
const pdfMsg = apiMessage(pdfErr).message
@@ -188,6 +207,9 @@ const ExamTemplateSetupInner: React.FC = () => {
if (editor) {
syncPdfPages(editor, pages)
loadShapes(editor, shapesFromTemplate(detail, geometries))
setBoundaryPairs(boundaryPairSummaries(editor, geometries))
} else {
setBoundaryPairs([])
}
setDirty(false)
} catch (e) {
@@ -197,7 +219,7 @@ const ExamTemplateSetupInner: React.FC = () => {
} finally {
setLoading(false)
}
}, [templateId])
}, [templateId, refreshBoundaryPairs])
useEffect(() => { void load() }, [load])
@@ -212,6 +234,7 @@ const ExamTemplateSetupInner: React.FC = () => {
const saved = await examRepository.replaceTemplate(templateId, payload)
setTemplate(saved)
loadShapes(editor, shapesFromTemplate(saved, pageGeometriesRef.current))
refreshBoundaryPairs()
setDirty(false)
} catch (e) {
const msg = apiMessage(e)
@@ -220,7 +243,7 @@ const ExamTemplateSetupInner: React.FC = () => {
} finally {
setSaving(false)
}
}, [template, templateId])
}, [template, templateId, refreshBoundaryPairs])
const toolButtons = useMemo(() => TOOLS.map((tool) => (
<Tooltip title={tool.tip} key={tool.id} placement="right">
@@ -228,7 +251,7 @@ const ExamTemplateSetupInner: React.FC = () => {
size="small"
variant={activeTool === tool.id ? 'contained' : 'outlined'}
color={tool.color}
startIcon={tool.id === 'select' ? <MouseIcon fontSize="small" /> : <Box component="span" sx={{ minWidth: 22, textAlign: 'center', fontWeight: 900 }}>{tool.icon}</Box>}
startIcon={tool.icon}
onClick={() => {
const editor = editorRef.current
if (!editor) return
@@ -242,9 +265,93 @@ const ExamTemplateSetupInner: React.FC = () => {
</Tooltip>
)), [activeTool])
const canvasCss = {
'& .tlui-layout': { display: 'none' },
'& .exam-canvas-shape': {
width: '100%',
height: '100%',
boxSizing: 'border-box',
position: 'relative',
border: '2px var(--exam-shape-border-style) var(--exam-shape-stroke)',
borderRadius: 'var(--exam-shape-radius)',
background: 'var(--exam-shape-fill)',
color: 'var(--exam-shape-stroke)',
fontFamily: 'Inter, system-ui, sans-serif',
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
gap: 0.75,
padding: 1,
boxShadow: '0 10px 22px rgba(15,23,42,0.10)',
overflow: 'hidden',
},
'& .exam-canvas-shape--boundary': {
alignItems: 'center',
justifyContent: 'center',
height: '100%',
minHeight: 8,
padding: '0 64px',
background: 'transparent',
boxShadow: 'none',
},
'& .exam-canvas-shape__main-label': {
fontSize: 12,
fontWeight: 900,
textTransform: 'uppercase',
letterSpacing: 0.6,
background: 'rgba(255,255,255,0.90)',
border: '1px solid rgba(15,23,42,0.12)',
borderRadius: 999,
padding: '2px 8px',
display: 'inline-flex',
alignItems: 'center',
gap: 0.5,
lineHeight: 1.2,
},
'& .exam-canvas-shape__icon': { minWidth: 14, textAlign: 'center' },
'& .exam-canvas-shape__badge': {
fontSize: 10,
fontWeight: 800,
letterSpacing: 0.7,
textTransform: 'uppercase',
background: 'rgba(255,255,255,0.68)',
borderRadius: 999,
padding: '2px 7px',
color: 'inherit',
},
'& .exam-canvas-shape__endcap': {
position: 'absolute',
top: '50%',
transform: 'translateY(-50%)',
fontSize: 11,
fontWeight: 900,
borderRadius: 999,
padding: '1px 7px',
background: 'var(--exam-shape-stroke)',
color: '#fff',
boxShadow: '0 2px 8px rgba(0,0,0,0.16)',
},
'& .exam-canvas-shape__endcap--left': { left: 6 },
'& .exam-canvas-shape__endcap--right': { right: 6 },
...(theme.palette.mode === 'dark' ? {
'& .exam-canvas-shape': {
borderColor: 'var(--exam-shape-stroke-dark)',
background: 'var(--exam-shape-fill-dark)',
color: 'var(--exam-shape-stroke-dark)',
boxShadow: '0 10px 22px rgba(0,0,0,0.28)',
},
'& .exam-canvas-shape--boundary': { background: 'transparent', boxShadow: 'none' },
'& .exam-canvas-shape__main-label, & .exam-canvas-shape__badge': {
background: 'rgba(15,23,42,0.84)',
borderColor: 'rgba(255,255,255,0.16)',
},
'& .exam-canvas-shape__endcap': { background: 'var(--exam-shape-stroke-dark)', color: '#0f172a' },
} : {}),
}
return (
<Box sx={{ position: 'fixed', inset: 0, zIndex: (t) => t.zIndex.drawer + 20, bgcolor: 'background.default' }}>
<Box sx={{ position: 'absolute', inset: 0, '& .tlui-layout': { display: 'none' } }} data-testid="exam-template-setup-canvas">
<Box sx={{ position: 'absolute', inset: 0, ...canvasCss }} data-testid="exam-template-setup-canvas">
<Tldraw
shapeUtils={examCanvasShapeUtils as any}
tools={examCanvasTools as any}
@@ -254,8 +361,9 @@ const ExamTemplateSetupInner: React.FC = () => {
onMount={(editor) => {
editorRef.current = editor
editor.user.updateUserPreferences({ colorScheme: theme.palette.mode === 'dark' ? 'dark' : 'light' })
editor.store.listen(() => setDirty(true), { scope: 'document' })
editor.store.listen(() => { setDirty(true); refreshBoundaryPairs() }, { scope: 'document' })
if (template) loadShapes(editor, shapesFromTemplate(template, pageGeometriesRef.current)); else seedGuide(editor)
refreshBoundaryPairs()
}}
/>
</Box>
@@ -265,7 +373,7 @@ const ExamTemplateSetupInner: React.FC = () => {
<Divider orientation="vertical" flexItem />
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography variant="subtitle1" noWrap>{template?.title ?? 'Template setup'}</Typography>
<Typography variant="caption" color="text.secondary">Exam Marker Setup · coloured tools map to persisted regions; boundary start/end pairs can span pages.</Typography>
<Typography variant="caption" color="text.secondary">Exam Marker Setup · draw boundaries, part boxes, and regions; Save persists a full replace.</Typography>
</Box>
<Chip size="small" color={dirty ? 'warning' : 'success'} label={dirty ? 'Unsaved' : 'Saved'} />
<Button variant="contained" startIcon={saving ? <CircularProgress size={16} color="inherit" /> : <SaveIcon />} onClick={save} disabled={saving || loading || !template}>Save</Button>
@@ -277,19 +385,25 @@ const ExamTemplateSetupInner: React.FC = () => {
<Paper elevation={4} sx={{ position: 'absolute', right: 16, bottom: 16, maxWidth: 460, p: 2, borderRadius: 3, bgcolor: 'background.paper' }}>
<Typography variant="subtitle2" gutterBottom>Setup guide</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
1) Boundary start/end lines define each main question. 2) Draw amber Part boxes for markable sub-questions. 3) Draw coloured Response, Context, Q Number, Mark Area, Reference, and Furniture regions; Save derives parent links by containment.
<Typography variant="body2" color="text.secondary">
Start with boundaries: place the top line, then the bottom line. If a question continues, scroll to the later page and place the bottom boundary there. Next draw Part boxes, then Response/Context/metadata regions; Save links regions by spatial containment.
</Typography>
<Stack direction="row" spacing={0.75} useFlexGap flexWrap="wrap" sx={{ my: 1 }}>
{(['boundary', 'part', 'response', 'context', 'question_number', 'mark_area', 'reference', 'furniture'] as const).map((kind) => {
const p = canvasShapePalette[kind]
return <Chip key={kind} size="small" label={`${p.icon} ${p.label}`} sx={{ borderColor: p.stroke, color: p.stroke, bgcolor: p.fill, fontWeight: 700 }} variant="outlined" />
})}
<Stack direction="row" spacing={0.75} flexWrap="wrap" useFlexGap sx={{ mt: 1 }}>
<Chip size="small" color="error" variant="outlined" label="Boundary = paired red lines" />
<Chip size="small" color="warning" variant="outlined" label="Part = amber markable box" />
<Chip size="small" color="primary" variant="outlined" label="Response = blue writing area" />
<Chip size="small" color="secondary" variant="outlined" label="Context = purple stimulus" />
</Stack>
<Divider sx={{ my: 1 }} />
<Typography variant="caption" color="text.secondary" display="block">Multi-page boundary pairing</Typography>
<Typography variant="body2" sx={{ fontWeight: 700 }}>Draw Q start on page N, then Q end on a later page; save pairs boundaries by reading order into one question span.</Typography>
<Typography variant="caption" color="text.secondary" display="block" sx={{ mt: 0.75 }}>Open design choices resolved for v1: labels use Q start/end; persistent Attached pills confirm containment; rectangles stay simple for dense multi-column papers; Back button remains explicit.</Typography>
<Box sx={{ mt: 1.25, p: 1, borderRadius: 2, bgcolor: (t) => t.palette.mode === 'dark' ? 'rgba(248,113,113,0.12)' : 'rgba(239,68,68,0.06)', border: '1px dashed', borderColor: 'error.main' }}>
<Typography variant="caption" sx={{ fontWeight: 800, display: 'block' }}>Boundary pairing preview</Typography>
{boundaryPairs.length ? boundaryPairs.slice(0, 4).map((pair) => (
<Typography key={`${pair.index}-${pair.label}`} variant="caption" color={pair.multiPage ? 'warning.main' : 'text.secondary'} sx={{ display: 'block' }}>
{pair.label}: p{pair.startPage} top p{pair.endPage} bottom{pair.multiPage ? ' · multi-page span' : ''}
</Typography>
)) : (
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>Draw two Boundary lines to preview the saved question span.</Typography>
)}
</Box>
<Typography variant="caption" color={pdfStatus === 'ready' ? 'success.main' : pdfStatus === 'error' ? 'error.main' : 'text.secondary'} sx={{ display: 'block', mt: 1 }}>
PDF backdrop: {pdfStatus === 'ready' ? 'loaded and locked behind regions' : pdfStatus === 'loading' ? 'loading…' : pdfStatus === 'missing' ? 'no source PDF for this template' : pdfError ?? 'failed to load'}
</Typography>
+25 -47
View File
@@ -36,71 +36,49 @@ export type ExamCanvasTLShape = TLBaseBoxShape & {
}
}
type CanvasPaletteEntry = {
stroke: string
fill: string
darkStroke: string
darkFill: string
dash?: string
label: string
icon: string
role: string
const palette: Record<ExamCanvasShapeKind, { stroke: string; strokeDark: string; fill: string; fillDark: string; dash?: string; label: string; icon: string; badge: string }> = {
boundary: { stroke: '#dc2626', strokeDark: '#f87171', fill: 'rgba(239,68,68,0.06)', fillDark: 'rgba(248,113,113,0.12)', dash: '12 7', label: 'Boundary', icon: '↕', badge: 'TOP / BOTTOM' },
part: { stroke: '#d97706', strokeDark: '#fbbf24', fill: 'rgba(245,158,11,0.18)', fillDark: 'rgba(251,191,36,0.26)', label: 'Part', icon: '□', badge: 'MARKABLE BOX' },
response: { stroke: '#2563eb', strokeDark: '#60a5fa', fill: 'rgba(37,99,235,0.17)', fillDark: 'rgba(96,165,250,0.32)', label: 'Response', icon: '✎', badge: 'STUDENT WRITES' },
context: { stroke: '#7c3aed', strokeDark: '#c4b5fd', fill: 'rgba(124,58,237,0.14)', fillDark: 'rgba(167,139,250,0.28)', dash: '7 5', label: 'Context', icon: '◌', badge: 'STIMULUS' },
question_number: { stroke: '#0f766e', strokeDark: '#5eead4', fill: 'rgba(15,118,110,0.15)', fillDark: 'rgba(45,212,191,0.24)', label: 'Question #', icon: '#', badge: 'OCR LABEL' },
mark_area: { stroke: '#16a34a', strokeDark: '#86efac', fill: 'rgba(22,163,74,0.15)', fillDark: 'rgba(74,222,128,0.24)', label: 'Mark Area', icon: '✓', badge: 'PRINTED MARKS' },
reference: { stroke: '#0891b2', strokeDark: '#67e8f9', fill: 'rgba(8,145,178,0.14)', fillDark: 'rgba(34,211,238,0.24)', label: 'Reference', icon: '📎', badge: 'RESOURCE' },
furniture: { stroke: '#64748b', strokeDark: '#cbd5e1', fill: 'rgba(100,116,139,0.12)', fillDark: 'rgba(148,163,184,0.22)', dash: '3 5', label: 'Furniture', icon: '×', badge: 'IGNORE' },
}
export const canvasShapePalette: Record<ExamCanvasShapeKind, CanvasPaletteEntry> = {
boundary: { stroke: '#ef4444', fill: 'rgba(239,68,68,0.06)', darkStroke: '#f87171', darkFill: 'rgba(248,113,113,0.10)', dash: '8 6', label: 'Boundary', icon: '↕', role: 'start/end rule' },
part: { stroke: '#f59e0b', fill: 'rgba(245,158,11,0.18)', darkStroke: '#fbbf24', darkFill: 'rgba(251,191,36,0.26)', label: 'Part', icon: '□', role: 'markable box' },
response: { stroke: '#2563eb', fill: 'rgba(37,99,235,0.18)', darkStroke: '#60a5fa', darkFill: 'rgba(96,165,250,0.34)', label: 'Response', icon: '✎', role: 'student writing' },
context: { stroke: '#7c3aed', fill: 'rgba(124,58,237,0.14)', darkStroke: '#a78bfa', darkFill: 'rgba(167,139,250,0.28)', dash: '6 5', label: 'Context', icon: '◉', role: 'stimulus' },
question_number: { stroke: '#0f766e', fill: 'rgba(15,118,110,0.14)', darkStroke: '#2dd4bf', darkFill: 'rgba(45,212,191,0.24)', label: 'Question #', icon: '#', role: 'printed label' },
mark_area: { stroke: '#16a34a', fill: 'rgba(22,163,74,0.14)', darkStroke: '#4ade80', darkFill: 'rgba(74,222,128,0.23)', label: 'Marks', icon: '[2]', role: 'printed marks' },
reference: { stroke: '#0891b2', fill: 'rgba(8,145,178,0.14)', darkStroke: '#22d3ee', darkFill: 'rgba(34,211,238,0.24)', label: 'Reference', icon: '§', role: 'resource' },
furniture: { stroke: '#64748b', fill: 'rgba(100,116,139,0.12)', darkStroke: '#cbd5e1', darkFill: 'rgba(148,163,184,0.18)', dash: '3 5', label: 'Furniture', icon: '×', role: 'ignore' },
}
const shapeCss = `
.exam-canvas-shape { --exam-stroke: var(--exam-light-stroke); --exam-fill: var(--exam-light-fill); }
[data-color-mode="dark"] .exam-canvas-shape, .tl-theme__dark .exam-canvas-shape { --exam-stroke: var(--exam-dark-stroke); --exam-fill: var(--exam-dark-fill); }
.exam-canvas-shape__pill { background: rgba(255,255,255,.90); color: var(--exam-stroke); box-shadow: 0 1px 4px rgba(15,23,42,.14); }
[data-color-mode="dark"] .exam-canvas-shape__pill, .tl-theme__dark .exam-canvas-shape__pill { background: rgba(15,23,42,.88); color: var(--exam-stroke); box-shadow: 0 1px 5px rgba(0,0,0,.35); }
`
function renderShape(shape: ExamCanvasTLShape) {
const kind = shape.props.kind
const p = canvasShapePalette[kind] ?? canvasShapePalette.response
const p = palette[kind] ?? palette.response
const isBoundary = kind === 'boundary'
const label = shape.props.label || p.label
return (
<HTMLContainer id={shape.id} style={{ width: toDomPrecision(shape.props.w), height: toDomPrecision(shape.props.h), pointerEvents: 'all' }}>
<style>{shapeCss}</style>
<div
className={`exam-canvas-shape exam-canvas-shape--${kind}`}
className={`exam-canvas-shape exam-canvas-shape--${kind.replace('_', '-')}`}
style={{
'--exam-light-stroke': p.stroke,
'--exam-light-fill': p.fill,
'--exam-dark-stroke': p.darkStroke,
'--exam-dark-fill': p.darkFill,
width: '100%', height: '100%', boxSizing: 'border-box', border: `${isBoundary ? 2 : 1.5}px solid var(--exam-stroke)`,
borderStyle: p.dash ? 'dashed' : 'solid', borderRadius: isBoundary ? 999 : 10,
background: isBoundary ? 'transparent' : 'var(--exam-fill)', color: 'var(--exam-stroke)', fontFamily: 'Inter, system-ui, sans-serif',
display: 'flex', alignItems: isBoundary ? 'center' : 'flex-start', justifyContent: isBoundary ? 'center' : 'space-between',
padding: isBoundary ? '0 8px' : 8, boxShadow: isBoundary ? '0 0 0 3px rgba(239,68,68,0.08)' : '0 10px 22px rgba(15,23,42,0.10)', overflow: 'hidden', gap: 6,
'--exam-shape-stroke': p.stroke,
'--exam-shape-stroke-dark': p.strokeDark,
'--exam-shape-fill': p.fill,
'--exam-shape-fill-dark': p.fillDark,
'--exam-shape-border-style': p.dash ? 'dashed' : 'solid',
'--exam-shape-radius': isBoundary ? '999px' : kind === 'part' ? '6px' : '10px',
} as React.CSSProperties}
aria-label={`${p.label}: ${p.role}`}
title={`${p.label}: ${p.role}`}
>
<span className="exam-canvas-shape__pill" style={{ fontSize: 12, fontWeight: 900, textTransform: 'uppercase', letterSpacing: 0.6, borderRadius: 999, padding: '2px 7px', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
<span aria-hidden="true">{p.icon}</span>
{shape.props.label || p.label}
<span className="exam-canvas-shape__main-label">
<span className="exam-canvas-shape__icon" aria-hidden="true">{p.icon}</span>
<span>{label}</span>
</span>
{!isBoundary && shape.props.questionId && <span className="exam-canvas-shape__pill" style={{ fontSize: 11, fontWeight: 800, borderRadius: 999, padding: '2px 7px' }}>Attached</span>}
{isBoundary && <span className="exam-canvas-shape__pill" style={{ fontSize: 10, fontWeight: 800, borderRadius: 999, padding: '1px 6px' }}>pair across pages</span>}
{!isBoundary && <span className="exam-canvas-shape__badge">{shape.props.questionId ? 'Attached' : p.badge}</span>}
{isBoundary && <span className="exam-canvas-shape__endcap exam-canvas-shape__endcap--left">{label.toLowerCase().includes('end') ? 'B' : 'T'}</span>}
{isBoundary && <span className="exam-canvas-shape__endcap exam-canvas-shape__endcap--right">{label.toLowerCase().includes('end') ? 'Bottom' : 'Top'}</span>}
</div>
</HTMLContainer>
)
}
function defaultProps(kind: ExamCanvasShapeKind, w: number, h: number) {
const p = canvasShapePalette[kind]
const p = palette[kind]
return { w, h, label: p.label, kind, responseForm: kind === 'response' ? 'lines' : undefined, contextType: kind === 'context' ? 'generic' : undefined }
}
+2 -10
View File
@@ -12,27 +12,20 @@ export interface PdfPageImage {
height: number
}
export async function loadPdfPageImages(
pdfBytes: ArrayBuffer,
targetWidth = PAGE_WIDTH,
onPageReady?: (pages: PdfPageImage[]) => void,
): Promise<PdfPageImage[]> {
export async function loadPdfPageImages(pdfBytes: ArrayBuffer, targetWidth = PAGE_WIDTH): Promise<PdfPageImage[]> {
const pdf = await pdfjsLib.getDocument({ data: new Uint8Array(pdfBytes) }).promise
const pages: PdfPageImage[] = []
// Reuse a single canvas across all pages to avoid allocating ~120 MB of canvas memory
// for a typical 36-page exam paper.
const canvas = document.createElement("canvas")
for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber += 1) {
const page = await pdf.getPage(pageNumber)
const baseViewport = page.getViewport({ scale: 1 })
const scale = targetWidth / baseViewport.width
const viewport = page.getViewport({ scale })
const canvas = document.createElement("canvas")
canvas.width = Math.ceil(viewport.width)
canvas.height = Math.ceil(viewport.height)
const context = canvas.getContext("2d")
if (!context) throw new Error("Unable to create PDF render canvas")
context.clearRect(0, 0, canvas.width, canvas.height)
await page.render({ canvasContext: context, viewport }).promise
pages.push({
pageNumber,
@@ -40,7 +33,6 @@ export async function loadPdfPageImages(
width: canvas.width,
height: canvas.height,
})
onPageReady?.([...pages])
}
return pages