meo-canvas 0.2.1

Describe a picture, get image bytes back. CSS flexbox, grid and block layout on a Skia backend.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
//! The nested tree a caller writes, and its flattening into the scene's arena.
//!
//! A scene is a `Vec<Node>` indexed by `NodeId` — a shape a codec round-trips
//! and a person does not write. An [`Element`] is the same tree nested, which
//! is how it is described:
//!
//! ```
//! use meo_canvas::{Column, Styled, Text, all, hex_rgb, px};
//!
//! let card = Column::new().padding(all(px(24.0))).gap(px(8.0)).children([
//!     Text::new("Ukasyah").font_size(24.0).bold(),
//!     Text::new("Bandung").color(hex_rgb(0x88_88_90)),
//! ]);
//!
//! // The markup in each `Text` is parsed here rather than in `Text::new`,
//! // so this is also where anything the parser could not use is reported.
//! let (scene, diagnostics) = card.into_scene(320.0, 180.0)?;
//! assert_eq!(scene.nodes.len(), 3);
//! assert!(diagnostics.is_empty());
//! # Ok::<(), meo_canvas_scene::SceneError>(())
//! ```
//!
//! Properties are named flat on the node, from [`Styled`]. Beyond them a node
//! has `new` (or the constructor taking its essential argument) and
//! `children`, and that set never grows: a new property is a new entry in the
//! property table, not a method on seven types.

use meo_canvas_core::diagnostic::Diagnostic;
use meo_canvas_scene::{
    Length, Scene, SceneError, Size,
    node::{
        HttpOptions, ImageSource, LineCap, LineJoin, Node, NodeId, NodeKind,
        PathPaint,
    },
    style::{
        effect::FillRule,
        paint::{Color, ColorValue, ObjectFit},
        text::{ParagraphStyle, TextSegment},
    },
};

use crate::{Style, Styled};

/// What an element draws, before the tree is walked.
///
/// **Not [`NodeKind`], because one case is not resolved yet.** `Text::new`
/// takes markup and the markup is parsed during the walk, so between the
/// constructor and `into_scene` a text node holds a string rather than the
/// runs the scene stores. Everything else is already a scene node and passes
/// through untouched. A second field holding the markup beside a scene
/// `kind` would be two representations of one paragraph.
#[derive(Debug, Clone, PartialEq)]
pub enum ElementKind {
    /// A node the scene already describes.
    Node(NodeKind),
    /// Text whose markup has not been parsed yet.
    ///
    /// Parsed during the walk that [`Element::into_scene`] runs, in its
    /// `write_page`, which is the only place that can hand the diagnostics
    /// anywhere -- a constructor returns an `Element` and has nowhere to put
    /// them.
    Markup {
        /// The markup as the caller wrote it.
        content: String,
        /// Properties of the paragraph as a whole.
        paragraph: ParagraphStyle,
    },
}

impl From<NodeKind> for ElementKind {
    fn from(kind: NodeKind) -> Self {
        Self::Node(kind)
    }
}

/// One node of the tree, with its style and its children.
///
/// Produced by the node constructors rather than written directly, though the
/// fields are reachable for a caller assembling a tree programmatically.
#[derive(Debug, Clone, PartialEq)]
pub struct Element {
    /// What this node draws.
    pub kind: ElementKind,
    /// How it is styled.
    pub style: Style,
    /// Its children, in paint order before `z_index` applies.
    pub children: Vec<Self>,
    /// A name carried through for diagnostics, which the renderer never reads.
    pub name: Option<String>,
}

impl Element {
    /// A node of the given kind, styled with nothing and holding no children.
    #[must_use]
    pub const fn new(kind: NodeKind) -> Self {
        Self {
            kind: ElementKind::Node(kind),
            style: Style::new(),
            children: Vec::new(),
            name: None,
        }
    }

    /// Layers a whole style over this node's, property by property.
    ///
    /// The secondary idiom. A node is normally styled by naming properties on
    /// it directly — `Row::new().gap(px(16.0))` — and this is for the case the
    /// flat setters cannot express: a reusable base, declared once as a
    /// `const`, applied to many nodes.
    ///
    /// ```
    /// use meo_canvas::{Row, Style, Styled, all, px};
    ///
    /// const CARD: Style = Style::new().padding(all(px(24.0))).gap(px(16.0));
    ///
    /// let tight = Row::new().with_style(CARD).gap(px(8.0));
    /// ```
    ///
    /// Not called `style`, so it cannot read as a nested style object —
    /// properties sit directly on the node on both surfaces.
    ///
    /// # It merges rather than replacing
    ///
    /// A property the argument names wins. A property it leaves absent leaves
    /// what the node already had, including what its constructor set:
    ///
    /// ```
    /// use meo_canvas::{Column, FlexDirection, Style, Styled, pct};
    ///
    /// // Still a column. The style said nothing about the direction.
    /// let kept = Column::new().with_style(Style::new().width(pct(100.0)));
    ///
    /// // A row, because this style did say. Merge is not a rule that the
    /// // constructor always wins — it is that absent is not a value.
    /// let row = Column::new()
    ///     .with_style(Style::new().flex_direction(FlexDirection::Row));
    /// ```
    ///
    /// [`Style::merge`] is what this calls. Order matters only between two
    /// styles naming the same property, where the later wins -- the flat
    /// setters' own rule, applied to many properties at once, and what the
    /// JavaScript surface's `{ flexDirection, ...props }` spread does.
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = core::mem::take(&mut self.style).merge(style);
        self
    }

    /// A name carried through for diagnostics.
    ///
    /// Not a style property and not on [`crate::Styled`]: the scene
    /// keeps it on the node beside the kind rather than in a style group, and
    /// nothing inherits it. The renderer never reads it — it is there so a
    /// tree dumped to `.mcs` and looked at later says which node is which.
    ///
    /// ```
    /// use meo_canvas::Row;
    ///
    /// let card = Row::new().name("card");
    /// ```
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Replaces this node's children.
    ///
    /// Takes one element, an array, a `Vec`, an `Option` that contributes
    /// nothing when it is `None`, or [`each`] over anything iterable.
    #[must_use]
    pub fn children(mut self, children: impl IntoElements) -> Self {
        let mut collected = Vec::new();
        children.write_elements(&mut collected);
        self.children = collected;
        self
    }

    /// Flattens this tree into a scene of one page at the given size.
    ///
    /// This element becomes the page root, so its style is the page's.
    ///
    /// What [`Canvas`](crate::Canvas) uses for a single page, and public for
    /// the case where a caller wants a `Scene` and nothing else — to write
    /// to disk, to send over the wire, or to render more than once. A
    /// caller who wants pages, or options, reaches for `Canvas` instead.
    ///
    /// The size is bare pixels rather than a [`Length`], and deliberately: a
    /// canvas size is in device-independent pixels, and a percentage of nothing
    /// has no meaning. A `Length` parameter would admit `pct(50.0)`, compile,
    /// and produce a zero-width canvas with nothing said — a caller could only
    /// discover it by looking at the picture. The type refuses it instead:
    ///
    /// ```compile_fail
    /// use meo_canvas::{Box, pct, px};
    ///
    /// // `pct` yields a `Length`, which is not a canvas size.
    /// let scene = Box::new().into_scene(pct(50.0), 112.0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`SceneError::TooManyNodes`] when the tree holds more nodes than
    /// the codec can address. Nothing else here can fail: the tree is a tree by
    /// construction, so the cycle and reachability rules
    /// [`Scene::validate`] enforces cannot be broken by building one this way.
    pub fn into_scene(
        self,
        width: f32,
        height: f32,
    ) -> Result<(Scene, Vec<Diagnostic>), SceneError> {
        // **The runtime half of the promise the type already makes.** The
        // signature refuses `pct(50.0)` here, with a `compile_fail` doctest
        // saying why a percentage of nothing has no meaning; a `NaN` or a
        // negative width is the same claim and the type cannot see it.
        let size = Size::new(width, height);
        if !meo_canvas_scene::size_is_pixels(size) {
            return Err(SceneError::canvas_size(width, height));
        }

        let mut scene = Scene::new(size);
        let root = scene.root().ok_or(SceneError::NoPages)?;
        let mut found = Vec::new();
        write_page(&mut scene, root, self, &mut found)?;
        Ok((scene, found))
    }
}

