stationery 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dc2011ee51b715eb946943e60d0512157f2215acd871133433c6edf4f81bb9a9
4
- data.tar.gz: a5a9c654b4c415ab77ba005eb228ba67fae05f87af1adeb39871ccb3353a00a3
3
+ metadata.gz: bfd8cada05438bcc43cc85da2535da95b55c2dbf6020bf95607bd8ebb65c8346
4
+ data.tar.gz: 1115be789042eebfdd48a036fc433994694236c4c133ede893a554478b6174bf
5
5
  SHA512:
6
- metadata.gz: 239ad178900f1cce55589e1e6882fda2e713631df0a0d732945eefd0d8df762e9baa0a44efde7ea13fa643e6ee0dd038594886cd09cc14aac2cb0486ef88f05b
7
- data.tar.gz: 0ac757cdf6a15a654c83b26fa80c5be99e20e9e28e09653c31c299627a5c46c5cfb3965cfa58e58c2c6ade241c3b86f07fbe37a761ad2738e09207ce0711c200
6
+ metadata.gz: 2e55c39993d7c6c7c66373f5097a8796ac655b46eabe34eb148808cca220823112a728d4c26b971c54f163dc2b6c45f50f3b6481c050089871daf5964a4011d6
7
+ data.tar.gz: 456ca535dc230cbc747dac22322d7a0886ea8da7f70b159bb59224a2afe211dd1cb1a6e79a2a1a7c1f7b0d2007701b465fb49434484953db010a869ae6e4ad97
data/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 (2026-09-28)
4
+
5
+ Instrumentation, so a render shows up in AppSignal and friends, and a faster text pipeline.
6
+
7
+ - Instrumentation: `Stationery.instrument` emits `render.stationery` (the whole `to_pdf`: `document:`, `pages:`, `bytes:`, `warnings:`), `build.stationery`, `paginate.stationery`, `write.stationery` (serialise, subset, deflate), `image.stationery` (each decode on a cache miss: `format:`, `width:`, `height:`, `bytes:`), `font.stationery` (`action: :parse` on a cache miss, `action: :subset` per embedded font with `glyphs:`) and `parse.stationery` (`format: :html | :markdown`). `Stationery.instrumenter` is `ActiveSupport::Notifications` when it is loaded (the Railtie pins it), so AppSignal, Skylight and log subscribers pick the events up with no setup; otherwise a no-op. Assign any object responding to `instrument(name, payload, &block)` to plug something else in. Output is unchanged.
8
+ - `FontBook#resolve` memoises by family, weight and style instead of hashing the whole 13-field `Text::Style` on every measurement: the lookup is 4x faster and a photo-heavy 4-page document renders 22% faster.
9
+
10
+ ## 0.5.0 (2026-09-27)
11
+
12
+ Rotated, overlapping, cropped photos (the collage look), and fixes from the first weeks of use.
13
+
14
+ - `stack { … }` and `layer(top:, right:, bottom:, left:, width:, height:, **box) { … }`: overlapping content. The stack's ordinary children set its height; each layer is a box placed with CSS-inset semantics relative to the stack (points, or fractions of the stack's width/height; negative insets overhang) and takes no flow height. A stack moves to the next page whole. `examples/postcard.rb` shows the collage: a cover photo with two tilted, framed, shadowed photos over its corners.
15
+ - `box(rotate:)` turns a box clockwise around its centre without moving its layout rectangle (a rotated box never splits); `box(shadow: true | { offset:, blur:, color:, opacity: })` paints a soft drop shadow as stacked rounded rectangles at fading opacity, an artifact taking no space; `box(overflow: :hidden)` clips the content to the rounded outline. `column` takes the same options.
16
+ - `image(fit: :cover, width:, height:)` scales up to fill the box and clips the excess around the centre; `image(radius:)` clips to rounded corners; `image(rotate:)` turns the painted image around its centre. Sizing, measuring and the tagged `Figure` bbox are unchanged; plain images are byte-for-byte as before.
17
+ - `Canvas#rotate(degrees, around: [x, y]) { … }` and `Canvas#transform([a, b, c, d, e, f]) { … }` wrap a block in a `cm` transform given in top-left space, clockwise like CSS `rotate()`. Link and form-widget rectangles are annotations in page space, so they stay unrotated.
18
+ - `html`/`markdown` write link annotations only for `http`, `https`, `mailto` and `tel` hrefs (and `#anchor`); anything else (`javascript:`, `data:`, a relative path) keeps its text without a link and is reported as a `Warnings::DroppedLink`. `links: %w[http https]` changes the list, `links: :all` keeps every href from a trusted source.
19
+ - `html`/`markdown` `styles:` take `ul:` and `ol:` (`gap:`, `indent:`, `marker_gap:`, `marker_color:`, plus `style:` for `ul` and `format:`/`suffix:` for `ol`), passed straight to the list elements, so dense documents can tighten the 4pt item gap.
20
+ - Whitespace no font has (an ideographic space U+3000, a figure space U+2007, a narrow no-break space U+202F, thin and hair spaces, …) is drawn as a blank of the character's conventional width instead of `.notdef`, and no longer reports `MissingGlyph`; font fallback keeps every Unicode White_Space character with its neighbours.
21
+ - Testing: the RSpec matchers include `RSpec::Matchers::Composable`, so `have_pdf_text(…).and have_bookmark(…)`, `.or` and use inside `all`/`include` work. `Inspector#lang` reads the catalog `/Lang`; `have_pdf_language("de")` and `assert_pdf_language` assert it.
22
+ - Previews: `Stationery::Preview#around_render(name, params)` wraps both the preview method and `to_pdf`, for an I18n locale or `CurrentAttributes` that must be in effect while the document renders (`?locale=de`); `Preview#to_pdf(name, params, debug:)` is the entry point the previews controller uses.
23
+
3
24
  ## 0.4.0 (2026-09-27)
