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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use laravel::config::{Env, Section};

/// The file format of a card.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Format {
    /// Lossless, keeps a flat card crisp.
    #[default]
    Png,
    /// A fraction of the size once a photograph is behind the text. Flattened onto white.
    Jpg,
    /// Written lossless: the encoder of Laravel Rust's image stack has no lossy WebP.
    Webp,
}

impl Format {
    /// The file extension of the format.
    pub fn extension(self) -> &'static str {
        match self {
            Self::Png => "png",
            Self::Jpg => "jpg",
            Self::Webp => "webp",
        }
    }
}

/// Which line of a fitted block lands on its `baseline`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Anchor {
    /// The first line. Everything grows downwards.
    #[default]
    Top,
    /// The last line, so a one-line headline and a three-line one sit on the same rule.
    Bottom,
}

/// How the text of a block is anchored on its `x`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Align {
    /// `x` is where every line starts.
    #[default]
    Left,
    /// `x` is the centre of every line.
    Center,
    /// `x` is where every line ends.
    Right,
}

/// A bar of colour behind each line of a block, as wide as the line's measured text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Highlight {
    /// Pixels of colour on each side of a line.
    pub padding_x: i32,
    /// Pixels of colour above and below a line.
    pub padding_y: i32,
    /// The colour of the bars in an image template. An SVG template colours them itself.
    pub color: String,
}

impl Default for Highlight {
    fn default() -> Self {
        Self {
            padding_x: 10,
            padding_y: 6,
            color: "#000000".to_owned(),
        }
    }
}

impl Highlight {
    /// A highlight with the given padding.
    pub fn padded(padding_x: i32, padding_y: i32) -> Self {
        Self {
            padding_x,
            padding_y,
            ..Self::default()
        }
    }

    /// The colour of the bars in an image template.
    #[must_use]
    pub fn color(mut self, color: impl Into<String>) -> Self {
        self.color = color.into();

        self
    }
}

/// One fit rule: how a field is wrapped, sized and placed.
#[derive(Debug, Clone, PartialEq)]
pub struct FitRule {
    /// The name of a face under `fonts`.
    pub font: String,
    /// Where the lines are anchored horizontally.
    pub x: i32,
    /// The width of the column, in pixels.
    pub max_width: i32,
    /// The most lines the block may take.
    pub max_lines: usize,
    /// Candidate font sizes, largest first.
    pub sizes: Vec<i32>,
    /// The distance between baselines, as a multiple of the font size.
    pub line_height: f64,
    /// Which line lands on `baseline`.
    pub anchor: Anchor,
    /// The baseline of the anchored line.
    pub baseline: Option<i32>,
    /// The colour of the text of an image template: `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()` or `rgba()`.
    pub color: String,
    /// How the text is anchored on `x`.
    pub align: Align,
    /// Bars of colour behind the lines.
    pub highlight: Option<Highlight>,
}

impl Default for FitRule {
    fn default() -> Self {
        Self {
            font: "default".to_owned(),
            x: 80,
            max_width: 1040,
            max_lines: 3,
            sizes: vec![72, 64, 56, 48],
            line_height: 1.17,
            anchor: Anchor::Top,
            baseline: None,
            color: "#ffffff".to_owned(),
            align: Align::Left,
            highlight: None,
        }
    }
}

impl FitRule {
    /// A rule with the defaults of the PHP package.
    pub fn new() -> Self {
        Self::default()
    }

    /// The face to measure and draw with.
    #[must_use]
    pub fn font(mut self, font: impl Into<String>) -> Self {
        self.font = font.into();

        self
    }

    /// Where the lines are anchored horizontally.
    #[must_use]
    pub fn x(mut self, x: i32) -> Self {
        self.x = x;

        self
    }

    /// The width of the column.
    #[must_use]
    pub fn max_width(mut self, max_width: i32) -> Self {
        self.max_width = max_width;

        self
    }

    /// The most lines the block may take.
    #[must_use]
    pub fn max_lines(mut self, max_lines: usize) -> Self {
        self.max_lines = max_lines;

        self
    }

    /// Candidate font sizes, largest first.
    #[must_use]
    pub fn sizes(mut self, sizes: impl IntoIterator<Item = i32>) -> Self {
        self.sizes = sizes.into_iter().collect();

        self
    }