impl Element {
    /// The paragraph style of a text node, from either arm: `Text::new`
    /// returns the markup arm, so reaching only [`ElementKind::Node`] would
    /// make `max_lines` and `ellipsis` silently do nothing on it.
    const fn paragraph_mut(&mut self) -> Option<&mut ParagraphStyle> {
        match &mut self.kind {
            ElementKind::Node(NodeKind::Text { paragraph, .. })
            | ElementKind::Markup { paragraph, .. } => Some(paragraph),
            ElementKind::Node(_) => None,
        }
    }
}

impl Styled for Element {
    fn style_mut(&mut self) -> &mut Style {
        &mut self.style
    }
}

/// What a `children` call accepts: one element, many, or none.
///
/// A single element, an array, a `Vec`, or an `Option<Element>` that is `None`
/// and contributes nothing -- so a conditional that does not render writes
/// nothing rather than an empty node, as a falsy child does on the JavaScript
/// surface.
///
/// ```
/// use meo_canvas::{Row, Styled, Text, px};
///
/// let show_subtitle = false;
/// let card = Row::new().gap(px(8.0)).children([
///     Some(Text::new("Ukasyah")),
///     show_subtitle.then(|| Text::new("subtitle")),
/// ]);
/// ```
pub trait IntoElements {
    /// Appends what this contributes onto `out`.
    ///
    /// Appends rather than returning a `Vec`, so nesting one of these inside
    /// another costs no intermediate allocation.
    fn write_elements(self, out: &mut Vec<Element>);
}

impl IntoElements for Element {
    fn write_elements(self, out: &mut Vec<Element>) {
        out.push(self);
    }
}

impl IntoElements for Option<Element> {
    fn write_elements(self, out: &mut Vec<Element>) {
        if let Some(inner) = self {
            out.push(inner);
        }
    }
}

impl<T: IntoElements> IntoElements for Vec<T> {
    fn write_elements(self, out: &mut Vec<Element>) {
        for item in self {
            item.write_elements(out);
        }
    }
}

impl<T: IntoElements, const N: usize> IntoElements for [T; N] {
    fn write_elements(self, out: &mut Vec<Element>) {
        for item in self {
            item.write_elements(out);
        }
    }
}

/// Children from anything iterable, without collecting first.
///
/// ```
/// use meo_canvas::{Column, Text, each};
///
/// let names = ["Ada", "Grace", "Katherine"];
/// let list =
///     Column::new().children(each(names.iter().map(|name| Text::new(*name))));
/// ```
///
/// A wrapper rather than a blanket `impl IntoElements for I: IntoIterator`,
/// which cannot exist: `Vec`, `[T; N]` and `Option` are all `IntoIterator`, so
/// it would overlap every impl above and rustc refuses it — `Option<Element>`
/// conflicts even when narrowed, because a future std release could make it an
/// iterator and coherence has to assume one might.
pub const fn each<I>(items: I) -> Each<I>
where
    I: IntoIterator,
    I::Item: IntoElements,
{
    Each(items)
}

/// What [`each`] returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Each<I>(I);

impl<I> IntoElements for Each<I>
where
    I: IntoIterator,
    I::Item: IntoElements,
{
    fn write_elements(self, out: &mut Vec<Element>) {
        for item in self.0 {
            item.write_elements(out);
        }
    }
}

/// Turns an element's kind into the scene's, parsing markup on the way: the
/// facade's only parse site, since a constructor has nowhere to put a
/// diagnostic.
fn resolve(kind: ElementKind, found: &mut Vec<Diagnostic>) -> NodeKind {
    match kind {
        ElementKind::Node(node) => node,
        ElementKind::Markup { content, paragraph } => {
            let (segments, reported) =
                meo_canvas_core::markup::parse_paragraph_reporting(&content);
            found.extend(reported);
            NodeKind::Text {
                segments,
                paragraph,
            }
        }
    }
}

