Add Draw mode for Apple Pencil annotation on scripture panel

Adds a third layout option alongside Stacked and Split. In Draw mode a
canvas overlay covers the scripture panel; the Pointer Events API routes
Apple Pencil input to perfect-freehand strokes while letting finger
touches fall through for normal scrolling. A floating toolbar provides
pen, highlighter, and eraser tools, six color swatches, S/M/L sizes,
undo, clear, and a Done button to return to Stacked view.

Strokes are stored as inkStrokes[] on each chunk and rendered as a
read-only transparent canvas overlay (InkLayer) in Stacked/Split modes.
migrateChunk is updated so all existing chunks get inkStrokes: [] on
first load.

Also adds a simple in-memory rate limiter on auth endpoints (10 attempts
per 15 min per IP).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
nmemmert
2026-08-12 08:29:20 -04:00
parent 96b6e840a3
commit 791e809222
7 changed files with 390 additions and 10 deletions
+7
View File
@@ -17,6 +17,7 @@
"express-session": "^1.19.0",
"mammoth": "^1.12.0",
"otplib": "^12.0.1",
"perfect-freehand": "^1.2.3",
"qrcode": "^1.5.4",
"react": "^19.0.0",
"react-dom": "^19.0.0"
@@ -4970,6 +4971,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/perfect-freehand": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/perfect-freehand/-/perfect-freehand-1.2.3.tgz",
"integrity": "sha512-bHZSfqDHGNlPpgH2yxXgPHlQSPpEbo+qg7li0M78J9vNAi2yjwLeA4x79BEQhX44lEWpCLSFCeRZwpw0niiXPA==",
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+1
View File
@@ -26,6 +26,7 @@
"express-session": "^1.19.0",
"mammoth": "^1.12.0",
"otplib": "^12.0.1",
"perfect-freehand": "^1.2.3",
"qrcode": "^1.5.4",
"react": "^19.0.0",
"react-dom": "^19.0.0"
+21
View File
@@ -31,6 +31,22 @@ if (isProd && !process.env.SESSION_SECRET) {
// Trust the reverse proxy (needed for secure cookies to work behind nginx/etc).
app.set('trust proxy', 1);
// Simple in-memory rate limiter for auth endpoints — 10 attempts per 15 min per IP.
const _authAttempts = new Map();
setInterval(() => {
const now = Date.now();
for (const [ip, e] of _authAttempts) if (now > e.resetAt) _authAttempts.delete(ip);
}, 60 * 60 * 1000);
function checkAuthRateLimit(ip) {
const now = Date.now();
const window = 15 * 60 * 1000;
const e = _authAttempts.get(ip) ?? { count: 0, resetAt: now + window };
if (now > e.resetAt) { e.count = 0; e.resetAt = now + window; }
e.count += 1;
_authAttempts.set(ip, e);
return e.count > 10;
}
app.use(express.json({ limit: '10mb' }));
app.use(session({
store: new SqliteSessionStore(),
@@ -59,6 +75,7 @@ app.get('/api/health', (_req, res) => {
app.post('/api/auth/register', async (req, res) => {
try {
if (checkAuthRateLimit(req.ip)) return res.status(429).json({ error: 'Too many attempts. Please wait 15 minutes.' });
const email = String(req.body?.email ?? '').trim().toLowerCase();
const password = String(req.body?.password ?? '');
@@ -93,6 +110,7 @@ app.post('/api/auth/register', async (req, res) => {
app.post('/api/auth/login', async (req, res) => {
try {
if (checkAuthRateLimit(req.ip)) return res.status(429).json({ error: 'Too many attempts. Please wait 15 minutes.' });
const email = String(req.body?.email ?? '').trim().toLowerCase();
const password = String(req.body?.password ?? '');
@@ -121,6 +139,7 @@ app.post('/api/auth/login', async (req, res) => {
app.post('/api/auth/mfa/verify', async (req, res) => {
try {
if (checkAuthRateLimit(req.ip)) return res.status(429).json({ error: 'Too many attempts. Please wait 15 minutes.' });
const pendingUserId = req.session?.pendingUserId;
if (!pendingUserId) {
return res.status(400).json({ error: 'No sign-in in progress.' });
@@ -314,6 +333,8 @@ app.put('/api/projects/:id', requireAuth, (req, res) => {
if (body.id !== req.params.id) {
return res.status(400).json({ error: 'URL id does not match body id.' });
}
if (body.id.length > 100) return res.status(400).json({ error: 'Invalid project id.' });
if (body.title.length > 500) return res.status(400).json({ error: 'Project title is too long.' });
const saved = upsertProject(body, req.session.userId);
if (!saved) {
return res.status(403).json({ error: 'That project belongs to a different account.' });
+9 -1
View File
@@ -168,6 +168,7 @@ export function migrateChunk(chunk) {
episodeTitle: chunk.episodeTitle ?? '',
finalScript: chunk.finalScript ?? '',
tags: chunk.tags ?? [],
inkStrokes: chunk.inkStrokes ?? [],
}; // already new format
}
return {
@@ -177,6 +178,7 @@ export function migrateChunk(chunk) {
application: '',
crossReferences: [],
tags: [],
inkStrokes: [],
spilloverEndVerse: null,
generalNotes: '',
episodeNumber: '',
@@ -1283,7 +1285,10 @@ const App = () => {
}, []);
const [studyLayout, setStudyLayout] = useState(
() => localStorage.getItem('studyLayout') || 'stacked',
); // 'stacked' | 'split'
); // 'stacked' | 'split' | 'annotate'
const [drawTool, setDrawTool] = useState('pen');
const [drawColor, setDrawColor] = useState('#0f172a');
const [drawSize, setDrawSize] = useState(0.012);
const [activeStudyTab, setActiveStudyTab] = useState(
() => localStorage.getItem('activeStudyTab') || 'notes',
);
@@ -3751,6 +3756,9 @@ const deleteProject = (id) => {
selectedChunkVerses,
selectedChunkGlobalIndex,
studyLayout, setStudyLayout,
drawTool, setDrawTool,
drawColor, setDrawColor,
drawSize, setDrawSize,
activeStudyTab, setActiveStudyTab,
mobileStudyTab, setMobileStudyTab,
collapsedSections, setCollapsedSections,
+264
View File
@@ -0,0 +1,264 @@
import { useEffect, useRef, useCallback } from 'react';
import { useApp } from '../context/AppContext.js';
import { renderInkToCanvas } from '../utils/inkRender.js';
const INK_COLORS = ['#0f172a', '#ef4444', '#3b82f6', '#16a34a', '#f59e0b', '#a855f7'];
const INK_SIZES = [
{ label: 'S', value: 0.006 },
{ label: 'M', value: 0.012 },
{ label: 'L', value: 0.025 },
];
// Read-only ink overlay shown in Stacked / Split mode.
export function InkLayer({ strokes }) {
const canvasRef = useRef(null);
const strokesRef = useRef(strokes);
strokesRef.current = strokes;
const render = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas) return;
renderInkToCanvas(canvas, strokesRef.current);
}, []);
useEffect(() => { render(); }, [strokes, render]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const obs = new ResizeObserver(render);
obs.observe(canvas);
return () => obs.disconnect();
}, [render]);
if (!strokes.length) return null;
return (
<canvas
ref={canvasRef}
className="pointer-events-none absolute inset-0 h-full w-full"
style={{ zIndex: 5 }}
/>
);
}
// Interactive draw canvas overlay for Draw mode.
export default function DrawCanvas() {
const {
selectedChunk,
updateChunk,
drawTool, setDrawTool,
drawColor, setDrawColor,
drawSize, setDrawSize,
setStudyLayout,
} = useApp();
const canvasRef = useRef(null);
const activeStrokeRef = useRef([]);
// Refs prevent stale closures in ResizeObserver callback
const strokesRef = useRef([]);
const drawToolRef = useRef(drawTool);
const drawColorRef = useRef(drawColor);
const drawSizeRef = useRef(drawSize);
strokesRef.current = selectedChunk?.inkStrokes ?? [];
drawToolRef.current = drawTool;
drawColorRef.current = drawColor;
drawSizeRef.current = drawSize;
const render = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas) return;
renderInkToCanvas(
canvas,
strokesRef.current,
activeStrokeRef.current,
drawToolRef.current,
drawColorRef.current,
drawSizeRef.current,
);
}, []);
useEffect(() => { render(); }, [selectedChunk?.inkStrokes, drawTool, drawColor, drawSize, render]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const obs = new ResizeObserver(render);
obs.observe(canvas);
return () => obs.disconnect();
}, [render]);
const getPoint = useCallback((e) => {
const canvas = canvasRef.current;
if (!canvas) return [0, 0, 0.5];
const rect = canvas.getBoundingClientRect();
return [
(e.clientX - rect.left) / rect.width,
(e.clientY - rect.top) / rect.height,
e.pressure ?? 0.5,
];
}, []);
const onPointerDown = useCallback((e) => {
if (e.pointerType === 'touch') return;
e.preventDefault();
canvasRef.current?.setPointerCapture(e.pointerId);
activeStrokeRef.current = [getPoint(e)];
render();
}, [getPoint, render]);
const onPointerMove = useCallback((e) => {
if (e.pointerType === 'touch') return;
if (!canvasRef.current?.hasPointerCapture(e.pointerId)) return;
e.preventDefault();
const pt = getPoint(e);
activeStrokeRef.current = [...activeStrokeRef.current, pt];
if (drawToolRef.current === 'eraser') {
const [ex, ey] = pt;
const r = drawSizeRef.current * 3;
const remaining = strokesRef.current.filter((s) =>
!s.points.some(([sx, sy]) => Math.hypot(sx - ex, sy - ey) < r),
);
if (remaining.length !== strokesRef.current.length) {
updateChunk(selectedChunk.id, { inkStrokes: remaining });
}
}
render();
}, [getPoint, render, updateChunk, selectedChunk]);
const onPointerUp = useCallback((e) => {
if (e.pointerType === 'touch') return;
const pts = activeStrokeRef.current;
if (drawToolRef.current !== 'eraser' && pts.length > 1) {
updateChunk(selectedChunk.id, {
inkStrokes: [
...strokesRef.current,
{
id: crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`,
tool: drawToolRef.current,
color: drawColorRef.current,
size: drawSizeRef.current,
points: pts,
},
],
});
}
activeStrokeRef.current = [];
render();
}, [render, updateChunk, selectedChunk]);
const strokes = selectedChunk?.inkStrokes ?? [];
const undo = () => {
if (strokes.length > 0)
updateChunk(selectedChunk.id, { inkStrokes: strokes.slice(0, -1) });
};
const clear = () => {
if (strokes.length > 0 && window.confirm('Clear all annotations on this chunk?'))
updateChunk(selectedChunk.id, { inkStrokes: [] });
};
return (
<>
<canvas
ref={canvasRef}
className="absolute inset-0 z-10 h-full w-full cursor-crosshair"
style={{ touchAction: 'pan-y pinch-zoom' }}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
/>
{/* Floating toolbar */}
<div className="absolute bottom-4 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1 rounded-2xl border border-slate-200 bg-white/95 px-3 py-2 shadow-xl backdrop-blur-sm">
{/* Tool buttons */}
{[
{ id: 'pen', label: '✒', title: 'Pen' },
{ id: 'highlighter', label: '▐', title: 'Highlighter' },
{ id: 'eraser', label: '⌫', title: 'Eraser' },
].map((t) => (
<button
key={t.id}
type="button"
title={t.title}
onClick={() => setDrawTool(t.id)}
className={`flex h-8 w-8 items-center justify-center rounded-xl text-sm font-bold transition ${
drawTool === t.id
? 'bg-slate-900 text-white'
: 'text-slate-600 hover:bg-slate-100'
}`}
>
{t.label}
</button>
))}
<div className="mx-1 h-5 w-px bg-slate-200" />
{/* Color swatches */}
{INK_COLORS.map((c) => (
<button
key={c}
type="button"
onClick={() => { setDrawColor(c); if (drawTool === 'eraser') setDrawTool('pen'); }}
style={{ background: c }}
className={`h-5 w-5 rounded-full border-2 transition ${
drawColor === c && drawTool !== 'eraser'
? 'scale-125 border-slate-900'
: 'border-white shadow-sm'
}`}
/>
))}
<div className="mx-1 h-5 w-px bg-slate-200" />
{/* Size buttons */}
{INK_SIZES.map((s) => (
<button
key={s.label}
type="button"
onClick={() => setDrawSize(s.value)}
className={`flex h-8 w-8 items-center justify-center rounded-xl text-xs font-bold transition ${
drawSize === s.value
? 'bg-slate-900 text-white'
: 'text-slate-600 hover:bg-slate-100'
}`}
>
{s.label}
</button>
))}
<div className="mx-1 h-5 w-px bg-slate-200" />
<button
type="button"
onClick={undo}
disabled={strokes.length === 0}
className="rounded-xl px-2.5 py-1 text-xs font-semibold text-slate-600 hover:bg-slate-100 disabled:opacity-40"
>
Undo
</button>
<button
type="button"
onClick={clear}
disabled={strokes.length === 0}
className="rounded-xl px-2.5 py-1 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-40"
>
Clear
</button>
<div className="mx-1 h-5 w-px bg-slate-200" />
<button
type="button"
onClick={() => setStudyLayout('stacked')}
className="rounded-xl bg-slate-900 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-slate-800"
>
Done
</button>
</div>
</>
);
}
+21 -5
View File
@@ -2,6 +2,7 @@ import { createPortal } from 'react-dom';
import DOMPurify from 'dompurify';
import { useApp } from '../context/AppContext.js';
import { STUDY_TABS, COMMENTARY_OPTIONS, NT_BOOK_NUMBER, formatChunkReference, CrossRefChip } from '../App.jsx';
import DrawCanvas, { InkLayer } from './DrawCanvas.jsx';
export default function StudyPage() {
const {
@@ -192,14 +193,26 @@ export default function StudyPage() {
Choose a chunk to study.
</div>
)}
<div className="max-sm:hidden flex divide-x divide-slate-200 overflow-hidden rounded-2xl border border-slate-300">
{[
{ id: 'stacked', label: '☰ Stacked' },
{ id: 'split', label: '◫ Split' },
{ id: 'annotate', label: '✏ Draw' },
].map((m) => (
<button
key={m.id}
type="button"
onClick={() => setStudyLayout((m) => (m === 'split' ? 'stacked' : 'split'))}
className="max-sm:hidden rounded-2xl border border-slate-300 bg-white px-3 py-2 text-sm font-semibold text-slate-700 transition hover:border-slate-400"
title="Toggle two-pane study layout"
onClick={() => setStudyLayout(m.id)}
className={`px-3 py-2 text-sm font-semibold transition ${
studyLayout === m.id
? 'bg-slate-900 text-white'
: 'bg-white text-slate-700 hover:bg-slate-50'
}`}
>
{studyLayout === 'split' ? '☰ Stacked View' : '◫ Split View'}
{m.label}
</button>
))}
</div>
</div>
</div>
@@ -232,7 +245,7 @@ export default function StudyPage() {
<div className="mt-6 space-y-6">
<div className={`space-y-6 ${studyLayout === 'split' ? 'lg:flex lg:items-start lg:gap-6 lg:space-y-0' : ''}`}>
{/* Scripture */}
<div className={`rounded-3xl border border-slate-200 bg-slate-50 p-5 ${mobileStudyTab !== 'scripture' ? 'max-sm:hidden' : ''} ${studyLayout === 'split' ? 'lg:sticky lg:top-6 lg:flex-1 lg:basis-0 lg:min-w-0 lg:self-start' : ''}`}>
<div className={`relative overflow-hidden rounded-3xl border border-slate-200 bg-slate-50 p-5 ${mobileStudyTab !== 'scripture' && studyLayout !== 'annotate' ? 'max-sm:hidden' : ''} ${studyLayout === 'split' ? 'lg:sticky lg:top-6 lg:flex-1 lg:basis-0 lg:min-w-0 lg:self-start' : ''}`}>
<div className="mb-4 flex items-center justify-between gap-3">
<div>
<p className="text-sm font-semibold text-slate-700">Scripture</p>
@@ -251,6 +264,9 @@ export default function StudyPage() {
))}
</div>
<InkLayer strokes={selectedChunk?.inkStrokes ?? []} />
{studyLayout === 'annotate' && <DrawCanvas />}
{/* Interlinear */}
<div className="mt-4 border-t border-slate-200 pt-4">
<button
+63
View File
@@ -0,0 +1,63 @@
import { getStroke } from 'perfect-freehand';
function pathFromStroke(points) {
if (!points.length) return '';
const d = [`M ${points[0][0].toFixed(2)} ${points[0][1].toFixed(2)}`];
for (let i = 1; i < points.length - 1; i++) {
const mx = ((points[i][0] + points[i + 1][0]) / 2).toFixed(2);
const my = ((points[i][1] + points[i + 1][1]) / 2).toFixed(2);
d.push(`Q ${points[i][0].toFixed(2)} ${points[i][1].toFixed(2)} ${mx} ${my}`);
}
d.push('Z');
return d.join(' ');
}
// Renders saved strokes + optional active stroke onto a canvas element.
// Coordinates are stored as fractions [0,1] of the draw canvas dimensions.
// size is stored as a fraction of canvas height (e.g. 0.012 ≈ 8px on a 600px canvas).
export function renderInkToCanvas(
canvas,
strokes,
activeStroke = [],
activeTool = 'pen',
activeColor = '#0f172a',
activeSize = 0.012,
) {
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth;
const h = canvas.clientHeight;
if (!w || !h) return;
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
for (const s of strokes) {
const pts = s.points.map(([x, y, p]) => [x * w, y * h, p]);
const outline = getStroke(pts, {
size: s.size * h,
thinning: s.tool === 'highlighter' ? 0 : 0.5,
smoothing: 0.5,
streamline: 0.4,
});
ctx.globalAlpha = s.tool === 'highlighter' ? 0.35 : 1;
ctx.fillStyle = s.color;
ctx.fill(new Path2D(pathFromStroke(outline)));
}
if (activeStroke.length > 1 && activeTool !== 'eraser') {
const pts = activeStroke.map(([x, y, p]) => [x * w, y * h, p]);
const outline = getStroke(pts, {
size: activeSize * h,
thinning: activeTool === 'highlighter' ? 0 : 0.5,
smoothing: 0.5,
streamline: 0.4,
});
ctx.globalAlpha = activeTool === 'highlighter' ? 0.35 : 1;
ctx.fillStyle = activeColor;
ctx.fill(new Path2D(pathFromStroke(outline)));
}
ctx.globalAlpha = 1;
}