@hamster-note/reader
React reader component package for Hamster Note.
安装
Install the package and its peer dependencies:
yarn add @hamster-note/reader "@hamster-note/painting@>=0.8.4 <0.10" @hamster-note/selection@0.3.0 react react-dom
使用
Styles are not injected automatically. Import @hamster-note/reader/style.css explicitly before rendering Reader.
import { Reader } from '@hamster-note/reader'
import type { ReaderProps } from '@hamster-note/reader'
import '@hamster-note/reader/style.css'
const document: NonNullable<ReaderProps['document']> = {
id: 'demo-document',
title: 'Hello Hamster',
pages: []
}
export function App() {
return <Reader document={document} emptyText='No document' />
}
How It Works
Reader is parser-agnostic. It accepts an intermediate document (produced by parser packages such as @hamster-note/pdf-parser, @hamster-note/docx-parser, etc.) and renders it through the intermediate-document renderer. Layout pages use VirtualPaper reading mode by default, with contain mode disabled for continuous document navigation.
The browser Demo and Expo host use Foliate for EPUB and the official PDF.js viewer for PDF by default. Library consumers can supply engineSource={{ format: 'epub', data: bytes }} (or format: 'pdf', with workerSrc when needed) alongside the compatibility document. Memoize the source per file; original bytes stay outside persisted ReaderData. EPUB uses Foliate in both modes; PDF Text keeps the compatible text view. Existing document-only consumers and other formats retain the shared renderer. Setup, acceptance evidence, backups and rollback are documented in docs/ham91-final-acceptance.md.
The renderer lazily loads page content on demand via a visibility-debounced queue with concurrency control and offscreen-release, designed for long documents without blocking the main thread.
Unified Reader data
Use data as the single persistence-friendly entry point for page crop, hidden pages, text and rectangle highlights, page drawings, the last VirtualPaper position/scale, and bookmarks. A field supplied through data takes precedence over its legacy flat prop; the flat props remain supported for compatibility.
import { Reader } from '@hamster-note/reader'
import type { ReaderData } from '@hamster-note/reader'
import { useState } from 'react'
export function PersistedReader() {
const [data, setData] = useState<ReaderData>({
edgeCrop: {
// Ratios use the original page size and may differ on every edge.
all: { top: 0.05, right: 0.08, bottom: 0.04, left: 0.08 },
// A page-specific crop replaces, rather than adds to, the global crop.
pages: {
'page-3': { top: 0.12, right: 0.03, bottom: 0.1, left: 0.03 }
}
},
// Numbers are 1-based page numbers; strings are public page IDs.
hiddenPages: [2, 'page-7'],
ranges: [],
rects: [],
pagePaintings: {},
virtualPaper: { x: 0, y: 0, scale: 1 },
bookmarks: [
{
pageNumber: 1,
textId: 'page-1-introduction',
text: 'Introduction',
offset: 0
}
]
})
return (
<Reader
document={document}
data={data}
// Fired after a VirtualPaper pan/zoom gesture ends.
onDataChange={setData}
onSelect={(range) =>
setData((current) => ({
...current,
ranges: [...(current.ranges ?? []), range]
}))
}
onPagePaintingsChange={(pagePaintings) =>
setData((current) => ({ ...current, pagePaintings }))
}
/>
)
}
edgeCrop ratios are clamped to the valid page area. edgeCrop.all applies globally, while edgeCrop.pages['page-N'] fully overrides it for that page. Visual edge crop is layout-mode only; hiddenPages applies to both layout and text modes. Invalid hidden-page values are ignored. Public page IDs always use page-${pageNumber}.
onDataChange reports the final VirtualPaper Layout position as { x, y, scale, anchor? }, the native Layout viewport position through data.layoutReadingProgress, and the Text position as { currentPageNumber, anchor? } through data.textReadingProgress. PDF.js Layout progress always stores { pageNumber, verticalPercentage }, measured from the safe reading line within the displayed page, independently of text extraction. Other native Layout readers retain text-first progress. PDF Layout ↔ Text switching independently captures the first visible source character in the safe viewport, falling back to page proportion only after text is confirmed absent. containMarginTop/Bottom/X describe remaining overlap inside the reader; pass zero for space already reserved outside it. Historic Layout text anchors remain readable without an automatic rewrite. A text anchor stores { pageNumber, textId, text, offset }; offset is the target text's character offset within that page, not within the whole document. Restoration uses textId first and falls back to the page-local offset when that ID no longer exists. The legacy shapes without anchor remain valid and restore by transform or page number.
Pass the saved ReaderData back to restore either reading position. Precise bookmark toggles are merged into data.bookmarks through the same onDataChange callback. Highlight, rectangle, and drawing edits continue to use their existing typed callbacks. The deprecated bookmarkedPageNumbers and onTogglePageBookmark APIs remain available for hosts that still use page-only bookmarks.
Lazy Page Loading Props
The following optional props control the lazy loading queue:
| Prop |
Type |
Default |
Description |
initialLoadedPages |
number |
1 |
Number of pages to load immediately on mount (before visibility-based queue kicks in). |
pageLoadConcurrency |
number |
3 |
Maximum number of pages loaded concurrently. |
pageLoadEnterDelayMs |
number |
500 |
A non-initial page must remain continuously visible for this duration (ms) before its content load is enqueued. Prevents fast-scroll from triggering loads. |
pagePreloadRadius |
number |
3 |
Number of adjacent pages to preload on each side of every visible page. The window is clipped safely at the beginning and end of the document. |
pageUnloadDelayMs |
number |
5000 |
After a loaded page leaves the visible window, wait this duration (ms) before unloading its content back to an empty shell. Re-entering before the delay cancels the unload. |
Render Timing
To diagnose bottlenecks in the render pipeline, you can opt in to stage-by-stage timing logs. Production builds emit no timing output by default.
Activation paths:
-
Callback prop — receive every timing entry in code:
<Reader
document={document}
onIntermediateDocumentRenderTiming={(entry) => {
console.table(entry)
}}
/>
-
Environment flag — print console.debug logs when no callback is provided:
VITE_HAMSTER_READER_INTERMEDIATE_TIMING=true
Each entry has the following shape:
| Field |
Type |
Description |
stage |
string |
One of document-resolution, shell-rendering, initial-page-loading, content-extraction, page-content-rendering, visibility-lazy-loading, offscreen-unload, ocr-processing. |
startedAt |
number |
Start timestamp (ms). |
endedAt |
number |
End timestamp (ms). |
durationMs |
number |
endedAt - startedAt. |
pageNumber |
number (optional) |
Present for page-scoped stages. |
detail |
object (optional) |
Stage-specific context such as pageCount, textCount, imageCount, or status. |
Demo Upload Formats
The browser Demo supports uploading and previewing the following formats:
- PDF (
.pdf)
- TXT (
.txt)
- DOCX (
.docx)
- EPUB (
.epub)
- Markdown (
.md, .markdown)
- Images (
.png, .jpg, .jpeg, .gif, .webp, .bmp, .svg)
EPUB support uses @hamster-note/epub-parser. Both Layout and Text modes render the EPUB cover and embedded chapter images; reflowable EPUB pages still follow the parser's flow layout rather than fixed-layout fidelity.
API Notes
OCR
The default Reader toolbar includes an OCR toggle that starts off. Turn it on to recognize every loaded page immediately and automatically recognize pages loaded afterward. Hosts can control the same behavior with the ocr prop and onOcrChange, and listen for text selection updates with onTextSelectionChange and onTextSelectionEnd.
<Reader
document={document}
ocr
onTextSelectionChange={(text, detail) => {
// handle selection change
}}
onTextSelectionEnd={(text, detail) => {
// handle selection end
}}
/>
ocr accepts two shapes:
| Value |
Behavior |
true / { enabled: true } |
Auto mode: OCR runs for every currently loaded page and each page loaded afterward. |
{ enabled: true, pages: [...] } |
Manual mode: only the listed page numbers (1-based) are recognized and displayed. Removing a page from the list closes OCR for that page (in-flight results are discarded and the cache is invalidated). |
false / { enabled: false } |
Global off: all OCR text layers are cleared for the current document. |
Recognized text is rendered as a transparent, selectable text layer on top of the page image. While a page is being recognized, the page shows an in-page loading badge that disappears on success or failure.
OCR always runs on the original-size page image (IntermediatePage.getThumbnail(1)), re-requested from the parser — never on the zoom-dependent display thumbnail. Recognition resolution is therefore stable across zoom levels, and the returned polygons align with the page coordinate space. Pages whose only image is an inline thumbnail/image property fall back to that inline image.
OCR results can be controlled by the host to avoid repeated recognition (for example, when restoring persisted data):
| Prop |
Type |
Description |
extraOCR |
(imageBase64: string) => IntermediatePage \| Promise<IntermediatePage> |
Optional external OCR provider. It receives the original-size page image and replaces the built-in image parser for recognition. Defaults to undefined. |
onOcrChange |
(enabled: boolean) => void |
Fired when the default toolbar OCR toggle changes. When ocr is controlled, update the host value from this callback. |
ocrTexts |
Readonly<Record<number, readonly IntermediateText[]>> |
Controlled OCR text per page (1-based). Pages with data are rendered directly and never re-recognized; in manual mode only pages listed in ocr.pages are displayed. |
onOcrTextsChange |
(pageNumber: number, texts: IntermediateText[]) => void |
Fired when a page finishes OCR. Persist the result and pass it back via ocrTexts. |
onOcrError |
(error: unknown, detail: { pageNumber: number }) => void |
Fired when a page's OCR fails. A failed page is not retried until it is closed and reopened. |
ocrDebug |
boolean |
Dev/debug mode: OCR text is rendered visibly (black at 50% opacity) with a red outline instead of transparent, so you can verify recognition position and content. Rendering-only; stored/onOcrTextsChange data is unaffected. Defaults to false. |
const [ocrPages, setOcrPages] = useState<number[]>([])
const [ocrTexts, setOcrTexts] = useState<Record<number, IntermediateText[]>>({})
<Reader
document={document}
ocr={{ enabled: true, pages: ocrPages }}
extraOCR={async (imageBase64) => externalOcrService.recognize(imageBase64)}
ocrTexts={ocrTexts}
onOcrTextsChange={(pageNumber, texts) =>
setOcrTexts((current) => ({ ...current, [pageNumber]: texts }))
}
/>
Text render mode
Reader uses renderMode='layout' by default. Set renderMode='text' to render a flow reading view that mounts and loads only the virtual pages currently visible in the scroll viewport.