    /// The distance between baselines, as a multiple of the font size.
    #[must_use]
    pub fn line_height(mut self, line_height: f64) -> Self {
        self.line_height = line_height;

        self
    }

    /// Which line lands on `baseline`.
    #[must_use]
    pub fn anchor(mut self, anchor: Anchor) -> Self {
        self.anchor = anchor;

        self
    }

    /// The baseline of the anchored line.
    #[must_use]
    pub fn baseline(mut self, baseline: i32) -> Self {
        self.baseline = Some(baseline);

        self
    }

    /// The colour of the text of an image template.
    #[must_use]
    pub fn color(mut self, color: impl Into<String>) -> Self {
        self.color = color.into();

        self
    }

    /// How the text is anchored on `x`.
    #[must_use]
    pub fn align(mut self, align: Align) -> Self {
        self.align = align;

        self
    }

    /// Draw a bar of colour behind each line. `Highlight::default()` is `'highlight' => true` in PHP.
    #[must_use]
    pub fn highlight(mut self, highlight: Highlight) -> Self {
        self.highlight = Some(highlight);

        self
    }
}

/// A group of blocks centred as one unit, each below the previous.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stack {
    /// The fields of the group, in order. A block that comes out empty drops out.
    pub fields: Vec<String>,
    /// Where the middle of the group sits.
    pub center_y: i32,
    /// The space between two blocks.
    pub gap: i32,
}

impl Stack {
    /// A stack of these fields, centred at 315 with a gap of 24 like the PHP package.
    pub fn new<S: Into<String>>(fields: impl IntoIterator<Item = S>) -> Self {
        Self {
            fields: fields.into_iter().map(Into::into).collect(),
            center_y: 315,
            gap: 24,
        }
    }

    /// Where the middle of the group sits.
    #[must_use]
    pub fn center_y(mut self, center_y: i32) -> Self {
        self.center_y = center_y;

        self
    }

    /// The space between two blocks.
    #[must_use]
    pub fn gap(mut self, gap: i32) -> Self {
        self.gap = gap;

        self
    }
}

/// One template: an SVG with placeholders, or a PNG, JPG or WebP the text is drawn onto.
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateConfig {
    /// The file, relative to `paths.templates`.
    pub file: String,
    /// The width of this template's cards. The root `width` when absent.
    pub width: Option<u32>,
    /// The height of this template's cards. The root `height` when absent.
    pub height: Option<u32>,
    /// The format of this template's cards. The root `format` when absent.
    pub format: Option<Format>,
    /// The fit rules, by field.
    pub fit: Vec<(String, FitRule)>,
    /// A group of blocks centred together.
    pub stack: Option<Stack>,
}

impl TemplateConfig {
    /// A template without fit rules yet.
    pub fn new(file: impl Into<String>) -> Self {
        Self {
            file: file.into(),
            width: None,
            height: None,
            format: None,
            fit: Vec::new(),
            stack: None,
        }
    }

    /// The width of this template's cards.
    #[must_use]
    pub fn width(mut self, width: u32) -> Self {
        self.width = Some(width);

        self
    }

    /// The height of this template's cards.
    #[must_use]
    pub fn height(mut self, height: u32) -> Self {
        self.height = Some(height);

        self
    }

    /// The format of this template's cards.
    #[must_use]
    pub fn format(mut self, format: Format) -> Self {
        self.format = Some(format);

        self
    }

    /// Add a fit rule for a field. The same field again replaces the rule.
    #[must_use]
    pub fn fit(mut self, field: impl Into<String>, rule: FitRule) -> Self {
        let field = field.into();

        match self.fit.iter_mut().find(|(name, _)| *name == field) {
            Some(existing) => existing.1 = rule,
            None => self.fit.push((field, rule)),
        }

        self
    }

    /// Centre a group of blocks as one unit.
    #[must_use]
    pub fn stack(mut self, stack: Stack) -> Self {
        self.stack = Some(stack);

        self
    }
}

/// How SVG templates are rendered. The PHP package shells out to `rsvg-convert` or `resvg`; this
/// crate renders with the `resvg` library, so the only choice left is which fonts it knows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resvg {
    /// Font files to load besides the ones under `fonts`.
    pub font_files: Vec<String>,
    /// Also load the fonts installed on the machine.
    pub system_fonts: bool,
}