/// Writes `element` onto the existing page root and adds its subtree. The
/// element styles the root rather than becoming its child, so its
/// `background_color` paints the canvas. Shared by [`Element::into_scene`] and
/// [`crate::Canvas`], so a page means the same thing in both.
pub(crate) fn write_page(
    scene: &mut Scene,
    root: NodeId,
    element: Element,
    found: &mut Vec<Diagnostic>,
) -> Result<(), SceneError> {
    let mut kind = resolve(element.kind, found);
    apply_image_style(&mut kind, &element.style);
    let (layout, paint, text, effects) = element.style.into_parts();
    if let Some(node) = scene.get_mut(root) {
        node.kind = kind;
        node.layout = layout;
        node.paint = paint;
        node.text = text;
        node.effects = effects;
        node.name = element.name;
    }

    for child in element.children {
        push(scene, root, child, found)?;
    }
    Ok(())
}

/// Writes the image properties a flat style carries -- `object_fit`,
/// `object_position` and `frame` -- into [`NodeKind::Image`], where the scene
/// keeps them. A node that is not an image ignores them.
const fn apply_image_style(kind: &mut NodeKind, style: &Style) {
    if let NodeKind::Image {
        fit,
        position,
        frame,
        ..
    } = kind
    {
        if let Some(value) = style.object_fit {
            *fit = value;
        }
        if let Some(value) = style.object_position {
            *position = value;
        }
        if style.frame.is_some() {
            *frame = style.frame;
        }
    }
}

/// Adds `element` and its subtree under `parent`, recursively: a tree deep
/// enough to overflow the stack here would overflow it in the codec too.
fn push(
    scene: &mut Scene,
    parent: NodeId,
    element: Element,
    found: &mut Vec<Diagnostic>,
) -> Result<NodeId, SceneError> {
    let mut kind = resolve(element.kind, found);
    apply_image_style(&mut kind, &element.style);
    let (layout, paint, text, effects) = element.style.into_parts();
    let mut node = Node::new(kind);
    node.layout = layout;
    node.paint = paint;
    node.text = text;
    node.effects = effects;
    node.name = element.name;

    let id = scene.push(parent, node)?;
    for child in element.children {
        push(scene, id, child, found)?;
    }
    Ok(id)
}

/// A plain container.
///
/// Lays its children out as a row by default, following CSS's `display: flex`
/// rather than Yoga's column.
///
/// ```
/// use meo_canvas::{Box, Styled, px};
///
/// let spacer = Box::new().size(px(8.0), px(8.0));
/// ```
///
/// # Importing this shadows `std::boxed::Box`
///
/// `Box<T>` is in the prelude, so a `use meo_canvas::Box` takes that name for
/// the rest of the file. Nothing warns.
///
/// **The fix is to spell the heap allocation in full, not to rename the
/// node.** `std::boxed::Box<dyn Error>` is unambiguous, it is one occurrence
/// in a file that mostly draws, and it leaves the component called what it is
/// called everywhere else -- in the JavaScript surface and in every example.
/// Aliasing our own name to make room for the standard library's is backwards:
/// the qualification belongs on the thing that is not the subject of the file.
///
/// Both names in one file, compiled here rather than asserted:
///
/// ```
/// use meo_canvas::{Box, Styled, px};
///
/// let spacer = Box::new().size(px(8.0), px(8.0));
/// let held: std::boxed::Box<dyn std::error::Error> = "in full".into();
/// # let _ = (spacer, held);
/// ```
///
/// A file that never heap-allocates needs none of this, which is most of them.
#[derive(Debug)]
#[non_exhaustive]
pub struct Box;

impl Box {
    /// A container, with `display: flex` set explicitly.
    ///
    /// **Named rather than inherited.** The scene's default display is
    /// `block`, which is what a browser gives a `<div>`; a `Box` that laid its
    /// children out as a block would stop honouring `gap`, `align_items` and
    /// `justify_content` without saying so.
    #[must_use]
    #[expect(
        clippy::new_ret_no_self,
        reason = "the node types are constructors for `Element`, not types a caller holds"
    )]
    pub fn new() -> Element {
        Element::new(NodeKind::Box)
            .display(meo_canvas_scene::style::layout::Display::Flex)
    }
}

/// A container whose children run horizontally.
///
/// ```
/// use meo_canvas::{Row, Style, px};
///
/// let bar = Row::new().with_style(Style::new().gap(px(12.0)));
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct Row;

impl Row {
    /// A row, with `flex-direction: row` set explicitly.
    ///
    /// Explicit rather than inherited from the default, so the direction
    /// survives a caller layering a style that names one.
    #[must_use]
    #[expect(
        clippy::new_ret_no_self,
        reason = "the node types are constructors for `Element`, not types a caller holds"
    )]
    pub fn new() -> Element {
        Element::new(NodeKind::Box)
            .display(meo_canvas_scene::style::layout::Display::Flex)
            .flex_direction(meo_canvas_scene::style::layout::FlexDirection::Row)
    }
}

/// A container whose children run vertically.
#[derive(Debug)]
#[non_exhaustive]
pub struct Column;

impl Column {
    /// A column, with `flex-direction: column` set explicitly.
    #[must_use]
    #[expect(
        clippy::new_ret_no_self,
        reason = "the node types are constructors for `Element`, not types a caller holds"
    )]
    pub fn new() -> Element {
        Element::new(NodeKind::Box)
            .display(meo_canvas_scene::style::layout::Display::Flex)
            .flex_direction(
                meo_canvas_scene::style::layout::FlexDirection::Column,
            )
    }
}

/// A container whose children are placed on a grid.
#[derive(Debug)]
#[non_exhaustive]
pub struct Grid;

impl Grid {
    /// A grid, with `display: grid` set explicitly.
    #[must_use]
    #[expect(
        clippy::new_ret_no_self,
        reason = "the node types are constructors for `Element`, not types a caller holds"
    )]
    pub fn new() -> Element {
        Element::new(NodeKind::Box)
            .display(meo_canvas_scene::style::layout::Display::Grid)
    }
}

/// A run of text.
#[derive(Debug)]
#[non_exhaustive]
pub struct Text;

