Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add Rapid Reader cursor resume

[._.]/ Adam Eivyc83b4dfa441a
diff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsx
index e5192b6f49..20b2f86197 100644
--- a/client/src/components/RapidReader.jsx
+++ b/client/src/components/RapidReader.jsx
@@ -1,8 +1,9 @@
import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
-import { Play, Pause, RotateCcw, Rewind, FastForward, X, Zap } from 'lucide-react';
+import { Bookmark, Play, Pause, RotateCcw, Rewind, FastForward, X, Zap } from 'lucide-react';
import Modal from './ui/Modal';
import useKeyCapture from '../hooks/useKeyCapture';
import { noPointerFocusSurfaceProps } from '../lib/a11yKeyboard';
+import { rapidReaderWords } from '../lib/rapidReaderPosition';
// Optimal Recognition Point — the focal letter the eye lands on. Spritz-style:
// shorter words use a left-shifted ORP, longer words shift right. Returns the
@@ -17,28 +18,16 @@ const orpIndex = (word) => {
return 4;
};
-// Tokenize while preserving punctuation attached to words. Strips empty tokens.
-// Each token may be one or two words depending on `chunkSize`. Short connector
-// words (≤3 chars) merge into the next token when chunkSize=2 — feels natural
-// at speed and keeps WPM honest.
-const tokenize = (text, chunkSize) => {
- if (!text) return [];
- const raw = text.replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
- if (chunkSize === 1) return raw;
- const out = [];
- let i = 0;
- while (i < raw.length) {
- const a = raw[i];
- const b = raw[i + 1];
- if (b && (a.length <= 3 || b.length <= 3) && (a.length + b.length) <= 12) {
- out.push(`${a} ${b}`);
- i += 2;
- } else {
- out.push(a);
- i += 1;
- }
+// Build the display chunk from the canonical word position. This keeps cursor
+// starts and bookmarks exact even when they land where a prior 2-word chunk
+// would have begun one word earlier.
+const chunkAt = (words, wordIndex, chunkSize) => {
+ const a = words[wordIndex]?.text || '';
+ const b = words[wordIndex + 1]?.text;
+ if (chunkSize === 2 && b && (a.length <= 3 || b.length <= 3) && (a.length + b.length) <= 12) {
+ return { value: `${a} ${b}`, wordCount: 2 };
}
- return out;
+ return { value: a, wordCount: 1 };
};
// Sentence-end detection: word ends with terminal punctuation. Used to add a
@@ -56,33 +45,43 @@ export default function RapidReader({
autoPlay = false,
compact = false,
inDialog = false,
+ initialWordIndex = 0,
onClose,
- onComplete
+ onComplete,
+ onPositionChange,
+ onBookmark,
+ onWpmChange,
+ onChunkSizeChange,
}) {
const [wpm, setWpm] = useState(initialWpm);
const [chunkSize, setChunkSize] = useState(initialChunk);
- const [idx, setIdx] = useState(0);
+ const [wordIndex, setWordIndex] = useState(initialWordIndex);
const [playing, setPlaying] = useState(autoPlay);
const timeoutRef = useRef(null);
- const tokens = useMemo(() => tokenize(text, chunkSize), [text, chunkSize]);
- const total = tokens.length;
- const current = tokens[idx] || '';
+ const words = useMemo(() => rapidReaderWords(text), [text]);
+ const totalWords = words.length;
+ const current = useMemo(() => chunkAt(words, wordIndex, chunkSize), [words, wordIndex, chunkSize]);
+
+ // Position is a canonical word offset, so changing chunk size never jumps to
+ // a different place in the source text.
+ useEffect(() => {
+ setWordIndex(Math.max(0, Math.min(initialWordIndex, Math.max(0, totalWords - 1))));
+ }, [text, initialWordIndex, totalWords]);
- // Keep idx in range when text/chunkSize changes
useEffect(() => {
- if (idx >= tokens.length && tokens.length > 0) setIdx(tokens.length - 1);
- }, [tokens.length, idx]);
+ onPositionChange?.({ wordIndex, wordCount: totalWords, wpm, chunkSize, playing });
+ }, [wordIndex, totalWords, wpm, chunkSize, playing, onPositionChange]);
// Per-token delay: base = 60000/wpm ms. Long chunks and sentence boundaries
// get extra time; ultra-short tokens get a small bonus too.
const delayFor = useCallback((token) => {
const base = 60000 / Math.max(60, wpm);
let mult = 1;
- if (endsSentence(token)) mult = 1.8;
- else if (endsClause(token)) mult = 1.3;
- if (token && token.length > 8) mult *= 1.15;
- return base * mult;
+ if (endsSentence(token?.value)) mult = 1.8;
+ else if (endsClause(token?.value)) mult = 1.3;
+ if (token?.value.length > 8) mult *= 1.15;
+ return base * token.wordCount * mult;
}, [wpm]);
useEffect(() => {
@@ -90,16 +89,16 @@ export default function RapidReader({
if (timeoutRef.current) clearTimeout(timeoutRef.current);
return;
}
- if (idx >= total) {
- setPlaying(false);
- onComplete?.();
- return;
- }
timeoutRef.current = setTimeout(() => {
- setIdx((i) => i + 1);
+ const nextWordIndex = wordIndex + current.wordCount;
+ if (nextWordIndex < totalWords) setWordIndex(nextWordIndex);
+ else {
+ setPlaying(false);
+ onComplete?.();
+ }
}, delayFor(current));
return () => clearTimeout(timeoutRef.current);
- }, [playing, idx, total, current, delayFor, onComplete]);
+ }, [playing, wordIndex, totalWords, current, delayFor, onComplete]);
// Keyboard controls — only active while this component is mounted. Claimed in
// the capture phase so a handled key never reaches a bubble-phase window
@@ -108,31 +107,45 @@ export default function RapidReader({
useKeyCapture({
enabledInDialog: inDialog,
onKeyDown: (e) => {
- if (e.key === ' ') setPlaying((p) => !p);
- else if (e.key === 'ArrowLeft') setIdx((i) => Math.max(0, i - 1));
- else if (e.key === 'ArrowRight') setIdx((i) => Math.min(total - 1, i + 1));
- else if (e.key === 'r' || e.key === 'R') { setIdx(0); setPlaying(true); }
- else if (e.key === '+' || e.key === '=') setWpm((w) => Math.min(1200, w + 25));
- else if (e.key === '-' || e.key === '_') setWpm((w) => Math.max(100, w - 25));
+ if (e.key === ' ') {
+ if (wordIndex >= totalWords - 1) { setWordIndex(0); setPlaying(true); }
+ else setPlaying((p) => !p);
+ }
+ else if (e.key === 'ArrowLeft') setWordIndex((value) => Math.max(0, value - 1));
+ else if (e.key === 'ArrowRight') setWordIndex((value) => Math.min(totalWords - 1, value + 1));
+ else if (e.key === 'r' || e.key === 'R') { setWordIndex(0); setPlaying(true); }
+ else if ((e.key === 'b' || e.key === 'B') && onBookmark) onBookmark(wordIndex);
+ else if (e.key === '+' || e.key === '=') setWpm((value) => {
+ const next = Math.min(1000, value + 25);
+ onWpmChange?.(next);
+ return next;
+ });
+ else if (e.key === '-' || e.key === '_') setWpm((value) => {
+ const next = Math.max(100, value - 25);
+ onWpmChange?.(next);
+ return next;
+ });
else if (e.key === 'Escape' && onClose) onClose();
else return false;
return true;
},
});
- const restart = () => { setIdx(0); setPlaying(true); };
+ const restart = () => { setWordIndex(0); setPlaying(true); };
const togglePlay = () => {
- if (idx >= total - 1) { restart(); return; }
+ if (wordIndex >= totalWords - 1) { restart(); return; }
setPlaying((p) => !p);
};
- const back = () => { setPlaying(false); setIdx((i) => Math.max(0, i - 5)); };
- const fwd = () => { setPlaying(false); setIdx((i) => Math.min(total - 1, i + 5)); };
+ const back = () => { setPlaying(false); setWordIndex((value) => Math.max(0, value - 5)); };
+ const fwd = () => { setPlaying(false); setWordIndex((value) => Math.min(totalWords - 1, value + 5)); };
+ const changeWpm = (next) => { setWpm(next); onWpmChange?.(next); };
+ const changeChunkSize = (next) => { setChunkSize(next); onChunkSizeChange?.(next); };
- const progress = total ? ((idx + 1) / total) * 100 : 0;
- const elapsedSec = Math.round(((idx + 1) * 60) / Math.max(60, wpm));
- const totalSec = Math.round((total * 60) / Math.max(60, wpm));
+ const progress = totalWords ? (Math.min(totalWords, wordIndex + current.wordCount) / totalWords) * 100 : 0;
+ const elapsedSec = Math.round(((wordIndex + 1) * 60) / Math.max(60, wpm));
+ const totalSec = Math.round((totalWords * 60) / Math.max(60, wpm));
- if (!total) {
+ if (!totalWords) {
return (
<div className={`bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500 ${compact ? '' : 'min-h-64'}`}>
Paste or pass some text to start reading.
@@ -156,7 +169,7 @@ export default function RapidReader({
style={{ minWidth: '12ch' }}
>
{/* Position chunk so its focal letter sits on the center guide */}
- <FocalSlot chunk={current} focalColor={focalColor} />
+ <FocalSlot chunk={current.value} focalColor={focalColor} />
</div>
</div>
@@ -207,6 +220,17 @@ export default function RapidReader({
>
<RotateCcw size={16} />
</button>
+ {onBookmark && (
+ <button
+ type="button"
+ onClick={() => onBookmark(wordIndex)}
+ className="min-h-10 min-w-10 flex items-center justify-center rounded-lg border border-port-border text-gray-400 hover:text-white hover:bg-port-bg/60"
+ title="Save bookmark (B)"
+ aria-label="Save bookmark"
+ >
+ <Bookmark size={16} />
+ </button>
+ )}
{onClose && (
<button
type="button"
@@ -229,7 +253,8 @@ export default function RapidReader({
max={1000}
step={25}
value={wpm}
- onChange={(e) => setWpm(Number(e.target.value))}
+ onChange={(e) => changeWpm(Number(e.target.value))}
+ aria-label="Reading speed"
className="w-28 sm:w-32 accent-port-accent"
/>
<span className="font-mono text-gray-300 w-10 text-right">{wpm}</span>
@@ -237,7 +262,7 @@ export default function RapidReader({
<div className="flex items-center gap-1 border border-port-border rounded-md overflow-hidden">
<button
type="button"
- onClick={() => setChunkSize(1)}
+ onClick={() => changeChunkSize(1)}
className={`px-2 py-1 text-xs ${chunkSize === 1 ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}
aria-pressed={chunkSize === 1}
aria-label="Show one word at a time"
@@ -246,7 +271,7 @@ export default function RapidReader({
</button>
<button
type="button"
- onClick={() => setChunkSize(2)}
+ onClick={() => changeChunkSize(2)}
className={`px-2 py-1 text-xs ${chunkSize === 2 ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}
aria-pressed={chunkSize === 2}
aria-label="Show two words at a time"
@@ -255,7 +280,7 @@ export default function RapidReader({
</button>
</div>
<span className="font-mono text-gray-500">
- {idx + 1}/{total} · {elapsedSec}s/{totalSec}s
+ {Math.min(wordIndex + 1, totalWords)}/{totalWords} words · {elapsedSec}s/{totalSec}s
</span>
</div>
</div>
diff --git a/client/src/components/RapidReader.test.jsx b/client/src/components/RapidReader.test.jsx
index 40e9c4d137..cf3b6e3c19 100644
--- a/client/src/components/RapidReader.test.jsx
+++ b/client/src/components/RapidReader.test.jsx
@@ -56,6 +56,27 @@ describe('RapidReader keyboard transport', () => {
expect(voiceHotkey()).not.toHaveBeenCalled();
});
+ it('starts at a canonical word offset and keeps that place when chunk size changes', () => {
+ const { container } = renderReader({ initialWordIndex: 2 });
+ expect(container.textContent).toContain('3/4 words');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show two words at a time' }));
+
+ expect(container.textContent).toContain('3/4 words');
+ expect(container.textContent).toContain('charlie');
+ });
+
+ it('saves the current canonical position from the bookmark button or B key', () => {
+ const onBookmark = vi.fn();
+ renderReader({ initialWordIndex: 2, onBookmark });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save bookmark' }));
+ act(() => { fireEvent.keyDown(document.body, { key: 'b', code: 'KeyB' }); });
+
+ expect(onBookmark).toHaveBeenNthCalledWith(1, 2);
+ expect(onBookmark).toHaveBeenNthCalledWith(2, 2);
+ });
+
it('stands down while an unrelated dialog is open', () => {
const { container } = renderReader();
const dialog = document.createElement('div');
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index b79fa0e29d..c37012bb03 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -133,6 +133,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
+| `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useOpenWorldSettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 1944a79f94..fc21ea669a 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -105,6 +105,7 @@ export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './morsePractice.js';
export * from './moodBoardItemSrc.js';
+export * from './rapidReaderPosition.js';
export * from './registerServiceWorker.js';
export * from './safeStorage.js';
export * from './sameJsonShape.js';
diff --git a/client/src/lib/rapidReaderPosition.js b/client/src/lib/rapidReaderPosition.js
new file mode 100644
index 0000000000..3b467c66ad
--- /dev/null
+++ b/client/src/lib/rapidReaderPosition.js
@@ -0,0 +1,83 @@
+import {
+ safeReadJsonStorage,
+ safeWriteJsonStorage,
+} from './safeStorage.js';
+
+export const RAPID_READER_PROGRESS_KEY = 'portos-rapid-reader-progress-v1';
+
+const MAX_SAVED_DOCUMENTS = 20;
+
+export const rapidReaderWords = (text = '') => Array.from(text.matchAll(/\S+/g), (match) => ({
+ text: match[0],
+ start: match.index,
+ end: match.index + match[0].length,
+}));
+
+export const rapidReaderWordIndexAtCursor = (text, cursor = 0) => {
+ const words = rapidReaderWords(text);
+ if (!words.length) return 0;
+ const boundedCursor = Math.max(0, Math.min(Number.isFinite(cursor) ? cursor : 0, text.length));
+ const nextIndex = words.findIndex((word) => word.end > boundedCursor);
+ return nextIndex === -1 ? words.length - 1 : nextIndex;
+};
+
+// A compact, deterministic identifier lets reading progress follow pasted text
+// without persisting that potentially-private text in localStorage.
+export const rapidReaderDocumentId = (text = '') => {
+ let hash = 0x811c9dc5;
+ for (let index = 0; index < text.length; index += 1) {
+ hash ^= text.charCodeAt(index);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return `${text.length}-${(hash >>> 0).toString(36)}`;
+};
+
+const validProgress = (entry, wordCount) => {
+ if (!entry || entry.wordCount !== wordCount) return null;
+ if (!Number.isInteger(entry.wordIndex) || entry.wordIndex < 0 || entry.wordIndex >= wordCount) return null;
+ return {
+ wordIndex: entry.wordIndex,
+ wordCount,
+ wpm: Number.isFinite(entry.wpm) ? Math.max(100, Math.min(1000, entry.wpm)) : 350,
+ chunkSize: entry.chunkSize === 2 ? 2 : 1,
+ updatedAt: Number.isFinite(entry.updatedAt) ? entry.updatedAt : 0,
+ };
+};
+
+export const readRapidReaderProgress = (text, identity = {}) => {
+ const wordCount = identity.wordCount ?? rapidReaderWords(text).length;
+ if (!wordCount) return null;
+ const stored = safeReadJsonStorage(RAPID_READER_PROGRESS_KEY, null);
+ if (stored?.version !== 1 || typeof stored.entries !== 'object' || !stored.entries) return null;
+ const documentId = identity.documentId ?? rapidReaderDocumentId(text);
+ return validProgress(stored.entries[documentId], wordCount);
+};
+
+export const writeRapidReaderProgress = (text, progress, identity = {}) => {
+ const wordCount = identity.wordCount ?? rapidReaderWords(text).length;
+ const entry = validProgress({ ...progress, wordCount, updatedAt: Date.now() }, wordCount);
+ if (!entry || entry.wordIndex === 0) return null;
+
+ const stored = safeReadJsonStorage(RAPID_READER_PROGRESS_KEY, null);
+ const previousEntries = stored?.version === 1 && stored.entries && typeof stored.entries === 'object'
+ ? stored.entries
+ : {};
+ const documentId = identity.documentId ?? rapidReaderDocumentId(text);
+ const entries = Object.fromEntries(
+ Object.entries({ ...previousEntries, [documentId]: entry })
+ .sort(([, left], [, right]) => (right?.updatedAt || 0) - (left?.updatedAt || 0))
+ .slice(0, MAX_SAVED_DOCUMENTS),
+ );
+ safeWriteJsonStorage(RAPID_READER_PROGRESS_KEY, { version: 1, entries });
+ return entry;
+};
+
+export const clearRapidReaderProgress = (text, identity = {}) => {
+ const stored = safeReadJsonStorage(RAPID_READER_PROGRESS_KEY, null);
+ if (stored?.version !== 1 || typeof stored.entries !== 'object' || !stored.entries) return;
+ const documentId = identity.documentId ?? rapidReaderDocumentId(text);
+ if (!Object.hasOwn(stored.entries, documentId)) return;
+ const entries = { ...stored.entries };
+ delete entries[documentId];
+ safeWriteJsonStorage(RAPID_READER_PROGRESS_KEY, { version: 1, entries });
+};
diff --git a/client/src/lib/rapidReaderPosition.test.js b/client/src/lib/rapidReaderPosition.test.js
new file mode 100644
index 0000000000..78aeb4ce13
--- /dev/null
+++ b/client/src/lib/rapidReaderPosition.test.js
@@ -0,0 +1,55 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ RAPID_READER_PROGRESS_KEY,
+ clearRapidReaderProgress,
+ rapidReaderDocumentId,
+ rapidReaderWordIndexAtCursor,
+ readRapidReaderProgress,
+ writeRapidReaderProgress,
+} from './rapidReaderPosition.js';
+
+beforeEach(() => {
+ localStorage.clear();
+ vi.useRealTimers();
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('rapidReaderWordIndexAtCursor', () => {
+ it('starts at the word containing the cursor or the next word in whitespace', () => {
+ const text = 'alpha bravo charlie';
+ expect(rapidReaderWordIndexAtCursor(text, 2)).toBe(0);
+ expect(rapidReaderWordIndexAtCursor(text, 5)).toBe(1);
+ expect(rapidReaderWordIndexAtCursor(text, 8)).toBe(1);
+ expect(rapidReaderWordIndexAtCursor(text, text.length)).toBe(2);
+ });
+});
+
+describe('Rapid Reader progress persistence', () => {
+ it('stores progress by fingerprint without storing the source text', () => {
+ vi.spyOn(Date, 'now').mockReturnValue(1234);
+ const text = 'alpha bravo charlie delta';
+
+ writeRapidReaderProgress(text, { wordIndex: 2, wpm: 425, chunkSize: 2 });
+
+ expect(readRapidReaderProgress(text)).toEqual({
+ wordIndex: 2,
+ wordCount: 4,
+ wpm: 425,
+ chunkSize: 2,
+ updatedAt: 1234,
+ });
+ const raw = localStorage.getItem(RAPID_READER_PROGRESS_KEY);
+ expect(raw).toContain(rapidReaderDocumentId(text));
+ expect(raw).not.toContain(text);
+ });
+
+ it('rejects stale or invalid progress and can clear a bookmark', () => {
+ const text = 'alpha bravo charlie';
+ writeRapidReaderProgress(text, { wordIndex: 1, wpm: 350, chunkSize: 1 });
+ expect(readRapidReaderProgress(`${text} delta`)).toBeNull();
+
+ clearRapidReaderProgress(text);
+ expect(readRapidReaderProgress(text)).toBeNull();
+ });
+});
diff --git a/client/src/pages/RapidReader.jsx b/client/src/pages/RapidReader.jsx
index c3ff22ef75..c8ca4add60 100644
--- a/client/src/pages/RapidReader.jsx
+++ b/client/src/pages/RapidReader.jsx
@@ -1,8 +1,15 @@
-import { useState } from 'react';
-import { BookOpen, ClipboardPaste, Eraser, ExternalLink, Zap } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Bookmark, BookOpen, ClipboardPaste, Eraser, ExternalLink, Play, Zap } from 'lucide-react';
import RapidReader from '../components/RapidReader';
import PageHeader from '../components/PageHeader';
import { readClipboard } from '../lib/clipboard';
+import {
+ clearRapidReaderProgress,
+ rapidReaderDocumentId,
+ rapidReaderWordIndexAtCursor,
+ readRapidReaderProgress,
+ writeRapidReaderProgress,
+} from '../lib/rapidReaderPosition';
import { useAsyncAction } from '../hooks/useAsyncAction';
import {
ACCELERANDO_LICENSE_URL,
@@ -22,12 +29,27 @@ const focalPalette = [
export default function RapidReaderPage() {
const [text, setText] = useState('');
- const [active, setActive] = useState('');
+ const [active, setActive] = useState(null);
const [wpm, setWpm] = useState(350);
const [chunkSize, setChunkSize] = useState(1);
const [focalColor, setFocalColor] = useState('#ef4444');
+ const [bookmark, setBookmark] = useState(null);
const [bookStatus, setBookStatus] = useState('idle');
const [bookError, setBookError] = useState('');
+ const textareaRef = useRef(null);
+ const latestProgressRef = useRef(null);
+ const lastAutoSavedWordRef = useRef(-1);
+
+ const documentText = useMemo(() => text.trim(), [text]);
+ const wordCount = useMemo(() => documentText ? documentText.split(/\s+/).length : 0, [documentText]);
+ const documentIdentity = useMemo(() => ({
+ documentId: rapidReaderDocumentId(documentText),
+ wordCount,
+ }), [documentText, wordCount]);
+
+ useEffect(() => {
+ setBookmark(readRapidReaderProgress(documentText, documentIdentity));
+ }, [documentText, documentIdentity]);
const [loadBook, loadingBook] = useAsyncAction(async () => {
setBookStatus('loading');
@@ -48,22 +70,62 @@ export default function RapidReaderPage() {
return book;
});
- const start = () => {
- const trimmed = text.trim();
- if (!trimmed) return;
- setActive(trimmed);
+ const startAt = (wordIndex, saved = null) => {
+ if (!documentText) return;
+ if (saved) {
+ setWpm(saved.wpm);
+ setChunkSize(saved.chunkSize);
+ }
+ latestProgressRef.current = null;
+ lastAutoSavedWordRef.current = -1;
+ setActive({ text: documentText, initialWordIndex: wordIndex, ...documentIdentity });
};
+ const persistProgress = useCallback((document, progress, updateBookmark = true) => {
+ if (!document?.text || !progress || progress.wordIndex <= 0) return;
+ if (progress.wordIndex >= progress.wordCount - 1) {
+ clearRapidReaderProgress(document.text, document);
+ if (updateBookmark) setBookmark(null);
+ return;
+ }
+ const saved = writeRapidReaderProgress(document.text, progress, document);
+ if (saved && updateBookmark) setBookmark(saved);
+ }, []);
+
+ const handlePositionChange = useCallback((progress) => {
+ latestProgressRef.current = progress;
+ if (!active || progress.wordIndex <= 0) return;
+ if (lastAutoSavedWordRef.current >= 0 && progress.wordIndex - lastAutoSavedWordRef.current < 10) return;
+ lastAutoSavedWordRef.current = progress.wordIndex;
+ persistProgress(active, progress);
+ }, [active, persistProgress]);
+
+ const saveBookmark = useCallback((wordIndex) => {
+ if (!active) return;
+ persistProgress(active, { ...latestProgressRef.current, wordIndex });
+ }, [active, persistProgress]);
+
const reset = () => {
- setActive('');
+ if (active) persistProgress(active, latestProgressRef.current);
+ setActive(null);
+ };
+
+ const complete = () => {
+ if (!active) return;
+ clearRapidReaderProgress(active.text, active);
+ setBookmark(null);
};
+ useEffect(() => {
+ if (!active) return undefined;
+ return () => persistProgress(active, latestProgressRef.current, false);
+ }, [active, persistProgress]);
+
const pasteFromClipboard = async () => {
const t = await readClipboard();
if (t) setText(t);
};
- const wordCount = text.trim() ? text.trim().split(/\s+/).length : 0;
const estSec = Math.round((wordCount * 60) / Math.max(60, wpm));
return (
@@ -78,15 +140,22 @@ export default function RapidReaderPage() {
{active ? (
<div className="space-y-4">
<RapidReader
- text={active}
+ text={active.text}
wpm={wpm}
chunkSize={chunkSize}
focalColor={focalColor}
+ initialWordIndex={active.initialWordIndex}
autoPlay
onClose={reset}
+ onComplete={complete}
+ onPositionChange={handlePositionChange}
+ onBookmark={saveBookmark}
+ onWpmChange={setWpm}
+ onChunkSizeChange={setChunkSize}
/>
<div className="flex flex-wrap items-center gap-3 text-xs text-gray-500">
- <span>Space = play/pause · ← → step · R restart · +/− WPM · Esc close</span>
+ <span>Space = play/pause · ← → step · B bookmark · R restart · +/− WPM · Esc close</span>
+ <span>Progress also saves automatically while reading.</span>
</div>
</div>
) : (
@@ -179,6 +248,7 @@ export default function RapidReaderPage() {
</div>
<textarea
id="rr-text"
+ ref={textareaRef}
value={text}
onChange={(e) => setText(e.target.value)}
rows={10}
@@ -250,15 +320,41 @@ export default function RapidReaderPage() {
</div>
</div>
- <div className="flex items-center gap-3">
+ <div className="flex flex-wrap items-center gap-3">
<button
type="button"
- onClick={start}
+ onClick={() => startAt(0)}
disabled={!text.trim()}
className="inline-flex items-center gap-2 min-h-10 px-4 py-2 rounded-lg bg-port-accent text-white font-medium disabled:opacity-40 disabled:cursor-not-allowed hover:bg-port-accent/90"
>
<Zap size={16} /> Start reading
</button>
+ <button
+ type="button"
+ onClick={() => startAt(rapidReaderWordIndexAtCursor(text, textareaRef.current?.selectionStart || 0))}
+ disabled={!documentText}
+ className="inline-flex items-center gap-2 min-h-10 px-4 py-2 rounded-lg border border-port-accent/50 text-port-accent font-medium disabled:opacity-40 disabled:cursor-not-allowed hover:bg-port-accent/10"
+ >
+ <Play size={16} /> Start at cursor
+ </button>
+ {bookmark && (
+ <>
+ <button
+ type="button"
+ onClick={() => startAt(bookmark.wordIndex, bookmark)}
+ className="inline-flex items-center gap-2 min-h-10 px-4 py-2 rounded-lg border border-port-border text-gray-200 font-medium hover:border-port-accent/60 hover:bg-port-bg/40"
+ >
+ <Bookmark size={16} className="text-port-accent" /> Resume at word {bookmark.wordIndex + 1}
+ </button>
+ <button
+ type="button"
+ onClick={() => { clearRapidReaderProgress(documentText, documentIdentity); setBookmark(null); }}
+ className="min-h-10 px-3 py-2 text-xs text-gray-500 hover:text-white"
+ >
+ Clear bookmark
+ </button>
+ </>
+ )}
<span className="text-xs text-gray-500">
Tip: many surfaces in PortOS expose a Rapid Read button — Briefing, Wiki notes, and more.
</span>
diff --git a/client/src/pages/RapidReader.test.jsx b/client/src/pages/RapidReader.test.jsx
index fc8f1a25af..5f88be52b9 100644
--- a/client/src/pages/RapidReader.test.jsx
+++ b/client/src/pages/RapidReader.test.jsx
@@ -10,6 +10,7 @@ const api = vi.hoisted(() => ({
vi.mock('../services/api', () => api);
const RapidReaderPage = (await import('./RapidReader')).default;
+const { writeRapidReaderProgress } = await import('../lib/rapidReaderPosition');
const BOOK = {
id: 'accelerando',
@@ -20,7 +21,10 @@ const BOOK = {
cached: false,
};
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+});
describe('RapidReader Accelerando loader', () => {
it('waits for the explicit load action and puts the book into the reader text area', async () => {
@@ -64,3 +68,41 @@ describe('RapidReader Accelerando loader', () => {
expect(screen.getByRole('button', { name: 'Load Accelerando' })).toBeEnabled();
});
});
+
+describe('RapidReader reading position', () => {
+ it('starts from the word under the textarea cursor', () => {
+ render(<RapidReaderPage />);
+ const textarea = screen.getByRole('textbox', { name: 'Text to read' });
+ fireEvent.change(textarea, { target: { value: 'alpha bravo charlie delta' } });
+ textarea.setSelectionRange(13, 13);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Start at cursor' }));
+
+ expect(screen.getByText(/3\/4 words/)).toBeInTheDocument();
+ });
+
+ it('offers and restores saved progress for the same text', () => {
+ const text = 'alpha bravo charlie delta echo';
+ writeRapidReaderProgress(text, { wordIndex: 2, wpm: 425, chunkSize: 1 });
+ render(<RapidReaderPage />);
+
+ fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), { target: { value: text } });
+ fireEvent.click(screen.getByRole('button', { name: 'Resume at word 3' }));
+
+ expect(screen.getByText(/3\/5 words/)).toBeInTheDocument();
+ expect(screen.getByLabelText('Reading speed')).toHaveValue('425');
+ });
+
+ it('saves a bookmark from the reader and offers it after closing', () => {
+ render(<RapidReaderPage />);
+ fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), {
+ target: { value: 'alpha bravo charlie delta echo' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Start reading' }));
+ fireEvent.keyDown(document.body, { key: 'ArrowRight', code: 'ArrowRight' });
+ fireEvent.click(screen.getByRole('button', { name: 'Save bookmark' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
+
+ expect(screen.getByRole('button', { name: 'Resume at word 2' })).toBeInTheDocument();
+ });
+});