impl Default for Resvg {
    fn default() -> Self {
        Self {
            font_files: Vec::new(),
            system_fonts: true,
        }
    }
}

/// The renderers, as in `laracards.renderers`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Renderers {
    /// The native renderer.
    pub resvg: Resvg,
}

/// The directories the package reads and writes. A relative path starts at the application's base path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paths {
    /// Where the templates live.
    pub templates: String,
    /// Where a card without an explicit output path is written.
    pub output: String,
    /// The manifest of generated cards.
    pub manifest: String,
}

impl Default for Paths {
    fn default() -> Self {
        Self {
            templates: "resources/cards".to_owned(),
            output: "public/img/cards".to_owned(),
            manifest: "storage/app/laracards/manifest.json".to_owned(),
        }
    }
}

/// The Unsplash background driver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsplash {
    /// The API access key, from `UNSPLASH_ACCESS_KEY`.
    pub access_key: Option<String>,
    /// Where downloaded photos are kept.
    pub cache: String,
}

impl Default for Unsplash {
    fn default() -> Self {
        Self {
            access_key: None,
            cache: "storage/app/laracards/backgrounds".to_owned(),
        }
    }
}

/// The background drivers, as in `laracards.backgrounds`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Backgrounds {
    /// Photos from Unsplash.
    pub unsplash: Unsplash,
}

fn default_fonts() -> BTreeMap<String, String> {
    BTreeMap::from([("default".to_owned(), "public/fonts/Lato-Bold.ttf".to_owned())])
}

fn default_templates() -> BTreeMap<String, TemplateConfig> {
    BTreeMap::from([(
        "post".to_owned(),
        TemplateConfig::new("post.svg").fit("title", FitRule::new().sizes([82, 72, 64, 56, 48]).baseline(320)),
    )])
}

fn backgrounds_from_env(env: &Env) -> Option<Backgrounds> {
    let access_key = env.get::<String>("UNSPLASH_ACCESS_KEY")?;

    Some(Backgrounds {
        unsplash: Unsplash {
            access_key: Some(access_key),
            ..Unsplash::default()
        },
    })
}

/// The package's configuration, the equivalent of `config/laracards.php`.
///
/// Only the Unsplash key reads the environment, through `UNSPLASH_ACCESS_KEY`. The rest describes how
/// the application draws its cards and is set in `src/app.rs` with `with_config`. The `sources` key of
/// the PHP config is not here, because a source is code: register it on the provider.
#[derive(Debug, Clone, Section)]
pub struct LaracardsConfig {
    /// How SVG templates are rendered.
    pub renderers: Renderers,

    /// The default width of a card.
    #[section(default = 1200)]
    pub width: u32,

    /// The default height of a card.
    #[section(default = 630)]
    pub height: u32,

    /// The default format of a card.
    pub format: Format,

    /// The quality of a JPEG, from 1 to 100. WebP is written lossless and ignores it.
    #[section(default = 85)]
    pub quality: u8,

    /// The directories the package reads and writes.
    pub paths: Paths,

    /// The faces text is measured with, by name. Point them at the faces the templates declare, or the
    /// measurement drifts from the render. They are also loaded into the renderer.
    #[section(default = default_fonts())]
    pub fonts: BTreeMap<String, String>,

    /// The background drivers.
    #[env(with = backgrounds_from_env)]
    pub backgrounds: Backgrounds,

    /// The templates, by name.
    #[section(default = default_templates())]
    pub templates: BTreeMap<String, TemplateConfig>,
}

impl LaracardsConfig {
    /// A configured path as an absolute one: relative paths start at `base`.
    pub fn resolve(base: &Path, path: &str) -> PathBuf {
        let path = Path::new(path);

        if path.is_absolute() {
            path.to_path_buf()
        } else {
            base.join(path)
        }
    }

    /// The package's configuration, as the running application has it.
    pub fn current() -> Self {
        laravel::config().section::<Self>().clone()
    }

    /// The application's base path.
    pub fn base() -> PathBuf {
        laravel::config().app.base_path.clone()
    }
}