impl Text {
    /// Text with the given content.
    ///
    /// The content is a constructor argument rather than a setter, so it cannot
    /// be forgotten — a `Text` with no text is not a thing worth being able to
    /// write.
    ///
    /// The string is markup, not a literal: escape sequences and the five
    /// styling tags are resolved by [`meo_canvas_core::markup::parse`], the
    /// parser the JavaScript surface's `Text()` runs, so one string gives rich
    /// text on both.
    ///
    /// ```
    /// use meo_canvas::{Style, Text};
    ///
    /// let name = Text::new("Ukasyah").with_style(Style::new().font_size(24.0));
    /// let mixed = Text::new("plain <b>bold</b>");
    /// ```
    ///
    /// Use [`Text::rich`] for content that must not be interpreted, or that
    /// carries styles the five tags cannot name.
    ///
    /// # What it could not use
    ///
    /// **The markup is not parsed here.** This constructor stores the string
    /// and [`Element::into_scene`] parses it during the walk, which is the
    /// first point that has both the markup and somewhere to put what it
    /// could not use -- a constructor returns an `Element` and has nowhere.
    ///
    /// So a tag this parser does not know, or a value it cannot read, is
    /// reported by the call that builds the scene rather than by this one:
    ///
    /// ```
    /// use meo_canvas::{Element, Text};
    ///
    /// let (_scene, found) = Text::new("<nope>a</nope> b")
    ///     .into_scene(100.0, 20.0)
    ///     .unwrap_or_else(|error| unreachable!("{error}"));
    ///
    /// assert_eq!(found.len(), 1);
    /// assert_eq!(found[0].path, "<nope>");
    /// ```
    ///
    /// Without that, `<nope>a</nope> b` renders exactly as `a b` does and
    /// nothing in the output can tell a caller their tag did nothing.
    #[must_use]
    #[expect(
        clippy::new_ret_no_self,
        reason = "the node types are constructors for `Element`, not types a caller holds"
    )]
    pub fn new(content: impl Into<String>) -> Element {
        Element {
            kind: ElementKind::Markup {
                content: content.into(),
                paragraph: ParagraphStyle::default(),
            },
            style: Style::new(),
            children: Vec::new(),
            name: None,
        }
    }

    /// Text made of runs that differ in style, given directly.
    ///
    /// Each segment's own style overrides the node's for that run. Nothing here
    /// is parsed, which is what makes this the way to write content containing
    /// a literal `<` — [`Text::new`] would read it as markup — and the way to
    /// give a run a style the five markup tags cannot name.
    #[must_use]
    pub fn rich(
        segments: impl IntoIterator<Item = (String, Style)>,
    ) -> Element {
        let segments = segments
            .into_iter()
            .map(|(text, style)| {
                let (_, _, text_style, _) = style.into_parts();
                TextSegment {
                    text,
                    style: text_style,
                }
            })
            .collect();
        Element::new(NodeKind::Text {
            segments,
            paragraph: ParagraphStyle::default(),
        })
    }
}

/// A raster image.
#[derive(Debug)]
#[non_exhaustive]
pub struct Image;

impl Image {
    /// An image read from a local path.
    ///
    /// ```
    /// use meo_canvas::{Image, Style, px};
    ///
    /// let avatar = Image::path("avatar.png")
    ///     .with_style(Style::new().size(px(64.0), px(64.0)));
    /// ```
    #[must_use]
    pub fn path(path: impl Into<String>) -> Element {
        Self::source(ImageSource::Path(path.into()))
    }

    /// An image from bytes the caller already holds.
    #[must_use]
    pub fn bytes(bytes: impl Into<Vec<u8>>) -> Element {
        Self::source(ImageSource::Bytes(bytes.into()))
    }

    /// An image from a URL, fetched with no options.
    ///
    /// Whether it is fetched at all is a build-time decision: without the
    /// `net` feature this crate forwards, a scene carrying one of these
    /// reaches `meo-canvas-core` as
    /// [`Error::UnresolvedSource`](crate::Error::UnresolvedSource), and no HTTP
    /// stack is linked. [`Image::url_with`] is the same source carrying
    /// headers.
    #[must_use]
    pub fn url(url: impl Into<String>) -> Element {
        Self::source(ImageSource::url(url))
    }

    /// An image from a URL, with headers on the request that fetches it.
    ///
    /// The options belong to the source rather than to this node, so the same
    /// spelling reaches a background image and a mask through
    /// [`ImageSource::url_with`]. A node-level field would have given those
    /// two no way to say it.
    ///
    /// ```
    /// use meo_canvas::{Image, scene::HttpOptions};
    ///
    /// let logo = Image::url_with(
    ///     "https://example.invalid/private.png",
    ///     HttpOptions::new().header("authorization", "Bearer t"),
    /// );
    /// ```
    #[must_use]
    pub fn url_with(url: impl Into<String>, http: HttpOptions) -> Element {
        Self::source(ImageSource::url_with(url, http))
    }

    /// An image from a source already in hand.
    #[must_use]
    pub const fn source(source: ImageSource) -> Element {
        Element::new(NodeKind::Image {
            source,
            fit: ObjectFit::Fill,
            position: (Length::Percent(0.5), Length::Percent(0.5)),
            frame: None,
        })
    }
}

/// An arbitrary shape from SVG path data.
///
/// # Importing this shadows `std::path::Path`
///
/// The same collision as [`Box`], and a likelier one: **both spell their
/// constructor `Path::new`**, so a file that draws a shape and opens a font
/// file has two `Path::new` calls meaning different things, and the compiler
/// reports the second as a type error rather than as a name clash.
///
/// The fix is the same and so is the reason: spell the standard library's in
/// full where you need it, and leave the component called `Path`.
///
/// ```
/// use meo_canvas::Path;
///
/// let arrow = Path::d("M0 0 L10 5 L0 10 Z");
/// let font = std::path::Path::new("/usr/share/fonts/Inter.ttf");
/// # let _ = (arrow, font);
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct Path;

/// Properties that belong to one node kind rather than to every node.
///
/// These sit on [`Element`] beside the flat style setters, but they are not
/// style: `max_lines` describes a paragraph and `stroke` describes a path, and
/// neither inherits or means anything on a node of another kind. The scene
/// holds them in the node's [`NodeKind`] for that reason, and these write
/// there.
///
/// **A setter for the wrong kind is ignored**, as CSS ignores a property an
/// element does not define. A `max_lines` on a `Box` is a caller saying
/// something about a paragraph that is not there, and the alternatives are
/// worse: a panic makes a typo fatal, and a `Result` puts error handling on
/// every line of a builder chain.
impl Element {
    /// How many lines a paragraph draws before it is truncated.
    ///
    /// ```
    /// use meo_canvas::Text;
    ///
    /// let excerpt = Text::new("a long paragraph").max_lines(2).ellipsis("…");
    /// ```
    #[must_use]
    pub const fn max_lines(mut self, lines: u32) -> Self {
        if let Some(paragraph) = self.paragraph_mut() {
            paragraph.max_lines = Some(lines);
        }
        self
    }