4
25
 
5
26
  Interactive forms and tagged (accessible) PDF.
data/README.md CHANGED
@@ -70,7 +70,7 @@ InvoicePdf.new(invoice).to_pdf # => "%PDF-1.7…" (binary String)
70
70
  InvoicePdf.new(invoice).to_pdf("a.pdf") # also writes a path or an IO
71
71
  ```
72
72
 
73
- `examples/` has a complete, runnable invoice, annual report, letter, packing slip and fillable form; `bundle exec rake examples`
73
+ `examples/` has a complete, runnable invoice, annual report, letter, packing slip, fillable form and postcard collage; `bundle exec rake examples`
74
74
  renders them all, or render one with `stationery render examples/report.rb`.
75
75
 
76
76
  ## Elements
@@ -80,12 +80,14 @@ renders them all, or render one with `stationery render examples/report.rb`.
80
80
  | `text(string, **style)` | A paragraph. Plain strings are literal. |
81
81
  | `text(string, markup: true)` | Reads `<b> <i> <u> <strikethrough> <sub> <sup> <br> <color rgb=""> <font size="" name=""> <link href="">`; decodes numeric and HTML 4 named entities. |
82
82
  | `text { b "Total"; plain " due" }` | Styled runs in Ruby. Take a block argument (`{ \|t\| t.b @x }`) to keep your own `self`. |
83
- | `box(padding:, background:, border:, radius:, width:, height:, min_height:, overflow:, at:, link:, outset:, break_inside:, decoration:) { }` | A container. Moves to the next page whole when it fits there and continues across pages when it does not; `break_inside: :auto` splits it at any page break, `:avoid` never splits it. At a cut, `decoration: :slice` (default) drops the padding and border, `:clone` keeps the padding. `overflow: :truncate` or `:shrink_to_fit` for fixed heights; a fixed `height:` never splits. `min_height:` is a floor that still splits: the first fragment keeps as much of it as the page holds, the next carries the rest (not combinable with `height:`). `at: [x, y]` pins it to a page position. `link:` makes the whole box clickable. `outset:` bleeds the background past the box (e.g. into the page margins). |
83
+ | `box(padding:, background:, border:, radius:, width:, height:, min_height:, overflow:, at:, link:, outset:, break_inside:, decoration:, rotate:, shadow:) { }` | A container. Moves to the next page whole when it fits there and continues across pages when it does not; `break_inside: :auto` splits it at any page break, `:avoid` never splits it. At a cut, `decoration: :slice` (default) drops the padding and border, `:clone` keeps the padding. `overflow: :truncate` or `:shrink_to_fit` for fixed heights; a fixed `height:` never splits. `min_height:` is a floor that still splits: the first fragment keeps as much of it as the page holds, the next carries the rest (not combinable with `height:`). `at: [x, y]` pins it to a page position. `link:` makes the whole box clickable. `outset:` bleeds the background past the box (e.g. into the page margins). `rotate: -3` turns the painted box around its centre (layout box unchanged, never splits; a `link:` keeps its unrotated rectangle). `shadow: true` or `{ offset: [0, 4], blur: 8, color:, opacity: 0.15 }` paints a soft drop shadow under it, taking no space. `overflow: :hidden` clips the content to the rounded outline. |
84
84
  | `row(gap:, align:, break_inside:) { column(width:) { } }` | Columns side by side. `width:` is points, a fraction (`0.5`), `:auto` or `nil` (equal share). Splits across pages like a box, every column at once; a row with a fixed-height column never splits; columns with `min_height:` do. |
85
85
  | `table(rows, widths:, width:, header:, split_rows:, cell:) { \|t\| }` | Tables. Cells are strings, layout nodes, procs built with the DSL (`-> { image logo }`) or components. Style with `t.row(0)`, `t.rows(-1)`, `t.column(1)`, `t.columns(1..)`, chained, plus `t.zebra`. Header rows repeat after a page break. A cell may be `{ content:, colspan:, rowspan: }` plus any cell option; rows list only the cells they start, as in HTML, and pages never break through a rowspan. Spans are set in the rows, not through selections. A row taller than the page continues on the next page, cut through its cells, with the header repeated; `split_rows: true` cuts any row that reaches the page bottom instead of moving it whole. |
86
- | `image(path_or_io, width:, height:, fit:, align:)` | JPEG or PNG, aspect preserved. |
86
+ | `image(path_or_io, width:, height:, fit:, align:, radius:, rotate:)` | JPEG or PNG, aspect preserved. `fit: [w, h]` scales to fit inside; `fit: :cover` fills `width:` × `height:` and crops around the centre. `radius:` rounds the corners; `rotate:` turns it (degrees, clockwise) without changing the space it takes. |
87
87
  | `svg(source_or_path, width:, height:, color:, align:)` | Vector icons and drawings; `currentColor` takes `color:`. Linear and radial gradients (`fill="url(#id)"`, `href` chains, both gradient units); `text`/`tspan` in the document's fonts; `<style>` stylesheets (element, class, id and `*` selectors). |
88
88
  | `wrap(gap:, row_gap:, align:) { }` | Children side by side at their own widths, wrapping onto new rows (chips, tags). |
89
+ | `stack(gap:, align:) { }` | A base with layers painted over it: ordinary children set the height, `layer` children float over them and take no space. Moves to the next page whole. |
90
+ | `layer(top:, right:, bottom:, left:, width:, height:, **box) { }` | Inside `stack`: a box placed by insets from the stack's edges, in points or as a fraction (`0.4`, `1/3r`) of its width/height; negative insets overhang. Takes every box option (`rotate:`, `shadow:`, `radius:`, …). |
89
91
  | `ul(style:, gap:, indent:, marker_gap:, marker_color:) { li "…" }` | Bulleted list. `style:` is `:disc`, `:circle`, `:square`, `:dash` or any String; unstyled nested lists cycle disc → circle → square. Any node added inside (not only `li`) becomes an item. Items split across pages; the marker stays with the first line. |
90
92
  | `ol(format:, start:, suffix:, gap:, indent:, marker_gap:, marker_color:) { }` | Numbered list. `format:` is `:decimal`, `:alpha`, `:upper_alpha`, `:roman`, `:upper_roman` or a Proc `(n) -> String`; `suffix:` defaults to `"."`. Markers right-align so bodies line up. |
91
93
  | `li(string, **style)`, `li(gap:) { }` | A list item: a paragraph, or a block of any elements (including nested lists). |
@@ -93,14 +95,14 @@ renders them all, or render one with `stationery render examples/report.rb`.
93
95
  | `group(keep_together: true, align:) { }` | Keep a block on one page. |
94
96
  | `keep_with_next: true \| points` | On `text`, `box` or `group`: never end a page with this node; with a number, keep at least that many points of what follows with it. |
95
97
  | `text_style(**style) { }` | Default text style for a block. |
96
- | `canvas(height:) { \|canvas, rect\| }` | Draw directly: rectangles, rounded rectangles, circles, lines, Bézier paths, clipping, images, links. |
98
+ | `canvas(height:) { \|canvas, rect\| }` | Draw directly: rectangles, rounded rectangles, circles, lines, Bézier paths, clipping, images, links; `rotate(degrees, around:) { }` and `transform([a, b, c, d, e, f]) { }` blocks. |
97
99
  | `text_field(name, value:, width:, height:, multiline:, max_length:, comb:, read_only:, required:, font_size:, border:, background:, radius:, at:)` | An interactive text input (AcroForm). `width:` is `:full` or points; dotted names (`"address.city"`) group fields. See [Forms](#forms). |
98
100
  | `checkbox(name, checked:, size:, label:, at:)` | An interactive check box, with an optional label drawn to its right. |
99
101
  | `radio(name, value, checked:, size:, label:, at:)` | One choice of a radio group: radios sharing `name` form one field whose value is the checked `value`. |
100
102
  | `select(name, options:, value:, width:, height:, editable:, at:)` | A drop-down (combo box); `editable: true` also accepts typed values. |
101
103
  | `signature_field(name, width:, height:, label:, at:)` | An empty signature field for the signer to fill, drawn as a rule over the label. |
102
- | `html(source, styles:, gap:, images:, base_path:, bookmarks:)` | Rich text from HTML (ActionText/Trix, CMS output): paragraphs, headings, lists, quotes, code, rules, tables, images, inline marks and links. See [HTML and Markdown](#html-and-markdown). |
103
- | `markdown(source, styles:, gap:, images:, base_path:, bookmarks:)` | The same from CommonMark (plus GFM tables and strikethrough). |
104
+ | `html(source, styles:, gap:, images:, base_path:, bookmarks:, links:)` | Rich text from HTML (ActionText/Trix, CMS output): paragraphs, headings, lists, quotes, code, rules, tables, images, inline marks and links. See [HTML and Markdown](#html-and-markdown). |
105
+ | `markdown(source, styles:, gap:, images:, base_path:, bookmarks:, links:)` | The same from CommonMark (plus GFM tables and strikethrough). |
104
106
 
105
107
  Text style options: `font`, `size`, `weight` (`:regular`, `:bold`), `style` (`:italic`), `color`,
106
108
  `letter_spacing`, `underline`, `strikethrough`, `link`, `opacity`, `kerning` (default `true`), `ligatures` (default `true`), `align` (`:left`, `:center`, `:right`, `:justify`), `leading`.
@@ -128,7 +130,12 @@ end
128
130
  points; bold, `keep_with_next`), `p`, `a` (colour, underline), `code` (`font:`; register a
129
131
  monospace family for inline and block code, otherwise the text font is used), `pre` and
130
132
  `blockquote` (box options), `hr` (rule options), `table` (`cell:` options, `header:` text style),
131
- `li` (text style) and `img` (`max_width:`).
133
+ `ul` and `ol` (list options: `gap:`, `indent:`, `marker_gap:`, `marker_color:`, plus `style:` for
134
+ `ul` and `format:`/`suffix:` for `ol`), `li` (text style) and `img` (`max_width:`).
135
+ - Links are written only for `http`, `https`, `mailto` and `tel` hrefs (and `#anchor`); anything
136
+ else (`javascript:`, `data:`, a relative path) keeps its text without a link and is reported as a
137
+ `DroppedLink` warning. `links: %w[http https]` changes the list, `links: :all` keeps every href
138
+ from a trusted source.
132
139
  - `gap:` spaces the blocks (default 6); `bookmarks: true` adds h1–h3 to the PDF outline.
