章 24.4 · 篇 III · 实践
集成:页面查看器
postext-viewer:可嵌入的查看器,显示页面,以Markdown范围和偏移量报告选区和点按,绘制批注标记,在每页上方为宿主系统提供图层,并在页面坐标和屏幕坐标之间换算;附React组件
简单来说
本页写给开发者。它介绍一个现成的查看器,只要一次调用,就能把一本书的页面放进网页。用户可以滚动、缩放和选中文字,系统会知道他们选的是原文中的哪些字。系统可以在页面上画自己的标记,也可以在页面上方放自己的按钮。查看器也支持键盘操作和读屏软件。
postext-viewer显示页面,并用Markdown范围说话:选中了什么,按了什么,标记放在哪里。
npm install postext postext-viewerimport { buildDocument } from 'postext';
import { createViewer } from 'postext-viewer';
const doc = buildDocument({ markdown }, config);
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown });
viewer.on('select', ({ range, text }) => {
console.log(range, text); // { start: 52, end: 65 } 'hives at dawn'
});查看器会填满它的容器:请给容器设定高度。它在一个滚动的纵列里显示页面,用renderPageToCanvas按显示尺寸乘以屏幕的像素比来绘制。只绘制可见的页面和两侧各两页(overscan);更远的页面会释放内存,所以一本600页的书也只占几页的canvas。
和renderPage一样,在查看器绘制之前,先加载文档用到的字体并注册图像(document.fonts.load、registerResourceImage)。
import { buildDocument } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';
const paragraph = 'The keeper walked the hives at dawn, lifting each lid with care and reading the frames for brood, honey and the queen. A hive that hums low in the cold keeps its cluster tight; one that roars at noon wants more room before the flow.';
const markdown = ['# The apiary', ...Array.from({ length: 10 }, () => paragraph)].join('\n\n');
const config = {
page: { width: { value: 120, unit: 'mm' }, height: { value: 170, unit: 'mm' } },
bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 11, unit: 'pt' }, lineHeight: { value: 15, unit: 'pt' } },
};
// Postext measures text with the fonts the browser has loaded.
await Promise.all([
document.fonts.load('16px "EB Garamond"'),
document.fonts.load('italic 16px "EB Garamond"'),
document.fonts.load('bold 16px "Open Sans"'),
]);
const doc = buildDocument({ markdown }, config);
// Fitted to the width, but never larger than 1.4 CSS px per page px.
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown, maxZoom: 1.4 });
// The host's own records. Postext only sees ranges and kinds.
const marks = [];
let selected = null;
const selection = document.getElementById('selection');
const highlight = document.getElementById('highlight');
const note = document.getElementById('note');
const list = document.getElementById('marks');
viewer.on('selectionchange', ({ range, text }) => {
selected = range;
const shown = text.length > 80 ? `${text.slice(0, 80)}…` : text;
selection.textContent = range ? `“${shown}” (Markdown ${range.start}–${range.end})` : 'Select some words on the page.';
highlight.disabled = note.disabled = !range;
});
function add(kind) {
if (!selected) return;
const id = `m${marks.length + 1}`;
marks.push({ id, kind, range: selected, label: kind === 'note' ? String(marks.length + 1) : undefined });
viewer.setAnnotations(marks);
viewer.setSelection(null);
draw();
}
highlight.addEventListener('click', () => add('highlight'));
note.addEventListener('click', () => add('note'));
function draw() {
list.replaceChildren(...marks.map((m) => {
const li = document.createElement('li');
const go = document.createElement('button');
go.textContent = `${m.kind}: ${markdown.slice(m.range.start, m.range.end)}`;
go.addEventListener('click', () => viewer.revealAnnotation(m.id, { behavior: 'smooth' }));
li.append(go);
return li;
}));
}
// A press on a mark, with the pointer or the keyboard.
viewer.on('annotationclick', ({ id }) => {
const i = marks.findIndex((m) => m.id === id);
list.children[i]?.querySelector('button')?.focus();
});index.html
<main>
<div id="pages"></div>
<aside>
<p id="selection">Select some words on the page.</p>
<div class="actions">
<button id="highlight" disabled>Highlight</button>
<button id="note" disabled>Note</button>
</div>
<ol id="marks"></ol>
</aside>
</main>style.css
body {
margin: 0;
font-family: system-ui, sans-serif;
color: #1d1d1f;
}
main {
display: grid;
grid-template-columns: 1fr 240px;
height: 100vh;
}
/* The viewer fills its container: give it a height. */
#pages {
height: 100vh;
min-width: 0;
--pv-background: #ecebe6;
}
aside {
padding: 16px;
border-left: 1px solid #d8d6cf;
overflow: auto;
font-size: 14px;
}
#selection {
min-height: 3.5em;
color: #555;
}
.actions {
display: flex;
gap: 8px;
}
button {
min-height: 44px;
padding: 0 14px;
font: inherit;
border: 1px solid #2f6fd6;
border-radius: 6px;
background: #fff;
color: #1f4f9e;
cursor: pointer;
}
button:disabled {
border-color: #c8c6bf;
color: #8a8880;
cursor: default;
}
#marks {
padding-left: 20px;
}
#marks li {
margin: 8px 0;
}
#marks button {
min-height: 32px;
border: 0;
padding: 0;
text-align: left;
color: #1d1d1f;
text-decoration: underline;
}从codepen.io加载一个交互式编辑器。示例从CDN导入postext的最新版本。
#选项
| 选项 | 默认值 | 作用 |
|---|---|---|
document | 排好的文档。 | |
markdown | 排出这份文档的Markdown:双击取词、选中的文字和复制都需要它。 | |
annotations | [] | 来自postext/annotate的标记。 |
zoom | 'fit-width' | 一个数字(每页面px对应的CSS px)、'fit-width'或'fit-page'。 |
minZoom、maxZoom | 0.1、8 | 数字缩放的上下限。 |
gap | 16 | 页面之间和页面四周的CSS px。 |
trim | false | 显示裁切后的页面,不带出血和裁切线。坐标仍按纸面计算。 |
selectable | true | 拖动时是否选中文字。 |
overscan | 2 | 可见页面两侧各多绘制的页数。 |
render | renderPageToCanvas的选项(singleInk、printPreview、finishes…)。 | |
geometry | 书中某一章用的{ ownChapter }(见页面上的文字)。 | |
marks | layoutAnnotations的选项(fontFamily、noteSide、paper…)。 | |
layers | [] | 宿主系统的图层,从下到上。 |
labels | 英文 | 查看器朗读和命名所用的文字,可换成宿主系统的语言。 |
copyText | Markdown原文 | (range, markdown) => string:复制时放进剪贴板的内容。 |
#事件
viewer.on(type, handler)返回一个用来移除该处理函数的函数。
| 事件 | 时机 | 携带 |
|---|---|---|
selectionchange | 选区变化时,拖动过程中也会触发。 | range(或null)、text、rects |
select | 完成一次选择:松开指针、双击一个词、Shift + 方向键。 | 同上 |
click | 在页面上按下。 | pageIndex、x、y(页面px)、offset、chapter、blockId、annotations(id,最上层的在前)、originalEvent |
hover | 指针移到另一个块或另一些标记上。 | 与click相同 |
annotationclick | 用指针或键盘按下了一个标记。 | id、annotation、pageIndex、originalEvent |
pagechange | 可见面积最大的页面变了。 | pageIndex |
zoomchange | 缩放变了(一次调用,或适应模式下尺寸改变)。 | zoom |
render | 一页绘制完成。 | pageIndex |
最初几页在createViewer之后的下一帧绘制,所以紧接着添加的处理函数能收到第一次render和pagechange。
把选区变成一条评论,宿主系统这边的全部代码:
viewer.on('select', async ({ range }) => {
if (!range) return;
const body = prompt('Comment');
if (!body) return;
const anchor = textAnchor(markdown, range);
const saved = await api.createComment({ chapter, anchor, body }); // 宿主系统自己的API
viewer.setAnnotations([...viewer.annotations, { id: saved.id, kind: 'note', range, label: String(saved.number) }]);
viewer.setSelection(null);
});
viewer.on('annotationclick', ({ id }) => openThread(id));#方法
| 方法 | 作用 |
|---|---|
setDocument(doc, markdown?) | 显示新的排版结果(修改之后)。可见的页面、选区的偏移量和标记都会保留。 |
setMarkdown(md) | 更换Markdown而不重新排版。 |
setAnnotations(list)、annotations | 替换标记。 |
setSelection(range)、selection | 用代码选中一个范围,传入null则清除。 |
setZoom(zoom)、zoom | 缩放,保持可见的位置不变。 |
goToPage(i)、pageIndex | 滚动到某一页。 |
revealRange(range)、revealAnnotation(id) | 把一个范围或一个标记滚动到可见处。它不在任何页面上时返回false。 |
rangeRects(range) | 在当前显示的文档上调用rangeRects。 |
pageToClient(page, x, y)、clientToPage(x, y) | 页面px与视口px互相换算,用于摆放弹出框。 |
pageElement(i) | 某一页的元素。 |
addLayer(layer)、removeLayer(id)、refreshLayers() | 宿主系统的图层。 |
destroy() | 移除查看器并释放它的canvas。 |
#宿主系统的图层
图层在页面上方画出属于宿主系统的东西:评论图钉、协作者的光标、翻译记忆匹配项的方框。
viewer.addLayer({
id: 'pins',
// 画在canvas上,单位为页面px,位于标记之上
paint(ctx, { pageIndex, page }) {
for (const c of commentsOn(pageIndex)) {
ctx.fillStyle = c.color;
ctx.beginPath();
ctx.arc(page.width - 24, c.y, 7, 0, Math.PI * 2);
ctx.fill();
}
},
// 页面上方的DOM;其中的CSS px就是页面px
mount(el, { pageIndex }) {
const root = createRoot(el);
root.render(<Avatars page={pageIndex} />);
return () => root.unmount();
},
});mount在页面进入绘制窗口时运行,它的返回值在页面离开时运行,所以再长的书,宿主系统的DOM也只有几页。宿主系统的数据变化后,refreshLayers()重新绘制并挂载图层。
#键盘与读屏软件
- 查看器是一个可获得焦点的区域,名称取自
labels.viewer;每一页的名称形如“Page 3 of 41”。 - Page Up和Page Down向前、向后翻一页,Home和End跳到第一页和最后一页;Ctrl或⌘加+和−缩放。
- Escape清除选区;Shift + ←和→把选区的终点移动一个字符。
- 每个标记都是覆盖在它所指文字上的按钮,有“Replacement: young bees”这样的名称,并在Tab键顺序中;Enter或Space触发
annotationclick。 - 选区会在实时区域中朗读出来(“13 characters selected”)。
labels可以翻译这一切:
createViewer(el, {
document: doc,
labels: {
viewer: 'Páginas del libro',
page: 'Página {n} de {count}',
selection: '{count} caracteres seleccionados',
selectionCleared: 'Selección borrada',
kinds: { replace: 'Sustitución', note: 'Nota' },
},
});#外观
查看器会添加一个小样式表。在容器或任意祖先元素上设置以下自定义属性:
| 属性 | 默认值 |
|---|---|
--pv-background | #e8e6e1 |
--pv-page-background | #fff |
--pv-page-shadow | 柔和的双层阴影 |
--pv-selection | rgb(47 111 214 / .3) |
--pv-focus | #2f6fd6 |
#React
import { PostextViewer } from 'postext-viewer/react';
function Proofs({ doc, markdown, marks, onComment }) {
const viewer = useRef(null);
return (
<PostextViewer
ref={viewer}
document={doc}
markdown={markdown}
annotations={marks}
onSelect={({ range }) => range && onComment(range)}
onAnnotationClick={({ id }) => openThread(id)}
style={{ height: '80vh' }}
/>
);
}属性与选项和事件一一对应(onSelect、onSelectionChange、onClick、onHover、onAnnotationClick、onPageChange、onZoomChange、onRender)。document、markdown、annotations、zoom、layers和selection变化时会应用到正在运行的查看器上;处理函数在每次渲染时都可以是新的函数。ref就是查看器的句柄,带有上面所有的方法。
#不用查看器
有自己的页面显示方式的宿主系统(已经在画的canvas、页面图像、3D书本)不需要查看器:页面上的文字和批注标记以调用的形式提供同样的几何信息和标记。
#排版食谱中的示例
用到本页内容的食谱,每道列在最贴切的小节下。每道食谱都把页面和完整脚本并排展示。