    /// What a truncated last line ends with.
    ///
    /// Only drawn when [`Element::max_lines`] truncates something. Unset
    /// truncates without a marker, and so does an empty one.
    ///
    /// [`DEFAULT_ELLIPSIS`](crate::scene::DEFAULT_ELLIPSIS) is the marker CSS
    /// uses, so a caller who wants the ordinary one need not know the code
    /// point. It is what the JavaScript surface's `ellipsis: true` resolves to.
    ///
    /// ```
    /// use meo_canvas::{Text, scene::DEFAULT_ELLIPSIS};
    ///
    /// let excerpt = Text::new("a long paragraph")
    ///     .max_lines(2)
    ///     .ellipsis(DEFAULT_ELLIPSIS);
    /// ```
    #[must_use]
    pub fn ellipsis(mut self, marker: impl Into<String>) -> Self {
        if let Some(paragraph) = self.paragraph_mut() {
            paragraph.ellipsis = Some(marker.into());
        }
        self
    }

    /// How a path's interior is painted. `None` leaves it unfilled.
    ///
    /// ```
    /// use meo_canvas::{ColorValue, Path, hex_rgb, scene::PathPaint};
    ///
    /// let tick = Path::d("M2 8 L6 12 L14 3")
    ///     .fill(None)
    ///     .stroke(Some(PathPaint::Solid(hex_rgb(0x22_cc_66).into())))
    ///     .line_width(2.0);
    /// // In the text colour, as an SVG `stroke="currentColor"` is.
    /// let inked = Path::d("M2 8 L6 12 L14 3")
    ///     .fill(None)
    ///     .stroke(Some(PathPaint::Solid(ColorValue::Current)));
    /// ```
    #[must_use]
    pub fn fill(mut self, paint: Option<PathPaint>) -> Self {
        if let ElementKind::Node(NodeKind::Path { fill, .. }) = &mut self.kind {
            *fill = paint;
        }
        self
    }

    /// The coordinate space this path's `d` is written in, as SVG's
    /// `viewBox`: `(min_x, min_y, width, height)`.
    ///
    /// The drawing is scaled into the node's content box, inside its padding
    /// and border and at its size before rounding, as Chrome maps an
    /// `<svg>`'s `viewBox`. **The node must have a size**, since a path node
    /// has no intrinsic one. Without a box the `d` is absolute.
    ///
    /// ```
    /// use meo_canvas::Path;
    ///
    /// // A unit square that fills whatever box it is given.
    /// let square =
    ///     Path::d("M0 0 H10 V10 H0 Z").view_box(Some((0.0, 0.0, 10.0, 10.0)));
    /// ```
    #[must_use]
    pub const fn view_box(
        mut self,
        view: Option<(f32, f32, f32, f32)>,
    ) -> Self {
        if let ElementKind::Node(NodeKind::Path { view_box, .. }) =
            &mut self.kind
        {
            *view_box = view;
        }
        self
    }

    /// Whether a path with a `view_box` may be stretched to fill its node.
    ///
    /// SVG's `preserveAspectRatio`, and only its `none` value: `false` is the
    /// default `xMidYMid meet`, which fits the drawing without distorting it,
    /// and `true` scales each axis independently so it fills the node exactly.
    ///
    /// **It does not distort the pen**, for the reason
    /// [`view_box`](Self::view_box) gives -- so a circle authored in a
    /// stretched box comes out an ellipse while its stroke stays even.
    ///
    /// ```
    /// use meo_canvas::Path;
    ///
    /// // A line plot fills its box rather than being letterboxed into it.
    /// let plot = Path::d("M 0 100 L 100 0")
    ///     .view_box(Some((0.0, 0.0, 100.0, 100.0)))
    ///     .stretch(true);
    /// ```
    #[must_use]
    pub const fn stretch(mut self, stretched: bool) -> Self {
        if let ElementKind::Node(NodeKind::Path { stretch, .. }) =
            &mut self.kind
        {
            *stretch = stretched;
        }
        self
    }

    /// How a path's outline is painted. `None` leaves it unstroked.
    #[must_use]
    pub fn stroke(mut self, paint: Option<PathPaint>) -> Self {
        if let ElementKind::Node(NodeKind::Path { stroke, .. }) = &mut self.kind
        {
            *stroke = paint;
        }
        self
    }

    /// How wide a path's stroke is drawn, in logical pixels.
    #[must_use]
    pub const fn line_width(mut self, width: f32) -> Self {
        if let ElementKind::Node(NodeKind::Path { line_width, .. }) =
            &mut self.kind
        {
            *line_width = width;
        }
        self
    }

    /// Which side of a path's winding counts as inside.
    #[must_use]
    pub const fn fill_rule(mut self, rule: FillRule) -> Self {
        if let ElementKind::Node(NodeKind::Path { fill_rule, .. }) =
            &mut self.kind
        {
            *fill_rule = rule;
        }
        self
    }

    /// How a path's stroke ends are drawn.
    #[must_use]
    pub const fn line_cap(mut self, cap: LineCap) -> Self {
        if let ElementKind::Node(NodeKind::Path { line_cap, .. }) =
            &mut self.kind
        {
            *line_cap = cap;
        }
        self
    }

    /// How a path's stroke corners are drawn.
    #[must_use]
    pub const fn line_join(mut self, join: LineJoin) -> Self {
        if let ElementKind::Node(NodeKind::Path { line_join, .. }) =
            &mut self.kind
        {
            *line_join = join;
        }
        self
    }

    /// Alternating dash and gap lengths. Empty draws a solid line.
    #[must_use]
    pub fn line_dash(mut self, pattern: impl IntoIterator<Item = f32>) -> Self {
        if let ElementKind::Node(NodeKind::Path { line_dash, .. }) =
            &mut self.kind
        {
            *line_dash = pattern.into_iter().collect();
        }
        self
    }

    /// How far into the dash pattern the stroke begins.
    #[must_use]
    pub const fn line_dash_offset(mut self, offset: f32) -> Self {
        if let ElementKind::Node(NodeKind::Path {
            line_dash_offset, ..
        }) = &mut self.kind
        {
            *line_dash_offset = offset;
        }
        self
    }
}