133
140
 
134
141
  ### Links, bookmarks and table of contents
@@ -393,6 +400,21 @@ that take an argument (`?id=42`); `?debug=1` passes `debug: true` to `to_pdf`
393
400
  when the document supports it. Preview files are re-`load`ed on every request,
394
401
  so edits show up on refresh.
395
402
 
403
+ Anything that must be in effect *while* the document renders (an I18n locale,
404
+ `CurrentAttributes`, a time zone) goes in `around_render`, which wraps both the
405
+ preview method and `to_pdf`:
406
+
407
+ ```ruby
408
+ class FlyerPdfPreview < Stationery::Preview
409
+ def month(params) = FlyerPdf.new(Event.upcoming)
410
+
411
+ def around_render(_name, params) = I18n.with_locale(params.fetch("locale", I18n.default_locale)) { yield }
412
+ end
413
+ ```
414
+
415
+ `/rails/stationery/previews/flyer_pdf/month?locale=de` renders in German.
416
+ `Preview#to_pdf(name, params, debug:)` is the same entry point for your own code.
417
+
396
418
  The gem has no Rails dependency; the Railtie loads only inside a Rails app.
397
419
 
398
420
  ## CLI
@@ -481,9 +503,12 @@ end
481
503
  ```
482
504
 
483
505
  Spaces, joiners, variation selectors and combining marks stay with the
484
- character before them. A glyph no font has is drawn as the family's
485
- `.notdef` and reported as a `Warnings::MissingGlyph` counting each drawn
486
- occurrence (so `strict` raises on it). Fallback covers every text element,
506
+ character before them. Whitespace no font has (an ideographic space U+3000,
507
+ a figure space, a narrow no-break space, …) is drawn as a blank of the
508
+ character's conventional width, never as `.notdef`. Any other glyph no font
509
+ has is drawn as the family's `.notdef` and reported as a
510
+ `Warnings::MissingGlyph` counting each drawn occurrence (so `strict` raises
511
+ on it). Fallback covers every text element,
487
512
  table cell, list marker, table of contents entry and page template text;
488
513
  direct `canvas.text` calls draw with the font they are given.
489
514
 
@@ -534,6 +559,7 @@ RSpec.describe InvoicePdf do
534
559
  it { is_expected.to have_pdf_link("mailto:hello@acme.test") }
535
560
  it { is_expected.to have_image_count(1) }
536
561
  it { is_expected.to have_no_warnings }
562
+ it { is_expected.to have_pdf_language("en") } # the catalog /Lang from `metadata lang:`
537
563
  it { is_expected.to have_tagged_content } # a tagged PDF with every text tagged or an artifact
538
564
  it { is_expected.to have_structure([[:Document, [[:H1, "Invoice"], [:P, "INV-7"]]]]) }
539
565
  end
@@ -554,6 +580,7 @@ class InvoicePdfTest < Minitest::Test
554
580
  assert_page_count pdf, 2
555
581
  assert_pdf_link pdf, /acme\.test/
556
582
  assert_no_pdf_warnings pdf
583
+ assert_pdf_language pdf, "en"
557
584
  assert_tagged_content pdf
558
585
  assert_pdf_structure pdf, [[:Document, [[:H1, "Invoice"], [:P, "INV-7"]]]]
559
586
  end
@@ -562,9 +589,10 @@ end
562
589
 
563
590
  The matcher names carry a `pdf_` prefix so they never clash with Capybara's
564
591
  `have_text` and `have_link`. `have_bookmark` / `assert_bookmark` match outline
565
- titles. For anything else, `Stationery::Testing::Inspector.new(subject)`
592
+ titles. The RSpec matchers compose like the built-ins: `.and` / `.or`, and inside
593
+ `all`, `include` or `match`. For anything else, `Stationery::Testing::Inspector.new(subject)`
566
594
  exposes `text`, `page_texts`, `page_count`, `links`, `internal_links`,
567
- `image_count`, `bookmarks`, `metadata`, `warnings`, `tagged?`, `untagged_text` and
595
+ `image_count`, `bookmarks`, `metadata`, `lang`, `warnings`, `tagged?`, `untagged_text` and
568
596
  `structure` — a tagged PDF's structure tree as nested arrays, each element's text
569
597
  read from its marked content: `[type, "text"]`, `[type, [children]]` (its own text
570
598
  between the children, as for a `P` holding a `Link`) or `[type]` when empty; a
@@ -578,6 +606,41 @@ between the children, as for a `P` holding a `Link`) or `[type]` when empty; a
578
606
  a browser per worker; stray processes and memory are the price.
579
607
  - **Typst** is excellent but a native extension and a second template language.
580
608
 
609
+ ## Instrumentation
610
+
611
+ Every render reports its phases as events named `<phase>.stationery`, so an
612
+ APM that subscribes to `ActiveSupport::Notifications` (AppSignal, Skylight,
613
+ Rails' own log subscribers) shows where a slow PDF spends its time with no
614
+ setup: AppSignal groups them under "stationery" in the event tree. Outside
615
+ Rails the events go to a null instrumenter that costs one method call.
616
+
617
+ | Event | Around | Payload |
618
+ |---|---|---|
619
+ | `render.stationery` | the whole `to_pdf` | `document:`, `pages:`, `bytes:`, `warnings:` (count) |
620
+ | `build.stationery` | building the component tree | `document:` |
621
+ | `paginate.stationery` | layout, page breaks and page templates | `document:`, `pages:` |
622
+ | `write.stationery` | serialising, subsetting and deflating | `document:`, `bytes:` |
623
+ | `image.stationery` | decoding one image (cache misses only) | `format:`, `width:`, `height:`, `bytes:` |
624
+ | `font.stationery` | parsing a font file (`action: :parse`, cache misses only) or subsetting one for a document (`action: :subset`, `glyphs:`) | `path:` or `font:`, `action:` |
625
+ | `parse.stationery` | parsing an `html` or `markdown` source | `format:`, `bytes:` |
626
+
627
+ Payload values known only afterwards (`pages:`, `bytes:`) are filled in
628
+ before the event finishes, so subscribers always see them. Log every phase
629
+ slower than 100 ms:
630
+
631
+ ```ruby
632
+ ActiveSupport::Notifications.subscribe(/\.stationery\z/) do |name, start, finish, _id, payload|
633
+ ms = (finish - start) * 1000
634
+ Rails.logger.info("#{name} #{ms.round}ms #{payload.inspect}") if ms > 100
635
+ end
636
+ ```
637
+
638
+ Any object answering `instrument(name, payload) { |payload| }` can take the
639
+ events instead (`Stationery.instrumenter = MyInstrumenter.new`), and
640
+ `Stationery.instrument("custom.stationery", key: value) { … }` adds your own
641
+ spans inside a document. When you hit a slow render, a trace with these
642
+ events attached is the most useful thing to put in an issue.
643
+
581
644
  ## Performance
582
645
 
583
646
  `bundle exec rake bench` renders two documents with Stationery and with Prawn
@@ -62,6 +62,17 @@ module Stationery
62
62
  @containers.pop
63
63
  end
64
64
 
65
+ # Whether nodes are being added straight into a stack's flow (where a
66
+ # layer may go).
67
+ def in_stack? = stacks.include?(@containers.last)
68
+
69
+ def stack(flow, &)
70
+ stacks << flow
71
+ within(flow, &)
72
+ ensure
73
+ stacks.delete(flow)
74
+ end
75
+
65
76
  def with_text(**overrides)
66
77
  @text << text_defaults.merge(overrides.compact)
67
78
  yield
@@ -70,6 +81,7 @@ module Stationery
70
81
  end
71
82
 
72
83
  def text_defaults = @text.last
84
+ def stacks = @stacks ||= []
73
85
  def outline = @outline ||= Outline.new
74
86
  def warnings = @book.warnings
75
87
 
@@ -9,7 +9,7 @@ module Stationery
9
9
  DEBUG_COLORS = {
10
10
  box: "#E11D48", padding: "#E11D48", column: "#2563EB", cell: "#16A34A", cell_padding: "#16A34A",
11
11
  flow: "#9CA3AF", positioned: "#DB2777", image: "#0D9488", page: "#06B6D4", region: "#0EA5E9",
12
- field: "#7C3AED"
12
+ field: "#7C3AED", stack: "#F59E0B"
13
13
  }.freeze
14
14
  DEBUG_DASHES = { padding: [2, 2], cell_padding: [2, 2], flow: [1, 2] }.freeze
15
15
 
@@ -31,6 +31,32 @@ module Stationery
31
31
  emit("Q")
32
32
  end
33
33
 
34
+ # Paints the block with the affine `matrix` [a, b, c, d, e, f] applied,
35
+ # given in top-left space (x' = ax + cy + e, y' = bx + dy + f with y
36
+ # growing downwards). Annotations (`link`, `widget`) keep their
37
+ # untransformed page rectangles.
38
+ def transform(matrix)
39
+ a, b, c, d, e, f = matrix
40
+ height = @page.height
41
+ pdf_matrix = [a, -b, -c, d, (c * height) + e, height - (d * height) - f]
42
+ save do
43
+ emit("#{pdf_matrix.map { |v| num(v) }.join(" ")} cm")
44
+ yield self
45
+ end
46
+ end
47
+
48
+ # Paints the block rotated `degrees` clockwise around the page point
49
+ # `around` ([x, y]), as CSS `rotate()` turns an element. Zero just yields.
50
+ def rotate(degrees, around:, &)
51
+ return yield self if degrees.zero?
52
+
53
+ radians = degrees * Math::PI / 180
54
+ cos = Math.cos(radians)
55
+ sin = Math.sin(radians)
56
+ cx, cy = around
57
+ transform([cos, sin, -sin, cos, cx - (cx * cos) + (cy * sin), cy - (cx * sin) - (cy * cos)], &)
58
+ end
59
+
34
60
  def clip(x, y, w, h, radius: 0)
35
61
  save do
36
62
  emit(Path.new(self).rounded_rect(x, y, w, h, radius).to_s, "W n")
@@ -95,21 +95,9 @@ module Stationery
95
95
 
96
96
  def to_pdf(target = nil, strict: self.class.config[:strict], debug: false, encrypt: self.class.config[:encrypt],
97
97
  tagged: self.class.config[:tagged])
98
- encryption = encrypt && PDF::Encryption::StandardSecurity.new(**encrypt)
99
- tagging = Tagging::Tree.new if tagged
100
- warnings = Warnings.new
101
- book = Fonts::FontBook.new(self.class.config[:families], fallbacks: self.class.config[:fallbacks], warnings:)
102
- call(builder = Builder.new(book:, text: self.class.config[:text]))
103
- resources = Resources.new
104
- pages = paginate(builder.root, book:, resources:, warnings:, debug:, tagging:)
105
- outline = builder.outline.resolve(Structure.resolve(pages, warnings:, resources:, book:, tagging:))
106
- tagging&.audit(pages, warnings, lang: metadata[:lang])
107
- @warnings = warnings
108
- @fields = Forms::AcroForm.values(pages)
109
- raise WarningsError, warnings if strict && warnings.any?
110
-
111
- assembler = PDF::Assembler.new(pages:, resources:, info:, outline:, encryption:, tagging:, lang: metadata[:lang])
112
- write(assembler.render, target)
98
+ Stationery.instrument("render.stationery", document: self.class.name) do |event|
99
+ write(render_pdf(event, strict:, debug:, encrypt:, tagged:), target)
100
+ end
113
101
  end
114
102
 
115
103
  # Used by page templates to build nodes into their own root.
@@ -130,11 +118,43 @@ module Stationery
130
118
 
131
119
  private
132
120
 
121
+ # The PDF bytes; `event` is the render.stationery payload it fills in.
122
+ def render_pdf(event, strict:, debug:, encrypt:, tagged:)
123
+ tagging = Tagging::Tree.new if tagged
124
+ warnings = Warnings.new
125
+ book = Fonts::FontBook.new(self.class.config[:families], fallbacks: self.class.config[:fallbacks], warnings:)
126
+ builder = Builder.new(book:, text: self.class.config[:text])
127
+ Stationery.instrument("build.stationery", document: self.class.name) { call(builder) }
128
+ resources = Resources.new
129
+ pages = paginate(builder.root, book:, resources:, warnings:, debug:, tagging:)
130
+ outline = builder.outline.resolve(Structure.resolve(pages, warnings:, resources:, book:, tagging:))
131
+ tagging&.audit(pages, warnings, lang: metadata[:lang])
132
+ @warnings = warnings
133
+ @fields = Forms::AcroForm.values(pages)
134
+ event[:pages] = pages.size
135
+ event[:warnings] = warnings.size
136
+ raise WarningsError, warnings if strict && warnings.any?
137
+
138
+ assemble(pages, resources, outline, encrypt:, tagging:).tap { |pdf| event[:bytes] = pdf.bytesize }
139
+ end
140
+
141
+ def assemble(pages, resources, outline, encrypt:, tagging:)
142
+ encryption = encrypt && PDF::Encryption::StandardSecurity.new(**encrypt)
143
+ assembler = PDF::Assembler.new(pages:, resources:, info:, outline:, encryption:, tagging:,
144
+ lang: metadata[:lang])
145
+ Stationery.instrument("write.stationery", document: self.class.name) do |event|
146
+ assembler.render.tap { |pdf| event[:bytes] = pdf.bytesize }
147
+ end
148
+ end
149
+
133
150
  def paginate(root, book:, resources:, warnings:, debug:, tagging:)
134
- regions = Regions.new(self.class.config[:regions], measure: region_measure(book))
135
- paginator = Layout::Paginator.new(resources:, page: page_options, warnings:, debug:, regions:, tagging:)
136
- paginator.paginate(root).tap do |pages|
137
- PageTemplates.new(self, book:, resources:, debug:, regions:, warnings:, tagging:).apply(pages)
151
+ Stationery.instrument("paginate.stationery", document: self.class.name) do |event|
152
+ regions = Regions.new(self.class.config[:regions], measure: region_measure(book))
153
+ paginator = Layout::Paginator.new(resources:, page: page_options, warnings:, debug:, regions:, tagging:)
154
+ paginator.paginate(root).tap do |pages|
155
+ PageTemplates.new(self, book:, resources:, debug:, regions:, warnings:, tagging:).apply(pages)
156
+ event[:pages] = pages.size
157
+ end
138
158
  end
139
159
  end
140
160
 
@@ -5,16 +5,18 @@ module Stationery
5
5
  module Elements
6
6
  # HTML such as ActionText's `record.body.to_s`. `images:` resolves an
7
7
  # image src to a path or IO (nil skips it); otherwise it is read from
8
- # under `base_path:`. Remote images are never fetched.
9
- def html(source, styles: {}, gap: 6, images: nil, base_path: nil, bookmarks: false)
8
+ # under `base_path:`. Remote images are never fetched. `links:` lists the
9
+ # URL schemes written as links (default http, https, mailto and tel;
10
+ # `#anchor` always is); `:all` keeps every href for trusted sources.
11
+ def html(source, styles: {}, gap: 6, images: nil, base_path: nil, bookmarks: false, links: nil)
10
12
  require_relative "../html/document"
