laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};

use image::RgbaImage;
use sha1::{Digest, Sha1};

use crate::card::Card;
use crate::config::{Align, Anchor, FitRule, Format, LaracardsConfig, TemplateConfig};
use crate::contracts::Renderer;
use crate::exceptions::RenderFailed;
use crate::support::{DataUri, ImageComposer, Layer, Manifest, Raster, Template, Text, TextFitter};

/// A fitted block and where it sits.
struct Block {
    lines: Vec<String>,
    size: i32,
    x: i32,
    dy: i32,
    baseline: Option<i32>,
    last_offset: i32,
    fitter: Arc<TextFitter>,
    rules: FitRule,
}

impl Block {
    fn align(&self) -> Align {
        self.rules.align
    }

    /// One box behind each line, as wide as the line's measured text: the highlighted headline, a marker
    /// pen run over each line. An SVG cannot draw it on its own, since it cannot measure its text, so the
    /// boxes are worked out here.
    ///
    /// The template still decides where the text goes: `align` only tells the boxes how the lines are
    /// anchored on `x`, so an SVG centring them with `text-anchor="middle"` needs `Align::Center` as well.
    fn highlights(&self) -> Vec<[i32; 4]> {
        let Some(highlight) = &self.rules.highlight else {
            return Vec::new();
        };
        let metrics = self.fitter.metrics(self.size);
        let baseline = self.baseline.unwrap_or(0);

        self.lines
            .iter()
            .enumerate()
            .map(|(index, line)| {
                let width = self.fitter.width(line, self.size);
                let left = match self.align() {
                    Align::Center => self.x - width / 2,
                    Align::Right => self.x - width,
                    Align::Left => self.x,
                };
                let line_baseline = baseline + index as i32 * self.dy;

                [
                    left - highlight.padding_x,
                    line_baseline - metrics.ascent - highlight.padding_y,
                    width + 2 * highlight.padding_x,
                    metrics.ascent + metrics.descent + 2 * highlight.padding_y,
                ]
            })
            .collect()
    }
}

/// Composes a card: fits the text, embeds the background, fills the template and hands the resulting SVG
/// to the renderer.
///
/// A template that is an image instead of an SVG takes the other road: the same fitted text is drawn
/// onto it, with no renderer at all.
pub struct CardGenerator {
    renderer: Arc<dyn Renderer>,
    manifest: Manifest,
    fitters: Mutex<HashMap<String, Arc<TextFitter>>>,
}

impl CardGenerator {
    /// A generator that draws SVG templates with `renderer` and remembers its cards in `manifest`.
    pub fn new(renderer: Arc<dyn Renderer>, manifest: Manifest) -> Self {
        Self {
            renderer,
            manifest,
            fitters: Mutex::new(HashMap::new()),
        }
    }

    /// The manifest of generated cards.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// The renderer SVG templates go through.
    pub fn renderer(&self) -> &Arc<dyn Renderer> {
        &self.renderer
    }

    /// Returns the output path, or `None` when the card was already up to date.
    ///
    /// # Errors
    ///
    /// Fails when the template is not configured or cannot be read, a font is missing, the background
    /// cannot be fetched, or the card cannot be drawn or written.
    pub async fn generate(&self, card: &Card, force: bool) -> laravel::Result<Option<PathBuf>> {
        let config = LaracardsConfig::current();
        let base = LaracardsConfig::base();
        let output = card.output_path();
        let template = Self::template_config(&config, card.template_name())?;
        let template_path = Self::template_path(&config, &base, template);
        let is_image = ImageComposer::handles(&template_path);

        let (width, height) = Self::size(&config, template);
        let format = card.output_format().or(template.format).unwrap_or(config.format);

        let fingerprint = Self::fingerprint(card, &template_path, template, (width, height), format);

        if !force && !self.manifest.is_stale(card.key(), &fingerprint, &output) {
            return Ok(None);
        }

        let layout = self.layout(&config, &base, template, card)?;

        if let Some(directory) = output.parent() {
            std::fs::create_dir_all(directory)?;
        }

        let background = card.background_driver().resolve().await?;
        let quality = config.quality;
        let target = output.clone();

        let written = if is_image {
            let layers = Self::layers(card.template_name(), &layout)?;

            tokio::task::spawn_blocking(move || {
                let image = ImageComposer.compose(&template_path, width, height, background.as_deref(), &layers)?;

                Raster::write(&image, &target, format, quality)
            })
        } else {
            if !self.renderer.available() {
                return Err(RenderFailed::new(
                    "Laracards: the renderer is not available. Install one, or use an image template.",
                )
                .into());
            }

            let mut data: Vec<(String, String)> = card
                .payload()
                .keys()
                .map(|key| (key.clone(), Text::escape(&card.scalar(key))))
                .collect();

            data.extend(Self::placeholders(&layout));
            data.push((
                "background_uri".to_owned(),
                DataUri::from_file(background.as_deref()).unwrap_or_default(),
            ));

            let svg = Template::new(&template_path)?.render(data)?;
            let renderer = Arc::clone(&self.renderer);

            tokio::task::spawn_blocking(move || {
                let image: RgbaImage = renderer.render(&svg, width, height)?;

                Raster::write(&image, &target, format, quality)
            })
        };

        written
            .await
            .map_err(|error| laravel::Error::msg(format!("Laracards: the render task failed: {error}")))??;

        self.manifest.put(card.key(), &fingerprint);

        Ok(Some(output))
    }