impl Path {
    /// A path from an SVG `d` attribute.
    ///
    /// ```
    /// use meo_canvas::Path;
    ///
    /// let tick = Path::d("M2 8 L6 12 L14 3");
    /// ```
    #[must_use]
    pub fn d(data: impl Into<String>) -> Element {
        Element::new(NodeKind::Path {
            data: data.into(),
            // Absolute coordinates unless a caller asks otherwise, which is
            // what `d` alone has always meant.
            view_box: None,
            stretch: false,
            fill: Some(PathPaint::Solid(ColorValue::Rgba(Color::BLACK))),
            stroke: None,
            line_width: 1.0,
            fill_rule: FillRule::NonZero,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            line_dash: Vec::new(),
            line_dash_offset: 0.0,
        })
    }
}

#[cfg(test)]
mod tests {
    use meo_canvas_scene::{
        SceneError,
        node::{ImageSource, LineCap, LineJoin, NodeKind, PathPaint},
        style::{
            PaintOrder,
            effect::{FillRule, Mask, MaskShape},
            layout::{
                Align, BoxSizing, Direction, Display, FlexDirection, FlexWrap,
                GridAutoFlow, Justify, JustifyItems, JustifySelf,
                LegacyPosition, Overflow, OverflowPosition, PositionType,
                SelfPosition,
            },
            paint::{
                BackgroundImage, BackgroundRepeat, BlendMode, BorderStyle,
                Color, ColorValue, Gradient, GradientGeometry, ObjectFit,
            },
            text::{
                FontStyle, LineHeight, ParagraphStyle, TextAlign,
                TextDecoration, TextStroke, VerticalAlign,
            },
        },
    };

    use super::{
        Box, Column, Element, ElementKind, Grid, Image, Path, Row, Text,
    };
    use crate::{Style, Styled, hex_rgb, pct, px};

    #[test]
    fn a_paragraph_setter_writes_the_node_and_not_the_style() {
        let ElementKind::Markup { paragraph, .. } =
            Text::new("x").max_lines(2).ellipsis("…").kind
        else {
            unreachable!("Text::new builds a text node");
        };
        assert_eq!(paragraph.max_lines, Some(2));
        assert_eq!(paragraph.ellipsis.as_deref(), Some("…"));
    }

    #[test]
    fn a_path_setter_writes_every_part_of_the_payload() {
        let ElementKind::Node(NodeKind::Path {
            fill,
            stroke,
            line_width,
            fill_rule,
            line_cap,
            line_join,
            line_dash,
            line_dash_offset,
            ..
        }) = Path::d("M0 0 L4 4")
            .fill(None)
            .stroke(Some(PathPaint::Solid(Color::rgba(5, 6, 7, 8).into())))
            .line_width(2.5)
            .fill_rule(FillRule::EvenOdd)
            .line_cap(LineCap::Round)
            .line_join(LineJoin::Bevel)
            .line_dash([1.0, 2.0])
            .line_dash_offset(0.5)
            .kind
        else {
            unreachable!("Path::d builds a path node");
        };
        assert_eq!(fill, None);
        assert_eq!(
            stroke,
            Some(PathPaint::Solid(Color::rgba(5, 6, 7, 8).into()))
        );
        assert!((line_width - 2.5).abs() < f32::EPSILON);
        assert_eq!(fill_rule, FillRule::EvenOdd);
        assert_eq!(line_cap, LineCap::Round);
        assert_eq!(line_join, LineJoin::Bevel);
        assert_eq!(line_dash, vec![1.0, 2.0]);
        assert!((line_dash_offset - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn a_setter_for_the_wrong_kind_is_ignored() {
        // As CSS ignores a property an element does not define. The
        // alternatives are worse: a panic makes a typo fatal, and a `Result`
        // puts error handling on every line of a builder chain.
        let box_node = Box::new().max_lines(2).ellipsis("…").line_width(9.0);
        assert_eq!(box_node.kind, ElementKind::Node(NodeKind::Box));

        // And a path setter on a text node leaves the paragraph alone.
        let ElementKind::Markup { paragraph, .. } =
            Text::new("x").line_width(9.0).kind
        else {
            unreachable!("Text::new builds a text node");
        };
        assert_eq!(paragraph, ParagraphStyle::default());
    }

    /// The runs a text element produces, read from the scene it builds rather
    /// than off `.kind`: the markup is parsed during the walk, so the
    /// constructor holds only the string.
    fn runs_of(
        element: Element,
    ) -> Vec<meo_canvas_scene::style::text::TextSegment> {
        let (scene, _) = element
            .into_scene(100.0, 40.0)
            .unwrap_or_else(|error| unreachable!("{error}"));
        let root = scene
            .get(scene.pages[0])
            .unwrap_or_else(|| unreachable!("the page has a root"));
        match &root.kind {
            NodeKind::Text { segments, .. } => segments.clone(),
            other => unreachable!("expected text, found {other:?}"),
        }
    }

    #[test]
    fn text_new_reads_its_string_as_markup() {
        // The parser lives in `meo-canvas-core`, below every surface, so a
        // Rust caller gets a bold run where a literal `<b>` would otherwise
        // reach the glyphs.
        let segments = runs_of(Text::new("plain <b>bold</b>"));
        let texts: Vec<&str> =
            segments.iter().map(|s| s.text.as_str()).collect();
        assert_eq!(texts, vec!["plain ", "bold"]);
        assert!(segments[1].style.font_weight.is_some());
        assert!(segments[0].style.font_weight.is_none());
    }

    #[test]
    fn text_rich_reads_nothing_so_a_literal_angle_bracket_survives() {
        let segments =
            runs_of(Text::rich([("a <b> b".to_owned(), Style::new())]));
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].text, "a <b> b");
    }

    #[test]
    fn text_that_says_nothing_is_still_a_paragraph() {
        // A string of nothing but tags parses to no runs. The node still has
        // to be a paragraph, so one empty run stands in for it.
        let segments = runs_of(Text::new("<b></b>"));
        assert_eq!(segments.len(), 1);
        assert!(segments[0].text.is_empty());
    }

    #[test]
    fn the_root_element_styles_the_page_rather_than_becoming_a_child_of_it() {
        // Otherwise every tree gains a wrapper nobody asked for, and a caller's
        // `background_color` paints a box inside the canvas instead of the
        // canvas.
        let scene = Box::new()
            .with_style(
                Style::new().background_color(hex_rgb(0x10_10_14).into()),
            )
            .into_scene(100.0, 50.0)
            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);

        assert_eq!(scene.nodes.len(), 1);
        assert_eq!(scene.size.width.to_bits(), 100.0_f32.to_bits());
        assert_eq!(scene.size.height.to_bits(), 50.0_f32.to_bits());
        let root = scene
            .get(scene.pages[0])
            .unwrap_or_else(|| unreachable!("the page has a root"));
        assert_eq!(root.paint.background_color, hex_rgb(0x10_10_14).into());
    }

