bern-ir 0.1.2

Versioned, platform-independent intermediate representation of Bern applications
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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
//! Bern's intermediate representation.
//!
//! The IR states cross-platform semantics only: no DOM, SwiftUI, GTK or
//! WinUI types appear here. Every target module consumes the same
//! [`Application`] and decides privately how to realize it.

pub mod spec;
pub mod style;

use bern_protocol::{LocalizedText, ProtocolDescriptor, Type, TypeTable, Value};

mod corners;
mod television;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Version of the IR layout. Targets declare the range they consume.
pub const IR_VERSION: u32 = 8;

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Application {
    pub ir_version: u32,
    pub app: AppInfo,
    pub languages: Languages,
    pub theme: Theme,
    /// The engine protocol the UI binds to.
    pub protocol: ProtocolDescriptor,
    /// Protocol types merged with UI-only value types.
    pub types: TypeTable,
    pub sessions: Vec<SessionDef>,
    pub windows: WindowCatalog,
    /// Media players owned by the application, shared by every window.
    pub players: Vec<PlayerDef>,
    pub components: Vec<ComponentDef>,
    /// Every localized text with its stable resource key.
    pub texts: Vec<LocalizedText>,
    /// Files shipped with the application, sorted by name.
    pub resources: Vec<ResourceDef>,
    /// Layout breakpoints from `[layouts]`, when the application declares
    /// them.
    pub layouts: Option<LayoutConfig>,
    /// Feature contracts with the coverage the compiler proved.
    pub contracts: Vec<FeatureContract>,
    /// Style overrides and motion tokens from `style!`.
    #[serde(default)]
    pub style: style::StyleSheet,
}

impl Application {
    /// Visit the nodes of every component and then of every window's
    /// content, depth first, each with the kind of the nearest element
    /// around it.
    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node, Option<&'a str>)) {
        for component in &self.components {
            component.body.walk_in(None, visit);
        }
        for window in &self.windows.windows {
            window.content.walk_in(None, visit);
        }
    }

    pub fn component(&self, name: &str) -> Option<&ComponentDef> {
        self.components
            .iter()
            .find(|component| component.name == name)
    }

    pub fn session(&self, name: &str) -> Option<&SessionDef> {
        self.sessions.iter().find(|session| session.name == name)
    }

    pub fn window(&self, id: &str) -> Option<&WindowDef> {
        self.windows.windows.iter().find(|window| window.id == id)
    }

    /// Whether any declaration plays media.
    pub fn uses_media(&self) -> bool {
        let mut uses = !self.players.is_empty();
        let mut visit = |node: &Node| {
            if let Node::Element(element) = node
                && element.kind == "Video"
            {
                uses = true;
            }
        };
        for component in &self.components {
            component.body.walk(&mut visit);
        }
        for window in &self.windows.windows {
            window.content.walk(&mut visit);
        }
        uses
    }
}

/// Breakpoints choosing between layout sizes, from `[layouts]`.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutConfig {
    /// Available width, in logical units, below which `compact` applies.
    pub compact_below: f64,
    /// Below which `medium` applies; without it there is no `medium`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub medium_below: Option<f64>,
    /// Below which `expanded` applies, and `large` from it; without it
    /// there is no `large`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expanded_below: Option<f64>,
}

impl LayoutConfig {
    /// The size for an available width: every width maps to exactly one.
    pub fn size(&self, width: f64) -> LayoutSize {
        if width < self.compact_below {
            LayoutSize::Compact
        } else if self.medium_below.is_some_and(|below| width < below) {
            LayoutSize::Medium
        } else if self.expanded_below.is_none_or(|below| width < below) {
            LayoutSize::Expanded
        } else {
            LayoutSize::Large
        }
    }

    /// Whether the breakpoints give `size` a range of widths.
    pub fn has(&self, size: LayoutSize) -> bool {
        match size {
            LayoutSize::Compact | LayoutSize::Expanded => true,
            LayoutSize::Medium => self.medium_below.is_some(),
            LayoutSize::Large => self.expanded_below.is_some(),
        }
    }
}

/// A layout size of `Adaptive`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LayoutSize {
    Compact,
    Medium,
    Expanded,
    Large,
}

impl LayoutSize {
    /// Every size, narrowest first.
    pub const ALL: [LayoutSize; 4] = [
        LayoutSize::Compact,
        LayoutSize::Medium,
        LayoutSize::Expanded,
        LayoutSize::Large,
    ];

    /// Sizes every `Adaptive` gives a layout of its own, and feature
    /// contracts are checked in; the others borrow one.
    pub const REQUIRED: [LayoutSize; 2] = [LayoutSize::Compact, LayoutSize::Expanded];

    pub fn name(self) -> &'static str {
        match self {
            LayoutSize::Compact => "compact",
            LayoutSize::Medium => "medium",
            LayoutSize::Expanded => "expanded",
            LayoutSize::Large => "large",
        }
    }

    /// The size whose layout this one shows when it has none of its own:
    /// the next larger declared size, else the next smaller.
    pub fn shown(self, declared: &[LayoutSize]) -> Option<LayoutSize> {
        if declared.contains(&self) {
            return Some(self);
        }
        let larger = Self::ALL.iter().copied().filter(|size| *size > self);
        let smaller = Self::ALL.iter().rev().copied().filter(|size| *size < self);
        larger.chain(smaller).find(|size| declared.contains(size))
    }

    pub fn parse(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|size| size.name() == name)
    }
}

/// A `#[bern::features]` contract: what users can do within the scope of
/// one component, and how each feature is reached in each layout size.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureContract {
    /// The features enum, for example `MediaFeature`.
    pub name: String,
    /// The component whose subtree is the contract's scope.
    pub component: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub doc: String,
    pub features: Vec<FeatureDef>,
    pub source: SourceLocation,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FeatureDef {
    /// The variant, for example `Clip`.
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub doc: String,
    /// Command ids implementing the feature: protocol commands such as
    /// `showcase.feature`, or standard media commands such as `media.play`.
    pub commands: Vec<String>,
    /// Sizes the feature applies to.
    pub layouts: Vec<LayoutSize>,
    /// A manual guarantee for coverage that cannot be proven statically.
    pub guaranteed: Option<String>,
    pub exemptions: Vec<Exemption>,
    /// What the compiler proved, per applicable size.
    pub coverage: Vec<SizeCoverage>,
    pub source: SourceLocation,
}