    /// Everything that decides how a card is drawn, as a hash.
    ///
    /// The template and the output geometry are inputs like any other: editing the SVG, or asking for a
    /// different size or format, has to make every card drawn with it stale, or the change never lands.
    /// An image template keeps its colours and positions in the config rather than in the file, so for
    /// those the config is an input too.
    pub fn fingerprint(
        card: &Card,
        template_path: &Path,
        template: &TemplateConfig,
        size: (u32, u32),
        format: Format,
    ) -> String {
        let mut parts = vec![
            card.fingerprint(),
            std::fs::read(template_path)
                .map(|contents| hex(&Sha1::digest(contents)))
                .unwrap_or_default(),
            size.0.to_string(),
            size.1.to_string(),
            format.extension().to_owned(),
        ];

        if ImageComposer::handles(template_path) {
            parts.push(hex(&Sha1::digest(format!("{template:?}"))));
        }

        hex(&Sha1::digest(parts.join("|")))
    }

    /// Whether a template is drawn onto an image instead of rendered from an SVG.
    ///
    /// # Errors
    ///
    /// Fails when the template is not configured.
    pub fn uses_image(&self, template: &str) -> laravel::Result<bool> {
        let config = LaracardsConfig::current();
        let template = Self::template_config(&config, template)?;

        Ok(ImageComposer::handles(&Self::template_path(
            &config,
            &LaracardsConfig::base(),
            template,
        )))
    }

    /// Output size, per template with the global values as the fallback.
    fn size(config: &LaracardsConfig, template: &TemplateConfig) -> (u32, u32) {
        (
            template.width.unwrap_or(config.width),
            template.height.unwrap_or(config.height),
        )
    }

    /// Fits every configured block and works out where it sits.
    ///
    /// Shared by both roads: the SVG path turns it into placeholders and the image path draws it, so a
    /// card lays out the same way either way.
    fn layout(
        &self,
        config: &LaracardsConfig,
        base: &Path,
        template: &TemplateConfig,
        card: &Card,
    ) -> laravel::Result<Vec<(String, Block)>> {
        let mut layout = Vec::new();

        for (field, rules) in &template.fit {
            let fitter = self.fitter(config, base, &rules.font)?;
            let sizes = if rules.sizes.is_empty() {
                vec![72, 64, 56, 48]
            } else {
                rules.sizes.clone()
            };
            let result = fitter.fit(&card.scalar(field), rules.max_width, rules.max_lines, &sizes);

            let dy = (f64::from(result.size) * rules.line_height).round() as i32;
            let last_offset = result.lines.len().saturating_sub(1) as i32 * dy;

            // SVG cannot do arithmetic, so the baseline of the first line is computed here. Anchoring at
            // the bottom keeps a one-line title and a three-line one sitting on the same rule, which is
            // the only way a variable-length headline stays visually stable on the card.
            let baseline = rules.baseline.map(|baseline| match rules.anchor {
                Anchor::Bottom => baseline - last_offset,
                Anchor::Top => baseline,
            });

            layout.push((
                field.clone(),
                Block {
                    lines: result.lines,
                    size: result.size,
                    x: rules.x,
                    dy,
                    baseline,
                    last_offset,
                    fitter,
                    rules: rules.clone(),
                },
            ));
        }

        Ok(Self::stack(template, layout))
    }

    /// Centres a group of blocks as one unit, each below the previous.
    ///
    /// A title that runs to one line or three, with a subtitle that may or may not be there, only stays
    /// centred if the whole group is measured first. A stacked block's baseline is computed here and wins
    /// over its own.
    fn stack(template: &TemplateConfig, mut layout: Vec<(String, Block)>) -> Vec<(String, Block)> {
        let Some(stack) = &template.stack else {
            return layout;
        };

        let fields: Vec<&String> = stack
            .fields
            .iter()
            .filter(|field| {
                layout
                    .iter()
                    .any(|(name, block)| name == *field && !block.lines.is_empty())
            })
            .collect();

        if fields.is_empty() {
            return layout;
        }

        let heights = |field: &String| {
            layout
                .iter()
                .find(|(name, _)| name == field)
                .map_or(0, |(_, block)| block.lines.len() as i32 * block.dy)
        };
        let total = stack.gap * (fields.len() as i32 - 1) + fields.iter().map(|field| heights(field)).sum::<i32>();
        let mut top = (f64::from(stack.center_y) - f64::from(total) / 2.0).round() as i32;
        let fields: Vec<String> = fields.into_iter().cloned().collect();

        for field in fields {
            let Some((_, block)) = layout.iter_mut().find(|(name, _)| *name == field) else {
                continue;
            };
            let metrics = block.fitter.metrics(block.size);

            // The first baseline sits inside the first line box so the glyphs, not the box, are what end
            // up centred.
            let offset = (f64::from(block.dy - metrics.ascent - metrics.descent) / 2.0).round() as i32 + metrics.ascent;

            block.baseline = Some(top + offset);
            top += block.lines.len() as i32 * block.dy + stack.gap;
        }

        layout
    }