11
- rich(HTML.parse(source.to_s), styles:, gap:, images:, base_path:, bookmarks:)
13
+ rich(HTML.parse(source.to_s), styles:, gap:, images:, base_path:, bookmarks:, links:)
12
14
  end
13
15
 
14
16
  # CommonMark (plus GFM tables and strikethrough); options as for html.
15
- def markdown(source, styles: {}, gap: 6, images: nil, base_path: nil, bookmarks: false)
17
+ def markdown(source, styles: {}, gap: 6, images: nil, base_path: nil, bookmarks: false, links: nil)
16
18
  require_relative "../markdown/document"
17
- rich(Markdown.parse(source.to_s), styles:, gap:, images:, base_path:, bookmarks:)
19
+ rich(Markdown.parse(source.to_s), styles:, gap:, images:, base_path:, bookmarks:, links:)
18
20
  end
19
21
 
20
22
  private
@@ -51,6 +51,29 @@ module Stationery
51
51
  @_builder.add(node)
52
52
  end
53
53
 
54
+ # A base with layers painted over it: every ordinary child is part of the
55
+ # base (which sets the height), every `layer` floats over it relative to
56
+ # the stack's rectangle, taking no space. The stack moves to the next
57
+ # page whole. Layers may overhang; wrap the stack in `box(padding:)` to
58
+ # keep them inside the page.
59
+ def stack(gap: 0, align: nil, &)
60
+ flow = Layout::Flow.new([], gap:, align: align || :left)
61
+ @_builder.stack(flow) { align ? @_builder.with_text(align:) { yield_content(&) } : yield_content(&) }
62
+ layers, base = flow.children.partition { |child| child.is_a?(Layout::Layer) }
63
+ @_builder.add(Layout::Stack.new(flow.with_children(base), layers))
64
+ end
65
+
66
+ # A box placed over the enclosing `stack` by insets from its edges:
67
+ # points, or a fraction (`0.4`, `1/3r`) of the stack's width or height;
68
+ # negative values overhang. Takes every box option (`rotate:`, `shadow:`,
69
+ # `padding:`, `background:`, `radius:`, `height:`, …).
70
+ def layer(top: nil, right: nil, bottom: nil, left: nil, width: nil, height: nil, align: nil, gap: 0, **, &)
71
+ raise ArgumentError, "layer must be inside a stack" unless @_builder.in_stack?
72
+
73
+ box = Layout::Box.new(container(align:, gap:, &), **)
74
+ @_builder.add(Layout::Layer.new(box, top:, right:, bottom:, left:, width:, height:))
75
+ end
76
+
54
77
  # Children kept in one vertical group; `keep_together: true` moves the