    #[test]
    fn a_canvas_size_that_is_not_a_length_is_refused() {
        // A `NaN`, negative or infinite size is refused rather than passing
        // `validate` to the renderer. The signature refuses `pct(50.0)` (a
        // `compile_fail` doctest); these are the numbers a type cannot see.
        for (width, height) in [
            (f32::NAN, 10.0),
            (10.0, f32::NAN),
            (-1.0, 10.0),
            (10.0, -1.0),
            (f32::INFINITY, 10.0),
            (10.0, f32::NEG_INFINITY),
        ] {
            let refused = Box::new().into_scene(width, height);
            assert!(
                matches!(refused, Err(SceneError::CanvasSize { .. })),
                "{width} by {height} was accepted"
            );
        }

        // **Zero is not in that list and must not be.** An empty canvas is a
        // canvas with nothing on it, which the encoders already answer for; a
        // rule that refused it would be a new refusal wearing a bug fix.
        assert!(Box::new().into_scene(0.0, 0.0).is_ok());
    }

    #[test]
    fn the_nested_tree_flattens_into_the_arena_in_order() {
        let scene = Column::new()
            .children([
                Text::new("one"),
                Row::new().children([Text::new("two"), Text::new("three")]),
            ])
            .into_scene(10.0, 10.0)
            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);

