跳到主要内容
食谱编号216

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

点击页面,找到源文

sourceAt 和 caretAt 把排好的页面上的一次点击变成 Markdown 的一个块和一个位置;CMS 在源文中标出那一行。

本页内容
难度
中级
Postext
已用Postext 1.103.1测试
需要≥ 1.103.0
许可证
更新于2026年12月4日
代码MIT · 文本CC BY 4.0
在第 1 页点击“a large correction”:所在块在页面上着色,插入符标出偏移量,旁边的源文本显示同一块以及链条 text › line › block。
在第 1 页点击“a large correction”:所在块在页面上着色,插入符标出偏移量,旁边的源文本显示同一块以及链条 text › line › block。
  • 英文样例:尚无中文版本
  • 成品尺寸148 × 210 mm
  • 1栏
  • Source Serif 4 9.5/13.5
  • IBM Plex Sans
  • 2页
  • 难度
  • Postext 1.103.1
  • 排版用时78 ms
  • 145行代码

简单来说

一本自行车修理手册的一章按页面显示,旁边是生成这些页面的文字。点击页面上的一个词,就能在文字里找到同一个词,标出它所在的段落,并给出行号。

成品一览

The Home Bicycle Workshop 的一章排在 148 × 210 mm 的页面上,左边在 postext-viewer 中显示,右边是编辑系统保存的那份 Markdown。点击页面上任何一处,源文面板就跳到指针下的那一行:两边的段落都会着色,一个绿色光标停在那个字符上,两行状态栏给出行、列和位置,以及该处所画内容的层级链。卡片上已经在第三节一个段落的中间点了一下。

这道食谱解答

  • 在页面上点击一下,怎样知道它落在Markdown的哪一部分?

简短回答

script.js · 第122–145行在完整代码中
const span = ({ level, source: s }) => `${level} ${s.kind === 'config' ? s.path
  : s.start === undefined ? s.resourceId : `[${s.start}, ${s.end})`}`;
function pick(pageIndex, x, y) {
  // What is painted there, innermost first: a glyph, its line, its paragraph, a box round
  // it; a running head answers with the config entry that set it.
  const chain = sourceAt(doc, pageIndex, x, y);
  $('chain').textContent = chain.map(span).join(' › ');
  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
  const hit = caretAt(doc, pageIndex, x, y); // the character boundary nearest the point
  if (!block || !hit) return view.setAnnotations([]);
  // Offsets count UTF-16 units of the whole file, front matter included, so the line and
  // column come from the Markdown itself.
  const before = markdown.slice(0, hit.offset).split('\n');
  const [line, column] = [before.length, before.at(-1).length + 1];
  $('where').textContent = t({ en: `Line ${line}, column ${column} · offset ${hit.offset}`,
    es: `Línea ${line}, columna ${column} · posición ${hit.offset}` });
  showSource(block, hit.offset, line);
  // The same ranges, drawn back on the page.
  view.setAnnotations([
    { id: 'block', kind: 'highlight', range: block, color: '#2a9aa6' },
    { id: 'caret', kind: 'insert', range: { start: hit.offset, end: hit.offset } },
  ]);
}
view.on('click', ({ pageIndex, x, y }) => pick(pageIndex, x, y));

用料

类型
Source Serif 4, IBM Plex Sans(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 用自己的设计排一章

script.js · 第33–43行在完整代码中
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(0.6), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
  head('verso-title', '{title}', 'even', 'top-left', 24),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };

页面是一本朴素的修车手册:正文 Source Serif 4,9.5 pt;标题用 IBM Plex Sans;书眉随页面左右换边。排版里没有任何东西是专为点击准备的,任何排好的文档都能回答同样的调用。

#2 · 问排版:这个点下面是什么

代码就是上面的简短回答。查看器的 click 事件给出页码和以页面 px 计的点,两个调用读取该点的排版。sourceAt 由内向外列出那里画的东西:字形、所在行、所在块、外面的框。跨两页的段落以整个范围作答;书眉则以放置它的配置项作答,而不是 Markdown。caretAt 给出最近的字符边界,就像在文本编辑器里点击一样。两者都按包括 front matter 在内的整个文件的 UTF-16 单位计数,所以行和列可以直接从 Markdown 算出来。

#3 · 在源文中显示那一行

script.js · 第149–177行在完整代码中
function showSource(block, offset, line) {
  const rows = [];
  let at = 0;
  for (const [i, text] of markdown.split('\n').entries()) {
    const row = document.createElement('div');
    row.className = 'row';
    row.dataset.n = String(i + 1);
    const body = row.appendChild(document.createElement('span')); // one grid cell
    // Cut the line where the block starts and ends and where the caret is.
    const cuts = [at, at + text.length];
    for (const c of [block.start, block.end, offset]) if (c > at && c < cuts[1]) cuts.push(c);
    cuts.sort((a, b) => a - b);
    for (let k = 0; k < cuts.length - 1; k++) {
      const [from, to] = [cuts[k], cuts[k + 1]];
      if (from === offset) body.append(Object.assign(document.createElement('span'),
        { className: 'caret' }));
      const inBlock = from >= block.start && to <= block.end;
      body.append(inBlock ? Object.assign(document.createElement('mark'),
        { textContent: markdown.slice(from, to) }) : markdown.slice(from, to));
    }
    if (offset === cuts.at(-1) && offset > at) body.append(Object.assign(
      document.createElement('span'), { className: 'caret' })); // a caret at the line's end
    rows.push(row);
    at += text.length + 1;
  }
  $('lines').replaceChildren(...rows);
  const target = rows[line - 1];
  $('lines').scrollTop = target.offsetTop - $('lines').clientHeight / 3;
}

面板在块的起止处和光标处切开每一行,所以标记和光标正好落在页面上显示的那些字符上。同样两个范围作为高亮和插入符号回到查看器,读者可以借此确认跳转落在了想要的地方。

完整食谱

// ═══ Postext Cookbook · Nº 216 · Click on the page to find the source ═════════════════
// https://postext.dev/en/cookbook/click-to-markdown-source
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, IBM Plex Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a workshop manual in postext-viewer, with its Markdown beside it. A click on a
// page asks the layout which character and which block lie under the point, and the source
// panel scrolls to that line with the block marked and a caret at the character, the way a
// CMS jumps from a proof to the text an author has to change.
import { buildDocumentWithFonts, renderPageToCanvas, sourceAt, caretAt, 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 = 'click-to-markdown-source';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1d2125', // text
  accent: '#1f6f78', // workshop teal: headings' rule, folios
  muted: '#68707a', // running heads
};
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
const LEAD = 13.5; // pt of body leading

// #region book: a manual's page with running heads by parity
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(0.6), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
  head('verso-title', '{title}', 'even', 'top-left', 24),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,

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

变化

#标出词,而不是段落

wordAt 把位置扩展到点下的那个词,按文档的语言切分词语。

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = wordAt(doc, pageIndex, x, y, markdown); // import wordAt from postext

#标出印出来的那一行

层级链中的 line 元素是排成页面上一行的那段 Markdown,校对的人指的正是它。

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = chain.find((e) => e.level === 'line' && e.source.kind === 'markdown')?.source;

致谢

文本
原创文字, CC BY 4.0
字体
Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)