55
78
  # whole group to the next page rather than splitting it.
56
79
  def group(gap: 0, align: nil, keep_together: false, keep_with_next: nil, anchor: nil, bookmark: nil, &)
@@ -97,7 +120,8 @@ module Stationery
97
120
  @_builder.add(node)
98
121
  end
99
122
 
100
- # `alt:` describes the image in a tagged PDF (false: decorative).
123
+ # `alt:` describes the image in a tagged PDF (false: decorative). Sizing,
124
+ # `fit: :cover`, `radius:` and `rotate:` as for Layout::Image.
101
125
  def image(source, align: nil, **)
102
126
  node = Layout::Image.new(source, **)
103
127
  @_builder.add(align ? Layout::Flow.new([node], align:) : node)
@@ -6,11 +6,13 @@ module Stationery
6
6
  # run's family, then the book's fallbacks in order, then bundled Inter. A
7
7
  # glyph no font has stays in the run's family and draws as .notdef.
8
8
  #
9
- # Whitespace, joiners, variation selectors and combining marks carry the
10
- # family of the character before them (or after them at the start of a
11
- # run) so words are not chopped and marks stay with their base.
9
+ # Whitespace (any Unicode White_Space), joiners, variation selectors and
10
+ # combining marks carry the family of the character before them (or
11
+ # after them at the start of a run) so words are not chopped and marks
12
+ # stay with their base; whitespace a font lacks draws as a blank of the
13
+ # right width (see Font::WHITESPACE).
12
14
  class Fallback
