本文へスキップ
レシピ番号213

レシピ集 · 第13章 · CMSへの組み込み

範囲のリストからハイライトを描く

レビューツールの記録(Markdown の範囲と判定)を、setAnnotations で組版したページに3色のハイライトとして描く。

このページの内容
出力
Canvas
レベル
初級
Postext
Postext 1.103.1で検証済み
1.103.0以上が必要
ライセンス
2026年12月4日更新
コードMIT · 本文CC BY 4.0
ニュースレターの五つの主張を判定ごとに色分け:確認済みは黄、出典が必要なものは青、著者への問い合わせはピンク。どれもページの横に一覧される。
ニュースレターの五つの主張を判定ごとに色分け:確認済みは黄、出典が必要なものは青、著者への問い合わせはピンク。どれもページの横に一覧される。
  • 英語の見本:日本語版はまだありません
  • 仕上がり160 × 230 mm
  • 1段
  • Source Serif 4 10.5/15
  • Source Sans 3
  • 1ページ
  • レベル
  • Postext 1.103.1
  • 組版時間46 ms
  • コード102行

かんたんな説明

ロンドンのプラタナスについてのニュースレター記事を、事実確認の担当者の目で表示します。確認済みの記述は判定に応じて黄・青・ピンクで塗られ、横のリストがそれを並べます。項目を押すとその語句までスクロールします。

できあがり

ロンドンのプラタナスについてのニュースレター記事を、事実確認の担当がレビューツールで見るように表示します。五つの記述に判定が付いています。黄は確認済み、青は筆者がまだ出典を示していないもの、ピンクは筆者への質問です。ハイライトは組んだページの上にあり、記述が改行されるところでは分かれます。右のリストには同じ五つの記録が読む順に並びます。項目を押すと、ビューアーがその語句を画面に運びます。

このレシピが答える質問

  • Markdownの範囲のリストから、ページ上にハイライトを描くには?

手短な答え

script.js · 112〜128行コード全体で見る
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-page', labels,
});
view.setAnnotations(claims.map(({ id, verdict, range }) => ({
  id, kind: 'highlight', range, color: VERDICTS[verdict].color, // 35 % over the text
})));
// The list beside the page: an entry brings its words into view.
const list = document.getElementById('claims');
for (const { id, verdict, range } of claims) {
  const item = document.createElement('button');
  item.style.setProperty('--tag', VERDICTS[verdict].color);
  item.innerHTML = '<b></b><span></span>';
  item.querySelector('b').textContent = VERDICTS[verdict].name;
  item.querySelector('span').textContent = markdown.slice(range.start, range.end);
  item.addEventListener('click', () => view.revealAnnotation(id, { behavior: 'smooth' }));
  list.append(item);
}

材料

種類
Source Serif 4, Source Sans 3 (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · 記録を範囲として持つ

script.js · 85〜103行コード全体で見る
// A CMS stores the offsets; the pen finds them from quotes so that both editions run.
const VERDICTS = {
  checked: { color: '#d39b00', name: t({ en: 'Checked', es: 'Comprobado' }) },
  source: { color: '#2f7fd6', name: t({ en: 'Needs a source', es: 'Falta la fuente' }) },
  query: { color: '#d64c86', name: t({ en: 'Query the author', es: 'Preguntar al autor' }) },
};
const claims = t({
  en: [['source', 'reached England from Virginia'],
    ['query', 'perhaps in Spain, perhaps in an English garden'], ['checked', 'set out in 1789'],
    ['source', 'it became the commonest street tree'],
    ['checked', 'first recorded in London in 2008']],
  es: [['source', 'llegó a Inglaterra desde Virginia'],
    ['query', 'quizá en España, quizá en un jardín inglés'], ['checked', 'plantados en 1789'],
    ['source', 'llegó a ser el árbol de calle más común'],
    ['checked', 'registrada por primera vez en Londres en 2008']],
}).map(([verdict, quote], i) => {
  const start = markdown.indexOf(quote);
  return { id: `c${i + 1}`, verdict, range: { start, end: start + quote.length } };
});

記録とは、ツールがすでに保存しているものです。章の Markdown の中の範囲 { start, end } と、確認者の判定です。印は判定について何も知りません。サイトが判定ごとに色を決めます。ここではオフセットを本文の引用から求め、英語版とスペイン語版の両方が動くようにしています。コンテンツ管理システムならデータベースから読みます。

#2 · ハイライトとして描く

コードは上の手短な答えです。setAnnotations はビューアーが表示する印を置き換えます。ハイライトは範囲の各断片に重ねる半透明の塗りで、color の 35 % なので、下の文字は黒いままです。記録が変わったら新しいリストでもう一度呼べば、ビューアーは見えているページだけを描き直します。右のリストは同じ記録です。revealAnnotation は、サイトが付けた id で印を画面に運びます。

#3 · 印に読者の言語で名前を付ける

script.js · 107〜108行コード全体で見る
const labels = t({ en: {}, es: { viewer: 'Páginas del boletín', page: 'Página {n} de {count}',
  kinds: { highlight: 'Resaltado' } } });

ビューアーは各印をキーボード用のボタンにし、labels.kinds と印の付いた語句から名前を付けます。スクリーンリーダーは「Highlight: set out in 1789」と読み上げます。スペイン語版は独自の名前を渡し、英語版は何も要りません。

レシピの全体

// ═══ Postext Cookbook · Nº 213 · Highlights from a list of ranges ═══════════════════
// https://postext.dev/en/cookbook/highlights-from-ranges
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A newsletter article on the London plane, as a fact-checker sees it in a review tool: the
// claims the desk has looked at are highlighted in three colours, one per verdict, and the
// list beside the page is the same records. A click on an entry brings its words into view.
import { buildDocumentWithFonts, renderPageToCanvas } 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 = 'highlights-from-ranges';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#22201c', // text
  accent: '#3d6b35', // leaf green: 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 newsletter page, one wide column
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(230), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(24), right: mm(24) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4.5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Source Sans 3', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(26), lineHeight: pt(30), marginTop: pt(0), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10.5), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Source Sans 3',
      fontSize: pt(8), fontWeight: 700, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#塗りを濃くする

クリーム色や色付きの紙面では、35 % の塗りは薄すぎることがあります。

-  document: doc, markdown, zoom: 'fit-page', labels,
+  document: doc, markdown, zoom: 'fit-page', labels, marks: { highlightOpacity: 0.5 },

#塗る代わりに下線を引く

控えめな校正刷りにするなら、判定の色で下線を引きます。

-  id, kind: 'highlight', range, color: VERDICTS[verdict].color, // 35 % over the text
+  id, kind: 'underline', range, color: VERDICTS[verdict].color, // under the baseline

クレジット

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