# Από μια συμβολοσειρά Markdown σε μια σχεδιασμένη σελίδα

> Συμβολοσειρά Markdown με frontmatter γίνεται σελίδες περιοδικού δύο στηλών σε καμβά, με έξι ονομασμένα χρώματα αντί για το προεπιλεγμένο μπλε.

- Έκδοση HTML: https://postext.dev/el/cookbook/first-page-from-markdown
- Συνταγή Αρ. 012 · Έξοδος και ενσωμάτωση · Επίπεδο 2 (Μεσαίο) · Έξοδοι: Canvas
- Είδη: Περιοδικά και fanzines
- Απαιτεί postext ≥ 1.88.1 · δοκιμασμένη με 1.93.0 στις 2026-11-23
- Σελίδες: [1](https://postext.dev/cookbook/first-page-from-markdown/en/p01.webp?v=d86cf17b), [2](https://postext.dev/cookbook/first-page-from-markdown/en/p02.webp?v=d86cf17b)
- Άνοιγμα στο Sandbox: https://postext.dev/el/sandbox#recipe=first-page-from-markdown&lang=en (.postext: https://postext.dev/cookbook/first-page-from-markdown/en/first-page-from-markdown.postext)
- Τελευταία ενημέρωση: 2026-10-16
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/first-page-from-markdown.md), [es](https://postext.dev/es/cookbook/first-page-from-markdown.md), [ca](https://postext.dev/ca/cookbook/first-page-from-markdown.md), [de](https://postext.dev/de/cookbook/first-page-from-markdown.md), [fr](https://postext.dev/fr/cookbook/first-page-from-markdown.md), [it](https://postext.dev/it/cookbook/first-page-from-markdown.md), [pt](https://postext.dev/pt/cookbook/first-page-from-markdown.md), [zh](https://postext.dev/zh/cookbook/first-page-from-markdown.md), [ja](https://postext.dev/ja/cookbook/first-page-from-markdown.md), [ar](https://postext.dev/ar/cookbook/first-page-from-markdown.md)

## Με λίγα λόγια

Οι δύο πρώτες σελίδες ενός ταξιδιωτικού άρθρου σε ένα μικρό περιοδικό, με μια χρωματιστή ταινία και μια εικόνα. Δείχνει πώς ένα απλό κείμενο με λίγες επικεφαλίδες γίνεται σχεδιασμένη σελίδα στα δικά σας χρώματα.

## Τι θα στοιχειοθετήσετε

Οι πρώτες σελίδες ενός ταξιδιωτικού άρθρου στο *Field Notes*, ένα μικρό περιοδικό. Η σελίδα 1 είναι μια εναρκτήρια δεξιά σελίδα: μια φωτογραφία με αλυκές και έναν αμμόλοφο στο σούρουπο στο πάνω 58% της σελίδας, ο τίτλος σε Young Serif των 54 pt, και δύο στήλες με πλήρη στοίχιση από κάτω που αρχίζουν το κείμενο με μια έντονη εισαγωγή. Η σελίδα 2, στο πίσω μέρος του φύλλου, συνεχίζει κάτω από μια τρέχουσα κεφαλίδα σε αραιωμένα κεφαλαία και τελειώνει με ένα σήμα τέλους και έναν κολοφώνα. Η σχεδίαση ορίζεται από μία συνάρτηση διαμόρφωσης και μια παλέτα έξι χρωμάτων. Ο τίτλος προέρχεται από την επικεφαλίδα πρώτου επιπέδου, και το εισαγωγικό κείμενο, ο συντάκτης και η ημερομηνία από το frontmatter της συμβολοσειράς Markdown, έτσι το ίδιο pen στοιχειοθετεί κάθε άρθρο του οποίου ο τίτλος χωρά σε δύο γραμμές· μόνο η φωτογραφία ανήκει σε αυτό το άρθρο.

**Αυτή η συνταγή απαντά:**

- Πώς βάζω Markdown σε σχεδιασμένες σελίδες χωρίς το προεπιλεγμένο μπλε σε επικεφαλίδες, έντονα και κουκκίδες;
- Πώς στήνω μια σελίδα βιβλίου: διάσταση σελίδας, κατοπτρικά εσωτερικά και εξωτερικά περιθώρια, δύο στήλες και διάκενο;
- Πώς μετατρέπω μια συμβολοσειρά Markdown σε στοιχειοθετημένες σελίδες και σχεδιάζω μία σε καμβά;

## Η σύντομη απάντηση

```js
// script.js, γραμμές 125–164
const config = () => ({
  locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
  colorPalette: colorPalette(),
  page: { // mirror: left is the inner margin and right the outer one; versos swap them
    width: mm(PAGE.width), height: mm(PAGE.height),
    margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
      right: mm(MARGIN.outer), mirror: true },
  },
  // 'double' is the default, stated so that the whole page setup reads in one place
  layout: { layoutType: 'double', gutterWidth: mm(6) },
  bodyText: { // justified, hyphenated and broken by paragraph: all on by default
    fontFamily: 'Newsreader', // one family name: there is no fallback chain
    fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: mm(4), indentAfterHeading: false,
    // Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
    // tightened by at most 4 thousandths of an em, so the grey of the text stays even.
    minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
  },
  headings: {
    fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
    levels: [
      // span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
      // next article pasted in on a recto, with a blank verso only when one is needed.
      { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
        advancedDesign: opener() },
      // A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
      // default) rounds up to 3, so the text below lands back on the grid.
      { level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
        marginBottom: pt(0) },
    ],
  },
  unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
    marginTop: pt(0), marginBottom: pt(0) },
  calloutStyles: [colophon()],
  header: header(),
  footer: footer(),
  // The magazine's name is its masthead, the same on every story (#849).
  checks: { contentInConfig: { allow: [MAGAZINE] } },
});
```

## Υλικά

**Διδάσκει**

- [Μεταδεδομένα εγγράφου](https://postext.dev/el/docs/document-format.md#μεταδεδομένα-frontmatter): Frontmatter YAML με τίτλο, υπότιτλο, συγγραφέα και ημερομηνία, που τα τυπώνουν τα σύμβολα κράτησης θέσης των τρεχουσών κεφαλίδων και των εξωφύλλων και που το PDF παίρνει ως τίτλο του.
- [Σημασιολογική χρωματική παλέτα](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων): Ονομασμένα χρώματα με τα οποία συνδέεται κάθε ρύθμιση μέσω id, ώστε ολόκληρο το έγγραφο να αλλάζει χρώματα αλλάζοντας ένα δείγμα· τα προεπιλεγμένα χρώματα προκύπτουν από το main-color.
- [Τρέχουσες κεφαλίδες και αριθμοί σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα): Θέσεις κεφαλίδας και υποσέλιδου με σύμβολα κράτησης θέσης ({pageNumber}, {chapterTitle}, {title}…), που ορίζονται χωριστά για δεξιά και αριστερή σελίδα, με τους μεγάλους τίτλους να περικόπτονται ή να αναδιπλώνονται.

**Χρησιμοποιεί επίσης**

- [Σελίδες σε καμβά](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap)
- [Σχεδιασμένες εναρκτήριες σελίδες](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση)
- [Ταινία κεφαλαίου πλήρους πλάτους](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση)
- [Εικόνες στις σχεδιάσεις σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-εικόνας)
- [Αγκύρωση στοιχείων σχεδίασης](https://postext.dev/el/docs/configuration-headers-footers.md#τοποθέτηση-στοιχείων)
- [Κεφαλίδες ανά ρόλο σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-κειμένου)
- [Γραμματοσειρές πριν από τη σελιδοποίηση](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση)
- [Διάσταση σελίδας](https://postext.dev/el/docs/configuration-page-layout.md#προκαθορισμένα-μεγέθη-σελίδας)
- [Συμμετρικά περιθώρια](https://postext.dev/el/docs/configuration-page-layout.md#κατοπτρικά-περιθώρια)
- [Μία ή δύο στήλες](https://postext.dev/el/docs/configuration-page-layout.md#τύποι-διάταξης)
- [Γράμματα κυρίως κειμένου](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο)
- [Έντονα, πλάγια και τα χρώματά τους](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο)
- [Δείγματα χρώματος](https://postext.dev/el/docs/document-format-inline.md#μορφοποίηση-μέσα-στη-γραμμή)
- [Συλλαβισμός και γλώσσα του εγγράφου](https://postext.dev/el/docs/justification.md#υποστηριζόμενες-γλώσσες)
- [Λίστες με κουκκίδες και λίστες ελέγχου](https://postext.dev/el/docs/configuration-lists-math.md#λίστες-με-κουκκίδες)
- [Πλαίσια σημειώσεων](https://postext.dev/el/docs/configuration-callouts.md#στιλ-πλαισίων)
- [Αλλαγές γραμμής στους τίτλους](https://postext.dev/el/docs/document-format-directives.md#αλλαγές-γραμμής-σε-τίτλους)
- [Εικόνες και πίνακες ως πόροι](https://postext.dev/el/docs/document-format-resources.md#πόροι)

**Η διαμόρφωση με μια ματιά**

- [`bodyText`](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο), [`calloutStyles`](https://postext.dev/el/docs/configuration-callouts.md#στιλ-πλαισίων), [`checks`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#έλεγχος-περιεχομένου-διαμόρφωση), [`colorPalette`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων), [`footer`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`header`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`headings`](https://postext.dev/el/docs/configuration-headings.md#επικεφαλίδες), [`layout`](https://postext.dev/el/docs/configuration-page-layout.md#διάταξη), [`locale`](https://postext.dev/el/docs/configuration-language.md#συλλαβισμός), [`page`](https://postext.dev/el/docs/configuration-page-layout.md#σελίδα), [`unorderedLists`](https://postext.dev/el/docs/configuration-lists-math.md#λίστες-με-κουκκίδες)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση), [`registerResourceImage`](https://postext.dev/el/docs/architecture.md#η-επιφάνεια-του-api), [`renderPageToCanvas`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap)

**Γραμματοσειρές**

- Newsreader (OFL-1.1), Young Serif (OFL-1.1), Inter Tight (OFL-1.1)

## Προετοιμασία

### 1 · Όλες οι γραμματοσειρές, πριν από την πρώτη κατασκευή

```js
// script.js, γραμμές 224–228
const FONTS = {
  Newsreader: ['400', '400i', '700'], // text
  'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
  'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};
```

Το Postext μετρά το κείμενο με τις γραμματοσειρές που έχει ο περιηγητής τη στιγμή που τρέχει η σελιδοποίηση, οπότε μια κατασκευή που θα έτρεχε πριν φτάσουν οι γραμματοσειρές θα κρατούσε τις αλλαγές γραμμής μιας εναλλακτικής γραμματοσειράς. Το `buildDocumentWithFonts` φορτώνει κάθε γραμματοσειρά που ονομάζει η διαμόρφωση, και όσες είναι στο `FONTS`, πριν από την πρώτη κατασκευή· το `kitFonts(FONTS)` του δίνει τα αρχεία από το Fontsource, τα ίδια αρχεία που θα ενσωμάτωνε ένα PDF. Έπειτα εξετάζει τις γραμματοσειρές που χρησιμοποιούν οι σελίδες, φορτώνει όποια λείπει ακόμη και κατασκευάζει ξανά. Μια γραμματοσειρά που δεν διαθέτει το Fontsource μένει σε εναλλακτική και καταγράφεται στο `doc.contentWarnings` ως `fontFallback`. Τα έντονα και τα πλάγια μιας γραμματοσειράς κειμένου φορτώνονται μόνο όταν η οικογένεια τα έχει.

### 2 · Ονομάστε τα χρώματα, και έπειτα δείξτε στα ονόματα

```js
// script.js, γραμμές 23–41
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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' } })),
  // The engine's defaults (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
```

Κάθε χρώμα της διαμόρφωσης είναι `col('id')`, ένα αναγνωριστικό της παλέτας με το hex του δίπλα. Τα `bodyText.boldColor`, `italicColor`, `referenceColor` και `unorderedLists.color` ονομάζουν το `ink`, και το `headings.color` ονομάζει το χρώμα έμφασης. Οι προεπιλογές της μηχανής για επικεφαλίδες, έντονα, πλάγια και κουκκίδες συνδέονται με το `main-color`, και αυτή η παλέτα δείχνει εκείνη την καταχώριση στο χρώμα έμφασης, έτσι όποιο από αυτά παραλείψετε βγαίνει λουλακί αντί για μπλε. Τα αντικείμενα της σχεδίασης είναι συναρτήσεις που καλεί το `config()` σε κάθε κατασκευή, και το `col()` αντιγράφει κάθε φορά το τρέχον hex από το `palette`, έτσι μία αλλαγή στο `palette` φτάνει εξίσου στο κείμενο, στους αριθμούς σελίδας και στην εναρκτήρια. Το σήμα τέλους είναι ένα δείγμα χρώματος μέσα στη γραμμή που ονομάζει το `band`, οπότε ένας νέος χρωματισμός φτάνει κι εκεί. Η προεπιλεγμένη τρέχουσα κεφαλίδα συνδέεται κι αυτή με το `main-color`, οπότε θα τυπωνόταν στο χρώμα έμφασης ώσπου να την αντικαταστήσετε (βήμα 5).

### 3 · Μια φωτογραφία κομμένη στο πλαίσιό της

```js
// script.js, γραμμές 45–51
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
    height: 1120 },
  altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
    + 'footprints crossing the pans towards it.' };
```

Οι αλυκές, ο αμμόλοφος και ο λιθοσωρός είναι μια φωτογραφία παραγμένη με μοντέλα διάχυσης, τραβηγμένη στο σούρουπο ώστε ο ανοιχτόχρωμος τίτλος να διαβάζεται πάνω σε σκοτεινό ουρανό. Το JPEG είναι κομμένο στο πλαίσιο της ταινίας, `PAGE.width` × `BAND` χιλιοστά, και ο πόρος δηλώνει τα εικονοστοιχεία του, 1440 × 1120, έτσι σε πλήρες πλάτος η εικόνα γεμίζει ακριβώς την ταινία. Μια βαθύτερη ταινία χρειάζεται μια εικόνα κομμένη στο νέο πλαίσιο. Η εναρκτήρια τη δείχνει μέσω ενός στοιχείου εικόνας που ονομάζει τον πόρο με το αναγνωριστικό του.

### 4 · Το frontmatter γράφει την εναρκτήρια

```js
// script.js, γραμμές 55–91
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
  fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
  letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
  offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
  enabled: true,
  minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
  slot: {
    elements: [
      // The photograph is PAGE.width × BAND (see art): at full width it fills the band.
      { kind: 'image', id: 'art', resourceId: 'landscape',
        placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
      { kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
        placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
          offset: { x: mm(MARGIN.inner), y: mm(20) } } },
      // {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
      // lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
      { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
        fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
        placement: below('kicker', 3, TITLE_W) },
      { kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
        fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
        placement: below('title', 5, DECK_W) },
      { kind: 'text', id: 'byline', ...label, color: col('sand'),
        content: t({ en: 'By {author} · {publishDate}',
          es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
          fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
        placement: below('deck', 4.5) },
    ],
  },
});
```

Η επικεφαλίδα πρώτου επιπέδου απλώνεται και στις δύο στήλες, και η εναρκτήριά της είναι μια θέση στοιχείων: η φωτογραφία ως το περιθώριο αιμορραγίας και τέσσερα κείμενα αλυσοδεμένα το ένα κάτω από το άλλο. Ένας μακρύτερος τίτλος σπρώχνει το εισαγωγικό κείμενο και την υπογραφή προς τα κάτω αντί να τα επικαλύψει, αλλά πέρα από τις δύο γραμμές η υπογραφή πέφτει πάνω στις ανοιχτόχρωμες αλυκές. Το `{titleText}` είναι το κείμενο της επικεφαλίδας· τα `{subtitle}`, `{author}` και `{publishDate}` είναι πεδία του frontmatter. Το `\\` στην επικεφαλίδα σπάει τον τίτλο εκεί όπου το βάζετε ([αλλαγές γραμμής σε τίτλους](https://postext.dev/el/docs/document-format-directives.md#αλλαγές-γραμμής-σε-τίτλους)). Το `minHeight` μετρά από το πάνω περιθώριο, έτσι το δεσμευμένο ύψος τελειώνει 5 mm κάτω από την ταινία.

### 5 · Τρέχουσες κεφαλίδες αντί για το μπλε της προεπιλογής

```js
// script.js, γραμμές 95–114
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
  kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
  elements: [ // folios on the outer margin's edge; each label hangs off its folio
    head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
    head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
    head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
    head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
  ],
});
const footer = () => ({
  elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
    ...label, color: col('band'),
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});
```

Αν παραλείψετε το `header`, επιστρέφει η προεπιλογή της μηχανής: Open Sans πάνω από μια γραμμή σε όλο το πλάτος, σε κάθε σελίδα. Εδώ κάθε αριθμός σελίδας αγκυρώνεται στη φυσική σελίδα και φιλτράρεται κατά μονή ή ζυγή σελίδα, οπότε κάθεται πάντα στην εξωτερική άκρη. Η ετικέτα του αγκυρώνεται στον αριθμό σελίδας, σε απόσταση `GAP` χιλιοστών με `right-of` ή `left-of`, και ένας αριθμός σελίδας τριών ή τεσσάρων ψηφίων σπρώχνει την ετικέτα πιο πέρα αντί να πέσει πάνω της. Το `pages: 'body'` κρατά και τα τέσσερα στοιχεία έξω από την εναρκτήρια. Το υποσέλιδο περιέχει έναν μόνο κατεβασμένο αριθμό σελίδας για την εναρκτήρια, και αφού το `footer` είναι ορισμένο, οι σελίδες του κυρίως κειμένου χάνουν τον προεπιλεγμένο κεντραρισμένο αριθμό σελίδας.

### 6 · Κατασκευάστε με νέα διαμόρφωση, και έπειτα ζωγραφίστε

```js
// script.js, γραμμές 233–243
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
  title: t({ en: 'From a Markdown string to a designed page',
    es: 'De una cadena Markdown a una página diseñada',
    pt: 'De uma string Markdown a uma página diagramada',
    fr: 'D’une chaîne Markdown à une page mise en forme',
    de: 'Von einem Markdown-String zur gestalteten Seite',
    it: 'Da una stringa Markdown a una pagina progettata' }),
});
```

Το `config()` είναι συνάρτηση ώστε κάθε κατασκευή να διαβάζει την παλέτα όπως είναι εκείνη τη στιγμή: καλεί ξανά τις συναρτήσεις σχεδίασης του βήματος 2. Ένα μόνο αντικείμενο διαμόρφωσης που αλλάζει επιτόπου θα δούλευε εξίσου: από το postext 1.25 η μηχανή βλέπει την αλλαγή στην επόμενη κατασκευή. Το `buildDocumentWithFonts` παίρνει το περιεχόμενο, αυτή τη διαμόρφωση και τις επιλογές γραμματοσειρών του kit, και επιστρέφει το έγγραφο. Το `showPages` απλώνει τις σελίδες όπως κάθονται σε ένα δεμένο βιβλίο, τη σελίδα 1 μόνη δεξιά, και ζωγραφίζει την καθεμία με το `renderPageToCanvas`.

## Η πλήρης συνταγή

Ένα αρχείο, συντεθειμένο από τον φάκελο της συνταγής με το δείγμα κειμένου και το κοινό κιτ του Συνταγολογίου ενσωματωμένα· φτιάχνει τη δική του σελίδα. Για να το εκτελέσετε, βάλτε το σε ένα `<script type="module">` σε μια κενή σελίδα, ή επικολλήστε το στο πάνελ JS ενός νέου CodePen (ως module). Εισάγει το postext από το esm.sh, οπότε δεν χρειάζεται εγκατάσταση ούτε build.

- Φάκελος πηγής: https://github.com/drnachio/postext/tree/main/cookbook/first-page-from-markdown

### script.js

```js
// ═══ Postext Cookbook · Nº 012 · From a Markdown string to a designed page ══════════
// https://postext.dev/en/cookbook/first-page-from-markdown
// Code: MIT · Text: original (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Young Serif, Inter Tight (SIL OFL 1.1) · Needs postext ≥ 1.88.1
//
// This pen sets a Markdown string with a frontmatter block on two magazine pages and paints
// them on canvases. The whole design is in config(); swap config() for {} in the build
// below to see the engine's defaults.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'first-page-from-markdown';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every setting that shapes the pages is in this part, from PAGE down to config().
const PAGE = { width: 180, height: 240 }; // mm: a 3:4 magazine page
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 14 }; // mm; inner is the spine side
const LEAD = 13.5; // pt: the body leading, the grid every vertical space steps on

// #region palette: six named colours; every colour in the config links to one of them
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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' } })),
  // The engine's defaults (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
// #endregion

// #region art: a photograph of the salt pans and the dunes at Sorra, cut for a page × band frame
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
    height: 1120 },
  altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
    + 'footprints crossing the pans towards it.' };
// #endregion

// #region opener: the H1 as a bleed band; kicker, title, standfirst and byline sit on it
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
  fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
  letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
  offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
  enabled: true,
  minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
  slot: {
    elements: [
      // The photograph is PAGE.width × BAND (see art): at full width it fills the band.
      { kind: 'image', id: 'art', resourceId: 'landscape',
        placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
      { kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
        placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
          offset: { x: mm(MARGIN.inner), y: mm(20) } } },
      // {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
      // lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
      { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
        fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
        placement: below('kicker', 3, TITLE_W) },
      { kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
        fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
        placement: below('title', 5, DECK_W) },
      { kind: 'text', id: 'byline', ...label, color: col('sand'),
        content: t({ en: 'By {author} · {publishDate}',
          es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
          fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
        placement: below('deck', 4.5) },
    ],
  },
});
// #endregion

// #region running-heads: folio and title on body pages, a drop folio under the opener
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
  kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
  elements: [ // folios on the outer margin's edge; each label hangs off its folio
    head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
    head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
    head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
    head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
  ],
});
const footer = () => ({
  elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
    ...label, color: col('band'),
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});
// #endregion

// The colophon: small sans under a 0.5 pt hairline, with no box around it.
const colophon = () => ({ id: 'colophon', backgroundEnabled: false, marginTop: pt(LEAD),
  stripe: { enabled: true, side: 'top', width: pt(0.5), color: col('rule') },
  padding: { top: mm(1.6), right: pt(0), bottom: pt(0), left: pt(0) },
  body: { fontFamily: 'Inter Tight', fontSize: pt(7), lineHeight: pt(9.5), color: col('muted'),
    textAlign: 'left', hyphenation: false, firstLineIndent: pt(0) } });

// #region answer: one config factory in place of the default skin: page, type, colour, slots
const config = () => ({
  locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
  colorPalette: colorPalette(),
  page: { // mirror: left is the inner margin and right the outer one; versos swap them
    width: mm(PAGE.width), height: mm(PAGE.height),
    margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
      right: mm(MARGIN.outer), mirror: true },
  },
  // 'double' is the default, stated so that the whole page setup reads in one place
  layout: { layoutType: 'double', gutterWidth: mm(6) },
  bodyText: { // justified, hyphenated and broken by paragraph: all on by default
    fontFamily: 'Newsreader', // one family name: there is no fallback chain
    fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: mm(4), indentAfterHeading: false,
    // Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
    // tightened by at most 4 thousandths of an em, so the grey of the text stays even.
    minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
  },
  headings: {
    fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
    levels: [
      // span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
      // next article pasted in on a recto, with a blank verso only when one is needed.
      { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
        advancedDesign: opener() },
      // A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
      // default) rounds up to 3, so the text below lands back on the grid.
      { level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
        marginBottom: pt(0) },
    ],
  },
  unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
    marginTop: pt(0), marginBottom: pt(0) },
  calloutStyles: [colophon()],
  header: header(),
  footer: footer(),
  // The magazine's name is its masthead, the same on every story (#849).
  checks: { contentInConfig: { allow: [MAGAZINE] } },
});
// #endregion

// ─── 2 · Content ────────────────────────────────────────────────────────────
// content.<lang>.md, inlined by the Cookbook. Its frontmatter feeds the opener and the
// running heads. The end mark is an inline swatch that names `band`, so it follows the
// palette too.
const markdown = String.raw`---
title: "The Salt Road"
subtitle: "Four days on foot along the carriers’ trail, from the salt pans of Arvela to the market at Castrel."
author: "Lena Varga"
publishDate: "May 2026"
---

# The Salt \\ Road

**The carriers set out from the dyke at Arvela.** At low water the flats below it run out for three kilometres, a grey plain scored by tidal channels, and from the dyke you see the salt pans before the sea: forty shallow squares of brine laid out like a chessboard, each one a shade whiter than the one before it.

For six centuries the salt of Arvela left the coast on people’s backs. They loaded up at dawn, thirty kilos to a wicker basket, and walked inland on a trail that nobody ever paved: across the flats, over the dunes of Sorra, through the pine country and up to the old market town of Castrel, four days on foot. The railway ended the trade in 1911, but walkers have kept the trail open since.

I walked it this April with Tomás Reis, whose grandmother carried salt when she was a girl, and who has spent twenty summers marking the route with cairns of white stones. “Watch the ground for *salt*,” he told me that first morning. “Where it was spilled, nothing grows.”

On the second day, in the dunes, the path disappears for hours, and then a pale seam shows in the sand, a few centimetres wide, as if someone had drawn it in chalk. It is salt that fell from the baskets over six centuries, a crust that the wind uncovers every spring. Tomás walks beside it and never steps on it.

We slept that night in a hollow of the dunes that the carriers called the Kitchen, because the wind never gets into it. Tomás lit no fire. He ate bread and dried fish and talked about his grandmother, who could taste a single grain and tell you whether it came from Arvela or from the pans of the south, and who never once, he says, lost the trail in fog.

## What came back

The baskets went back to the coast full. A carrier’s ledger from 1887, kept in the parish archive at Sorra, lists the return loads of its first spring:

- **Grain**, mostly rye and barley, from the upland farms above Castrel.
- **Pine resin** and tar, to caulk the fishing boats at Arvela each winter.
- **Wool and hides** from the May fair at Castrel.
- **Nails and fish-hooks** from the smithy at Orsa.

Until the railway came, a basket of salt bought a basket of grain. A good carrier made eleven round trips a year, eighty-eight days on the trail, and in between raked salt in the pans.

The ledger is written in three hands. The first is a careful copperplate that records every load to the half kilo; the second, from 1893 on, writes nothing but numbers; the third, a child’s hand, turns up in the winters and spells the town Castrell.

The last entry in the ledger, halfway down a page in the autumn of 1910, is a load of barley that was never marked as delivered, and nobody in Sorra knows why. Tomás thinks the carrier went to lay track for the railway, which paid in coin.

## Into the pines

The third day is the longest. Beyond Orsa the trail climbs for eight hours through pine woods that smell of resin, past the ruined relay houses where the carriers slept on straw and paid for their beds in salt. Every house has a cairn by its door, topped with a white stone that Tomás put there.

The best-kept house stands at the Nine Wells, an hour below the pass. Its lintel is cut with rows of short notches, one for each night a carrier slept under it, and in places they are so close that they have worn into one groove. Tomás tried to count them one winter and gave up at four thousand.

On the fourth afternoon the trail comes out of the pines onto a bare ridge, and Castrel appears below: a grey town built around a square that is still called the Salt Market, although nobody has sold salt there for a hundred years. Like the carriers, Tomás leaves a handful of salt on the stone rim of the fountain before he drinks.

Then he turns round and starts back towards the sea. The carriers never slept in Castrel, he says, because the inns there charged in coin and a carrier was paid in grain. :swatch{color="band"}

:::callout{type="colophon"}
A work of fiction: Arvela, Sorra, Orsa and Castrel are imaginary places. Set in Newsreader, Young Serif and Inter Tight (SIL Open Font License) · Text: original, CC BY 4.0 · Photo: diffusion models.
:::
`;
// The opener's image element points at the photograph by id.
const resources = [landscape];

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// #region fonts: every face the design uses, loaded before the first build
const FONTS = {
  Newsreader: ['400', '400i', '700'], // text
  'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
  'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};
// #endregion

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region build: the photograph, one buildDocumentWithFonts call with a fresh config, then paint
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
  title: t({ en: 'From a Markdown string to a designed page',
    es: 'De una cadena Markdown a una página diseñada',
    pt: 'De uma string Markdown a uma página diagramada',
    fr: 'D’une chaîne Markdown à une page mise en forme',
    de: 'Von einem Markdown-String zur gestalteten Seite',
    it: 'Da una stringa Markdown a una pagina progettata' }),
});
// #endregion

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Παραλλαγές

### Δείτε τι αντικαθιστά η διαμόρφωση

Κατασκευάστε με κενή διαμόρφωση και το ίδιο Markdown βγαίνει σε σελίδα 17 × 24 cm σε EB Garamond των 8 pt, με μπλε επικεφαλίδες σε Open Sans και μια μπλε τρέχουσα κεφαλίδα πάνω από μια γραμμή· η μηχανή φορτώνει κι αυτές τις δύο οικογένειες, αφού τις ονομάζει η προεπιλεγμένη διαμόρφωση.

```diff
-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));
```

### Χρωματίστε ξανά ολόκληρη τη σελίδα

Αλλάξτε το χρώμα έμφασης και η επόμενη εκτέλεση ζωγραφίζει τους αριθμούς σελίδας, τους υπότιτλους και το σήμα τέλους στο νέο χρώμα, επειδή το `col()` αντιγράφει το νέο hex δίπλα στο αναγνωριστικό κάθε φορά που τρέχει το `config()`. Η φωτογραφία κρατά τα δικά της χρώματα.

```diff
-  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
+  band: '#3f5b3a', // the one accent (a pine green): the folios, the subheads, the end mark
```

### Ζωγραφίστε μία σελίδα στον δικό σας καμβά

Το `renderPageToCanvas` δίνει στον καμβά το μέγεθος της σελίδας σε εικονοστοιχεία στα dpi του εγγράφου (300 από προεπιλογή) επί το `scale`, έτσι το `scale: 0.5` ζωγραφίζει περίπου στα 150 dpi, και το CSS αποφασίζει πόσο μεγάλος φαίνεται στην οθόνη.

```diff
-showPages(doc, {
-  title: t({ en: 'From a Markdown string to a designed page',
-    es: 'De una cadena Markdown a una página diseñada',
-    pt: 'De uma string Markdown a uma página diagramada',
-    fr: 'D’une chaîne Markdown à une page mise en forme',
-    de: 'Von einem Markdown-String zur gestalteten Seite',
-    it: 'Da una stringa Markdown a una pagina progettata' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });
```

## Συνήθη λάθη

- Η Young Serif διατίθεται σε ένα μόνο βάρος. Οι επικεφαλίδες είναι από προεπιλογή έντονες, οπότε εδώ χρειάζεται το `headings.fontWeight: 400`: χωρίς αυτό οι υπότιτλοι ζητούν μια έντονη Young Serif που το Fontsource δεν έχει, ο περιηγητής παχαίνει την κανονική, και το `doc.contentWarnings` καταγράφει τη γραμματοσειρά ως `fontFallback`.

## Ευχαριστίες

- Συνταγή: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Εικόνες: The salt pans and the dune at dusk on the opener, a photograph: Generated With Diffusion Models, πρωτότυπο
- Γραμματοσειρές: Newsreader (OFL-1.1), Young Serif (OFL-1.1), Inter Tight (OFL-1.1)
- Κώδικας: MIT · Δείγμα περιεχομένου: CC-BY-4.0

## Σχετικές συνταγές

- [Αρ. 004 · Θέμα περιοδικού: από τη φωτογραφία ως το σήμα τέλους](https://postext.dev/el/cookbook/magazine-feature-opener.md): Ένα άνοιγμα advancedDesign στήνει από την επικεφαλίδα φωτογραφία σε αιμορραγία, υπέρτιτλο, τίτλο, πρόλογο, υπογραφή· μετά δύο κινητά πλαίσια, σήμα τέλους. · Επίπεδο 3 (Προχωρημένο) · Περιοδικά και fanzines
- [Αρ. 005 · Τρέχουσες κεφαλίδες κατά μονή και ζυγή σε βιβλίο δοκιμίων](https://postext.dev/el/cookbook/running-heads-by-parity.md): Κεφαλίδες κατά μονή ή ζυγή και ρόλο σελίδας: τίτλος βιβλίου αριστερά, τίτλος δοκιμίου κομμένος δεξιά, γλωττίδες αριθμού στο περιθώριο, χαμηλός αριθμός αρχής. · Επίπεδο 2 (Μεσαίο) · Πεζογραφία, θέατρο και λογοτεχνικός λόγος
- [Αρ. 003 · Εναρκτήρια σελίδα κεφαλαίου σε ταινία ως την αιμορραγία](https://postext.dev/el/cookbook/chapter-opener-bleed-band.md): Εναρκτήρια σελίδα advancedDesign στην επικεφαλίδα επιπέδου 1: ταινία ως την αιμορραγία, ο αριθμός στη βάση της, υπέρτιτλος και εισαγωγή από την επικεφαλίδα. · Επίπεδο 3 (Προχωρημένο) · Σχολικά βιβλία