13
- CARRIED = /[\s‌‍︀-️\p{M}]/
15
+ CARRIED = /[\p{Space}‌‍︀-️\p{M}]/
14
16
 
15
17
  def self.carried?(char) = CARRIED.match?(char)
16
18
 
@@ -12,6 +12,18 @@ module Stationery
12
12
  class Font
13
13
  OBLIQUE_SKEW = Math.tan(12 * Math::PI / 180)
14
14
 
15
+ # Whitespace the font lacks draws as its space glyph advanced to the
16
+ # character's conventional width: a fraction of the em for the fixed
17
+ # spaces, a digit's or a period's advance for the figure and
18
+ # punctuation spaces, the space's own width for the rest (no-break,
19
+ # line and paragraph separators, ogham mark, …). Nothing is painted,
20
+ # nothing is .notdef.
21
+ WHITESPACE = /\A\p{Space}\z/
22
+ SPACE_FRACTIONS = { 0x2000 => 0.5, 0x2001 => 1.0, 0x2002 => 0.5, 0x2003 => 1.0, 0x2004 => 1.0 / 3,
23
+ 0x2005 => 0.25, 0x2006 => 1.0 / 6, 0x2009 => 0.2, 0x200A => 0.125, 0x205F => 4.0 / 18,
24
+ 0x3000 => 1.0 }.freeze
25
+ SPACE_LIKE = { 0x2007 => "0", 0x2008 => "." }.freeze
26
+
15
27
  attr_reader :ttf