/// A platform on which a feature need not be reachable, with the reason.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Exemption {
    pub platform: String,
    pub reason: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SizeCoverage {
    pub size: LayoutSize,
    pub coverage: Coverage,
}

/// Entries found for a feature in one size, by control target.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Coverage {
    /// At least one entry is present whatever the state.
    Covered {
        entries: Vec<String>,
    },
    /// Entries exist only under conditions the framework cannot prove.
    Conditional {
        entries: Vec<String>,
    },
    Missing,
}

/// The outcome for one feature in one size on one platform.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum FeatureResult {
    Covered {
        entries: Vec<String>,
    },
    /// Only conditional entries, accepted by a manual guarantee; not proven.
    Guaranteed {
        entries: Vec<String>,
        reason: String,
    },
    /// Not reachable, and exempt on this platform.
    Exempt {
        reason: String,
    },
    Missing,
    /// Only conditional entries and no guarantee.
    Unproven {
        entries: Vec<String>,
    },
}

impl FeatureResult {
    /// Whether the result fails a strict build.
    pub fn is_error(&self) -> bool {
        matches!(
            self,
            FeatureResult::Missing | FeatureResult::Unproven { .. }
        )
    }
}

impl FeatureDef {
    /// The results on `platform`, per applicable size.
    pub fn results(&self, platform: &str) -> Vec<(LayoutSize, FeatureResult)> {
        let exemption = self
            .exemptions
            .iter()
            .find(|exemption| exemption.platform == platform);
        self.coverage
            .iter()
            .map(|SizeCoverage { size, coverage }| {
                let result = match (coverage, exemption, &self.guaranteed) {
                    (Coverage::Covered { entries }, _, _) => FeatureResult::Covered {
                        entries: entries.clone(),
                    },
                    (_, Some(exemption), _) => FeatureResult::Exempt {
                        reason: exemption.reason.clone(),
                    },
                    (Coverage::Conditional { entries }, None, Some(reason)) => {
                        FeatureResult::Guaranteed {
                            entries: entries.clone(),
                            reason: reason.clone(),
                        }
                    }
                    (Coverage::Conditional { entries }, None, None) => FeatureResult::Unproven {
                        entries: entries.clone(),
                    },
                    (Coverage::Missing, None, _) => FeatureResult::Missing,
                };
                (*size, result)
            })
            .collect()
    }
}

/// A file the application ships with its build, declared in the
/// `[resources]` table of `Bern.toml`. Engines resolve it by name at run
/// time; each target decides where it lives in the product. Neither the
/// contents nor a build machine path are part of the IR.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceDef {
    /// The file's `/`-separated path relative to `Bern.toml`, for example
    /// `media/aurora.mp4`.
    pub name: String,
    /// The `[resources]` entry that declared the file.
    pub declared: SourceLocation,
    /// How an SVG document shows as a picture of it, with no document
    /// engine; `None` for one that moves or runs, and for other files.
    #[serde(default)]
    pub picture: Option<SvgPicture>,
}

/// How an SVG document shows as a picture of it (`bern_svg::picture`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SvgPicture {
    /// In its own colors.
    Still,
    /// In the color of the text around it, as a template.
    Tinted,
    /// In colors of its own for the light and for the dark appearance: a
    /// picture of each.
    Themed,
}

