跳到主要内容
食谱编号212

排版食谱 · 第13章 · CMS集成

在页面上选择,读取Markdown范围和文字

postext-viewer 把排好的页面上的选区报告为 Markdown 中的一个范围,连同它覆盖的 Markdown 和逐行的片段。

本页内容
输出
Canvas
难度
基础
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
在第 1 页选中一段引文:面板显示它在 Markdown 中的范围、这段范围带强调标记的 Markdown,以及源文本中的同一些词。
在第 1 页选中一段引文:面板显示它在 Markdown 中的范围、这段范围带强调标记的 Markdown,以及源文本中的同一些词。
  • 英文样例:尚无中文版本
  • 成品尺寸140 × 210 mm
  • 1栏
  • Newsreader 10.5/15
  • Archivo
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时53 ms
  • 104行代码

简单来说

一篇讲灯塔透镜的文章显示在页面查看器里,旁边有一个面板。有人在页面上选中文字时,面板显示这些文字在原稿中的位置,以及原稿在那里怎么写,连格式符号也照样显示。

成品一览

一篇两页的文章,讲灯塔透镜,显示在页面查看器里,右边有一个面板,就像审阅工具在讨论中的段落旁边放的那种。第一页上有一句话已被选中,面板用三种方式把它读出来:Markdown 文件中的范围 { start, end },范围内的 Markdown(斜体的法文名称保留着星号),以及标出选区的整段文字。在别的文字上拖动,面板会在拖动过程中跟着变化。

这道食谱解答

  • 编辑在页面上选中文字时,怎样得到它在Markdown中的范围和文字?

简短回答

script.js · 第97–118行在完整代码中
const view = createViewer($('viewer'), {
  document: doc,
  markdown, // with it, each selection event carries the Markdown it covers
  zoom: 'fit-page', labels: L.viewer,
});
view.on('selectionchange', ({ range, text }) => {
  $('panel').classList.toggle('empty', !range);
  if (!range) return void ($('range').textContent = L.none);
  $('range').textContent = `{ start: ${range.start}, end: ${range.end} }`;
  $('text').textContent = text; // the Markdown, emphasis marks included
  // The range is a plain value: the core API places it too, one piece per line, in page px.
  const rects = rangeRects(doc, range);
  const pages = [...new Set(rects.map((r) => r.pageIndex + 1))].join(', ');
  $('lines').textContent = L.lines(rects.length, pages);
  // The paragraph around it: offsets count in the Markdown file, front matter included.
  const from = markdown.lastIndexOf('\n\n', range.start) + 2;
  let to = markdown.indexOf('\n\n', range.end);
  if (to < 0) to = markdown.length; // the last paragraph
  const mark = Object.assign(document.createElement('mark'), { textContent: text });
  const [before, after] = [markdown.slice(from, range.start), markdown.slice(range.end, to)];
  $('source').replaceChildren(before, mark, after);
});

用料

类型
Newsreader, Archivo(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 排出一页供选择的版面

script.js · 第29–50行在完整代码中
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};

一页朴素的杂志版面:Newsreader 两端对齐单栏,港湾蓝的 Archivo 标题,页脚有页码。选择在任何版面上都一样有效,分栏、从右到左和竖排的页面也是如此,因为查看器会向版面询问每一行画在哪里。

#2 · 把选区读成 Markdown

代码就是上面的简短回答。把 markdown 传给 createViewer,每次 selectionchange 都会带来范围和它覆盖的 Markdown。范围只是一个 { start, end },所以核心的 rangeRects 不用查看器也能把它放到页面上,所跨的每一行一个片段。偏移量在 Markdown 文件里计数,包括前置元数据:选区所在的段落就是同一字符串的一段;今天保存的范围,只要文字没变,明天仍指向同样的字词。

#3 · 恢复保存的选区

script.js · 第122–125行在完整代码中
const quote = t({ en: 'The first *lentille à échelons* was lit in July 1823',
  es: 'La primera *lentille à échelons* se encendió en julio de 1823' });
const start = markdown.indexOf(quote);
view.setSelection({ start, end: start + quote.length });

setSelection 从代码接收一个范围,发出和拖动相同的事件,所以面板会自己填好。重新打开某条批注所在段落的工具就是这样做的;文字修改后如何让范围继续有效,见锚点与修改。

完整食谱

// ═══ Postext Cookbook · Nº 212 · Select on the page, read the Markdown range and text ═══
// https://postext.dev/en/cookbook/selection-as-markdown-range
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An article on lighthouse lenses in postext-viewer, with a panel beside it that a review
// tool would fill from the selection: the range in the Markdown, the Markdown it covers and
// the paragraph around it. The pen selects one sentence itself; drag over the page to change it.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'selection-as-markdown-range';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1b1f24', // text: a cool near-black
  accent: '#1d5c73', // harbour blue: headings and folio
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion

// #region page: a magazine page, one column, a folio at the foot
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#只在选区确定时处理

selectionchange 在拖动的每一步都会触发;select 只在松开指针或双击一个词时触发一次。

-view.on('selectionchange', ({ range, text }) => {
+view.on('select', ({ range, text }) => {

#按栏宽阅读

按栏宽显示时,更容易准确地拖出选区。

-  zoom: 'fit-page', labels: L.viewer,
+  zoom: 'fit-width', labels: L.viewer,

致谢

文本
原创文字, CC BY 4.0
字体
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)