16
28
 
17
29
  def initialize(ttf)
@@ -19,6 +31,7 @@ module Stationery
19
31
  @used = {}
20
32
  @pairs = {}
21
33
  @glyphs = {}
34
+ @blanks = {}
22
35
  @shapes = { true => {}, false => {} }
23
36
  @advances = { true => {}, false => {} }
24
37
  @kerns = { true => {}, false => {} }
@@ -59,12 +72,20 @@ module Stationery
59
72
  # `ligatures:` substitutes the font's standard ligatures; `kerning:`
60
73
  # then fills the adjustments with pair kerning between the glyphs.
61
74
  def glyph_run(text, kerning: false, ligatures: true)
62
- gids, chars = shape(text, ligatures)
63
- gids.each_with_index { |gid, i| @used[gid] ||= chars[i] }
64
- adjust = gids.each_with_index.map { |gid, i| kerning && i + 1 < gids.size ? pair(gid, gids[i + 1]) : 0 }
75
+ gids, chars, blanks = shape(text, ligatures)
76
+ gids.each_with_index { |gid, i| @used[gid] ||= blanks[i] ? " " : chars[i] }
77
+ adjust = gids.each_with_index.map do |gid, i|
78
+ kern = kerning && i + 1 < gids.size ? pair(gid, gids[i + 1]) : 0
79
+ blanks[i] ? kern + (blanks[i] * 1000.0 / @ttf.units_per_em) : kern
80
+ end
65
81
  GlyphRun.new(font: self, gids:, adjust:, chars:)
66
82
  end
67
83
 
84
+ # Whether a character the font lacks is drawn as a blank (see WHITESPACE).
85
+ def blank?(char)
86
+ @blanks.fetch(char) { @blanks[char] = WHITESPACE.match?(char) && !glyph?(char) && glyph?(" ") }
87
+ end
88
+
68
89
  def used?
69
90
  @used.any?
70
91
  end
@@ -83,7 +104,11 @@ module Stationery
83
104
 
84
105
  def build(writer)
85
106
  embedding = (@ttf.cff? ? Embedding::CFF : Embedding::TrueType).new(self)
86
- name, cid_font = embedding.build(writer, @used.keys.sort)
107
+ gids = @used.keys.sort
108
+ name, cid_font = Stationery.instrument("font.stationery", font: @ttf.postscript_name, action: :subset,
109
+ glyphs: gids.size) do
110
+ embedding.build(writer, gids)
111
+ end
87
112
 
