Add notebook draw mode to study and reader pages

Draw mode in the study page replaces all note panels with a full ruled
notebook canvas (no cross-refs, observations, or text boxes) so the user
has a clean writing surface. Ink strokes are saved per chunk and exported
as SVG in the HTML export.

The reader page gets a Draw toggle button that reveals the same notebook
canvas below the verse list, with strokes persisted per book+chapter in
localStorage via readerInkByPage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
nmemmert
2026-08-12 08:45:20 -04:00
parent 791e809222
commit ea44ff142d
5 changed files with 184 additions and 124 deletions
+44 -2
View File
@@ -1,5 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import mammoth from 'mammoth';
import { getStroke } from 'perfect-freehand';
import { pathFromStroke } from './utils/inkRender.js';
import { AppContext, useApp } from './context/AppContext.js';
import AdminPage from './pages/AdminPage.jsx';
@@ -425,6 +427,28 @@ export function formatRelativeDate(ts) {
const escHtml = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
function inkStrokesToSvgHtml(strokes) {
if (!strokes?.length) return '';
const W = 700, H = 500;
const lines = [];
for (let y = 32; y < H; y += 32)
lines.push(`<line x1="0" y1="${y}" x2="${W}" y2="${y}" stroke="#dde3ec" stroke-width="1"/>`);
lines.push(`<line x1="40" y1="0" x2="40" y2="${H}" stroke="#fca5a5" stroke-width="1"/>`);
const paths = strokes.map((s) => {
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,
});
const d = pathFromStroke(outline);
if (!d) return '';
return `<path d="${d}" fill="${escHtml(s.color)}" opacity="${s.tool === 'highlighter' ? '0.35' : '1'}"/>`;
}).filter(Boolean).join('');
return `<div class="ink-notes"><strong>INK NOTES:</strong><div style="margin-top:8px;border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;background:#fff;"><svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" style="display:block;max-width:100%;height:auto;">${lines.join('')}${paths}</svg></div></div>`;
}
export function buildExportHtml(project) {
const style = `
body { font-family: Georgia, serif; color: #0f172a; margin: 0; padding: 32px; }
@@ -435,7 +459,7 @@ export function buildExportHtml(project) {
.chunk { margin-bottom: 2rem; padding: 1.25rem 1.5rem; border: 1px solid #cbd5e1; border-radius: 0.75rem; background: #ffffff; }
.verse { margin: 0 0 0.75rem; line-height: 1.7; }
.scripture-ref { font-weight: 700; margin-bottom: 0.75rem; }
.oia, .cross-refs, .greek { margin-top: 1rem; }
.oia, .cross-refs, .greek, .ink-notes { margin-top: 1rem; }
.oia-section { margin-bottom: 0.75rem; }
.greek table { width: 100%; border-collapse: collapse; margin-top: 0.5rem; }
.greek th, .greek td { border: 1px solid #d1d5db; padding: 0.65rem; text-align: left; }
@@ -506,6 +530,8 @@ export function buildExportHtml(project) {
})
.join('');
const inkHtml = inkStrokesToSvgHtml(chunk.inkStrokes);
return `
<section class="chunk">
<div class="scripture-ref">${escHtml(scripture)}</div>
@@ -520,6 +546,7 @@ export function buildExportHtml(project) {
${greekRows ? greekTable : '<p><em>No Greek word notes.</em></p>'}
${extendedDefinitions}
</div>
${inkHtml}
</section>
`;
}).join('');
@@ -1168,6 +1195,10 @@ const App = () => {
const [audioNarrator, setAudioNarrator] = useState('souer');
const [audioState, setAudioState] = useState({ status: 'idle', chapter: 0, total: 0 });
const [readerAudioState, setReaderAudioState] = useState({ status: 'idle', chapter: 0 });
const [readerInkByPage, setReaderInkByPage] = useState(() => {
try { return JSON.parse(localStorage.getItem('readerInkByPage') ?? '{}'); }
catch { return {}; }
});
const audioRef = useRef(null);
const audioModeRef = useRef('book'); // 'book' | 'reader' — which player owns audioRef
const audioBookRef = useRef(audioBook);
@@ -1520,6 +1551,15 @@ const App = () => {
});
};
const updateReaderPageInk = useCallback((bookAbbrev, chapter, strokes) => {
const key = `${bookAbbrev}_${chapter}`;
setReaderInkByPage((prev) => {
const next = { ...prev, [key]: strokes };
try { localStorage.setItem('readerInkByPage', JSON.stringify(next)); } catch {}
return next;
});
}, []);
const cycleBookmarkColor = (verseKey) => {
setReaderBookmarks((prev) => {
const cur = prev[verseKey];
@@ -3705,6 +3745,8 @@ const deleteProject = (id) => {
readerSearchActive, setReaderSearchActive,
readerSearchScope, setReaderSearchScope,
readerAudioState,
readerInkByPage,
updateReaderPageInk,
bibleIndexStatus,
loadReaderChapter,
_bibleIndexCacheRef,
+68 -102
View File
@@ -9,58 +9,24 @@ const INK_SIZES = [
{ 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();
// Standalone notebook-style draw canvas.
// strokes: array of saved stroke objects
// onStrokesChange: (newStrokes) => void
// onDone: optional () => void — shows "Done" button when provided
export default function DrawCanvas({ strokes, onStrokesChange, onDone }) {
const { drawTool, setDrawTool, drawColor, setDrawColor, drawSize, setDrawSize } = useApp();
const canvasRef = useRef(null);
const activeStrokeRef = useRef([]);
// Refs prevent stale closures in ResizeObserver callback
const strokesRef = useRef([]);
// Refs prevent stale closures in stable callbacks
const strokesRef = useRef(strokes);
const onStrokesChangeRef = useRef(onStrokesChange);
const drawToolRef = useRef(drawTool);
const drawColorRef = useRef(drawColor);
const drawSizeRef = useRef(drawSize);
strokesRef.current = selectedChunk?.inkStrokes ?? [];
strokesRef.current = strokes;
onStrokesChangeRef.current = onStrokesChange;
drawToolRef.current = drawTool;
drawColorRef.current = drawColor;
drawSizeRef.current = drawSize;
@@ -78,7 +44,7 @@ export default function DrawCanvas() {
);
}, []);
useEffect(() => { render(); }, [selectedChunk?.inkStrokes, drawTool, drawColor, drawSize, render]);
useEffect(() => { render(); }, [strokes, drawTool, drawColor, drawSize, render]);
useEffect(() => {
const canvas = canvasRef.current;
@@ -113,26 +79,23 @@ export default function DrawCanvas() {
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),
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 });
}
if (remaining.length !== strokesRef.current.length)
onStrokesChangeRef.current(remaining);
}
render();
}, [getPoint, render, updateChunk, selectedChunk]);
}, [getPoint, render]);
const onPointerUp = useCallback((e) => {
if (e.pointerType === 'touch') return;
const pts = activeStrokeRef.current;
if (drawToolRef.current !== 'eraser' && pts.length > 1) {
updateChunk(selectedChunk.id, {
inkStrokes: [
onStrokesChangeRef.current([
...strokesRef.current,
{
id: crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`,
@@ -141,40 +104,22 @@ export default function DrawCanvas() {
size: drawSizeRef.current,
points: pts,
},
],
});
]);
}
activeStrokeRef.current = [];
render();
}, [render, updateChunk, selectedChunk]);
}, [render]);
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: [] });
};
const undo = () => strokes.length > 0 && onStrokesChange(strokes.slice(0, -1));
const clear = () =>
strokes.length > 0 &&
window.confirm('Clear all ink notes?') &&
onStrokesChange([]);
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 */}
<div className="overflow-hidden rounded-3xl border border-slate-200 shadow-sm">
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-1 border-b border-slate-200 bg-white px-3 py-2">
{[
{ id: 'pen', label: '✒', title: 'Pen' },
{ id: 'highlighter', label: '▐', title: 'Highlighter' },
@@ -185,10 +130,8 @@ export default function DrawCanvas() {
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'
className={`flex h-8 w-8 items-center justify-center rounded-lg text-sm font-bold transition ${
drawTool === t.id ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100'
}`}
>
{t.label}
@@ -197,7 +140,6 @@ export default function DrawCanvas() {
<div className="mx-1 h-5 w-px bg-slate-200" />
{/* Color swatches */}
{INK_COLORS.map((c) => (
<button
key={c}
@@ -205,25 +147,20 @@ export default function DrawCanvas() {
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'
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'
className={`flex h-8 w-8 items-center justify-center rounded-lg text-xs font-bold transition ${
drawSize === s.value ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100'
}`}
>
{s.label}
@@ -236,7 +173,7 @@ export default function DrawCanvas() {
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"
className="rounded-lg px-2.5 py-1 text-xs font-semibold text-slate-600 hover:bg-slate-100 disabled:opacity-40"
>
Undo
</button>
@@ -244,21 +181,50 @@ export default function DrawCanvas() {
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"
className="rounded-lg px-2.5 py-1 text-xs font-semibold text-rose-600 hover:bg-rose-50 disabled:opacity-40"
>
Clear
</button>
{onDone && (
<>
<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"
onClick={onDone}
className="rounded-lg bg-slate-900 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-slate-800"
>
Done
</button>
</div>
</>
)}
</div>
{/* Notebook canvas */}
<div
className="relative"
style={{
minHeight: 640,
background: 'white',
backgroundImage: 'repeating-linear-gradient(transparent 0px, transparent 31px, #dde3ec 31px, #dde3ec 32px)',
}}
>
{/* Red margin line */}
<div className="absolute bottom-0 left-10 top-0 w-px bg-rose-200" style={{ zIndex: 1 }} />
<canvas
ref={canvasRef}
className="absolute inset-0 h-full w-full"
style={{
zIndex: 2,
cursor: drawTool === 'eraser' ? 'cell' : 'crosshair',
touchAction: 'pan-y pinch-zoom',
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
/>
</div>
</div>
);
}
+27
View File
@@ -1,5 +1,7 @@
import { useState, useEffect } from 'react';
import { useApp } from '../context/AppContext.js';
import { bookOptions, BookmarkIcon, CopyIcon } from '../App.jsx';
import DrawCanvas from './DrawCanvas.jsx';
export default function ReaderPage() {
const {
@@ -41,9 +43,15 @@ export default function ReaderPage() {
copyVerse,
formatCrossRef,
setReaderCrossRefs,
readerInkByPage,
updateReaderPageInk,
} = useApp();
const readerBook = bookOptions.find((b) => b.abbrev === readerBookAbbrev);
const [readerDrawMode, setReaderDrawMode] = useState(false);
const readerPageInkStrokes = readerInkByPage?.[`${readerBookAbbrev}_${readerChapter}`] ?? [];
useEffect(() => { setReaderDrawMode(false); }, [readerBookAbbrev, readerChapter]);
const bookmarkEntries = Object.entries(readerBookmarks).map(([key, color]) => {
const [bAbbrev, chapterStr, verseStr] = key.split('-');
const bookIndex = bookOptions.findIndex((b) => b.abbrev === bAbbrev);
@@ -201,6 +209,14 @@ export default function ReaderPage() {
🔍 Search
</button>
)}
<div className="mx-2 h-4 w-px bg-slate-200" />
<button
type="button"
onClick={() => setReaderDrawMode((v) => !v)}
className={`rounded-lg px-3 py-1 text-xs font-semibold transition ${readerDrawMode ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-600 hover:bg-slate-50'}`}
>
Draw
</button>
</div>
{/* Whole-Bible search results */}
@@ -416,6 +432,17 @@ export default function ReaderPage() {
);
})()}
</div>
{/* Ink notebook — shown when Draw mode is active */}
{readerDrawMode && (
<div className="mt-4">
<DrawCanvas
strokes={readerPageInkStrokes}
onStrokesChange={(s) => updateReaderPageInk(readerBookAbbrev, readerChapter, s)}
onDone={() => setReaderDrawMode(false)}
/>
</div>
)}
</main>
</div>
);
+30 -5
View File
@@ -2,7 +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';
import DrawCanvas from './DrawCanvas.jsx';
export default function StudyPage() {
const {
@@ -243,9 +243,36 @@ export default function StudyPage() {
{selectedChunk ? (
<div className="mt-6 space-y-6">
{studyLayout === 'annotate' ? (
<div className="space-y-4">
{/* Compact scripture strip */}
<div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
<div className="mb-1.5 flex items-center justify-between gap-2">
<span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Scripture · read-only</span>
<span className="rounded-full bg-slate-200 px-2.5 py-0.5 text-xs font-semibold text-slate-600">
{formatChunkReference(project, selectedChunkChapterIndex, selectedChunk, '')}
</span>
</div>
<p className="font-serif text-sm leading-relaxed text-slate-700">
{selectedChunkVerses.map((verse) => (
<span key={`${verse.chapter}-${verse.number}`}>
<span className="font-semibold text-slate-900">{verse.chapter}:{verse.number} </span>
{verse.text}{' '}
</span>
))}
</p>
</div>
{/* Notebook canvas */}
<DrawCanvas
strokes={selectedChunk.inkStrokes ?? []}
onStrokesChange={(s) => updateChunk(selectedChunk.id, { inkStrokes: s })}
onDone={() => setStudyLayout('stacked')}
/>
</div>
) : (
<div className={`space-y-6 ${studyLayout === 'split' ? 'lg:flex lg:items-start lg:gap-6 lg:space-y-0' : ''}`}>
{/* Scripture */}
<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={`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="mb-4 flex items-center justify-between gap-3">
<div>
<p className="text-sm font-semibold text-slate-700">Scripture</p>
@@ -264,9 +291,6 @@ 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
@@ -880,6 +904,7 @@ export default function StudyPage() {
</div>
</div>
)}
{/* Prev / Next — sticky */}
<div className="sticky bottom-0 z-10 -mx-4 sm:-mx-6 mt-6 flex items-center justify-between gap-3 border-t border-slate-200 bg-white/95 px-4 py-3 backdrop-blur-sm sm:px-6">
+1 -1
View File
@@ -1,6 +1,6 @@
import { getStroke } from 'perfect-freehand';
function pathFromStroke(points) {
export 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++) {