本文へスキップ
レシピ番号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行

かんたんな説明

灯台のレンズについての記事をページビューアーで表示し、横にパネルを置きます。ページで語句を選ぶと、それが原稿のどこにあり、原稿にどう書かれているかを、書式の記号も含めてパネルに示します。

できあがり

灯台のレンズについての2ページの記事をページビューアーで表示し、右側にパネルを置きます。レビューツールが議論中の箇所の横に出すようなパネルです。1ページ目の一文が選択されていて、パネルはそれを三通りに読み返します。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 の両端揃えの1段組、港の青の Archivo の見出し、下にノンブル。選択はどの組版でも同じように働きます。段組でも、右から左のページや縦組のページでも同じです。ビューアーは各行がどこに描かれたかを組版に尋ねるからです。

#2 · 選択を Markdown として読む

コードは上の手短な答えです。createViewer に markdown を渡すと、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,

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)