/// An application player from the `#[bern::players]` catalog. Its id is
/// the stable `player_id` every entry uses.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlayerDef {
    pub id: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub doc: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppInfo {
    pub id: String,
    pub bundle_id: String,
    pub name: LocalizedText,
    pub version: String,
    /// The application icon from `[app].icon`: a square PNG's
    /// `/`-separated path relative to `Bern.toml`. Without one, targets use
    /// the Bern logo.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    /// Platform name to the icon that platform uses instead, from
    /// `[app.icon]`: a square PNG, or a file or folder in the platform's own
    /// form, as a `/`-separated path relative to `Bern.toml`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub platform_icons: BTreeMap<String, String>,
    /// Icons the application can switch to at run time, from
    /// `[app.alternate_icons.<name>]`: name to its entries, each as
    /// `[app.icon]` has them (`default` and platform names, `/`-separated
    /// paths relative to `Bern.toml`). `WindowSet(icon:)` chooses one.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub alternate_icons: BTreeMap<String, BTreeMap<String, String>>,
    /// Who publishes the application, from `[app].publisher`: shown by
    /// installers and package managers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<String>,
    /// `[app].files_folder`: on iOS the application's Documents folder shows
    /// in the Files app, for files the user puts there for it.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub files_folder: bool,
    /// `[app].background_audio`: the application's own audio plays on
    /// behind the lock screen and in the background (iOS's audio background
    /// mode).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub background_audio: bool,
    /// `[app].overlays`: the application draws text over other apps
    /// (`bern::overlay`), which Android asks the user to allow.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub overlays: bool,
    /// `[app].photos`: the application saves pictures to the user's photos
    /// (`bern::platform::save_image`), which iOS asks the user to allow.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub photos: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Languages {
    pub supported: Vec<String>,
    pub default: String,
    pub strict: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThemeMode {
    System,
    Light,
    Dark,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Srgb {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

impl Srgb {
    pub fn parse(hex: &str) -> Option<Self> {
        let hex = hex.strip_prefix('#')?;
        if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
        let byte = |index: usize| u8::from_str_radix(&hex[index..index + 2], 16).ok();
        Some(Self {
            red: byte(0)?,
            green: byte(2)?,
            blue: byte(4)?,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Theme {
    pub mode: ThemeMode,
    /// Optional brand color. Native targets map it to their accent color
    /// interface; algorithm targets seed the Bern palette with it.
    pub brand_seed: Option<Srgb>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SessionFieldDef {
    pub name: String,
    #[serde(rename = "type")]
    pub ty: Type,
    pub initial: Value,
}

/// Typed drafts owned by a UI session, one instance per hosting window.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SessionDef {
    pub name: String,
    pub fields: Vec<SessionFieldDef>,
}

impl SessionDef {
    pub fn field_index(&self, name: &str) -> Option<usize> {
        self.fields.iter().position(|field| field.name == name)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WindowInitial {
    Open,
    Closed,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Presentation {
    /// Native where the target has system windows, otherwise the host's
    /// virtual presentation (on the web: the page, or a dialog).
    Auto,
    /// The host's in-app presentation, even where native windows exist.
    Virtual,
    /// A draggable, resizable window: a native window, or a floating panel
    /// inside the page.
    Floating,
    NativeRequired,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WindowRole {
    Standard,
    /// Application preferences window.
    Settings,
    /// A modal window over the primary window, such as a first-run flow:
    /// a sheet where the platform has them.
    Dialog,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WindowDef {
    pub id: String,
    pub title: LocalizedText,
    pub initial: WindowInitial,
    pub presentation: Presentation,
    pub role: WindowRole,
    pub width: Option<f64>,
    pub height: Option<f64>,
    pub min_width: Option<f64>,
    pub min_height: Option<f64>,
    pub content: Node,
    /// Session state types instantiated for each instance of this window.
    pub sessions: Vec<String>,
    /// Declared close check, run whenever closing is requested.
    pub close: Option<CloseCheck>,
    /// Whether content extends under a transparent title bar.
    #[serde(default)]
    pub chrome: WindowChrome,
    /// While true, the window hides its title bar and toolbar (and on
    /// touch platforms the status bar), and the pointer once it rests.
    #[serde(default)]
    pub immersive: Option<Expr>,
    /// Seconds without input after which `window.idle` turns true.
    #[serde(default)]
    pub idle_after: Option<f64>,
    /// Pause the idle timer while interacting with persistent controls.
    #[serde(default)]
    pub idle_enabled: Option<Expr>,
    /// On a phone, the window stands in landscape while this is true and
    /// in portrait otherwise; elsewhere it follows the device.
    #[serde(default)]
    pub landscape: Option<Expr>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WindowChrome {
    /// The platform's title bar.
    #[default]
    Standard,
    /// Content under a transparent title bar, the system window controls
    /// over it.
    Unified,
}

/// The close check of a window. When `when` holds, closing waits for a
/// decision: Save (running `save`), Discard or Cancel. The expressions are
/// evaluated against the closing window's own session drafts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloseCheck {
    pub when: Expr,
    pub message: Text,
    /// Engine command a Save decision runs; closing waits for its result.
    pub save: Option<Action>,
}

/// Static window kinds declared by the root `WindowSet`. The first version
/// supports single-instance windows only.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WindowCatalog {
    pub handle: String,
    pub primary: String,
    pub windows: Vec<WindowDef>,
    /// The accent every window shows: an enum whose variants name accents
    /// of `style!`.
    #[serde(default)]
    pub accent: Option<Expr>,
    /// Optional JSON map of semantic roles to light/dark #RRGGBB pairs.
    /// The application supplies a complete, contrast-checked palette.
    #[serde(default)]
    pub palette: Option<Expr>,
    /// The appearance every window shows: an enum of `System`, `Light`
    /// and `Dark`.
    #[serde(default)]
    pub appearance: Option<Expr>,
    /// The application icon the system shows: an enum whose `Default`
    /// variant is `[app.icon]` and whose other variants name icons of
    /// `[app.alternate_icons]` (`DarkSkin` names `dark_skin`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<Expr>,
    /// The `MenuBar`: its `CommandMenu`s, their `CommandItem`s, dividers
    /// and submenus, whose drafts are the primary window's. Only a target
    /// with a system menu bar shows it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub menu_bar: Option<Element>,
    /// The `StatusItem`: the application's item in the system's status
    /// area and the `CommandItem`s, dividers and submenus of its menu, which
    /// run without a window. Only a target with a status area shows it; with
    /// it, closing the last window leaves the application running.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status_item: Option<Element>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceLocation {
    pub file: String,
    pub line: u32,
    pub column: u32,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ParamKind {
    /// The typed engine client of the application protocol (its namespace)
    /// or of one of its modules.
    Client { namespace: String },
    /// The generated window handle.
    Windows,
    /// The application's player catalog.
    Players,
    /// A value of a schema type, read-only inside the component.
    Value {
        #[serde(rename = "type")]
        ty: Type,
    },
    /// Session state owned by the hosting window.
    Session { session: String },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParamDef {
    pub name: String,
    pub kind: ParamKind,
    /// `#[content]`: text the component shows as data, so callers pass
    /// data and never a literal.
    #[serde(default, skip_serializing_if = "is_false")]
    pub content: bool,
}

fn is_false(value: &bool) -> bool {
    !value
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComponentDef {
    pub name: String,
    pub module: Vec<String>,
    pub params: Vec<ParamDef>,
    pub body: Node,
    pub source: SourceLocation,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BinaryOp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    And,
    Or,
}

/// Where a binding reads from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "scope", rename_all = "snake_case")]
pub enum Binding {
    /// Engine state field, then record field indices.
    Engine { field: usize, path: Vec<usize> },
    /// Session state of the hosting window.
    Session {
        session: String,
        field: usize,
        path: Vec<usize>,
    },
    /// Template variable, pattern binding or component parameter, with the
    /// type of the variable itself so record paths can be resolved.
    Local {
        name: String,
        path: Vec<usize>,
        root: Type,
    },
    /// UI state of the hosting window, such as `window.idle`.
    Window { field: String },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ExprKind {
    Literal {
        value: Value,
    },
    Binding {
        binding: Binding,
    },
    Variant {
        variant: u32,
        fields: Vec<Expr>,
    },
    Not {
        expr: Box<Expr>,
    },
    Neg {
        expr: Box<Expr>,
    },
    Binary {
        op: BinaryOp,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    },
    /// One of two values of the expression's type.
    If {
        cond: Box<Expr>,
        then: Box<Expr>,
        otherwise: Box<Expr>,
    },
    /// A named corner radius of `style!` (`corner { card: 22 }`), a float.
    /// `radius` is its value on every platform; [`Application::on_platform`]
    /// puts the platform's value in its place before a target generates.
    Corner {
        name: String,
        radius: f64,
    },
}

/// A type-checked restricted expression.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Expr {
    pub kind: ExprKind,
    #[serde(rename = "type")]
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Text {
    /// Declared translations, with typed interpolation arguments.
    Localized {
        text: LocalizedText,
        args: Vec<(String, Expr)>,
    },
    /// Runtime data such as user input or media titles.
    Dynamic { expr: Expr },
}

/// A writable session field bound to a control.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldRef {
    pub session: String,
    pub field: usize,
    #[serde(rename = "type")]
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Prop {
    Keyword {
        value: String,
    },
    Number {
        value: f64,
    },
    Icon {
        name: String,
    },
    /// A declared resource, by its name in `[resources]`.
    Resource {
        name: String,
    },
    Text {
        text: Text,
    },
    Expr {
        expr: Expr,
    },
    Field {
        field: FieldRef,
    },
    Window {
        id: String,
    },
    TypeName {
        name: String,
    },
    Key {
        field: usize,
        name: String,
    },
    Id {
        value: String,
    },
    /// An application player.
    Player {
        id: String,
    },
    /// A typed query call whose result feeds the element's template.
    Query {
        query: QueryBinding,
    },
    /// The feature of the enclosing contract an entry reaches.
    Feature {
        contract: String,
        feature: String,
    },
}

/// A query of the engine catalog bound with its arguments. The arguments
/// are restricted expressions; when their values change, the target asks
/// again under a new parameter version and shows only the current answer.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryBinding {
    /// Catalog index of the query in the protocol.
    pub query: usize,
    pub args: Vec<Expr>,
    /// The query's declared result.
    pub result: Type,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WindowOp {
    ToggleFullscreen,
    Open,
    Close,
    Activate,
}

/// A standard media command on an application player.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MediaOp {
    Open,
    Play,
    Pause,
    Seek,
    SetVolume,
    SetMuted,
}

impl MediaOp {
    pub const ALL: [MediaOp; 6] = [
        MediaOp::Open,
        MediaOp::Play,
        MediaOp::Pause,
        MediaOp::Seek,
        MediaOp::SetVolume,
        MediaOp::SetMuted,
    ];

    /// Method name in declarations, for example `open`.
    pub fn method(self) -> &'static str {
        match self {
            MediaOp::Open => "open",
            MediaOp::Play => "play",
            MediaOp::Pause => "pause",
            MediaOp::Seek => "seek",
            MediaOp::SetVolume => "set_volume",
            MediaOp::SetMuted => "set_muted",
        }
    }

    /// Command id in the media catalog, for example `media.open`.
    pub fn command(self) -> &'static str {
        match self {
            MediaOp::Open => "media.open",
            MediaOp::Play => "media.play",
            MediaOp::Pause => "media.pause",
            MediaOp::Seek => "media.seek",
            MediaOp::SetVolume => "media.set_volume",
            MediaOp::SetMuted => "media.set_muted",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Action {
    /// Engine command by catalog index with positional arguments.
    Engine { command: usize, args: Vec<Expr> },
    /// Generated window session command.
    Window { op: WindowOp, window: String },
    /// Standard media command on an application player; the player id is
    /// the first parameter, `args` the rest.
    Media {
        player: String,
        op: MediaOp,
        args: Vec<Expr>,
    },
    /// A change of a session draft: interface state such as an open panel
    /// or a step of a flow, not engine state.
    Session { field: FieldRef, op: SessionOp },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SessionOp {
    /// `draft.field.set(value)`.
    Set { value: Expr },
    /// `draft.field.toggle()` on a `bool`.
    Toggle,
    /// `draft.field.push_str(text)` on a `String`: the text after it, as
    /// a key of an on-screen keyboard types.
    PushStr { value: Expr },
    /// `draft.field.pop()` on a `String`: without its last character, as
    /// a keyboard's delete.
    Pop,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Template {
    pub var: String,
    #[serde(rename = "type")]
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Element {
    /// Built-in component name from [`spec::COMPONENTS`].
    pub kind: String,
    /// Control identity for interactive components.
    pub id: Option<String>,
    /// Structural path inside the declaring component, stable for a build.
    pub path: String,
    pub props: BTreeMap<String, Prop>,
    pub template: Option<Template>,
    pub children: Vec<Node>,
    pub action: Option<Action>,
    pub source: SourceLocation,
}

impl Element {
    pub fn prop(&self, name: &str) -> Option<&Prop> {
        self.props.get(name)
    }

    /// The items of its `ContextMenu`, dividers among them, if it has one.
    pub fn context_menu(&self) -> Option<Vec<&Element>> {
        self.children.iter().find_map(|node| match node {
            Node::Element(menu) if menu.kind == "ContextMenu" => Some(
                menu.children
                    .iter()
                    .filter_map(|node| match node {
                        Node::Element(item) => Some(item),
                        _ => None,
                    })
                    .collect(),
            ),
            _ => None,
        })
    }

    /// Whether it has children to show besides a `ContextMenu`.
    pub fn has_content(&self) -> bool {
        self.children
            .iter()
            .any(|node| !matches!(node, Node::Element(menu) if menu.kind == "ContextMenu"))
    }

    pub fn keyword(&self, name: &str) -> Option<&str> {
        match self.props.get(name) {
            Some(Prop::Keyword { value }) => Some(value),
            _ => None,
        }
    }

    pub fn number(&self, name: &str) -> Option<f64> {
        match self.props.get(name) {
            Some(Prop::Number { value }) => Some(*value),
            _ => None,
        }
    }

    pub fn text(&self, name: &str) -> Option<&Text> {
        match self.props.get(name) {
            Some(Prop::Text { text }) => Some(text),
            _ => None,
        }
    }

    pub fn icon(&self, name: &str) -> Option<&str> {
        match self.props.get(name) {
            Some(Prop::Icon { name }) => Some(name),
            _ => None,
        }
    }

    pub fn resource(&self, name: &str) -> Option<&str> {
        match self.props.get(name) {
            Some(Prop::Resource { name }) => Some(name),
            _ => None,
        }
    }

    /// What follows the element's action: with `submit: clear` on a
    /// `TextInput`, or `clears: draft.x` on a `Button`, the draft becomes
    /// empty, and the keyboard goes back to the window.
    pub fn clearing(&self) -> Option<Action> {
        let field = if self.keyword("submit") == Some("clear") {
            self.field("value")?
        } else {
            self.field("clears")?
        };
        Some(Action::Session {
            field: field.clone(),
            op: SessionOp::Set {
                value: Expr {
                    kind: ExprKind::Literal {
                        value: Value::Text(String::new()),
                    },
                    ty: Type::Text,
                },
            },
        })
    }

    pub fn field(&self, name: &str) -> Option<&FieldRef> {
        match self.props.get(name) {
            Some(Prop::Field { field }) => Some(field),
            _ => None,
        }
    }

    pub fn expr(&self, name: &str) -> Option<&Expr> {
        match self.props.get(name) {
            Some(Prop::Expr { expr }) => Some(expr),
            _ => None,
        }
    }

    pub fn query(&self, name: &str) -> Option<&QueryBinding> {
        match self.props.get(name) {
            Some(Prop::Query { query }) => Some(query),
            _ => None,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ComponentArg {
    Client,
    Windows,
    Players,
    Value { expr: Expr },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComponentRef {
    pub component: String,
    pub args: Vec<(String, ComponentArg)>,
    pub source: SourceLocation,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IfNode {
    pub branches: Vec<(Expr, Vec<Node>)>,
    pub otherwise: Vec<Node>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IfLetNode {
    pub var: String,
    pub value: Expr,
    #[serde(rename = "inner_type")]
    pub inner: Type,
    pub then: Vec<Node>,
    pub otherwise: Vec<Node>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MatchBinding {
    pub name: String,
    pub field: usize,
    #[serde(rename = "type")]
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MatchArm {
    /// `None` for the `_` arm.
    pub variant: Option<u32>,
    pub bindings: Vec<MatchBinding>,
    pub body: Vec<Node>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MatchNode {
    pub value: Expr,
    pub enum_name: String,
    pub arms: Vec<MatchArm>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "node", rename_all = "snake_case")]
pub enum Node {
    Element(Element),
    Component(ComponentRef),
    If(IfNode),
    IfLet(IfLetNode),
    Match(MatchNode),
}

impl Node {
    /// Visit this node and all descendants, depth first.
    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
        self.walk_in(None, &mut |node, _| visit(node));
    }

    /// Visit every element at or under this node, depth first, to change
    /// it.
    pub fn elements_mut(&mut self, visit: &mut impl FnMut(&mut Element)) {
        let children: Vec<&mut Node> = match self {
            Node::Element(element) => {
                visit(element);
                element.children.iter_mut().collect()
            }
            Node::Component(_) => Vec::new(),
            Node::If(node) => node
                .branches
                .iter_mut()
                .flat_map(|(_, body)| body.iter_mut())
                .chain(node.otherwise.iter_mut())
                .collect(),
            Node::IfLet(node) => node
                .then
                .iter_mut()
                .chain(node.otherwise.iter_mut())
                .collect(),
            Node::Match(node) => node
                .arms
                .iter_mut()
                .flat_map(|arm| arm.body.iter_mut())
                .collect(),
        };
        for child in children {
            child.elements_mut(visit);
        }
    }

    /// Visit this node and all descendants, depth first, each with the kind
    /// of the nearest element around it; `parent` is the one around this
    /// node.
    pub fn walk_in<'a>(
        &'a self,
        parent: Option<&'a str>,
        visit: &mut impl FnMut(&'a Node, Option<&'a str>),
    ) {
        visit(self, parent);
        let parent = match self {
            Node::Element(element) => Some(element.kind.as_str()),
            _ => parent,
        };
        match self {
            Node::Element(element) => {
                for child in &element.children {
                    child.walk_in(parent, visit);
                }
            }
            Node::Component(_) => {}
            Node::If(node) => {
                for (_, body) in &node.branches {
                    for child in body {
                        child.walk_in(parent, visit);
                    }
                }
                for child in &node.otherwise {
                    child.walk_in(parent, visit);
                }
            }
            Node::IfLet(node) => {
                for child in node.then.iter().chain(&node.otherwise) {
                    child.walk_in(parent, visit);
                }
            }
            Node::Match(node) => {
                for arm in &node.arms {
                    for child in &arm.body {
                        child.walk_in(parent, visit);
                    }
                }
            }
        }
    }
}

impl Expr {
    /// Visit this expression and every sub-expression.
    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Expr)) {
        visit(self);
        match &self.kind {
            ExprKind::Literal { .. } | ExprKind::Binding { .. } | ExprKind::Corner { .. } => {}
            ExprKind::Variant { fields, .. } => {
                for field in fields {
                    field.walk(visit);
                }
            }
            ExprKind::Not { expr } | ExprKind::Neg { expr } => expr.walk(visit),
            ExprKind::Binary { lhs, rhs, .. } => {
                lhs.walk(visit);
                rhs.walk(visit);
            }
            ExprKind::If {
                cond,
                then,
                otherwise,
            } => {
                cond.walk(visit);
                then.walk(visit);
                otherwise.walk(visit);
            }
        }
    }

    /// Session state types this expression reads.
    pub fn sessions(&self) -> Vec<String> {
        let mut sessions = Vec::new();
        self.walk(&mut |expr| {
            if let ExprKind::Binding {
                binding: Binding::Session { session, .. },
            } = &expr.kind
                && !sessions.contains(session)
            {
                sessions.push(session.clone());
            }
        });
        sessions
    }

    /// Whether this expression reads engine state.
    pub fn reads_engine(&self) -> bool {
        let mut reads = false;
        self.walk(&mut |expr| {
            if let ExprKind::Binding {
                binding: Binding::Engine { .. },
            } = &expr.kind
            {
                reads = true;
            }
        });
        reads
    }
}

impl Text {
    /// Expressions interpolated into this text.
    pub fn exprs(&self) -> Vec<&Expr> {
        match self {
            Text::Localized { args, .. } => args.iter().map(|(_, expr)| expr).collect(),
            Text::Dynamic { expr } => vec![expr],
        }
    }
}

impl CloseCheck {
    /// Every expression the check evaluates.
    pub fn exprs(&self) -> Vec<&Expr> {
        let mut exprs = vec![&self.when];
        exprs.extend(self.message.exprs());
        if let Some(Action::Engine { args, .. }) = &self.save {
            exprs.extend(args);
        }
        exprs
    }
}

pub use bern_protocol::label_key;

/// Version of the [`ComponentLibrary`] layout.
pub const LIBRARY_DESCRIPTOR_VERSION: u32 = 1;

/// Versioned description of a component library crate, generated from its
/// sources. Applications check it against their own configuration before
/// using its components: descriptor and IR versions, the crate version it
/// was generated from, and translations for every required language.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ComponentLibrary {
    pub descriptor_version: u32,
    pub ir_version: u32,
    /// Cargo package name of the library.
    pub package: String,
    /// Cargo package version the descriptor was generated from.
    pub version: String,
    /// Fingerprint of the library sources and configuration.
    pub source_fingerprint: String,
    pub languages: Vec<String>,
    pub types: TypeTable,
    pub components: Vec<ComponentDef>,
    pub texts: Vec<LocalizedText>,
}

/// Whether `node`, followed in a row by `next`, is the words that lead the
/// row: a text, or a column standing at its leading edge, before a spacer.
/// It takes the spacer's room itself, so the controls after it keep their
/// width and the words wrap in what is left, as a list row's label does.
pub fn leads_row(node: &Node, next: Option<&Node>) -> bool {
    let words = matches!(node, Node::Element(element)
        if element.prop("width").is_none()
            && (element.kind == "Text"
                || (element.kind == "Column"
                    && matches!(element.keyword("align"), None | Some("leading")))));
    words && matches!(next, Some(Node::Element(spacer)) if spacer.kind == "Spacer")
}

/// The `ForEach` of a grid that, standing in a vertical scroll view, builds
/// only the rows near what is in sight: a grid whose one child is a keyed
/// `ForEach`, not laid out as masonry. Every target builds such a grid
/// lazily; anywhere else it builds all its rows.
pub fn lazy_grid_items(grid: &Element) -> Option<&Element> {
    if grid.kind != "Grid" || grid.keyword("masonry") == Some("true") {
        return None;
    }
    match grid.children.as_slice() {
        [Node::Element(each)]
            if each.kind == "ForEach"
                && each.template.is_some()
                && each.expr("items").is_some()
                && matches!(each.prop("key"), Some(Prop::Key { .. })) =>
        {
            Some(each)
        }
        _ => None,
    }
}

/// The `align` a list lowered by [`lower_lists`] keeps: how its rows
/// stand across it, as in the column it came from.
pub fn lowered_list_align(grid: &Element) -> Option<&str> {
    (grid.kind == "Grid")
        .then(|| grid.keyword("align"))
        .flatten()
}

/// Whether `nodes`, the children of a column, hold a list lowered by
/// [`lower_lists`], directly or in their conditions.
pub fn holds_lowered_list(nodes: &[Node]) -> bool {
    nodes.iter().any(|node| match node {
        Node::Element(element) => lowered_list_align(element).is_some(),
        Node::If(node) => {
            node.branches
                .iter()
                .any(|(_, body)| holds_lowered_list(body))
                || holds_lowered_list(&node.otherwise)
        }
        Node::IfLet(node) => holds_lowered_list(&node.then) || holds_lowered_list(&node.otherwise),
        Node::Match(node) => node.arms.iter().any(|arm| holds_lowered_list(&arm.body)),
        Node::Component(_) => false,
    })
}

/// A list in a vertical scroll view builds only the rows near what is in
/// sight: a keyed `ForEach` among the children of a `Column` there (through
/// conditions) becomes a one-column grid of its rows, which every target
/// builds lazily (see [`lazy_grid_items`]). The grid keeps the column's
/// look: `align` says how the rows stand across it, `row_gap` is the
/// column's `gap` (absent when the column has none, for the target's own),
/// it staggers as the column does, and with no rows it takes no place. A
/// component counts as in a scroll view when every place that shows it is.
/// Columns that `reflow` keep building all their rows, since their rows
/// slide among each other.
pub fn lower_lists(app: &mut Application) {
    let mut windows: Vec<&mut Node> = app
        .windows
        .windows
        .iter_mut()
        .map(|window| &mut window.content)
        .collect();
    let mut components: Vec<(&str, &mut Node)> = app
        .components
        .iter_mut()
        .map(|component| (component.name.as_str(), &mut component.body))
        .collect();
    lower_bodies(&mut windows, &mut components);
}

/// [`lower_lists`] over the contents of the windows and the bodies of the
/// components, by name.
fn lower_bodies(windows: &mut [&mut Node], components: &mut [(&str, &mut Node)]) {
    // Which components are only ever shown inside a vertical scroll view,
    // found by going over the tree until nothing changes.
    let mut scrolled: BTreeMap<String, bool> = components
        .iter()
        .map(|(name, _)| (name.to_string(), true))
        .collect();
    loop {
        let mut calls: BTreeMap<String, bool> = BTreeMap::new();
        let mut note = |name: &str, inside: bool| {
            let entry = calls.entry(name.to_string()).or_insert(true);
            *entry = *entry && inside;
        };
        for window in windows.iter() {
            calls_in(window, false, &mut note);
        }
        for (name, body) in components.iter() {
            calls_in(body, scrolled[*name], &mut note);
        }
        let next: BTreeMap<String, bool> = scrolled
            .keys()
            .map(|name| (name.clone(), calls.get(name).copied().unwrap_or(false)))
            .collect();
        if next == scrolled {
            break;
        }
        scrolled = next;
    }
    for window in windows.iter_mut() {
        lower_in(window, false);
    }
    for (name, body) in components.iter_mut() {
        lower_in(body, scrolled[*name]);
    }
}

/// Whether what an element contains scrolls with a vertical scroll view
/// around it, given whether the element itself does.
fn scrolls_inside(element: &Element, scrolling: bool) -> bool {
    match element.kind.as_str() {
        "ScrollView" => element.keyword("axis") != Some("horizontal"),
        // A layer or page of its own, shown apart from the scroll view.
        "Modal" | "PopoverButton" | "Menu" | "ContextMenu" | "Toolbar" | "SplitView"
        | "Sidebar" | "Detail" | "Tabs" | "Tab" | "TabAccessory" | "Navigation" | "Destination"
        | "Window" | "WindowSet" | "Form" | "Table" => false,
        _ => scrolling,
    }
}

fn calls_in(node: &Node, scrolling: bool, note: &mut impl FnMut(&str, bool)) {
    match node {
        Node::Element(element) => {
            let inside = scrolls_inside(element, scrolling);
            for child in &element.children {
                calls_in(child, inside, note);
            }
        }
        Node::Component(call) => note(&call.component, scrolling),
        Node::If(node) => {
            for (_, body) in &node.branches {
                body.iter()
                    .for_each(|child| calls_in(child, scrolling, note));
            }
            node.otherwise
                .iter()
                .for_each(|child| calls_in(child, scrolling, note));
        }
        Node::IfLet(node) => {
            node.then
                .iter()
                .chain(&node.otherwise)
                .for_each(|child| calls_in(child, scrolling, note));
        }
        Node::Match(node) => {
            for arm in &node.arms {
                arm.body
                    .iter()
                    .for_each(|child| calls_in(child, scrolling, note));
            }
        }
    }
}

fn lower_in(node: &mut Node, scrolling: bool) {
    match node {
        Node::Element(element) => {
            let inside = scrolls_inside(element, scrolling);
            // What the rows hold first, so that the column a row's parts
            // are put in below is not taken for one of the app's.
            for child in &mut element.children {
                lower_in(child, inside);
            }
            if inside && element.kind == "Column" && element.prop("reflow").is_none() {
                let look = ListLook {
                    gap: element.prop("gap").cloned(),
                    align: element.keyword("align").unwrap_or("leading").to_string(),
                    stagger: element.prop("stagger").cloned(),
                    path: element.path.clone(),
                };
                let mut count = 0;
                lower_rows(&mut element.children, &look, &mut count);
            }
        }
        Node::Component(_) => {}
        Node::If(node) => {
            for (_, body) in &mut node.branches {
                body.iter_mut().for_each(|child| lower_in(child, scrolling));
            }
            node.otherwise
                .iter_mut()
                .for_each(|child| lower_in(child, scrolling));
        }
        Node::IfLet(node) => {
            node.then
                .iter_mut()
                .chain(&mut node.otherwise)
                .for_each(|child| lower_in(child, scrolling));
        }
        Node::Match(node) => {
            for arm in &mut node.arms {
                arm.body
                    .iter_mut()
                    .for_each(|child| lower_in(child, scrolling));
            }
        }
    }
}

/// How the column a list stands in lays it out.
struct ListLook {
    gap: Option<Prop>,
    align: String,
    stagger: Option<Prop>,
    path: String,
}

/// Each keyed `ForEach` among `children` (and in the branches of the
/// conditions among them), put in a one-column grid.
fn lower_rows(children: &mut [Node], look: &ListLook, count: &mut usize) {
    for child in children.iter_mut() {
        match child {
            Node::Element(each)
                if each.kind == "ForEach"
                    && each.template.is_some()
                    && each.expr("items").is_some()
                    && matches!(each.prop("key"), Some(Prop::Key { .. })) =>
            {
                let mut props = BTreeMap::new();
                // As many columns as fit this wide: one.
                props.insert("min_width".to_string(), Prop::Number { value: 1.0e6 });
                props.insert("gap".to_string(), Prop::Number { value: 0.0 });
                if let Some(gap) = &look.gap {
                    props.insert("row_gap".to_string(), gap.clone());
                }
                props.insert(
                    "align".to_string(),
                    Prop::Keyword {
                        value: look.align.clone(),
                    },
                );
                if let Some(stagger) = &look.stagger {
                    props.insert("stagger".to_string(), stagger.clone());
                }
                let source = each.source.clone();
                let path = format!("{}/list{}", look.path, count);
                *count += 1;
                let mut each = std::mem::replace(
                    child,
                    Node::Component(ComponentRef {
                        component: String::new(),
                        args: Vec::new(),
                        source: source.clone(),
                    }),
                );
                if let Node::Element(each) = &mut each {
                    stack_parts(each, look, &path);
                }
                *child = Node::Element(Element {
                    kind: "Grid".into(),
                    id: None,
                    path,
                    props,
                    template: None,
                    children: vec![each],
                    action: None,
                    source,
                });
            }
            Node::If(node) => {
                for (_, body) in &mut node.branches {
                    lower_rows(body, look, count);
                }
                lower_rows(&mut node.otherwise, look, count);
            }
            Node::IfLet(node) => {
                lower_rows(&mut node.then, look, count);
                lower_rows(&mut node.otherwise, look, count);
            }
            Node::Match(node) => {
                for arm in &mut node.arms {
                    lower_rows(&mut arm.body, look, count);
                }
            }
            _ => {}
        }
    }
}

/// A row of more than one part, such as a line and the divider under it,
/// keeps its parts one under another as they stood in the column: in a
/// column of their own, as far apart as the column's children and standing
/// across it as they did. A grid's cell holds one row on every target,
/// which otherwise lays several parts over one another or apart.
fn stack_parts(each: &mut Element, look: &ListLook, path: &str) {
    if each.children.len() < 2 {
        return;
    }
    let mut props = BTreeMap::new();
    if let Some(gap) = &look.gap {
        props.insert("gap".to_string(), gap.clone());
    }
    props.insert(
        "align".to_string(),
        Prop::Keyword {
            value: look.align.clone(),
        },
    );
    each.children = vec![Node::Element(Element {
        kind: "Column".into(),
        id: None,
        path: format!("{path}/row"),
        props,
        template: None,
        children: std::mem::take(&mut each.children),
        action: None,
        source: each.source.clone(),
    })];
}

/// Resource key of a text declared on an element property.
pub fn text_key(component: &str, node_path: &str, prop: &str) -> String {
    format!("{component}.{node_path}.{prop}")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn element(kind: &str, children: Vec<Node>) -> Node {
        Node::Element(Element {
            kind: kind.into(),
            id: None,
            path: kind.into(),
            props: BTreeMap::new(),
            template: None,
            children,
            action: None,
            source: SourceLocation::default(),
        })
    }

    fn with_props(node: Node, props: &[(&str, Prop)]) -> Node {
        let Node::Element(mut element) = node else {
            unreachable!()
        };
        for (name, prop) in props {
            element.props.insert(name.to_string(), prop.clone());
        }
        Node::Element(element)
    }

    fn keyed_rows() -> Node {
        let Node::Element(mut each) = element("ForEach", vec![element("Text", vec![])]) else {
            unreachable!()
        };
        each.template = Some(Template {
            var: "row".into(),
            ty: Type::Int,
        });
        each.props.insert(
            "items".into(),
            Prop::Expr {
                expr: Expr {
                    kind: ExprKind::Literal {
                        value: Value::Int(0),
                    },
                    ty: Type::Int,
                },
            },
        );
        each.props.insert(
            "key".into(),
            Prop::Key {
                field: 0,
                name: "id".into(),
            },
        );
        Node::Element(each)
    }

    fn kinds(node: &Node) -> Vec<String> {
        let Node::Element(element) = node else {
            return vec![];
        };
        element
            .children
            .iter()
            .map(|child| match child {
                Node::Element(child) => child.kind.clone(),
                Node::If(_) => "if".into(),
                _ => "other".into(),
            })
            .collect()
    }

    #[test]
    fn a_list_in_a_scroll_view_becomes_a_lazy_column_of_its_rows() {
        let column = with_props(
            element(
                "Column",
                vec![
                    element("Text", vec![]),
                    keyed_rows(),
                    element("Spacer", vec![]),
                ],
            ),
            &[
                ("gap", Prop::Number { value: 4.0 }),
                (
                    "align",
                    Prop::Keyword {
                        value: "center".into(),
                    },
                ),
            ],
        );
        let mut tree = element("ScrollView", vec![column]);
        lower_bodies(&mut [&mut tree], &mut []);
        let Node::Element(scroll) = &tree else {
            unreachable!()
        };
        assert_eq!(kinds(&scroll.children[0]), ["Text", "Grid", "Spacer"]);
        let Node::Element(column) = &scroll.children[0] else {
            unreachable!()
        };
        let Node::Element(grid) = &column.children[1] else {
            unreachable!()
        };
        assert_eq!(lowered_list_align(grid), Some("center"));
        assert_eq!(grid.number("row_gap"), Some(4.0));
        assert!(
            lazy_grid_items(grid).is_some(),
            "it is a grid every target builds lazily"
        );
    }

    #[test]
    fn a_row_of_several_parts_keeps_them_one_under_another() {
        // A line and the divider under it, and inside the row a list of
        // its own, which stays as the row's own.
        let Node::Element(mut each) = keyed_rows() else {
            unreachable!()
        };
        each.children = vec![
            element("Row", vec![]),
            element("Column", vec![element("Divider", vec![])]),
            keyed_rows(),
        ];
        let parts = each.children.clone();
        let column = with_props(
            element("Column", vec![Node::Element(each), keyed_rows()]),
            &[
                ("gap", Prop::Number { value: 4.0 }),
                (
                    "align",
                    Prop::Keyword {
                        value: "center".into(),
                    },
                ),
            ],
        );
        let mut tree = element("ScrollView", vec![column]);
        lower_bodies(&mut [&mut tree], &mut []);
        let rows_of = |at: usize| {
            let Node::Element(scroll) = &tree else {
                unreachable!()
            };
            let Node::Element(column) = &scroll.children[0] else {
                unreachable!()
            };
            let Node::Element(grid) = &column.children[at] else {
                unreachable!()
            };
            lazy_grid_items(grid).unwrap().clone()
        };
        let several = rows_of(0);
        assert_eq!(kinds(&Node::Element(several.clone())), ["Column"]);
        let Node::Element(stack) = &several.children[0] else {
            unreachable!()
        };
        assert_eq!(stack.children, parts, "the parts stay as they were");
        assert_eq!(stack.number("gap"), Some(4.0));
        assert_eq!(stack.keyword("align"), Some("center"));
        assert_eq!(stack.path, "Column/list0/row");
        // A row of one part is that part.
        assert_eq!(kinds(&Node::Element(rows_of(1))), ["Text"]);
    }

    #[test]
    fn lists_outside_scroll_views_and_reflowing_lists_stay_as_they_are() {
        let mut outside = element("Column", vec![keyed_rows()]);
        let mut sideways = with_props(
            element("ScrollView", vec![element("Column", vec![keyed_rows()])]),
            &[(
                "axis",
                Prop::Keyword {
                    value: "horizontal".into(),
                },
            )],
        );
        let mut reflowing = element(
            "ScrollView",
            vec![with_props(
                element("Column", vec![keyed_rows()]),
                &[(
                    "reflow",
                    Prop::Keyword {
                        value: "smooth".into(),
                    },
                )],
            )],
        );
        let before = (outside.clone(), sideways.clone(), reflowing.clone());
        lower_bodies(&mut [&mut outside, &mut sideways, &mut reflowing], &mut []);
        assert_eq!((outside, sideways, reflowing), before);
    }

    #[test]
    fn a_list_in_a_condition_and_in_a_component_shown_in_a_scroll_view_is_lowered() {
        let condition = Expr {
            kind: ExprKind::Literal {
                value: Value::Bool(true),
            },
            ty: Type::Bool,
        };
        let call = |name: &str| {
            Node::Component(ComponentRef {
                component: name.into(),
                args: vec![],
                source: SourceLocation::default(),
            })
        };
        let mut window = element("ScrollView", vec![call("songs")]);
        let mut songs = element(
            "Column",
            vec![Node::If(IfNode {
                branches: vec![(condition, vec![keyed_rows()])],
                otherwise: vec![],
            })],
        );
        // Shown both in a scroll view and outside one: left as it is.
        let mut window_two = element(
            "Column",
            vec![call("tags"), element("ScrollView", vec![call("tags")])],
        );
        let mut tags = element("Column", vec![keyed_rows()]);
        let tags_before = tags.clone();
        lower_bodies(
            &mut [&mut window, &mut window_two],
            &mut [("songs", &mut songs), ("tags", &mut tags)],
        );
        let Node::Element(column) = &songs else {
            unreachable!()
        };
        let Node::If(branch) = &column.children[0] else {
            unreachable!()
        };
        assert!(matches!(&branch.branches[0].1[0], Node::Element(grid) if grid.kind == "Grid"));
        assert_eq!(tags, tags_before);
    }

    #[test]
    fn walks_report_the_nearest_element_around_each_node() {
        let condition = Expr {
            kind: ExprKind::Literal {
                value: Value::Bool(true),
            },
            ty: Type::Bool,
        };
        let tree = element(
            "Sidebar",
            vec![Node::If(IfNode {
                branches: vec![(condition, vec![element("Search", vec![])])],
                otherwise: vec![element("Column", vec![element("Text", vec![])])],
            })],
        );
        let mut seen = Vec::new();
        tree.walk_in(None, &mut |node, parent| {
            let name = match node {
                Node::Element(element) => element.kind.as_str(),
                Node::If(_) => "if",
                _ => "other",
            };
            seen.push((name, parent));
        });
        assert_eq!(
            seen,
            [
                ("Sidebar", None),
                ("if", Some("Sidebar")),
                ("Search", Some("Sidebar")),
                ("Column", Some("Sidebar")),
                ("Text", Some("Column")),
            ]
        );
        let mut count = 0;
        tree.walk(&mut |_| count += 1);
        assert_eq!(count, seen.len());
    }
}