かんたんな説明
家庭菜園の暦の3月のページです。月のカレンダーと色分けした表があります。データから表を作る方法と、ページに収まらない幅の表を横に倒す方法を示します。
できあがり
イタリア語で書かれた家庭菜園の暦の、3月のページです。27ページは、淡い空の下で黒い土に並ぶ苗の水彩画で始まり、84ptの月名と農村のことわざが添えられます。2段組みの本文の下には、その月のカレンダーが入ります。これはサンプルのコードが日付から計算したものです。日曜はクリーム色の列に赤字で、復活祭の日曜と月曜はピンクの上に置き、月の4つの相はその日の横に描きます。28ページはその月の作業を2段組みの囲みに並べ、10×10のコンパニオンプランツの表を緑、ピンク、クリーム色に塗り分け、対角線上に各作物の画像を置きます。1年の種まき時期を38作物、半月刻みで示す表はページより幅が広いため、90度回して29ページと30ページに組み、2ページ目で表頭を繰り返します。
このレシピが答える質問
- 幅の広い表を、専用のページに横向きで組むには?
- 見出し行、結合セル、列幅、セルごとのそろえを備えた表を作るには?
- 1つの文書の中で、複数の表を異なるスタイル(塗り、縞模様のセル、角丸の枠)にするには?
- 表のセルに画像やアイコンを入れるには?
- 本文、キャプション、表の注に色見本(凡例の色)を加えるには?
手短な答え
// The chart's `placement` (#region resources): a quarter turn makes it a page-span float on
// pages of its own, flush to the spine; rows past the page's width go on under a repeated head.
const chartPlacement = { rotate: 'ccw' }; // a float: 'here' ignores the turn
const MONTHS = ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'];
const SEASONS = [['INVERNO', 2], ['PRIMAVERA', 3], ['ESTATE', 3], ['AUTUNNO', 3], ['INVERNO', 1]];
const STATES = { S: 'ochre', C: 'green', T: 'brown' }; // seedbed, sown outdoors, planted out
const fortnight = (key) => MONTHS.indexOf(key.slice(0, 3)) * 2 + Number(key[3]); // 'mar2' → 6
function sowingChart(data) { // 'Pomodoro: S feb2–mar2, T apr2–mag2'; a bare line is a family
const row = (first, isHeader = false) => [first, ...Array(24).fill('')]
.map((content) => ({ content, isHeader }));
let m = { headerRowCount: 2, columnWidths: [30, ...Array(24).fill(8.5)], // mm, as weights
rows: [row('', true), row('', true)] };
for (const line of data.trim().split('\n')) {
const [name, plan] = line.split(': ');
const r = m.rows.push(row(plan ? name : chip(name.toUpperCase(), 'famiglia'))) - 1;
if (!plan) { m = mergeCells(m, span(r, 0, r, 24)); continue; } // a family heads its crops
for (let f = 1; f <= 24; f++) { // every other month tinted, so a column reads down the page
if ((f - 1) % 4 < 2) m = setCellBackground(m, at(r, f), col('cream'));
}
for (const step of plan.split(', ')) { // 'S feb2–mar2': one state over a run of fortnights
const [state, range] = step.split(' ');
const [from, to = from] = range.split('–').map(fortnight);
for (let f = from; f <= to; f++) m = setCellBackground(m, at(r, f), col(STATES[state]));
}
}
// Merged heads: 'Coltura' down both rows, each season over its months, each month over its
// two fortnights. mergeCells marks the covered cells hiddenBy (gotcha: merged-cells-hiddenby).
const merge = (r0, c0, r1, c1, content) => { // the head's text goes in its first cell
m = mergeCells(setCellContent(m, at(r0, c0), content), span(r0, c0, r1, c1));
};
merge(0, 0, 1, 0, 'Coltura');
let c = 1;
for (const [name, n] of SEASONS) { merge(0, c, 0, c + 2 * n - 1, name); c += 2 * n; }
MONTHS.forEach((month, i) => merge(1, 2 * i + 1, 1, 2 * i + 2, month.toUpperCase()));
for (const r of [0, 1]) for (let f = 1; f <= 24; f++) m = setAlignment(m, at(r, f), 'center');
return setCellBackground(m, at(1, fortnight('mar1')), col('red')); // this month's head
}
材料
- 機能
- 横向きの表と図データから作る表セルの塗りページをまたぐ表名前付きの表スタイル表スタイル表のセル内の画像色見本インラインのチップ囲みの中や本文中の段組みデザインした章扉段抜きの章見出し帯見出しの属性セマンティックカラーパレット見開きの余白出典とクレジット「図」と「表」を文書の言語でハイフネーションと文書の言語リソースとしての図と表キャンバス上のページ
- 種類
- Piazzolla, Gilda Display, Commissioner (SIL OFL 1.1)
- 素材
campo-1680.jpg- The opener’s field of seedlings in March, a watercolour (Generated With Diffusion Models, オリジナル)
- The moon’s quarters and the ten crops, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)
作り方
#1 · 表を回し、次のページへ続ける
コードは上の手短な答えにあります。rotate: 'ccw'は、表を専用のページに置く全幅のフロートにします(配置)。表頭はページの左端を向き、奇数ページでも偶数ページでも背の側に寄ります。表は版面の高さ方向に組まれ、237mmのうち227mmを使います。収まる14ptのグリッド行47行分から、フロートの間隔の1行を引いた長さです。行は176mmの幅を横切って積み重なり、幅を超えると表は2つの行のあいだで切られ、2行の表頭とキャプションを付けて次のページへ続きます。キャプションの末尾には(segue)が付きます(ページより高い表)。回転できるのはフロートだけです。position: 'here'では回転は無視され、表は回転しないまま、段の終わりで行のあいだで分割されます。表頭のセルは3通りに結合しています。Colturaは表頭の2行を縦に通し、各季節はその月の上に、各月はその2つの半月の上にまたがります。
#2 · 日付から計算するカレンダー
const [YEAR, MONTH, DAY] = [2027, 3, 24 * 60 * 60 * 1000]; // DAY in ms
const epochDay = (m, d) => Date.UTC(YEAR, m - 1, d) / DAY; // 1 January 1970 was a Thursday
const weekday = (d) => (epochDay(MONTH, d) + 3) % 7; // 0 is Monday: Italian weeks start there
function easter(y) { // the Gregorian computus (Meeus): [month, day]
const a = y % 19, b = Math.floor(y / 100), c = y % 100, d = Math.floor(b / 4);
const g = Math.floor((8 * b + 13) / 25), h = (19 * a + b - d - g + 15) % 30;
const i = Math.floor(c / 4), k = c % 4, l = (32 + 2 * (b % 4) + 2 * i - h - k) % 7;
const n = h + l - 7 * Math.floor((a + 11 * h + 22 * l) / 451) + 114;
return [Math.floor(n / 31), (n % 31) + 1];
}
// The moon's age: mean synodic months since the new moon of 6 January 2000 at 18.14 UT.
const [SYNODIC, NEW_MOON] = [29.530588853, Date.UTC(2000, 0, 6, 18, 14) / DAY];
const quarter = (day) => Math.floor((((day - NEW_MOON) % SYNODIC) / SYNODIC) * 4); // 0–3
const PHASES = ['luna-nuova', 'primo-quarto', 'luna-piena', 'ultimo-quarto'];
const JOINER = '\u2060'; // a word joiner: the second line of a day without a note
const DAYS = ['LUNEDÌ', 'MARTEDÌ', 'MERCOLEDÌ', 'GIOVEDÌ', 'VENERDÌ', 'SABATO', 'DOMENICA'];
function calendarTable() { // the grid, and the quarters it draws, listed for the caption
const e = epochDay(...easter(YEAR)) - epochDay(MONTH, 0); // Easter as a day of MONTH: 28 in 2027
const feasts = { [e - 7]: 'Le Palme', [e]: 'Pasqua', [e + 1]: 'Pasquetta' };
const notes = { 19: 'S. Giuseppe', 20: 'Equinozio' }; // March 2027's, typed by hand
const first = weekday(1), days = epochDay(MONTH + 1, 1) - epochDay(MONTH, 1), moons = [];
const week = (names, isHeader) => names.flatMap((content) => [content, '']) // a day: moon, date
.map((content) => ({ content, isHeader }));
let m = { headerRowCount: 1, columnWidths: Array(7).fill([7, 18]).flat(), rows: [week(DAYS, true),
...Array.from({ length: Math.ceil((first + days) / 7) }, () => week(Array(7).fill('')))] };
for (let d = 1; d <= days; d++) {
const r = 1 + Math.floor((first + d - 1) / 7), c = 2 * weekday(d), sunday = c === 12;
// Sundays and feasts print in red. Every day has a second line, so all weeks are as tall.
const note = feasts[d] ? chip(feasts[d], 'festa') : notes[d] ? chip(notes[d], 'nota') : JOINER;
m = setCellContent(m, at(r, c + 1), `${sunday || feasts[d] ? chip(d, 'rosso') : d}\n${note}`);
const fill = d === e || d === e + 1 ? 'blush' : sunday ? 'cream' : null;
if (fill) for (const k of [c, c + 1]) m = setCellBackground(m, at(r, k), col(fill));
const midnight = epochDay(MONTH, d) - 1 / 24, q = quarter(midnight + 1); // 00.00 CET
if (q === quarter(midnight)) continue;
m = setCellImage(m, at(r, c), { resourceId: PHASES[q] }); // a quarter begins today
moons.push(`${PHASES[q].replace('-', ' ')} ${[1, 8, 11].includes(d) ? 'l’' : 'il '}${d}`);
}
for (let i = 0; i < 7; i++) m = mergeCells(m, span(0, 2 * i, 0, 2 * i + 1)); // one head a day
return { model: setCellBackground(m, at(0, 12), col('red')), moons: moons.join(', ') };
}
Date.UTCから得る通日で各日付の曜日が決まり、グリッドは3月1日の月曜から始まって5週分続きます。復活祭はコンプトゥス(復活祭の日付計算)から、月の相は平均朔望月から求めます。この方法では相が1日前後にずれることがあり、キャプションでもそう断っています。月を描くループは、その日付をキャプションにも書き込みます。セルの画像は常にテキストの上に置かれるため、各日は月の列と日付の列の2列を取ります。月を日付と同じセルに入れると、4日だけ日付が下に押されてしまいます。日曜と祝日は色だけを変えるチップスタイルで赤にし、注記は半分の大きさのチップにします。注記のない日には2行目にワードジョイナー(U+2060)を入れ、5週の高さをそろえます。
#3 · 貼り付けた記号から表を塗る
const FILLS = { '+': 'leaf', '−': 'blush', '': 'cream' }; // good, bad, no known effect
function companionTable(tsv) {
let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [26, ...Array(10).fill(15)] };
for (let r = 1; r < m.rows.length; r++) {
m = setAlignment(m, at(r, 0), 'left', 'middle');
for (let c = 1; c < m.rows[r].length; c++) {
const symbol = m.rows[r][c].content; // + and − stay printed, for greyscale copies
m = setCellContent(m, at(r, c), symbol && symbol !== '=' ? chip(symbol, 'segno') : '');
m = symbol === '=' // the diagonal pairs a crop with itself: its picture instead
? setCellImage(m, at(r, c), { resourceId: `veg-${r}`, width: 0.62 })
: setCellBackground(m, at(r, c), col(FILLS[symbol]));
m = setAlignment(m, at(r, c), 'center', 'middle');
}
}
for (let c = 1; c <= 10; c++) m = setAlignment(m, at(0, c), 'center');
return m;
}
作物の組み合わせはTSVで、セルごとに記号を1つ入力します。parseTSV(tsv, { headerRows: 1 })で、作物名の行が表頭になります。columnWidthsの重みは176mmの行長に対するミリメートルで、名前に26、各作物に15です。各記号は色見本の項目を指し、setCellBackgroundがそれをセルの塗りにします。+と−も1.4emのチップで刷るので、グレースケールで複写しても表は読めます。対角線上は作物とそれ自身の組み合わせなので、そこにはsetCellImageが作物の画像を、セルの内側の幅の62%で置きます。
#4 · 色の凡例を色見本で示す
const resourceTypes = [ // the almanac's own two: tables numbered through, a bare calendar
{ id: 'table', name: 'Tabella', shortLabel: 'Tab.', captionPrefix: 'Tabella',
captionStyle: { position: 'above' } },
{ id: 'calendar', name: 'Calendario', shortLabel: 'Cal.', captionPrefix: '' }, // no label
].map((t) => ({ numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal', ...t }));
const table = (id, typeId, caption, model, styleId, extra) => ({ id, typeId, kind: 'table',
caption, table: { model, styleId }, createdAt: 0, updatedAt: 0, ...extra });
const foot = { position: 'bottom', span: 'page' }; // across both columns, at the page's foot
const calendar = calendarTable(); // its key names the quarters the grid draws
const resources = [...pictures, // never cited: the opener and the cells draw them by id
table('calendario', 'calendar', ':swatch{color="cream"} domeniche · :swatch{color="blush"} '
+ `Pasqua e Pasquetta · ${calendar.moons}, sul mese sinodico medio: un giorno prima o dopo `
+ 'è possibile. Per tradizione in crescente si semina ciò che fruttifica sopra terra, in '
+ 'calante le radici.', calendar.model, 'calendario', { placement: foot }),
table('consociazioni', 'table', 'Consociazioni tra dieci ortaggi', companionTable(companions),
'matrice', { placement: foot, note: ':swatch{color="leaf"} + favorevole · '
+ ':swatch{color="blush"} − da evitare · :swatch{color="cream"} nessun effetto noto. '
+ 'Indicazioni della tradizione orticola.' }),
// Each part of a split table repeats its caption, so the key goes there; the note ends the last.
table('semine', 'table', 'Semine al Nord e al Centro, in pianura e collina: '
+ ':swatch{color="ochre"} in semenzaio protetto · :swatch{color="green"} in piena terra · '
+ ':swatch{color="brown"} trapianto o messa a dimora', sowingChart(sowing), 'semine', {
placement: chartPlacement, note: 'Al Sud e lungo le coste le date si anticipano di '
+ 'due-quattro settimane; in montagna si ritardano.' }),
];
:swatch{color="leaf"}は、文字サイズの4分の3の正方形を色見本の色で塗り、本文の色で縁取ります。これらのページでは、本文中、2つのキャプション、1つの注で使っています。表の凡例はキャプションに入れます。分割した表は各部分でキャプションを繰り返しますが、注は最後の部分の下にしか組まれないからです。カレンダーは独自のリソースの種類で、キャプションの接頭辞は空です。そのキャプションはTabellaのラベルではなく凡例で始まります。position: 'bottom'とspan: 'page'で、カレンダーと表をそれぞれのページの下端に2段にまたがって組みます。28ページは本文の最後のページです。章の最後のページでは、全幅のフロートが本文の1行下まで上がるため、表は地の余白より10mm上で終わります。layout.hugClosingFloats: falseにすれば下端に残ります。
#5 · 共通のスタイルと表ごとの変種
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
headerBackground: col('ink'), headerColor: col('paper'), headerFontFamily: LABEL,
headerFontSize: pt(7), bodyFontSize: pt(8.5), cellPadding: mm(1.2),
// An Italian document's split table says '(segue)' and 'Continua'; this spells the second out.
continuesMarker: 'Continua alla pagina seguente' };
const tableStyles = [
{ id: 'calendario', bodyFontFamily: DISPLAY, bodyFontSize: pt(15), cellPadding: mm(1.4) },
{ id: 'matrice', rules: 'grid', borderColor: col('paper'), borderWidth: pt(2), // tiles
headerBackgroundEnabled: false, headerColor: col('ink'), headerFontSize: pt(6.8) },
{ id: 'semine', rules: 'grid', borderColor: col('paper'), borderWidth: pt(1),
bodyFontSize: pt(7.8), headerFontSize: pt(6.6), cellPadding: mm(1.1) },
];
tableStyleで共通のスタイルを決めます。墨色の表頭にCommissionerの紙色のラベル、行のあいだにヘアライン、そして分割した表の各部分を締める1行です。イタリア語の文書では、続きのある部分の末尾にContinua、次の部分のキャプションに(segue)が入ります。この暦は前者をContinua alla pagina seguenteと書き切っています。名前付きの各スタイルには、その表が変える点だけを書きます。カレンダーは日付をGilda Displayの15ptで組み、コンパニオンプランツの表は表頭の塗りを外します。この表と種まき表は、紙の色で幅2ptと1ptの罫を引き、塗りをタイルに切り分けます。
#6 · 月は1枚の絵で始まる
const ART_H = 92, AIR = 5, BEARING = 1.5; // mm: painting, air under it, side bearing of the 84 pt M
const pin = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
...(size && { size }) }); // to: 'page', or '#id' of an element listed before
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
content, fontFamily: family, fontSize: pt(size), color: col(color), placement,
align: placement.anchor.edge.endsWith('right') ? 'right' : 'left',
overflow: 'wrap', ...extra }); // a long line takes a second one, in the heads too
const caps = (s) => ({ fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(s / 5) });
// minHeight: a floor under what the painting reserves, the first grid line AIR or more below it.
const OPENER_H = pt(LEAD * Math.ceil((ART_H + AIR - PAGE.top) / (LEAD * 25.4 / 72)));
const opener = { enabled: true, minHeight: OPENER_H, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'campo',
placement: pin('page', 'top-left', 0, 0, { width: mm(PAGE.w), height: mm(ART_H) }) },
text('kicker', '{attr.kicker}', LABEL, 8.5, 'red', pin('page', 'top-left', PAGE.inner, 12),
caps(8.5)), // page 1 is a recto: its inner margin is on the left
text('title', '{titleText}', DISPLAY, 84, 'ink', pin('#kicker', 'below', -BEARING, 1),
{ lineHeight: 1 }), // a multiple of the size: set solid
text('proverb', '{attr.proverb}', TEXT, 12.5, 'ink',
pin('#title', 'below', BEARING, 1, { width: mm(140) }), { italic: true, lineHeight: 1.3 }),
text('source', '{attr.source}', LABEL, 7, 'ink', pin('#proverb', 'below', 0, 1.6), caps(7)),
] } };
レベル1の見出しは要素のスロットから描きます。水彩画はページの頭に置いた画像要素で、キッカー、ことわざ、その出典は見出しの属性から取ります。見出しのデザインは水彩画の下端までを確保し、minHeightはそれより少し下に置いた下限です。画像の92mmに余白5mmを足し、天の余白22mmを引くと75mmで、14ptの行16行(79mm)に切り上がります。本文の1行目はページの上端から101mm、土の9mm下に来ます。題は1.5mm左へずらします。これは84ptのGilda DisplayのMのサイドベアリングで、Mのセリフがキッカーとそろいます。ことわざは同じ量だけ戻します。
レシピの全体
// ═══ Postext Cookbook · Nº 035 · Garden almanac: calendar grid and landscape chart ═════
// https://postext.dev/en/cookbook/garden-almanac
// Code: MIT · Text: original, Italian (CC BY 4.0) · Field: diffusion models · Icons: CC BY 4.0
// Fonts: Piazzolla, Gilda Display, Commissioner (SIL OFL 1.1) · Needs postext ≥ 1.57.0
import {
buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage, parseTSV,
mergeCells, setCellContent, setCellBackground, setCellImage, setAlignment,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'garden-almanac';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#262a22', paper: '#fbf8ef', // a green-black on unbleached paper
red: '#a2372a', // Sundays and feasts, as almanacs print them; kickers and labels
green: '#5b8a32', ochre: '#d39a2e', brown: '#7a5230', // sown outdoors, in a seedbed, planted
leaf: '#bfdaa2', blush: '#f3cdbd', cream: '#e9ddc1', // good pairs, bad pairs, neutral pairs
sky: '#cfe2e6', rule: '#cfc6b2', muted: '#6b6e63' }; // sky and work box; hairlines; notes
// col() links a colour to its palette entry; the hex is the value the entry holds.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.red }) // the defaults' id
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['Piazzolla', 'Gilda Display', 'Commissioner'];
const PAGE = { w: 210, h: 280, top: 22, bottom: 21, inner: 18, outer: 16 }; // mm, mirrored
const LEAD = 14; // pt: the body's leading and baseline grid
const at = (row, column) => ({ row, col: column });
const span = (r0, c0, r1, c1) => ({ start: at(r0, c0), end: at(r1, c1) });
const chip = (text, style) => `:chip[${text}]{style="${style}"}`;
// #region answer: a crops × fortnights chart, turned to landscape on pages of its own
// The chart's `placement` (#region resources): a quarter turn makes it a page-span float on
// pages of its own, flush to the spine; rows past the page's width go on under a repeated head.
const chartPlacement = { rotate: 'ccw' }; // a float: 'here' ignores the turn
const MONTHS = ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'];
const SEASONS = [['INVERNO', 2], ['PRIMAVERA', 3], ['ESTATE', 3], ['AUTUNNO', 3], ['INVERNO', 1]];
const STATES = { S: 'ochre', C: 'green', T: 'brown' }; // seedbed, sown outdoors, planted out
const fortnight = (key) => MONTHS.indexOf(key.slice(0, 3)) * 2 + Number(key[3]); // 'mar2' → 6
function sowingChart(data) { // 'Pomodoro: S feb2–mar2, T apr2–mag2'; a bare line is a family
const row = (first, isHeader = false) => [first, ...Array(24).fill('')]
.map((content) => ({ content, isHeader }));
let m = { headerRowCount: 2, columnWidths: [30, ...Array(24).fill(8.5)], // mm, as weights
rows: [row('', true), row('', true)] };
for (const line of data.trim().split('\n')) {
const [name, plan] = line.split(': ');
const r = m.rows.push(row(plan ? name : chip(name.toUpperCase(), 'famiglia'))) - 1;
if (!plan) { m = mergeCells(m, span(r, 0, r, 24)); continue; } // a family heads its crops
for (let f = 1; f <= 24; f++) { // every other month tinted, so a column reads down the page
if ((f - 1) % 4 < 2) m = setCellBackground(m, at(r, f), col('cream'));
組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)
アレンジ
#表を時計回りに回す
表頭はページの右端を向き、読者は本を反対向きに回します。
-const chartPlacement = { rotate: 'ccw' }; // a float: 'here' ignores the turn
+const chartPlacement = { rotate: 'cw' }; // a float: 'here' ignores the turnよくあるつまずき
- 表のセルの画像は、常にセルのテキストの上に描かれ、テキストと同じそろえ方になります。数字の横にアイコンを置くには、カレンダーが月にしているように、アイコンに専用の列を与えます。
- 分割した表の下の注は最後の部分にしか出ません。どの部分にも要る凡例はキャプションに入れます。
クレジット
- 本文
- 画像
- The opener’s field of seedlings in March, a watercolour · Generated With Diffusion Models · オリジナル
- The moon’s quarters and the ten crops, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
- フォント
- Piazzolla (SIL OFL 1.1) · Gilda Display (SIL OFL 1.1) · Commissioner (SIL OFL 1.1)


