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: improve rapid reader navigation and text flow

[._.]/ Adam Eivy0f21391f8adc
diff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsx
index 274a10c971..92d220fe50 100644
--- a/client/src/components/RapidReader.jsx
+++ b/client/src/components/RapidReader.jsx
@@ -7,34 +7,39 @@ import { rapidReaderWords } from '../lib/rapidReaderPosition';
import { formatCountdown } from '../utils/formatters';
// 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
-// index into the trimmed word that should be highlighted.
+// shorter words use a left-shifted ORP, longer words shift right. Punctuation
+// is ignored when choosing the focal letter, so a quote or closing bracket can
+// never become the visual anchor.
const orpIndex = (word) => {
- const w = word || '';
- const len = w.length;
- if (len <= 1) return 0;
- if (len <= 5) return 1;
- if (len <= 9) return 2;
- if (len <= 13) return 3;
- return 4;
+ const chars = Array.from(word || '');
+ const contentIndexes = chars
+ .map((char, index) => (/^[\p{L}\p{N}]$/u.test(char) ? index : -1))
+ .filter((index) => index >= 0);
+ const len = contentIndexes.length;
+ if (!len) return 0;
+ const contentIndex = len <= 1 ? 0 : len <= 5 ? 1 : len <= 9 ? 2 : len <= 13 ? 3 : 4;
+ return contentIndexes[Math.min(contentIndex, len - 1)];
};
+const MAX_TWO_WORD_CHARS = 20;
+
// 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.
+// would have begun one word earlier. A width cap keeps two long words from
+// becoming an unreadable wall on a phone-sized reader.
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 };
+ const chunkWords = words.slice(wordIndex, wordIndex + (chunkSize === 2 ? 2 : 1));
+ const value = chunkWords.map(({ text }) => text).join(' ');
+ if (chunkSize === 2 && chunkWords.length === 2 && value.length <= MAX_TWO_WORD_CHARS) {
+ return { value, words: chunkWords, wordCount: 2 };
}
- return { value: a, wordCount: 1 };
+ return { value: chunkWords[0]?.text || '', words: chunkWords.slice(0, 1), wordCount: 1 };
};
// Sentence-end detection: word ends with terminal punctuation. Used to add a
// brief extra pause so the reader can register the boundary.
-const endsSentence = (word) => /[.!?…]"?$/.test(word || '');
-const endsClause = (word) => /[,;:)]"?$/.test(word || '');
+const endsSentence = (word) => /[.!?…](?:["'”’»」』)\]]+)?$/u.test(word || '');
+const endsClause = (word) => /[,;:](?:["'”’»」』)\]]+)?$/u.test(word || '');
// Core reader display — drop into any container. Self-paced; emits onComplete
// when the last token is shown.
@@ -47,6 +52,7 @@ export default function RapidReader({
compact = false,
inDialog = false,
initialWordIndex = 0,
+ sections = [],
onClose,
onComplete,
onPositionChange,
@@ -63,6 +69,13 @@ export default function RapidReader({
const words = useMemo(() => rapidReaderWords(text), [text]);
const totalWords = words.length;
const current = useMemo(() => chunkAt(words, wordIndex, chunkSize), [words, wordIndex, chunkSize]);
+ const availableSections = useMemo(() => (Array.isArray(sections) ? sections : [])
+ .filter((section) => Number.isInteger(section?.wordIndex) && section.wordIndex >= 0 && section.wordIndex < totalWords)
+ .sort((left, right) => left.wordIndex - right.wordIndex), [sections, totalWords]);
+ const currentSection = useMemo(() => availableSections.reduce(
+ (selected, section) => (section.wordIndex <= wordIndex ? section : selected),
+ null,
+ ), [availableSections, wordIndex]);
// Position is a canonical word offset, so changing chunk size never jumps to
// a different place in the source text.
@@ -141,6 +154,12 @@ export default function RapidReader({
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 jumpToSection = (event) => {
+ const nextIndex = Number(event.target.value);
+ if (!Number.isInteger(nextIndex)) return;
+ setPlaying(false);
+ setWordIndex(Math.max(0, Math.min(totalWords - 1, nextIndex)));
+ };
const progress = totalWords ? (Math.min(totalWords, wordIndex + current.wordCount) / totalWords) * 100 : 0;
// Time left to finish, derived from the live `wpm` so it re-renders the moment
@@ -169,11 +188,11 @@ export default function RapidReader({
aria-hidden="true"
/>
<div
- className="relative font-mono text-3xl sm:text-5xl tracking-wide text-white whitespace-pre"
+ className="relative font-mono text-2xl sm:text-5xl tracking-wide text-white whitespace-pre"
style={{ minWidth: '12ch' }}
>
{/* Position chunk so its focal letter sits on the center guide */}
- <FocalSlot chunk={current.value} focalColor={focalColor} />
+ <FocalSlot words={current.words} focalColor={focalColor} />
</div>
</div>
@@ -192,7 +211,7 @@ export default function RapidReader({
type="button"
onClick={back}
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="Back 5 (←)"
+ title="Back 5 words"
aria-label="Back 5 words"
>
<Rewind size={16} />
@@ -201,7 +220,7 @@ export default function RapidReader({
type="button"
onClick={togglePlay}
className="min-h-10 min-w-10 flex items-center justify-center rounded-lg bg-port-accent/15 border border-port-accent/40 text-port-accent hover:bg-port-accent/25"
- title={playing ? 'Pause (space)' : 'Play (space)'}
+ title={playing ? 'Pause' : 'Play'}
aria-label={playing ? 'Pause' : 'Play'}
>
{playing ? <Pause size={16} /> : <Play size={16} />}
@@ -210,7 +229,7 @@ export default function RapidReader({
type="button"
onClick={fwd}
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="Forward 5 (→)"
+ title="Forward 5 words"
aria-label="Forward 5 words"
>
<FastForward size={16} />
@@ -219,7 +238,7 @@ export default function RapidReader({
type="button"
onClick={restart}
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="Restart (R)"
+ title="Restart"
aria-label="Restart"
>
<RotateCcw size={16} />
@@ -229,7 +248,7 @@ export default function RapidReader({
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)"
+ title="Save bookmark"
aria-label="Save bookmark"
>
<Bookmark size={16} />
@@ -249,6 +268,24 @@ export default function RapidReader({
</div>
<div className="flex flex-wrap items-center gap-3 text-xs text-gray-400">
+ {availableSections.length > 0 && (
+ <label className="flex items-center gap-2">
+ <span className="text-gray-500">Jump to</span>
+ <select
+ value={currentSection?.wordIndex ?? ''}
+ onChange={jumpToSection}
+ aria-label="Navigate sections"
+ className="max-w-[13rem] bg-port-bg border border-port-border rounded-md px-2 py-1.5 text-gray-300"
+ >
+ <option value="">Beginning</option>
+ {availableSections.map((section) => (
+ <option key={`${section.id}-${section.wordIndex}`} value={section.wordIndex}>
+ {section.kind === 'chapter' ? 'Chapter · ' : 'Part · '}{section.title}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
<label className="flex items-center gap-2">
<span className="text-gray-500">WPM</span>
<input
@@ -284,7 +321,7 @@ export default function RapidReader({
</button>
</div>
<span className="font-mono text-gray-500">
- {Math.min(wordIndex + 1, totalWords)}/{totalWords} words · {formatCountdown(remainingSec)} left
+ {Math.min(wordIndex + 1, totalWords)}{current.wordCount > 1 ? `–${Math.min(wordIndex + current.wordCount, totalWords)}` : ''}/{totalWords} words · {formatCountdown(remainingSec)} left
</span>
</div>
</div>
@@ -294,24 +331,23 @@ export default function RapidReader({
// Layout helper that anchors the focal letter on the vertical center guide.
// Splits the chunk so the focal char's left edge sits at the container midpoint.
-function FocalSlot({ chunk, focalColor }) {
- const parts = chunk.split(' ');
- const target = parts.length === 2
- ? (parts[0].length >= parts[1].length ? 0 : 1)
- : 0;
- const word = parts[target] || '';
- const idx = orpIndex(word);
- const left = word.slice(0, idx);
- const focal = word.charAt(idx);
- const right = word.slice(idx + 1);
+function FocalSlot({ words, focalColor }) {
+ const parts = words.map(({ text }) => text);
+ const target = parts.reduce((best, word, index) => {
+ const offset = parts.slice(0, index).reduce((total, part) => total + part.length + 1, 0) + orpIndex(word);
+ const bestOffset = parts.slice(0, best).reduce((total, part) => total + part.length + 1, 0) + orpIndex(parts[best]);
+ const midpoint = (parts.join(' ').length - 1) / 2;
+ return Math.abs(offset - midpoint) < Math.abs(bestOffset - midpoint) ? index : best;
+ }, 0);
+ const chars = Array.from(parts[target] || '');
+ const idx = orpIndex(parts[target]);
+ const left = chars.slice(0, idx).join('');
+ const focal = chars[idx] || '';
+ const right = chars.slice(idx + 1).join('');
// Build the left/right halves around the focal char.
- const leftHalf = parts.length === 2 && target === 1
- ? `${parts[0]} ${left}`
- : left;
- const rightHalf = parts.length === 2 && target === 0
- ? `${right} ${parts[1]}`
- : right;
+ const leftHalf = `${parts.slice(0, target).join(' ')}${target > 0 ? ' ' : ''}${left}`;
+ const rightHalf = `${right}${target < parts.length - 1 ? ` ${parts.slice(target + 1).join(' ')}` : ''}`;
return (
<div className="flex items-baseline justify-center">
diff --git a/client/src/components/RapidReader.test.jsx b/client/src/components/RapidReader.test.jsx
index 65443c4225..746271188d 100644
--- a/client/src/components/RapidReader.test.jsx
+++ b/client/src/components/RapidReader.test.jsx
@@ -62,10 +62,32 @@ describe('RapidReader keyboard transport', () => {
fireEvent.click(screen.getByRole('button', { name: 'Show two words at a time' }));
- expect(container.textContent).toContain('3/4 words');
+ expect(container.textContent).toContain('3–4/4 words');
expect(container.textContent).toContain('charlie');
});
+ it('keeps two-word frames readable and reports the full visible range', () => {
+ const { container } = renderReader({ text: 'alpha bravo charlie delta', chunkSize: 2 });
+
+ expect(container.textContent).toContain('1–2/4 words');
+ expect(container.textContent).toContain('alpha bravo');
+ });
+
+ it('jumps to a navigable section and pauses playback', () => {
+ const sections = [
+ { id: 'part-1', title: 'PART 1: Start', kind: 'part', wordIndex: 0 },
+ { id: 'chapter-1', title: 'Chapter 1: Alpha', kind: 'chapter', wordIndex: 2 },
+ ];
+ const { container } = renderReader({ text: 'one two three four', sections, autoPlay: true });
+ const select = screen.getByRole('combobox', { name: 'Navigate sections' });
+
+ fireEvent.change(select, { target: { value: '2' } });
+
+ expect(select).toHaveValue('2');
+ expect(container.textContent).toContain('Chapter · Chapter 1: Alpha');
+ expect(screen.getByLabelText('Play')).toBeInTheDocument();
+ });
+
it('saves the current canonical position from the bookmark button or B key', () => {
const onBookmark = vi.fn();
renderReader({ initialWordIndex: 2, onBookmark });
diff --git a/client/src/lib/rapidReaderPosition.js b/client/src/lib/rapidReaderPosition.js
index 3b467c66ad..67d2a4b04d 100644
--- a/client/src/lib/rapidReaderPosition.js
+++ b/client/src/lib/rapidReaderPosition.js
@@ -7,11 +7,53 @@ 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,
-}));
+const PUNCTUATION_ONLY = /^[\p{P}\p{S}]+$/u;
+const OPENING_PUNCTUATION_ONLY = /^[\p{Ps}\p{Pi}'"¿¡]+$/u;
+
+// RSVP should not spend a frame on a quote, bracket, comma, or ellipsis that
+// was separated from its word by line wrapping or HTML conversion. Keep
+// opening punctuation with the next word and closing punctuation with the
+// previous word while retaining source offsets for cursor resume.
+export const rapidReaderWords = (text = '') => {
+ const words = [];
+ let pendingPrefix = '';
+ let pendingStart = null;
+
+ for (const match of text.matchAll(/\S+/g)) {
+ const value = match[0];
+ const start = match.index;
+ const end = start + value.length;
+
+ if (PUNCTUATION_ONLY.test(value)) {
+ if (OPENING_PUNCTUATION_ONLY.test(value) || !words.length) {
+ pendingPrefix += value;
+ if (pendingStart == null) pendingStart = start;
+ } else {
+ const previous = words[words.length - 1];
+ previous.text += value;
+ previous.end = end;
+ }
+ continue;
+ }
+
+ words.push({
+ text: `${pendingPrefix}${value}`,
+ start: pendingStart ?? start,
+ end,
+ });
+ pendingPrefix = '';
+ pendingStart = null;
+ }
+
+ // A dangling opening quote at EOF still belongs to the final displayed
+ // word; dropping it would make the reader silently change the source text.
+ if (pendingPrefix && words.length) {
+ const previous = words[words.length - 1];
+ previous.text += pendingPrefix;
+ }
+
+ return words;
+};
export const rapidReaderWordIndexAtCursor = (text, cursor = 0) => {
const words = rapidReaderWords(text);
diff --git a/client/src/lib/rapidReaderPosition.test.js b/client/src/lib/rapidReaderPosition.test.js
index 78aeb4ce13..d28aa9dec1 100644
--- a/client/src/lib/rapidReaderPosition.test.js
+++ b/client/src/lib/rapidReaderPosition.test.js
@@ -3,6 +3,7 @@ import {
RAPID_READER_PROGRESS_KEY,
clearRapidReaderProgress,
rapidReaderDocumentId,
+ rapidReaderWords,
rapidReaderWordIndexAtCursor,
readRapidReaderProgress,
writeRapidReaderProgress,
@@ -25,6 +26,18 @@ describe('rapidReaderWordIndexAtCursor', () => {
});
});
+describe('rapidReaderWords', () => {
+ it('folds dangling punctuation into the nearest readable word', () => {
+ expect(rapidReaderWords('She said " hello ," then paused …').map(({ text }) => text)).toEqual([
+ 'She', 'said', '"hello,"', 'then', 'paused…',
+ ]);
+ });
+
+ it('does not count punctuation-only frames as words', () => {
+ expect(rapidReaderWords('wait — really?').map(({ text }) => text)).toEqual(['wait—', 'really?']);
+ });
+});
+
describe('Rapid Reader progress persistence', () => {
it('stores progress by fingerprint without storing the source text', () => {
vi.spyOn(Date, 'now').mockReturnValue(1234);
diff --git a/client/src/pages/RapidReader.jsx b/client/src/pages/RapidReader.jsx
index 542a48d829..4131bc1732 100644
--- a/client/src/pages/RapidReader.jsx
+++ b/client/src/pages/RapidReader.jsx
@@ -6,6 +6,7 @@ import { readClipboard } from '../lib/clipboard';
import {
clearRapidReaderProgress,
rapidReaderDocumentId,
+ rapidReaderWords,
rapidReaderWordIndexAtCursor,
readRapidReaderProgress,
writeRapidReaderProgress,
@@ -50,12 +51,14 @@ export default function RapidReaderPage() {
const [saveTitle, setSaveTitle] = useState('');
const [url, setUrl] = useState('');
const [pendingDelete, setPendingDelete] = useState(null);
+ const [bookText, setBookText] = useState('');
+ const [bookSections, setBookSections] = 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 wordCount = useMemo(() => rapidReaderWords(documentText).length, [documentText]);
const documentIdentity = useMemo(() => ({
documentId: rapidReaderDocumentId(documentText),
wordCount,
@@ -89,6 +92,8 @@ export default function RapidReaderPage() {
}
setText(book.text);
if (book.id === 'accelerando' && book.shelfStored !== false) setShelf((previous) => previous.some((entry) => entry.id === book.id) ? previous : [{ ...book, text: undefined }, ...previous]);
+ setBookText(book.text);
+ setBookSections(Array.isArray(book.sections) ? book.sections : []);
setBookStatus(book.cached ? 'cached' : book.cacheStored === false ? 'downloaded-uncached' : 'downloaded');
return book;
});
@@ -123,7 +128,12 @@ export default function RapidReaderPage() {
}
latestProgressRef.current = null;
lastAutoSavedWordRef.current = -1;
- setActive({ text: documentText, initialWordIndex: wordIndex, ...documentIdentity });
+ setActive({
+ text: documentText,
+ initialWordIndex: wordIndex,
+ sections: documentText === bookText ? bookSections : [],
+ ...documentIdentity,
+ });
};
const persistProgress = useCallback((document, progress, updateBookmark = true) => {
@@ -190,6 +200,7 @@ export default function RapidReaderPage() {
chunkSize={chunkSize}
focalColor={focalColor}
initialWordIndex={active.initialWordIndex}
+ sections={active.sections}
autoPlay
onClose={reset}
onComplete={complete}
@@ -199,7 +210,7 @@ export default function RapidReaderPage() {
onChunkSizeChange={setChunkSize}
/>
<div className="flex flex-wrap items-center gap-3 text-xs text-gray-500">
- <span>Space = play/pause · ← → step · B bookmark · R restart · +/− WPM · Esc close</span>
+ <span className="hidden sm:inline">Space = play/pause · ← → step · B bookmark · R restart · +/− WPM · Esc close</span>
<span>Progress also saves automatically while reading.</span>
</div>
</div>
diff --git a/client/src/pages/RapidReader.test.jsx b/client/src/pages/RapidReader.test.jsx
index 38456b809a..6474e406e7 100644
--- a/client/src/pages/RapidReader.test.jsx
+++ b/client/src/pages/RapidReader.test.jsx
@@ -34,6 +34,10 @@ const BOOK = {
text: 'A novel by Charles Stross. Chapter 1: Example.',
wordCount: 8,
cached: false,
+ sections: [
+ { id: 'part-1', title: 'PART 1: Example', kind: 'part', wordIndex: 0 },
+ { id: 'chapter-1', title: 'Chapter 1: Example', kind: 'chapter', wordIndex: 5 },
+ ],
};
beforeEach(() => {
@@ -111,6 +115,28 @@ describe('RapidReader reading position', () => {
expect(screen.getByLabelText('Reading speed')).toHaveValue('425');
});
+ it('offers Accelerando section navigation after loading the book', async () => {
+ api.getAccelerandoBook.mockResolvedValue(BOOK);
+ render(<RapidReaderPage />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load Accelerando' }));
+ await waitFor(() => expect(screen.getByRole('textbox', { name: 'Text to read' })).toHaveValue(BOOK.text));
+ fireEvent.click(screen.getByRole('button', { name: 'Start reading' }));
+
+ const select = screen.getByRole('combobox', { name: 'Navigate sections' });
+ expect(select).toHaveDisplayValue('Part · PART 1: Example');
+ fireEvent.change(select, { target: { value: '5' } });
+ expect(select).toHaveDisplayValue('Chapter · Chapter 1: Example');
+ });
+
+ it('keeps the keyboard hint for desktop layouts only', () => {
+ render(<RapidReaderPage />);
+ fireEvent.change(screen.getByRole('textbox', { name: 'Text to read' }), { target: { value: 'one two' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Start reading' }));
+
+ expect(screen.getByText(/Space = play\/pause/)).toHaveClass('hidden', 'sm:inline');
+ });
+
it('saves a bookmark from the reader and offers it after closing', async () => {
renderPage();
await waitFor(() => expect(api.listRapidReaderLibrary).toHaveBeenCalled());
diff --git a/server/services/rapidReader.js b/server/services/rapidReader.js
index 4f1c68e279..f232c0cc71 100644
--- a/server/services/rapidReader.js
+++ b/server/services/rapidReader.js
@@ -37,6 +37,7 @@ const REQUIRED_MARKERS = [
'Creative Commons Attribution-NonCommercial-NoDerivs 2.5',
'Chapter 1:',
];
+const PUNCTUATION_ONLY = /^[\p{P}\p{S}]+$/u;
function extractBookHtml(html) {
const opening = /<div\b[^>]*\bid\s*=\s*(["'])book\1[^>]*>/i.exec(html);
@@ -58,6 +59,55 @@ function extractBookHtml(html) {
return '';
}
+const readerWordCount = (text) => {
+ let count = 0;
+ for (const match of text.matchAll(/\S+/g)) {
+ const value = match[0];
+ if (PUNCTUATION_ONLY.test(value)) {
+ continue;
+ }
+ count += 1;
+ }
+ return count;
+};
+
+const sectionId = (title, index) => `${title
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '') || 'section'}-${index + 1}`;
+
+/**
+ * Extract the book's navigable Part and Chapter headings from the source
+ * edition. Offsets are counted with the same punctuation folding as the
+ * client reader, so a jump always lands on the heading it names.
+ */
+export function extractAccelerandoSections(bookHtml, text) {
+ if (typeof bookHtml !== 'string' || typeof text !== 'string') return [];
+ const sourceHtml = extractBookHtml(bookHtml) || bookHtml;
+ const sections = [];
+ const maxWordIndex = Math.max(0, readerWordCount(text) - 1);
+ const headings = /<h([23])\b[^>]*>([\s\S]*?)<\/h\1\s*>/gi;
+ let match;
+ while ((match = headings.exec(sourceHtml))) {
+ const title = htmlToText(match[2], { extraEntities: SOURCE_ENTITIES, collapseSpaces: true });
+ const chapter = /^chapter\b/i.test(title);
+ const part = /^part\b/i.test(title);
+ if (!title || (!chapter && !part)) continue;
+ const beforeHeading = htmlToText(sourceHtml.slice(0, match.index), {
+ extraEntities: SOURCE_ENTITIES,
+ paragraphBreak: '\n\n',
+ collapseSpaces: true,
+ });
+ sections.push({
+ id: sectionId(title, sections.length),
+ title,
+ kind: chapter ? 'chapter' : 'part',
+ wordIndex: Math.min(readerWordCount(beforeHeading), maxWordIndex),
+ });
+ }
+ return sections;
+}
+
/**
* Extract the book body from the official single-page HTML edition and turn it
* into the plain text the RSVP reader expects. The marker checks keep an error
@@ -87,23 +137,25 @@ async function readCachedSource() {
code: 'ACCELERANDO_CACHE_UNREADABLE',
});
}
- if (!result.value) return '';
- return extractAccelerandoText(result.value);
+ if (!result.value) return null;
+ const text = extractAccelerandoText(result.value);
+ return text ? { text, html: result.value } : null;
}
-function buildBook(text, cached, cacheStored = true) {
+function buildBook(text, cached, cacheStored = true, sourceHtml = '') {
return {
...ACCELERANDO_BOOK,
text,
- wordCount: text.split(/\s+/).length,
+ wordCount: readerWordCount(text),
+ sections: extractAccelerandoSections(sourceHtml, text),
cached,
cacheStored,
};
}
async function loadAccelerando() {
- const cachedText = await readCachedSource();
- if (cachedText) return buildBook(cachedText, true);
+ const cachedSource = await readCachedSource();
+ if (cachedSource) return buildBook(cachedSource.text, true, true, cachedSource.html);
const source = await fetchPublicText(ACCELERANDO_BOOK.sourceUrl, {
blockPrivate: true,
@@ -128,7 +180,7 @@ async function loadAccelerando() {
return false;
},
);
- return buildBook(text, false, cacheStored);
+ return buildBook(text, false, cacheStored, source);
}
let loadPromise = null;
diff --git a/server/services/rapidReader.test.js b/server/services/rapidReader.test.js
index 200cfa6caf..2c28645526 100644
--- a/server/services/rapidReader.test.js
+++ b/server/services/rapidReader.test.js
@@ -61,6 +61,25 @@ describe('extractAccelerandoText', () => {
});
});
+describe('extractAccelerandoSections', () => {
+ it('extracts Parts and Chapters with reader word offsets', () => {
+ const html = `<div id="book">
+ <p>A novel by Charles Stross</p>
+ <h2><a name="PART1">PART 1: Start</a></h2>
+ <p>Opening text.</p>
+ <h3><a name="ChapterOne">Chapter 1: Alpha</a></h3>
+ <p>Chapter text.</p>
+ </div>`;
+ const text = 'A novel by Charles Stross PART 1: Start Opening text. Chapter 1: Alpha Chapter text.';
+ const sections = service.extractAccelerandoSections(html, text);
+
+ expect(sections).toEqual([
+ { id: 'part-1-start-1', title: 'PART 1: Start', kind: 'part', wordIndex: 5 },
+ { id: 'chapter-1-alpha-2', title: 'Chapter 1: Alpha', kind: 'chapter', wordIndex: 10 },
+ ]);
+ });
+});
+
describe('getAccelerandoBook', () => {
it('fetches the fixed official source and caches the raw edition', async () => {
fetchPublicText.mockResolvedValue(SOURCE_HTML);
@@ -76,6 +95,9 @@ describe('getAccelerandoBook', () => {
licenseUrl: 'https://creativecommons.org/licenses/by-nc-nd/2.5/',
cached: false,
wordCount: expect.any(Number),
+ sections: expect.arrayContaining([
+ expect.objectContaining({ title: 'Chapter 1: Example', kind: 'chapter' }),
+ ]),
});
expect(fetchPublicText).toHaveBeenCalledWith(
service.ACCELERANDO_BOOK.sourceUrl,