88
113
  writer.add(
89
114
  Type: :Font, Subtype: :Type0, BaseFont: name, Encoding: :"Identity-H",
@@ -93,11 +118,13 @@ module Stationery
93
118
 
94
119
  private
95
120
 
96
- # [gids, source text of each glyph], remembered per string.
121
+ # [gids, source text of each glyph, extra advance in font units after
122
+ # each blank or nil], remembered per string.
97
123
  def shape(text, ligatures)
98
124
  @shapes[ligatures][text] ||= begin
99
- gids = text.each_char.map { |char| @ttf.glyph_id(char.ord) }
100
- ligatures ? ligate(gids, text) : [gids, text.chars].each(&:freeze).freeze
125
+ gids = text.each_char.map { |char| glyph_for(char) }
126
+ gids, chars = ligatures ? ligate(gids, text) : [gids, text.chars]
127
+ [gids, chars, chars.map { |char| blank_units(char) }].each(&:freeze).freeze
101
128
  end
102
129
  end
103
130
 
@@ -105,11 +132,31 @@ module Stationery
105
132
  start = 0
106
133
  glyphs = @ttf.ligatures.substitute(gids)
107
134
  chars = glyphs.map { |_gid, count| text[start, count].tap { start += count } }
108
- [glyphs.map(&:first), chars].each(&:freeze).freeze
135
+ [glyphs.map(&:first), chars]
136
+ end
137
+
138
+ def glyph_for(char)
139
+ blank?(char) ? @ttf.glyph_id(" ".ord) : @ttf.glyph_id(char.ord)
140
+ end
141
+
142
+ # How much wider (or narrower) than a space a blank's advance is.
143
+ def blank_units(char)
144
+ return unless blank?(char)
145
+
146
+ space = @ttf.advance(@ttf.glyph_id(" ".ord))
147
+ like = SPACE_LIKE[char.ord]
148
+ width = if (fraction = SPACE_FRACTIONS[char.ord]) then @ttf.units_per_em * fraction
149
+ elsif like && glyph?(like) then @ttf.advance(@ttf.glyph_id(like.ord))
150
+ else space
151
+ end
152
+ width - space
109
153
  end
110
154
 
111
155
  def advance_units(text, ligatures)
112
- @advances[ligatures][text] ||= shape(text, ligatures).first.sum { |gid| @ttf.advance(gid) }
156
+ @advances[ligatures][text] ||= begin
157
+ gids, _, blanks = shape(text, ligatures)
158
+ gids.sum { |gid| @ttf.advance(gid) } + blanks.sum { |units| units || 0 }
159
+ end
113
160
  end
114
161
 
115
162
  def kerning_units(text, ligatures)
@@ -26,9 +26,14 @@ module Stationery
26
26
  @families[name.to_s] = Family.build(name, **paths)
27
27
  end
28
28
 
29
- # Returns [Font, Family::Face] for a Text::Style, memoised per style.
29
+ # Returns [Font, Family::Face] for a Text::Style, memoised by the three
30
+ # fields that pick a face (family, weight, style) in nested hashes: a
31
+ # style's size, colour and the rest do not matter here, and hashing a
32
+ # 13-field Data on every text measurement did.
30
33
  def resolve(style)
31
- @resolved[style] ||= begin
34
+ weights = (@resolved[style.family] ||= {})
35
+ styles = (weights[style.weight] ||= {})
36
+ styles[style.style] ||= begin
32
37
  face = family(style.family).face(weight: style.weight, style: style.style)
33
38
  [@fonts[face.path] ||= Font.new(Registry.load(face.path)), face].freeze
34
39
  end
@@ -36,11 +36,17 @@ module Stationery
36
36
  def fetch(path, index, mtime)
37
37
  key = [path, index]
38
38
  cached_mtime, ttf = @cache.delete(key)
39
- ttf = TrueType.new(File.binread(path), index:) unless cached_mtime == mtime
39
+ ttf = parse(path, index) unless cached_mtime == mtime
40
40
  @cache[key] = [mtime, ttf]
41
41
  @cache.shift while @cache.size > SIZE
42
42
  ttf
43
43
  end
44
+
45
+ def parse(path, index)
46
+ Stationery.instrument("font.stationery", path: File.basename(path), action: :parse) do
47
+ TrueType.new(File.binread(path), index:)
48
+ end
49
+ end
44
50
  end
45
51
  end
46
52
  end
@@ -6,6 +6,10 @@ require_relative "tree_builder"
6
6
  module Stationery
7
7
  # Lenient HTML to rich-text blocks (see Stationery::Rich).
8
8
  module HTML
9
- def self.parse(source) = TreeBuilder.parse(Tokenizer.tokenize(source))
9
+ def self.parse(source)
10
+ Stationery.instrument("parse.stationery", format: :html, bytes: source.bytesize) do
11
+ TreeBuilder.parse(Tokenizer.tokenize(source))
12
+ end
13
+ end
10
14
  end
11
15
  end
@@ -14,7 +14,15 @@ module Stationery
14
14
  # Accepts a path, a Pathname or an IO-like object (read from its start).
15
15
  def load(source)
16
16
  data = read(source)
17
- Cache.fetch(data) { parse(data) }
17
+ Cache.fetch(data) do
18
+ Stationery.instrument("image.stationery", bytes: data.bytesize) do |event|
19
+ parse(data).tap do |image|
20
+ event[:format] = image.is_a?(JPEG) ? "JPEG" : "PNG"
21
+ event[:width] = image.width
22
+ event[:height] = image.height
23
+ end
24
+ end
25
+ end
18
26
  end
19
27
 
20
28
  def read(source)