本文へスキップ
レシピ番号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 を並べます。ページのどこかをクリックすると、原稿パネルがポインターの下の行まで移ります。段落は両側で色が付き、緑のキャレットがその文字に立ち、2行の状態表示が行・桁・位置と、その点に描かれているものの連なりを示します。カードには、3つ目の節の段落の途中をクリックした状態が写っています。

このレシピが答える質問

  • ページ上のクリックが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 での点を渡し、2つの呼び出しがその点の組版を読みます。sourceAt はそこに描かれているものを内側から順に並べます。グリフ、その行、そのブロック、周りの囲みです。2ページにまたがる段落は範囲全体で答え、柱は 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;
}

パネルは各行を、ブロックの始まりと終わり、そしてキャレットの位置で切ります。そのため印とキャレットは、ページが示すのと同じ文字に載ります。同じ2つの範囲はハイライトと挿入記号としてビューアーにも返り、読む人はジャンプが狙った場所に着いたかを確かめられます。

レシピの全体

// ═══ 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 要素は、ページの1行を組んでいる 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;

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)