    /// Turns the layout into `{{key_tspans}}`, `{{key_font_size}}` and friends.
    fn placeholders(layout: &[(String, Block)]) -> Vec<(String, String)> {
        let mut out = Vec::new();

        for (field, block) in layout {
            // Joined with nothing between them. Whitespace there becomes a space at the end of every line
            // but the last, and a centred or right-aligned line counts it, which shifts all of them but
            // the last by half a space.
            let tspans: String = block
                .lines
                .iter()
                .enumerate()
                .map(|(index, line)| {
                    format!(
                        "<tspan x=\"{}\" dy=\"{}\">{}</tspan>",
                        block.x,
                        if index == 0 { 0 } else { block.dy },
                        Text::escape(line)
                    )
                })
                .collect();

            out.push((format!("{field}_tspans"), tspans));
            out.push((format!("{field}_font_size"), block.size.to_string()));
            out.push((format!("{field}_line_count"), block.lines.len().to_string()));

            if let Some(baseline) = block.baseline {
                if block.rules.highlight.is_some() {
                    let boxes: Vec<String> = block
                        .highlights()
                        .iter()
                        .map(|[x, y, width, height]| {
                            format!("<rect x=\"{x}\" y=\"{y}\" width=\"{width}\" height=\"{height}\"/>")
                        })
                        .collect();

                    out.push((format!("{field}_highlights"), boxes.join("\n      ")));
                }

                out.push((format!("{field}_baseline"), baseline.to_string()));

                // Where the block ends. Lets a template hang the next element off the real bottom of a
                // variable-height block, instead of guessing a fixed position that only looks right
                // sometimes.
                out.push((format!("{field}_bottom"), (baseline + block.last_offset).to_string()));
            }
        }

        out
    }

    /// Turns the layout into drawable layers for an image template, which has no SVG to carry colour,
    /// alignment or position.
    fn layers(template: &str, layout: &[(String, Block)]) -> laravel::Result<Vec<Layer>> {
        let mut layers = Vec::new();

        for (field, block) in layout {
            if block.lines.is_empty() {
                continue;
            }

            let Some(baseline) = block.baseline else {
                return Err(laravel::Error::msg(format!(
                    "Laracards: '{field}' in the image template '{template}' needs a 'baseline', or to be listed under 'stack'."
                )));
            };

            layers.push(Layer {
                lines: block.lines.clone(),
                size: block.size,
                x: block.x,
                dy: block.dy,
                baseline,
                font: Arc::clone(&block.fitter),
                color: block.rules.color.clone(),
                align: block.align(),
                highlights: block.highlights(),
                highlight_color: block
                    .rules
                    .highlight
                    .as_ref()
                    .map_or_else(|| "#000000".to_owned(), |highlight| highlight.color.clone()),
            });
        }

        Ok(layers)
    }

    fn fitter(&self, config: &LaracardsConfig, base: &Path, font: &str) -> laravel::Result<Arc<TextFitter>> {
        let mut fitters = self.fitters.lock().unwrap_or_else(PoisonError::into_inner);

        if let Some(fitter) = fitters.get(font) {
            return Ok(Arc::clone(fitter));
        }

        let Some(path) = config.fonts.get(font).filter(|path| !path.is_empty()) else {
            return Err(laravel::Error::msg(format!(
                "Laracards: no font configured under laracards.fonts.{font}."
            )));
        };

        let fitter = Arc::new(TextFitter::new(LaracardsConfig::resolve(base, path))?);

        fitters.insert(font.to_owned(), Arc::clone(&fitter));

        Ok(fitter)
    }

    fn template_path(config: &LaracardsConfig, base: &Path, template: &TemplateConfig) -> PathBuf {
        LaracardsConfig::resolve(base, &config.paths.templates).join(&template.file)
    }

    fn template_config<'a>(config: &'a LaracardsConfig, name: &str) -> laravel::Result<&'a TemplateConfig> {
        config
            .templates
            .get(name)
            .filter(|template| !template.file.is_empty())
            .ok_or_else(|| laravel::Error::msg(format!("Laracards: template '{name}' is not configured.")))
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}