        // Root, "one", the row, "two", "three".
        assert_eq!(scene.nodes.len(), 5);
        assert!(scene.validate().is_ok(), "a built tree is a valid scene");
    }

    #[test]
    fn the_container_constructors_set_the_direction_they_name() {
        let (row, ..) = Row::new().style.into_parts();
        assert_eq!(row.flex_direction, FlexDirection::Row);

        let (column, ..) = Column::new().style.into_parts();
        assert_eq!(column.flex_direction, FlexDirection::Column);

        let (grid, ..) = Grid::new().style.into_parts();
        assert_eq!(grid.display, Display::Grid);
    }

    #[test]
    fn a_style_merges_rather_than_replaces() {
        // What the argument names wins; what it leaves absent, the node keeps.
        // A replace discarded the first call's `gap` here, and discarded the
        // direction a constructor had just set, which is the defect this is.
        let element = Box::new()
            .with_style(Style::new().gap(px(4.0)))
            .with_style(Style::new().opacity(0.5));

        assert_eq!(element.style.gap, Some((px(4.0), px(4.0))));
        assert_eq!(element.style.opacity, Some(0.5));
    }

    #[test]
    fn a_constructor_property_the_style_does_not_name_survives_it() {
        // `Column::new()` is a box plus `flex-direction: column`, and a style
        // that says nothing about the direction must not turn it into a row.
        let column = Column::new().with_style(Style::new().width(pct(100.0)));

        assert_eq!(column.style.flex_direction, Some(FlexDirection::Column));
        assert!(column.style.width.is_some(), "the style still applied");
    }

    #[test]
    fn a_constructor_property_the_style_does_name_is_overridden() {
        // The control for the test above: merge is not "the constructor always
        // wins". A `Some` in the argument replaces what the node held, which is
        // what makes the merge a merge rather than a precedence rule.
        let row = Column::new()
            .with_style(Style::new().flex_direction(FlexDirection::Row));

        assert_eq!(row.style.flex_direction, Some(FlexDirection::Row));
    }

    #[test]
    fn a_none_in_the_style_leaves_what_the_node_already_had() {
        // Absent is not a value. A style that sets nothing changes nothing,
        // which is what lets `with_style` be applied to an already-styled node
        // without auditing all sixty-eight properties for what it will erase.
        let kept = Box::new().gap(px(12.0)).with_style(Style::new());

        assert_eq!(kept.style.gap, Some((px(12.0), px(12.0))));
    }

    #[test]
    fn merge_carries_every_property_it_is_given() {
        // No `..` in this literal: a new field fails to compile here, and one
        // dismissed in `merge` with `_` (rustc's suggested fix) comes back
        // `None` and fails the equality. Carried-or-dropped only: a pure
        // replace passes this too, and the direction tests above catch that.
        let full = Style {
            display: Some(Display::Flex),
            position_type: Some(PositionType::Absolute),
            position: Some(<_>::default()),
            width: Some(<_>::default()),
            height: Some(<_>::default()),
            min_width: Some(<_>::default()),
            min_height: Some(<_>::default()),
            max_width: Some(<_>::default()),
            max_height: Some(<_>::default()),
            aspect_ratio: Some(<_>::default()),
            margin: Some(<_>::default()),
            padding: Some(<_>::default()),
            border: Some(<_>::default()),
            flex_direction: Some(FlexDirection::Row),
            flex_wrap: Some(FlexWrap::NoWrap),
            flex_grow: Some(<_>::default()),
            flex_shrink: Some(<_>::default()),
            flex_basis: Some(<_>::default()),
            justify_content: Some(Justify::FlexStart),
            align_items: Some(Align::FlexStart),
            align_self: Some(Align::FlexStart),
            align_content: Some(Align::FlexStart),
            justify_items: Some(JustifyItems::Legacy(LegacyPosition::Right)),
            justify_self: Some(JustifySelf::Position {
                position: SelfPosition::SelfEnd,
                overflow: Some(OverflowPosition::Safe),
            }),
            gap: Some(<_>::default()),
            overflow: Some((Overflow::Visible, Overflow::Visible)),
            box_sizing: Some(BoxSizing::BorderBox),
            direction: Some(Direction::Ltr),
            grid_template_columns: Some(<_>::default()),
            grid_template_rows: Some(<_>::default()),
            grid_auto_rows: Some(<_>::default()),
            grid_auto_columns: Some(<_>::default()),
            grid_auto_flow: Some(GridAutoFlow::Row),
            grid_column: Some(<_>::default()),
            grid_row: Some(<_>::default()),
            background_color: Some(ColorValue::Current),
            gradient: Some(Gradient {
                geometry: GradientGeometry::Linear {
                    direction: <_>::default(),
                },
                stops: Vec::new(),
            }),
            background_image: Some(BackgroundImage {
                source: ImageSource::Path("a.png".to_owned()),
                repeat: BackgroundRepeat::Repeat,
                size: <_>::default(),
                position: <_>::default(),
            }),
            border_color: Some(<_>::default()),
            border_color_all: Some(ColorValue::Current),
            border_style: Some(BorderStyle::Solid),
            border_radius: Some(<_>::default()),
            opacity: Some(<_>::default()),
            mix_blend_mode: Some(BlendMode::Normal),
            dither: Some(<_>::default()),
            z_index: Some(<_>::default()),
            object_fit: Some(ObjectFit::Fill),
            object_position: Some(<_>::default()),
            frame: Some(<_>::default()),
            font_family: Some(<_>::default()),
            font_size: Some(<_>::default()),
            font_weight: Some(<_>::default()),
            font_style: Some(FontStyle::Normal),
            color: Some(ColorValue::Current),
            text_align: Some(TextAlign::Start),
            text_decoration: Some(TextDecoration::None),
            vertical_align: Some(VerticalAlign::Top),
            paint_order: Some(PaintOrder::Fill),
            line_height: Some(LineHeight::Number(1.5)),
            line_gap: Some(<_>::default()),
            font_variant: Some(<_>::default()),
            letter_spacing: Some(<_>::default()),
            word_spacing: Some(<_>::default()),
            text_stroke: Some(TextStroke {
                width: 1.0,
                color: ColorValue::Current,
            }),
            transform: Some(<_>::default()),
            box_shadows: Some(<_>::default()),
            text_shadows: Some(<_>::default()),
            mask: Some(Mask::Shape(MaskShape::Circle)),
            filter: Some(<_>::default()),
            backdrop_filter: Some(<_>::default()),
        };

        assert_eq!(Style::new().merge(full.clone()), full);

        // And through the node surface, which is where a caller meets it.
        assert_eq!(Box::new().with_style(full.clone()).style, full);
    }

    #[test]
    fn children_takes_anything_iterable() {
        let from_map =
            Row::new().children(super::each((0..3).map(|_| Text::new("x"))));
        assert_eq!(from_map.children.len(), 3);

        let from_vec = Row::new().children(vec![Text::new("x")]);
        assert_eq!(from_vec.children.len(), 1);
    }

    #[test]
    fn the_image_properties_reach_the_image_node_and_nothing_else() {
        let styled = Style::new().object_fit(ObjectFit::Cover).frame(-1);

        let image = Image::path("a.png").with_style(styled.clone());
        let scene = image
            .into_scene(10.0, 10.0)
            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
        let root = scene
            .get(scene.pages[0])
            .unwrap_or_else(|| unreachable!("the page has a root"));

        match &root.kind {
            NodeKind::Image { fit, frame, .. } => {
                assert_eq!(*fit, ObjectFit::Cover);
                assert_eq!(*frame, Some(-1));
            }
            other => unreachable!("expected an image, found {other:?}"),
        }

        // A node that is not an image ignores them, as CSS ignores a property
        // an element does not define.
        let boxed = Box::new().with_style(styled);
        let scene = boxed
            .into_scene(10.0, 10.0)
            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
        let root = scene
            .get(scene.pages[0])
            .unwrap_or_else(|| unreachable!("the page has a root"));
        assert_eq!(root.kind, NodeKind::Box);
    }

    #[test]
    fn each_image_source_is_carried_as_the_kind_it_is() {
        let cases = [
            (Image::path("a.png"), ImageSource::Path("a.png".to_owned())),
            (
                Image::url("https://example.invalid/a.png"),
                ImageSource::url("https://example.invalid/a.png"),
            ),
            (Image::bytes(vec![1, 2]), ImageSource::Bytes(vec![1, 2])),
        ];

        for (element, expected) in cases {
            match element.kind {
                ElementKind::Node(NodeKind::Image { source, .. }) => {
                    assert_eq!(source, expected);
                }
                other => unreachable!("expected an image, found {other:?}"),
            }
        }
    }

    #[test]
    fn text_carries_its_content_and_rich_text_carries_a_run_per_segment() {
        // Through the walk: `Text::new` stores the markup and the parse
        // happens in `into_scene`, so the runs exist only once a scene does.
        let segments = runs_of(Text::new("hello"));
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0].text, "hello");

        let rich = Text::rich([
            ("plain ".to_owned(), Style::new()),
            ("bold".to_owned(), Style::new().bold()),
        ]);
        match rich.kind {
            ElementKind::Node(NodeKind::Text { segments, .. }) => {
                assert_eq!(segments.len(), 2);
                assert!(segments[0].style.font_weight.is_none());
                assert!(segments[1].style.font_weight.is_some());
            }
            other => unreachable!("expected text, found {other:?}"),
        }
    }

    #[test]
    fn a_path_carries_its_data() {
        match Path::d("M0 0 L1 1").kind {
            ElementKind::Node(NodeKind::Path { data, .. }) => {
                assert_eq!(data, "M0 0 L1 1");
            }
            other => unreachable!("expected a path, found {other:?}"),
        }
    }

    #[test]
    fn the_canvas_takes_the_size_it_was_given() {
        // A canvas size is device-independent pixels. A percentage of nothing
        // has no meaning, and the parameter's type is what refuses one -- the
        // `compile_fail` example on `into_scene` is the check that it does.
        let scene = Box::new()
            .into_scene(120.0, 40.0)
            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);

        assert_eq!(scene.size.width.to_bits(), 120.0_f32.to_bits());
        assert_eq!(scene.size.height.to_bits(), 40.0_f32.to_bits());
    }

    #[test]
    fn an_element_can_be_built_from_a_kind_directly() {
        let element = Element::new(NodeKind::Box);
        assert_eq!(element.children.len(), 0);
        assert_eq!(element.style, Style::new());
    }
}