pochoir 0.15.1

Main crate of the pochoir template engine used to compile and render pochoir files with components
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
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
//! The Server-side Web Components compiler
//!
//! ## Features
//!
//! ### Variables and expressions
//!
//! Variables needs to be defined in a *[`Context`]*. They can be inserted using [`Context::insert`]
//! but if you want child components to also inherit the data (like a global variable), you should
//! use [`Context::insert_inherited`]. Both functions take a key as first argument which is the name
//! of the variable usable in expressions and a value implementing the [`IntoValue`] trait
//! (implemented for a *lot* of default types and structures). The value will then be cloned and
//! transformed in each expression. If you want to pass enumerations or structures, you should
//! implement [`IntoValue`] on them using the [`IntoValue`] derive macro. The variable keys must
//! follow some rules to be valid: they must only contain lowercase and uppercase Latin letters,
//! underscores and digits (but the first character must not be a digit).
//!
//! When data needs to be inserted inside a page, you need to use an *expression*. Expressions are
//! tiny groups of variables and operators written in their own [custom language](`pochoir_lang`) that
//! manipulate data. They are written in a pair of curly brackets and can be used everywhere you write text.
//! The resulting value of expressions is escaped to prevent XSS attacks, but it is possible to opt
//! out of auto-escaping by replacing the inner curly brackets by exclamation marks.
//!
//! [`IntoValue`]: pochoir_lang::IntoValue
//!
//! ##### Example
//!
//! ```
//! // In a Rust file
//! use pochoir::Context;
//!
//! let mut context = Context::new();
//! context.insert("date", "August 26, 2023");
//! context.insert("html", "<b>some bold HTML</b>");
//! ```
//!
//! ```html
//! {# In an HTML file #}
//! Today it is {{ date }}.
//! Unescaped HTML can be inserted: {! html !}.
//! ```
//!
//! Will render as:
//!
//! ```html
//! Today it is August 26, 2023.
//! Unescaped HTML can be inserted: <b>some bold HTML</b>.
//! ```
//!
//! ### Statements
//!
//! Common statements can be used in templates. They are all written in curly brackets with inner
//! percentages.
//!
//! - `if`/`elif`/`else` *conditional statements* are used to check if an
//!   expression equals `true`. If it does, the inner content will be included, if not it won't. One
//!   additional feature is that you can use the `if let` (and `elif let`) syntax to check
//!   if a value is not null. It can be combined with an assignment to replicate the
//!   `if let Some(_) = _` syntax of Rust: "unwrap" the value if it is not null or don't
//!   execute a block content at all if the value is null. You need to note that assignments
//!   return the assigned value (like in Javascript) which enables the `if let` syntax to do that
//! - `for` *loop statements* are also supported. They are mostly used to iterate lists
//!   so they are written using the `for ... in ...` syntax. If you want to just get some ordered numbers,
//!   you would need to use ranges like `for ... in 3..12`. *Destructuring objects and arrays* is also
//!   supported, so if you iterate an array of objects and they all share the same structure you can
//!   bind their the fields to comma-separated variables instead of indexing them later. The same thing is
//!   supported for arrays, except that you can name the keys as you want, just the order in which
//!   they are defined is important. If a value cannot be destructured (because the field does not exist),
//!   the value will simply be `null`
//! - `let` statements can be used to assign a value to a variable and
//!   comments can be added with curly brackets with inner `#`s
//! - `spaceless` statements are used to remove spaces **between** elements (see [Whitespace control](#whitespace-control))
//! - `verbatim` statements are used to escape special templating characters
//!
//! ##### Example
//!
//! ```
//! // In a Rust file
//! use pochoir::{object, Context};
//!
//! let mut context = Context::new();
//! context.insert("date", "August 26, 2023");
//! context.insert("weather", "cloudy");
//! context.insert("users", vec![
//!     object! {
//!         "name" => "John",
//!         "job" => "Football player"
//!     },
//!     object! {
//!         "name" => "Jane",
//!         "job" => "Designer",
//!     }
//! ]);
//! ```
//!
//! ```html
//! {# In an HTML file #}
//! {% if date == "August 26, 2023" %}
//! It is today!
//! {% elif date == "August 25, 2023" %}
//! It is yesterday!
//! {% else %}
//! Oh welcome to the future.
//! {% endif %}
//!
//! {# Note that a single `=` is used here because it is an assignment. If `weather` is null, the
//! assignment will return `null` and the `if` block content will never run (because `if let`
//! checks for `null`ity) but if the value is something other than `null`, `current_weather` will
//! be different than `null` and the inner block will be run #}
//!
//! {% if let current_weather = weather %}
//! Today it is {{ current_weather }}.
//! {% endif %}
//!
//! {# We now define a variable in the template and iterate it in a for loop #}
//!
//! {% let alphabet = ["a", "b", "c", "d"] %}
//!
//! {% for letter in alphabet %}"{{ letter }}" then {% endfor %}"z"
//!
//! {# Objects are destructured here: the `name` and `job` fields will be extracted from the
//! objects to avoid having to later index them #}
//!
//! <ul>
//!   {% for name, job in users %}
//!   <li>{{ name }} is a {{ job }}</li>
//!   {% endfor %}
//! </ul>
//! ```
//!
//! Will render as (some newlines are ignored for clarity):
//!
//! ```html
//! It is today!
//!
//! Today it is cloudy.
//!
//! "a" then "b" then "c" then "d" then "z"
//!
//! <ul>
//!   <li>John is a Football player</li>
//!   <li>Jane is a Designer</li>
//! </ul>
//! ```
//!
//! ### What are providers?
//!
//! Providers are high-level structures storing the source of templates and components and
//! providing it to the compiler. You can generally insert templates in them using either the
//! builder pattern (`with_*` methods) or using an imperative API (`insert_*` methods). Two
//! official providers are available: the [`FilesystemProvider`] gets the source HTML from
//! the files in a directory, and the [`StaticMapProvider`] stores source files in a map
//! with the component name as key.
//!
//! ##### Example
//!
//! ```no_run
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, FilesystemProvider};
//!
//! // The `FilesystemProvider` selects files using two criterias: if they have a
//! // known extension (they can be configured, by default just `html` files can be
//! // used) and if they are in one of the inserted path. Here all files in the
//! // `templates` directory having a `.html` extension will be used
//! let provider = FilesystemProvider::new().with_path("templates");
//! let mut context = Context::new();
//!
//! let _html = provider.compile("index", &mut context)?;
//! # Ok(())
//! # }
//! ```
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! // The last argument is the path to the file if it was read from
//! // the filesystem, it is used in error messages to find the HTML file source
//! let provider = StaticMapProvider::new().with_template("index", "<h1>Index page</h1>", None);
//! let mut context = Context::new();
//!
//! let _html = provider.compile("index", &mut context)?;
//! # Ok(())
//! # }
//! ```
//!
//! But if you want more control over how the source files are fetched, you can use
//! the closure API by directly using the [`compile`] function. The closure
//! takes the name of the component and returns a [`ComponentFile`] with the file name and
//! data.
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, ComponentFile, error};
//! use std::path::Path;
//!
//! let html = pochoir::compile("index", &mut Context::new(), |name| {
//!     // In a real world usage, you would fetch the HTML from a complex, dynamic,
//!     // pipeline of sources, maybe from the network.
//!     // A `ComponentFile` is used to associate some data with a path to a file,
//!     // if it was fetched from the filesystem. You can use
//!     // `ComponentFile::new_inline` if you don't want to provide a path, in this
//!     // case the path will simply be `inline`
//!     Ok(match name {
//!         "index" => ComponentFile::new_inline("<h1>Index page</h1><my-button />"),
//!         "my-button" => ComponentFile::new(Path::new("my-button.html"), "<button>Click me!</button>"),
//!         _ => return Err(error::component_not_found(name)),
//!     })
//! })?;
//! # Ok(())
//! # }
//! ```
//!
//! [`StaticMapProvider`]: crate::StaticMapProvider
//! [`FilesystemProvider`]: crate::FilesystemProvider
//!
//! ### Components
//!
//! > From now on, we'll be using full Rust files as example with the [`StaticMapProvider`] to insert
//! > HTML sources but it is also perfectly possible to use the [`FilesystemProvider`] or the closure
//! > API, it is just easier to show here.
//!
//! Components can be defined using two ways: either you just *insert them in the provider of your
//! choice* (you can also return a [`ComponentFile`] in the component resolver) or you define them
//! using a *`<template>` element* directly in the HTML file. The components defined in the latter
//! case are **scoped to their parent and cannot be used before they are declared** to avoid
//! polluting the complete component. In both cases you can use them as custom elements by
//! *writing an element having the name* of the template in the HTML. The name of components must
//! follow some rules to be compatible with custom elements: **they must contain a dash, start with
//! a lowercase letter and must not be one of the reserved element names** (see
//! <https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name> for
//! more information). Moreover, each component name **should be unique**: if a component is
//! redefined it is overriden, however the old component cannot be inserted in the new one and
//! having two components with the same name can be incompatible with some transformers, e.g
//! `pochoir_extra::EnhancedCss`.
//!
//! ##### Example of components
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", "<my-button></my-button>", None)
//!     .with_template("my-button", "<button>Click me!</button>", None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, "<button>Click me!</button>");
//! # Ok(())
//! # }
//! ```
//!
//! Components can have *properties* passed from the parent to the component using HTML attributes.
//! By default, they are interpreted as strings (because HTML attributes *are* strings) except if
//! they contain an expression.
//! The keys of attributes should be in [kebab-case](https://en.wikipedia.org/wiki/Letter_case#Kebab_case)
//! (with dashes) but they will be converted into
//! [snake_case](https://en.wikipedia.org/wiki/Letter_case#Snake_case) (with underscores)
//! to be used in expressions.
//!
//! ##### Example of component properties
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", r#"
//!     <my-button some-classes="foo bar" count="{{ 2 }}" primary></my-button>"#, None)
//!     .with_template("my-button", r#"
//!     <button class="{{ some_classes }} {{ primary != null ? 'is-primary' : 'is-secondary' }}">
//!       Count: {{ count + 1 }}
//!     </button>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"
//!    
//!     <button class="foo bar is-primary">
//!       Count: 3
//!     </button>"#);
//! # Ok(())
//! # }
//! ```
//!
//! Components can have *slots*, HTML children passed from the parent to the component. By default,
//! all children of a component instance will be given as the default slot, but you can have
//! children contained in a *named slot* using the `slot` attribute. The slots can then be inserted
//! into the component HTML by using `<slot>` elements which can have the `name` attribute for
//! inserting named slots. If you need to pass variables from the component to the parent
//! slot, you can just give attributes to the `<slot>` element, they will then be usable in the
//! parent `<slot>` element. This process is called
//! [scoped slots](https://vuejs.org/guide/components/slots.html#scoped-slots). Finally, if you
//! want to make a slot optional and use some default slot content when no one is given, you can
//! just write elements *inside* the `<slot>` elements.
//!
//! ##### Example of component slots
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", r#"
//!     <my-card>
//!         <h1 slot="header">My header</h1>
//!         <p>Card content</p>
//!         All nodes not having a `slot` attribute belong to the default slot
//!     </my-card>"#, None)
//!     .with_template("my-card", r#"
//!     <div>
//!       <header>
//!         <slot name="header"></slot>
//!       </header>
//!       <main>
//!         <slot></slot>
//!       </main>
//!       <footer>
//!         <slot name="footer">Default footer content</slot>
//!       </footer>
//!     </div>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"
//!    
//!     <div>
//!       <header>
//!         <h1>My header</h1>
//!       </header>
//!       <main>
//!        
//!        
//!         <p>Card content</p>
//!         All nodes not having a `slot` attribute belong to the default slot
//!    
//!       </main>
//!       <footer>
//!         Default footer content
//!       </footer>
//!     </div>"#);
//! # Ok(())
//! # }
//! ```
//!
//! ### Inline components
//!
//! If you need to quickly define a component to avoid repeating a bunch of elements, you can
//! define **inline components** using a `<template>` element with the component name given as the
//! `name` attribute. Components defined this way will be **scoped to their parent element** and can only used in the children of the parent
//! element they were defined in.
//!
//! ##### Example of an inline component
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", r#"<div>
//!     <template name="my-button">
//!         <div class="btn btn-{{ type }}"><slot></slot></div>
//!     </template>
//!
//!     <my-button type="primary">Click me!</my-button>
//!     <my-button type="secondary">Another button</my-button>
//! </div>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"<div>
//!    
//!
//!    
//!         <div class="btn btn-primary">Click me!</div>
//!    
//!    
//!         <div class="btn btn-secondary">Another button</div>
//!    
//! </div>"#);
//! # Ok(())
//! # }
//! ```
//!
//! ### Client-side components
//!
//! If you really need to have client-side functionalities written in pure JS for interactivity, it
//! is possible to use the [`shadowrootmode` attribute](https://developer.chrome.com/articles/declarative-shadow-dom/#building-a-declarative-shadow-root) on a `<template>` element to turn it into a
//! client-side components. It **won't** replace `<slot>` elements or any other components but **will** wrap the `<template>` element in the component itself and evaluate and append its children (expressions **will** be evaluated in the children of the `<template>` element).
//!
//! ##### Example of a client component
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", r#"<my-button type="primary">
//!       <span slot="my-slot">Slot content</span>
//!       My button
//!     </my-button>"#, None)
//!    .with_template("my-button", r#"
//!     <template shadowrootmode="open">
//!       <style>
//!         button {
//!           color: seagreen;
//!         }
//!       </style>
//!       <button class="btn-{{ type }}">
//!         <slot name="my-slot"></slot>
//!       </button>
//!     </template>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"<my-button type="primary">
//!     <template shadowrootmode="open">
//!       <style>
//!         button {
//!           color: seagreen;
//!         }
//!       </style>
//!       <button class="btn-primary">
//!         <slot name="my-slot"></slot>
//!       </button>
//!     </template>
//!       <span slot="my-slot">Slot content</span>
//!       My button
//!     </my-button>"#);
//! # Ok(())
//! # }
//! ```
//!
//! ### The `pochoir-hybrid` attribute
//!
//! If you need to have a component defined in both the client and the server, you can
//! add the `pochoir-hybrid` attribute to any `<template>` element. It will register the component like
//! any other `pochoir-hybrid` component, meaning that you could use it like any other server-side
//! component but it will also be rendered as a client-side `<template>` element **without
//! evaluated expressions, slots, or sub-components**.
//!
//! ##### Example of a component using the `pochoir-hybrid` attribute
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("index", r#"<template name="my-btn" pochoir-hybrid>
//!       <button class="btn">{{ label }}</button>
//!     </template>
//!
//!     <my-btn label="Click me" />
//!
//!     <script>
//!     const template = document.querySelector("template[name='my-btn']");
//!     const cloned = template.content.cloneNode(true);
//!     // Do something with the cloned template node from client-side Javascript code
//!     </script>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"<template name="my-btn">
//!       <button class="btn">{{label}}</button>
//!     </template>
//!
//!    
//!       <button class="btn">Click me</button>
//!    
//!
//!     <script>
//!     const template = document.querySelector("template[name='my-btn']");
//!     const cloned = template.content.cloneNode(true);
//!     // Do something with the cloned template node from client-side Javascript code
//!     </script>"#);
//! # Ok(())
//! # }
//! ```
//!
//! ### The `pochoir-once` attribute
//!
//! If you need to have an HTML element contained in a component rendered only once even if the
//! component is used several times, you can use the `pochoir-once`.
//!
//! ##### Example of a component using the `pochoir-once` attribute
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{Context, StaticMapProvider};
//!
//! let provider = StaticMapProvider::new()
//!     .with_template("my-btn", r#"
//!     <button onclick="buttonClick('{{ label }}')">{{ label }}</button>
//!     <script pochoir-once>
//!     function buttonClick(label) {
//!       alert(label);
//!     }
//!     </script>"#, None)
//!     .with_template("index", r#"
//!     <my-btn label="Click me 1"></my-btn>
//!     <my-btn label="Click me 2"></my-btn>"#, None);
//! let mut context = Context::new();
//!
//! let html = provider.compile("index", &mut context)?;
//!
//! assert_eq!(html, r#"
//!    
//!     <button onclick="buttonClick('Click me 1')">Click me 1</button>
//!     <script>
//!     function buttonClick(label) {
//!       alert(label);
//!     }
//!     </script>
//!    
//!     <button onclick="buttonClick('Click me 2')">Click me 2</button>
//!     "#);
//! # Ok(())
//! # }
//! ```
//!
//! ### Whitespace control
//!
//! [Whitespace management](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace)
//! is a significant source of layout issues but `pochoir` provides some helpers to prevent them.
//!
//! By default, `pochoir` preserves all whitespace and new lines everywhere but if you need to have
//! all whitespace **between** elements removed, you can use the `spaceless` statement like that:
//!
//! ```text
//! {% spaceless %}
//! <ul>
//!   <li>List item</li>
//!   <li>Another list item</li>
//! </ul>
//! {% endspaceless %}
//! ```
//!
//! which will be rendered as `<ul><li>List item</li><li>Another list item</li></ul>`.
//!
//! Keep in mind that only whitespace **between** elements is removed and **not in** elements, e.g
//!
//! ```text
//! {% spaceless %}
//! <ul>
//!   <li>List item</li>
//!   <li>  Another list item  </li>
//! </ul>
//! {% endspaceless %}
//! ```
//!
//! will be rendered as `<ul><li>List item</li><li>  Another list item  </li></ul>`.
//!
//! `spaceless` will also remove whitespace around its own statement, e.g
//!
//! ```text
//! {% for num in [1, 2, 3] %}
//!   {% spaceless %}
//!   <span>{{ num }}</span>
//!   {% endspaceless %}
//! {% endfor %}
//! ```
//!
//! will be rendered as `<span>1</span><span>2</span><span>3</span>`.
//!
//! ### `verbatim`
//!
//! When it is needed to escape all expressions and statements and to render them as-is, you can
//! use the `verbatim` statement like that:
//!
//! ```text
//! {% verbatim %}
//! This won't be replaced: {{ something }}
//! {% endverbatim %}
//! ```
//!
//! ### Quirks
//!
//! - Nested objects defined in template expressions need to have spaces between their curly braces
//! to differentiate them from template expression delimiters.
//!
//! **Bad**:
//!
//! ```text
//! {{ {a: {b: "letters"}} }}
//! ```
//!
//! The error will be:
//!
//! <style>
//! pre#no-styles {
//!   background-color: initial;
//!   padding: 0px;
//!   line-height: initial;
//!   padding: 16px;
//!   border: 2px solid #D5D5D5;
//! }
//! </style>
//!
//! <pre id="no-styles" style="font-family: monospace, sans-serif;"><span style="color: red; font-weight: 600;">error</span><span style="font-weight: 600;">: unterminated object</span>
//! <span style="margin-left: 2rem; color: #666; font-size: 0.9em;">./index.html:1:7</span>
//!
//! <code style="background-color: #F5F5F5; color: black; width: max-content; display: inline-block; padding: 14px; line-height: 1.5;">1 | {{ {a:<span style="font-weight: 900; color: red;">{</span>b: "letters"}} }}</code></pre>
//!
//! **Fixed**:
//!
//! ```text
//! {{ {a: {b: "letters"} } }}
//! ```
//!
//! - Support for boolean HTML attributes like the [`selected` attribute of `<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/option#selected) is done using boolean values in expressions like:
//!   ```
//!   // In a Rust file
//!   use pochoir::{object, Context};
//!
//!   let mut context = Context::new();
//!   context.insert("fruits", vec!["Banana", "Orange", "Apple"]);
//!   context.insert("selected_fruit", "Orange");
//!   ```
//!
//!   ```html
//!   <select>
//!     {% for fruit in fruits %}
//!     <option selected="{{ fruit == selected_fruit }}">{{ fruit }}</option>
//!     {% endfor %}
//!   </select>
//!   ```
//!
//!   Will render as:
//!
//!   ```html
//!   <select>
//!     <option>Banana</option>
//!     <option selected>Orange</option>
//!     <option>Apple</option>
//!   </select>
//!   ```
//!
//!
//! ### Where to go next?
//!
//! - Check out [the `pochoir-lang` crate](`pochoir_lang`) to learn more about what syntax you can
//!   use in expressions (like how to do ranges, how to make or call a function)
//! - Check out [the examples](https://gitlab.com/encre-org/pochoir/-/tree/main/crates/pochoir/examples) to better know what is possible to do with `pochoir`
//! - Check out [the documentation about transformers](`crate::transformers`), they are used to manipulate HTML trees
//! - Check out [the documentation about providers](`crate::providers`), they are used to store
//!   your component sources
//!
//! ### Errors
//!
//! `pochoir` and its sibling crates use a flexible error management system based on the [`Spanned`] structure that you have to
//! check in order to get the span of text and the file name producing the error. `pochoir` adds a
//! third value that you can get: the name of the component throwing the error by using the
//! [`SpannedWithComponent`] wrapper structure. Moreover the [`Error`] structure of the `pochoir`
//! crate uses the [`AutoError`] trait to convert all errors of sibling crates (`pochoir-template-engine`,
//! `pochoir-lang`, …) to the single [`Error`] structure of the main crate).
//!
//! ### Playground
//!
//! A web playground using `WebAssembly` is available at <https://encre-org.gitlab.io/pochoir-playground>
//! to try the syntax out.
//!
//! [`Context::insert_inherited`]: Context::insert_inherited
use convert_case::{Case, Casing};
use std::{
    borrow::{Borrow, Cow},
    collections::{HashMap, HashSet},
    fmt::Write,
    path::Path,
};

use crate::component_file::ComponentFile;
use crate::error::{
    AutoError, AutoErrorWithName, AutoErrorWithNameOffset, Error, Result, SpannedWithComponent,
};
use crate::lang::{Context, Value};
use crate::parser::{Node, ParseEvent, Tree, TreeRefId, EMPTY_HTML_ELEMENTS};
use crate::template_engine::{Escaping, TemplateBlock};
use crate::transformers::Transformers;
use crate::{
    common::{Spanned, StreamParser},
    TransformerElementContext,
};

/// Tests if an element is a custom element using its name.
///
/// <https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name>
pub fn is_custom_element(name: &str) -> bool {
    name.starts_with(char::is_lowercase)
        && name.contains('-')
        && ![
            "annotation-xml",
            "color-profile",
            "font-face",
            "font-face-src",
            "font-face-uri",
            "font-face-format",
            "font-face-name",
            "missing-glyph",
        ]
        .contains(&name)
}

#[derive(Debug)]
struct CompilationContext<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h> {
    name: &'a str,
    context: &'b mut Context,
    tree: &'c Tree<'d>,
    node_ids: Vec<TreeRefId>,
    slots: &'e HashMap<Cow<'f, str>, Vec<TreeRefId>>,
    parent: Option<&'g CompilationContext<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h>>,
    extra_attr_on_all_elements: Option<&'h str>,
    raw: bool,
    spaceless: bool,
    verbatim: bool,
}

#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
fn eval_stmt<'a, 'b, 'c, 'd>(
    stmt_expr: &str,
    ctx: &mut CompilationContext<'_, '_, '_, 'a, '_, '_, '_, '_>,
    component_resolver: &mut impl FnMut(&str) -> Result<ComponentFile<'c, 'd>>,
    node_index: &mut usize,
    result: &mut String,
    components: Cow<HashMap<String, Tree<'a>>>,
    file_offset: usize,
    transformers: &mut Transformers,
    unique_elements: &mut HashSet<(String, usize)>,
) -> Result<()> {
    let mut parser = StreamParser::new(ctx.tree.file_path(), stmt_expr);

    if parser.take_exact("if ").is_ok() {
        parser.trim();
        let is_let = parser.take_exact("let ").is_ok();
        parser.trim();
        let expr_index = parser.index();
        let expr = parser.take_until_eoi().trim();

        let mut if_branches = vec![(expr.to_string(), is_let, vec![])];
        let mut else_branch = vec![];
        let mut in_else = false;
        let mut count_if = 0;

        while *node_index < ctx.node_ids.len() {
            let node_id = ctx.node_ids[*node_index];
            let node = ctx.tree.get(node_id);
            *node_index += 1;

            match &node.data() {
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s.starts_with("if ") => {
                    if in_else {
                        else_branch.push(node_id);
                    } else {
                        if_branches.last_mut().unwrap().2.push(node_id);
                    }
                    count_if += 1;
                }
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s.starts_with("elif ") => {
                    if count_if > 1 {
                        if in_else {
                            else_branch.push(node_id);
                        } else {
                            if_branches.last_mut().unwrap().2.push(node_id);
                        }
                    } else if in_else {
                        return Err(SpannedWithComponent::new(Error::ElifAfterElse)
                            .with_span(node.spanned_data().span().clone())
                            .with_file_path(ctx.tree.file_path())
                            .with_component_name(ctx.name));
                    } else {
                        let val = s.strip_prefix("elif ").unwrap().trim();
                        let (is_let, val) = if let Some(val) = val.strip_prefix("let ") {
                            (true, val.trim_start())
                        } else {
                            (false, val)
                        };
                        if_branches.push((val.to_string(), is_let, vec![]));
                    }
                }
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s == "endif" => {
                    if count_if == 0 {
                        break;
                    }

                    if in_else {
                        else_branch.push(node_id);
                    } else {
                        if_branches.last_mut().unwrap().2.push(node_id);
                    }
                    count_if -= 1;
                }
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s == "else" => {
                    if count_if == 0 {
                        in_else = true;
                    } else if in_else {
                        else_branch.push(node_id);
                    } else {
                        if_branches.last_mut().unwrap().2.push(node_id);
                    }
                }
                _ if in_else => else_branch.push(node_id),
                _ => if_branches.last_mut().unwrap().2.push(node_id),
            }
        }

        // Evaluate the conditions
        let mut if_matched = None;

        for (i, branch) in if_branches.iter().enumerate() {
            let cond_result = pochoir_lang::eval(
                ctx.tree.file_path(),
                &branch.0,
                ctx.context,
                file_offset + expr_index,
            )
            .auto_error()?;
            if (branch.1 && cond_result != Value::Null) || cond_result == Value::Bool(true) {
                if_matched = Some(i);
                break;
            }
        }

        if let Some(if_matched) = if_matched {
            let old_node_ids = ctx.node_ids.clone();
            ctx.node_ids = if_branches.remove(if_matched).2;
            compile_recursive(
                ctx,
                component_resolver,
                result,
                components,
                transformers,
                unique_elements,
            )?;
            ctx.node_ids = old_node_ids;
        } else {
            let old_node_ids = ctx.node_ids.clone();
            ctx.node_ids = else_branch;
            compile_recursive(
                ctx,
                component_resolver,
                result,
                components,
                transformers,
                unique_elements,
            )?;
            ctx.node_ids = old_node_ids;
        }
    } else if parser.take_exact("for ").is_ok() {
        parser.trim();
        let mut aliases = vec![];

        loop {
            parser.trim();

            let mut first = true;
            let alias = parser
                .take_while(|(_, ch)| {
                    if first {
                        first = false;
                        ch.is_alphabetic() || ch == '_'
                    } else {
                        ch.is_alphanumeric() || ch == '_'
                    }
                })
                .trim();
            aliases.push(alias);

            if parser.take_exact(",").is_err() {
                break;
            }
        }

        parser.trim();
        parser
            .take_exact("in ")
            .auto_error_with_name_offset(ctx.name, file_offset)?;
        parser.trim();

        let expr_index = parser.index();
        let expr = parser.take_until_eoi().trim();
        let expr_end_index = parser.index();

        let mut for_branch = vec![];
        let mut count_for = 0;

        while *node_index < ctx.node_ids.len() {
            let node_id = ctx.node_ids[*node_index];
            let node = ctx.tree.get(node_id);
            *node_index += 1;

            match &node.data() {
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s.starts_with("for ") => {
                    for_branch.push(node_id);
                    count_for += 1;
                }
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s == "endfor" => {
                    if count_for == 0 {
                        break;
                    }

                    for_branch.push(node_id);
                    count_for -= 1;
                }
                _ => for_branch.push(node_id),
            }
        }

        // Evaluate the list of values
        let old_values = aliases
            .iter()
            .map(|a| ctx.context.get(*a).cloned())
            .collect::<Vec<Option<Value>>>();
        let old_node_ids = ctx.node_ids.clone();

        let interpreted_val = crate::lang::eval(
            ctx.tree.file_path(),
            expr,
            ctx.context,
            file_offset + expr_index,
        )
        .auto_error_with_name(ctx.name)?;

        if let Value::Array(array) = interpreted_val {
            for item in array {
                if aliases.len() == 1 {
                    ctx.context.insert(aliases[0], item);
                } else {
                    match item {
                        Value::Array(array) => {
                            // The value can be destructured using the order of aliases
                            for (i, alias) in aliases.iter().enumerate() {
                                ctx.context
                                    .insert(*alias, array.get(i).cloned().unwrap_or(Value::Null));
                            }
                        }
                        Value::Object(object) => {
                            // The value can be destructured using the keys
                            for alias in &aliases {
                                ctx.context.insert(
                                    *alias,
                                    object.get(*alias).cloned().unwrap_or(Value::Null),
                                );
                            }
                        }
                        _ => {
                            // The value cannot be destructured, make all aliases null
                            for alias in &aliases {
                                ctx.context.insert(*alias, Value::Null);
                            }
                        }
                    }
                }

                ctx.node_ids.clone_from(&for_branch);

                compile_recursive(
                    ctx,
                    component_resolver,
                    result,
                    Cow::Borrowed(&*components),
                    transformers,
                    unique_elements,
                )?;
            }
        } else if let Value::Range(start, end) = interpreted_val {
            let range = match (start, end) {
                (Some(start), Some(end)) => start..end,
                _ => {
                    return Err(SpannedWithComponent::new(Error::UnboundedRangeInForLoop)
                        .with_span(file_offset + expr_index..file_offset + expr_end_index)
                        .with_file_path(ctx.tree.file_path())
                        .with_component_name(ctx.name));
                }
            };

            for item in range {
                if aliases.len() == 1 {
                    ctx.context.insert(aliases[0], item);
                } else {
                    for alias in &aliases {
                        ctx.context.insert(*alias, Value::Null);
                    }
                }

                ctx.node_ids.clone_from(&for_branch);

                compile_recursive(
                    ctx,
                    component_resolver,
                    result,
                    Cow::Borrowed(&*components),
                    transformers,
                    unique_elements,
                )?;
            }
        }

        ctx.node_ids = old_node_ids;

        for (i, old_val) in old_values.into_iter().enumerate() {
            if let Some(old_val) = old_val {
                ctx.context.insert(aliases[i], old_val);
            } else {
                ctx.context.remove(aliases[i]);
            }
        }
    } else if parser.take_exact("let ").is_ok() {
        parser.trim();
        let mut first = true;
        let name = parser
            .take_while(|(_, ch)| {
                if first {
                    first = false;
                    ch.is_alphabetic() || ch == '_'
                } else {
                    ch.is_alphanumeric() || ch == '_'
                }
            })
            .trim();
        parser.trim();
        parser
            .take_exact("=")
            .auto_error_with_name_offset(ctx.name, file_offset)?;
        parser.trim();
        let expr_index = parser.index();
        let expr = parser.take_until_eoi().trim();

        let val_evaluated = crate::lang::eval(
            ctx.tree.file_path(),
            expr,
            ctx.context,
            file_offset + expr_index,
        )
        .auto_error_with_name(ctx.name)?;

        ctx.context.insert((*name).to_string(), val_evaluated);
    } else if parser.take_exact("spaceless").is_ok() && parser.is_eoi() {
        let last_ch_not_whitespace_index = result
            .rfind(|ch: char| !ch.is_whitespace())
            .map_or(0, |i| i + 1);
        result.truncate(last_ch_not_whitespace_index);

        let mut spaceless_branch = vec![];

        while *node_index < ctx.node_ids.len() {
            let node_id = ctx.node_ids[*node_index];
            let node = ctx.tree.get(node_id);
            *node_index += 1;

            match &node.data() {
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s == "endspaceless" => break,
                _ => spaceless_branch.push(node_id),
            }
        }

        let old_spaceless = ctx.spaceless;
        ctx.spaceless = true;

        let old_node_ids = ctx.node_ids.clone();
        ctx.node_ids = spaceless_branch;

        compile_recursive(
            ctx,
            component_resolver,
            result,
            Cow::Borrowed(&*components),
            transformers,
            unique_elements,
        )?;
        ctx.spaceless = old_spaceless;

        // Make sure to remove spaces after the verbatim statement itself
        let old_result_len = result.len();
        while *node_index < old_node_ids.len() {
            let node_id = old_node_ids[*node_index];
            *node_index += 1;

            ctx.node_ids = vec![node_id];
            compile_recursive(
                ctx,
                component_resolver,
                result,
                Cow::Borrowed(&*components),
                transformers,
                unique_elements,
            )?;

            if result.len() != old_result_len {
                break;
            }
        }

        let ch_not_whitespace_index = result[old_result_len..]
            .find(|ch: char| !ch.is_whitespace())
            .unwrap_or(result.len() - old_result_len);
        result.drain(old_result_len..old_result_len + ch_not_whitespace_index);

        ctx.node_ids = old_node_ids;
    } else if parser.take_exact("verbatim").is_ok() && parser.is_eoi() {
        let mut verbatim_branch = vec![];

        while *node_index < ctx.node_ids.len() {
            let node_id = ctx.node_ids[*node_index];
            let node = ctx.tree.get(node_id);
            *node_index += 1;

            match &node.data() {
                Node::TemplateBlock(TemplateBlock::Stmt(s)) if s == "endverbatim" => break,
                _ => verbatim_branch.push(node_id),
            }
        }

        let old_verbatim = ctx.verbatim;
        ctx.verbatim = true;

        let old_node_ids = ctx.node_ids.clone();
        ctx.node_ids = verbatim_branch;

        compile_recursive(
            ctx,
            component_resolver,
            result,
            Cow::Borrowed(&*components),
            transformers,
            unique_elements,
        )?;
        ctx.verbatim = old_verbatim;
        ctx.node_ids = old_node_ids;
    } else {
        return Err(SpannedWithComponent::new(Error::UnknownStatement {
            stmt: stmt_expr[..stmt_expr
                .find(char::is_whitespace)
                .unwrap_or(stmt_expr.len())]
                .to_string(),
        })
        .with_span(
            // The last node was the statement node, that's why we need to use node_index - 1
            ctx.tree
                .get(ctx.node_ids[*node_index - 1])
                .spanned_data()
                .span()
                .clone(),
        )
        .with_file_path(ctx.tree.file_path())
        .with_component_name(ctx.name));
    }

    Ok(())
}

fn render_template_block<'a, 'b, 'c, 'd, 'e, T: Borrow<TemplateBlock<'e>>>(
    ctx: &mut CompilationContext<'_, '_, '_, 'a, '_, '_, '_, '_>,
    component_resolver: &mut impl FnMut(&str) -> Result<ComponentFile<'c, 'd>>,
    node_index: &mut usize,
    blocks: &[Spanned<T>],
    result: &mut String,
    components: &HashMap<String, Tree<'a>>,
    transformers: &mut Transformers,
    unique_elements: &mut HashSet<(String, usize)>,
) -> Result<()> {
    for block in blocks {
        match (**block).borrow() {
            TemplateBlock::RawText(text) => {
                // If the `spaceless` mode is used and the node before is an element, trim the
                // start of the text
                //
                // node_index points to the ID of the **next** node
                let needs_trimming = if ctx.spaceless {
                    if *node_index == 1 {
                        // If the text block is the first child of the parent element, it must be
                        // trimmed
                        true
                    } else {
                        matches!(
                            ctx.tree.get(ctx.node_ids[*node_index - 2]).data(),
                            Node::Element(_, _)
                        )
                    }
                } else {
                    false
                };

                if needs_trimming {
                    result.push_str(text.trim_start());
                } else {
                    result.push_str(text);
                }
            }
            TemplateBlock::Expr(expr, escape) => {
                if ctx.verbatim {
                    result.push_str("{{");
                    result.push_str(expr);
                    result.push_str("}}");
                } else {
                    let expr_evaluated = crate::lang::eval(
                        ctx.tree.file_path(),
                        expr,
                        ctx.context,
                        block.span().start,
                    )
                    .auto_error_with_name(ctx.name)?
                    .to_string();

                    if *escape {
                        result.push_str(&Escaping::Html.escape(&expr_evaluated));
                    } else {
                        result.push_str(&expr_evaluated);
                    }
                }
            }
            TemplateBlock::Stmt(stmt_expr) => {
                if ctx.verbatim {
                    result.push_str("{%");
                    result.push_str(stmt_expr);
                    result.push_str("%}");
                } else {
                    eval_stmt(
                        stmt_expr,
                        ctx,
                        component_resolver,
                        node_index,
                        result,
                        Cow::Borrowed(components),
                        block.span().start,
                        transformers,
                        unique_elements,
                    )?;
                }
            }
        }
    }

    Ok(())
}

fn compile_template_block<'a, 'b, 'c, 'd>(
    ctx: &mut CompilationContext<'_, '_, '_, 'a, '_, '_, '_, '_>,
    component_resolver: &mut impl FnMut(&str) -> Result<ComponentFile<'c, 'd>>,
    node_index: &mut usize,
    blocks: &[Spanned<TemplateBlock>],
    in_attr: bool,
    components: &HashMap<String, Tree<'a>>,
    transformers: &mut Transformers,
    unique_elements: &mut HashSet<(String, usize)>,
) -> Result<Value> {
    let mut evaluated_value = Value::String(String::new());

    for (i, block) in blocks.iter().enumerate() {
        let val = match &**block {
            TemplateBlock::RawText(text) => Value::String(text.to_string()),
            TemplateBlock::Expr(expr, _) => {
                crate::lang::eval(ctx.tree.file_path(), expr, ctx.context, block.span().start)
                    .auto_error_with_name(ctx.name)?
            }
            TemplateBlock::Stmt(stmt_expr) => {
                if in_attr {
                    // If an attribute contains a statement, its value will always be a string so
                    // we can consider all nodes as string and use the render function of the
                    // template engine on **all** blocks
                    let val: Cow<Value> = Cow::Owned(Value::String(
                        crate::template_engine::render_template(&blocks[i..], ctx.context)
                            .auto_error_with_name(ctx.name)?,
                    ));

                    return Ok(Value::String(
                        evaluated_value.to_string() + &val.to_string(),
                    ));
                }

                let mut value_string = String::new();
                eval_stmt(
                    stmt_expr,
                    ctx,
                    component_resolver,
                    node_index,
                    &mut value_string,
                    Cow::Borrowed(components),
                    block.span().start,
                    transformers,
                    unique_elements,
                )?;

                Value::String(value_string)
            }
        };

        if val == Value::Null {
            // Ignore Null values
        } else if matches!(&evaluated_value, Value::String(ref s) if s.is_empty()) {
            evaluated_value = val;
        } else {
            evaluated_value = Value::String(evaluated_value.to_string() + &val.to_string());
        }
    }

    Ok(evaluated_value)
}

fn parse_and_tranform<'a>(
    file_path: &Path,
    component_name: &str,
    data: &'a str,
    context: &mut Context,
    transformers: &mut Transformers,
) -> Result<Tree<'a>> {
    let mut builder = pochoir_parser::Builder::new();

    if !transformers.inner.is_empty() {
        builder = builder.on_event(|event, tree, id| match event {
            ParseEvent::BeforeElement => transformers.inner.iter_mut().try_for_each(|t| {
                t.on_before_element(&mut TransformerElementContext {
                    tree,
                    context,
                    element_id: id,
                })
            }),
            ParseEvent::AfterElement => transformers.inner.iter_mut().try_for_each(|t| {
                t.on_after_element(&mut TransformerElementContext {
                    tree,
                    context,
                    element_id: id,
                })
            }),
        });
    }

    let mut tree = builder
        .parse(file_path, data)
        .auto_error_with_name(component_name)?;

    if !transformers.inner.is_empty() {
        transformers
            .inner
            .iter_mut()
            .try_for_each(|t| {
                t.on_tree_parsed(&mut crate::TransformerTreeContext {
                    tree: &mut tree,
                    context,
                    component_name,
                    file_path,
                })
            })
            .map_err(|e| {
                SpannedWithComponent::new(Error::ParserError(
                    crate::parser::Error::EventHandlerError(e.to_string()),
                ))
                .with_file_path(file_path)
                .with_component_name(component_name)
            })?;
    }

    Ok(tree)
}

/// Compile template file with full control over how the source files are fetched.
///
/// This function uses a closure (the *component resolver*) taking the name of the component and
/// returning a [`ComponentFile`] with the file name and data.
///
/// ```
/// # fn main() -> pochoir::Result<()> {
/// use pochoir::{Context, ComponentFile, error};
/// use std::path::Path;
///
/// let html = pochoir::compile("index", &mut Context::new(), |name| {
///     // In a real world usage, you would fetch the HTML from a complex, dynamic,
///     // pipeline of sources, maybe from the network.
///     // A `ComponentFile` is used to associate some data with a path to a file,
///     // if it was fetched from the filesystem. You can use
///     // `ComponentFile::new_inline` if you don't want to provide a path, in this
///     // case the path will simply be `inline`
///     Ok(match name {
///         "index" => ComponentFile::new_inline("<h1>Index page</h1><my-button />"),
///         "my-button" => ComponentFile::new(Path::new("my-button.html"), "<button>Click me!</button>"),
///         _ => return Err(error::component_not_found(name)),
///     })
/// })?;
/// # Ok(())
/// # }
/// ```
///
/// If you want high level structures taking care of source for you, you can use [`providers`](`crate::providers`).
///
/// # Errors
///
/// It is up to you to format runtime errors (e.g using [`error::display_ansi_error`]
/// or [`error::display_html_error`]).
///
/// For example, to display the error using ANSI escape codes (to be used in shells) you can
/// call it like this:
///
/// ```
/// use pochoir::{compile, Context, ComponentFile};
///
/// let source = "<h1>A title</h1>{{ [1, 2]['abc'] }}";
/// let compiled = pochoir::compile("index", &mut Context::new(), |name| {
///     Ok(ComponentFile::new_inline(source))
/// }).map_err(|e| {
///     // Runtime error formatting happens here, it uses
///     // `pochoir::common::Spanned::component_name` to get
///     // the name of the component which raised the error and
///     // fetches it from the provider to get the text source of
///     // the component
///     pochoir::error::display_ansi_error(
///         &e,
///         &source,
///     )
/// });
///
/// assert_eq!(
///     compiled,
///     Err("\u{1b}[1m\u{1b}[31merror\u{1b}[0m\u{1b}[1m: array cannot be indexed by String, the index must be a positive number or a range\u{1b}[0m\n   inline:1:27\n\n \u{1b}[1m\u{1b}[34m1 |\u{1b}[0m <h1>A title</h1>{{ [1, 2][\u{1b}[1m\u{1b}[31m'abc'\u{1b}[0m] }}".to_string())
/// );
/// ```
///
/// [`error::display_ansi_error`]: crate::error::display_ansi_error
/// [`error::display_html_error`]: crate::error::display_html_error
pub fn compile<'a, 'b, 'c>(
    default_component_name: &str,
    default_context: &mut Context,
    component_resolver: impl FnMut(&str) -> Result<ComponentFile<'b, 'c>>,
) -> Result<String> {
    transform_and_compile(
        default_component_name,
        default_context,
        component_resolver,
        &mut Transformers::new(),
    )
}

/// Compile each template while applying transformers.
///
/// See [`transformers`](`crate::transformers`) and [`compile`].
///
/// # Errors
///
/// It is up to you to format runtime errors (e.g using [`error::display_ansi_error`]
/// or [`error::display_html_error`]).
///
/// For example, to display the error using ANSI escape codes (to be used in shells) you can
/// call it like this:
///
/// ```
/// use pochoir::{compile, Context, Transformers, ComponentFile};
///
/// let source = "<h1>A title</h1>{{ [1, 2]['abc'] }}";
/// let compiled = pochoir::transform_and_compile("index", &mut Context::new(), |name| {
///     Ok(ComponentFile::new_inline(source))
/// }, &mut Transformers::new()).map_err(|e| {
///     // Runtime error formatting happens here, it uses
///     // `pochoir::common::Spanned::component_name` to get
///     // the name of the component which raised the error and
///     // fetches it from the provider to get the text source of
///     // the component
///     pochoir::error::display_ansi_error(
///         &e,
///         &source,
///     )
/// });
///
/// assert_eq!(
///     compiled,
///     Err("\u{1b}[1m\u{1b}[31merror\u{1b}[0m\u{1b}[1m: array cannot be indexed by String, the index must be a positive number or a range\u{1b}[0m\n   inline:1:27\n\n \u{1b}[1m\u{1b}[34m1 |\u{1b}[0m <h1>A title</h1>{{ [1, 2][\u{1b}[1m\u{1b}[31m'abc'\u{1b}[0m] }}".to_string())
/// );
/// ```
///
/// [`error::display_ansi_error`]: crate::error::display_ansi_error
/// [`error::display_html_error`]: crate::error::display_html_error
pub fn transform_and_compile<'a, 'b, 'c>(
    default_component_name: &str,
    default_context: &mut Context,
    mut component_resolver: impl FnMut(&str) -> Result<ComponentFile<'b, 'c>>,
    transformers: &mut Transformers,
) -> Result<String> {
    component_resolver(default_component_name).and_then(|file| {
        let mut result = String::new();
        let tree = parse_and_tranform(
            &file.path,
            default_component_name,
            &file.data,
            default_context,
            transformers,
        )?;

        compile_recursive(
            &mut CompilationContext {
                name: default_component_name,
                context: default_context,
                tree: &tree,
                node_ids: tree.root_nodes(),
                slots: &HashMap::new(),
                parent: None,
                extra_attr_on_all_elements: None,
                raw: false,
                spaceless: false,
                verbatim: false,
            },
            &mut component_resolver,
            &mut result,
            Cow::Borrowed(&HashMap::new()),
            transformers,
            &mut HashSet::new(),
        )?;

        Ok(result)
    })
}

#[allow(clippy::too_many_lines)]
fn compile_recursive<'a, 'b, 'c, 'd>(
    ctx: &mut CompilationContext<'_, '_, '_, 'a, '_, '_, '_, '_>,
    component_resolver: &mut impl FnMut(&str) -> Result<ComponentFile<'c, 'd>>,
    result: &mut String,
    mut components: Cow<HashMap<String, Tree<'a>>>,
    transformers: &mut Transformers,
    unique_elements: &mut HashSet<(String, usize)>,
) -> Result<()> {
    let mut node_index = 0;

    while node_index < ctx.node_ids.len() {
        let node = ctx.tree.get(ctx.node_ids[node_index]);
        node_index += 1;

        match node.data() {
            Node::Element(el_name, attrs) => {
                if el_name == "slot" && !ctx.raw {
                    // Slot element
                    let slot_name_blocks = node
                        .attr_spanned("name")
                        .expect("attr_spanned is called on an element")
                        .unwrap_or(vec![Spanned::new(TemplateBlock::text("default"))]);

                    let mut slot_name = String::new();
                    render_template_block(
                        ctx,
                        component_resolver,
                        &mut node_index,
                        &slot_name_blocks,
                        &mut slot_name,
                        &components,
                        transformers,
                        unique_elements,
                    )?;

                    if let Some(node_ids) = ctx.slots.get(&*slot_name) {
                        // Add all the other attributes passed to the <slot> element to the
                        // context (for scoped slots)
                        let mut context = ctx
                            .parent
                            .expect("slot element should be used in a component")
                            .context
                            .clone();

                        // Insert inherited variables
                        for (key, val) in ctx
                            .context
                            .iter()
                            .filter(|(k, _)| ctx.context.is_inherited(&**k).unwrap())
                        {
                            context.insert(key, val.clone());
                            context.make_inherited(key);
                        }

                        for (key, val_blocks) in attrs {
                            if (**key == "slot" || **key == "'__p_attr'" || **key == "pochoir-once")
                                && !ctx.raw
                            {
                                // Ignore the `slot`, `'__p_attr'` and `pochoir-once` attributes
                                continue;
                            }

                            let evaluated_value = compile_template_block(
                                ctx,
                                component_resolver,
                                &mut node_index,
                                val_blocks,
                                true,
                                &components,
                                transformers,
                                unique_elements,
                            )?;

                            context.insert(&***key, evaluated_value);
                        }

                        let mut rendered = String::new();
                        compile_recursive(
                            &mut CompilationContext {
                                name: ctx
                                    .parent
                                    .expect("slot element should be used in a component")
                                    .name,
                                context: &mut context,
                                tree: ctx
                                    .parent
                                    .expect("slot element should be used in a component")
                                    .tree,
                                node_ids: node_ids.clone(),
                                parent: ctx
                                    .parent
                                    .expect("slot element should be used in a component")
                                    .parent,
                                slots: ctx
                                    .parent
                                    .expect("slot element should be used in a component")
                                    .slots,
                                extra_attr_on_all_elements: attrs
                                    .get("'__p_attr'")
                                    .and_then(|v| v.first())
                                    .and_then(|v| {
                                        if let TemplateBlock::RawText(attr_val) = &**v {
                                            Some(&**attr_val)
                                        } else {
                                            None
                                        }
                                    }),
                                raw: ctx.raw,
                                spaceless: ctx.spaceless,
                                verbatim: ctx.verbatim,
                            },
                            component_resolver,
                            &mut rendered,
                            Cow::Borrowed(&*components),
                            transformers,
                            unique_elements,
                        )?;

                        if rendered.is_empty() {
                            // Try to use the default content
                            //
                            // Default slot content must not have nested <slot> so it is safe to
                            // make an empty list of slots
                            compile_recursive(
                                &mut CompilationContext {
                                    name: ctx.name,
                                    context: ctx.context,
                                    tree: ctx.tree,
                                    node_ids: node.children_id(),
                                    parent: ctx.parent,
                                    slots: &HashMap::new(),
                                    extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                                    raw: ctx.raw,
                                    spaceless: ctx.spaceless,
                                    verbatim: ctx.verbatim,
                                },
                                component_resolver,
                                result,
                                Cow::Borrowed(&*components),
                                transformers,
                                unique_elements,
                            )?;
                        } else {
                            result.push_str(&rendered);
                        }
                    } else {
                        // Try to use the default content
                        //
                        // Default slot content must not have nested <slot> so it is safe to
                        // make an empty list of slots
                        compile_recursive(
                            &mut CompilationContext {
                                name: ctx.name,
                                context: ctx.context,
                                tree: ctx.tree,
                                node_ids: node.children_id(),
                                parent: ctx.parent,
                                slots: &HashMap::new(),
                                extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                                raw: ctx.raw,
                                spaceless: ctx.spaceless,
                                verbatim: ctx.verbatim,
                            },
                            component_resolver,
                            result,
                            Cow::Borrowed(&*components),
                            transformers,
                            unique_elements,
                        )?;
                    }
                } else if el_name == "template"
                    && node
                        .attr("shadowrootmode")
                        .expect("attr is called on an element")
                        .is_some()
                    && !ctx.raw
                {
                    // If the "shadowrootmode" attribute is set, components and slots must not be
                    // replaced but expressions are evaluated
                    compile_recursive(
                        &mut CompilationContext {
                            name: el_name,
                            context: ctx.context,
                            tree: ctx.tree,
                            node_ids: vec![node.id()],
                            slots: &HashMap::new(),
                            parent: ctx.parent,
                            extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                            raw: true,
                            spaceless: ctx.spaceless,
                            verbatim: ctx.verbatim,
                        },
                        component_resolver,
                        result,
                        Cow::Borrowed(&*components),
                        transformers,
                        &mut HashSet::new(),
                    )?;
                } else if el_name == "template"
                    && node
                        .attr("pochoir-hybrid")
                        .expect("attr is called on an element")
                        .is_some()
                {
                    let name_blocks = node
                        .attr_spanned("name")
                        .expect("attr_spanned is called on an element")
                        .unwrap_or(vec![Spanned::new(TemplateBlock::text("default"))]);

                    let mut name = String::new();
                    render_template_block(
                        ctx,
                        component_resolver,
                        &mut node_index,
                        &name_blocks,
                        &mut name,
                        &components,
                        transformers,
                        unique_elements,
                    )?;

                    components.to_mut().insert(name, node.sub_tree());

                    // Build the HTML tree corresponding to the template with the <template>
                    // element itself as root
                    let mut template_tree = Tree::new(ctx.tree.file_path());
                    template_tree.insert(TreeRefId::Root, node.spanned_data().clone());
                    template_tree
                        .get_mut(TreeRefId::Node(0))
                        .remove_attr("pochoir-hybrid");
                    template_tree
                        .get_mut(TreeRefId::Node(0))
                        .append_children(&node.sub_tree());

                    let rendered = pochoir_parser::render(&template_tree);
                    write!(result, "{rendered}").expect("writing to a String can't fail");
                } else if el_name == "template" && !ctx.raw {
                    let name_blocks = node
                        .attr_spanned("name")
                        .expect("attr_spanned is called on an element")
                        .unwrap_or(vec![Spanned::new(TemplateBlock::text("default"))]);

                    let mut name = String::new();
                    render_template_block(
                        ctx,
                        component_resolver,
                        &mut node_index,
                        &name_blocks,
                        &mut name,
                        &components,
                        transformers,
                        unique_elements,
                    )?;

                    components.to_mut().insert(name, node.sub_tree());
                } else if is_custom_element(el_name) {
                    // Component element
                    if el_name == ctx.name {
                        let spanned_data = node.spanned_data();
                        return Err(SpannedWithComponent::new(Error::CyclicComponent {
                            name: ctx.name.to_string(),
                        })
                        .with_span(spanned_data.span().clone())
                        .with_file_path(spanned_data.file_path())
                        .with_component_name(ctx.name));
                    }

                    // Attributes
                    let mut context = Context::new();

                    for (key, val_blocks) in attrs {
                        if (**key == "slot" || **key == "'__p_attr'" || **key == "pochoir-once")
                            && !ctx.raw
                        {
                            // Ignore the `slot`, `'__p_attr` and `pochoir-once` attribute
                            continue;
                        }

                        let evaluated_value = compile_template_block(
                            ctx,
                            component_resolver,
                            &mut node_index,
                            val_blocks,
                            true,
                            &components,
                            transformers,
                            unique_elements,
                        )?;
                        context.insert(key.to_case(Case::Snake), evaluated_value);
                    }

                    // Insert inherited variables
                    for (key, val) in ctx
                        .context
                        .iter()
                        .filter(|(k, _)| ctx.context.is_inherited(&**k).unwrap())
                    {
                        context.insert(key, val.clone());
                        context.make_inherited(key);
                    }

                    // To extend the lifetime of the component source in case it was resolved from
                    // the closure, we need to store it in an Option<T> before the closure is
                    // called.
                    let mut resolved_component_file = None;
                    let component_result = components
                        .get(&**el_name)
                        .ok_or(())
                        .map(Cow::Borrowed)
                        .or_else(|()| {
                            let file = component_resolver(el_name)?;
                            resolved_component_file = Some(file);
                            parse_and_tranform(
                                &resolved_component_file.as_ref().unwrap().path,
                                el_name,
                                &resolved_component_file.as_ref().unwrap().data,
                                &mut context,
                                transformers,
                            )
                            .map(Cow::Owned)
                        });

                    match component_result {
                        Ok(tree) => {
                            // Slots
                            let mut slots: HashMap<Cow<str>, Vec<TreeRefId>> = HashMap::new();

                            for child_id in node.children_id() {
                                let child = ctx.tree.get(child_id);

                                // Get the `slot` attribute or use the default slot if the node is
                                // not an element or if it's not present
                                let slot_name_blocks = child
                                    .attr_spanned("slot")
                                    .unwrap_or_default()
                                    .unwrap_or(vec![Spanned::new(TemplateBlock::text("default"))]);

                                let mut slot_name = String::new();
                                render_template_block(
                                    ctx,
                                    component_resolver,
                                    &mut node_index,
                                    &slot_name_blocks,
                                    &mut slot_name,
                                    &components,
                                    transformers,
                                    unique_elements,
                                )?;

                                if let Some(children) = slots.get_mut(&*slot_name) {
                                    children.push(child_id);
                                } else {
                                    slots.insert(Cow::Owned(slot_name), vec![child_id]);
                                }
                            }

                            let contains_shadowrootmode =
                                tree.select("template[shadowrootmode]").unwrap().is_some();

                            if contains_shadowrootmode {
                                write!(result, "<{el_name}")
                                    .expect("writing to a String can't fail");

                                // Attributes
                                for (key, val_blocks) in attrs {
                                    if (**key == "slot"
                                        || **key == "'__p_attr'"
                                        || **key == "pochoir-once")
                                        && !ctx.raw
                                    {
                                        // Ignore the `slot`, `'__p_attr` and `pochoir-once` attribute
                                        continue;
                                    }

                                    // We don't care about HTML elements (like slots or components) in attribute values, so we can
                                    // just use the render function of the template engine instead of the
                                    // render_template_block function
                                    let attr_val = crate::template_engine::render_template(
                                        val_blocks,
                                        ctx.context,
                                    )
                                    .auto_error_with_name(ctx.name)?;

                                    if attr_val.is_empty() {
                                        write!(result, " {}", **key)
                                            .expect("writing to a String can't fail");
                                    } else {
                                        write!(result, " {}=\"{}\"", **key, attr_val)
                                            .expect("writing to a String can't fail");
                                    }
                                }

                                write!(result, ">").expect("writing to a String can't fail");
                            }

                            compile_recursive(
                                &mut CompilationContext {
                                    name: el_name,
                                    context: &mut context,
                                    tree: &tree,
                                    node_ids: tree.root_nodes(),
                                    slots: &slots,
                                    parent: Some(ctx),
                                    extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                                    raw: ctx.raw,
                                    spaceless: ctx.spaceless,
                                    verbatim: ctx.verbatim,
                                },
                                component_resolver,
                                result,
                                Cow::Borrowed(&*components),
                                transformers,
                                unique_elements,
                            )?;

                            if contains_shadowrootmode {
                                compile_recursive(
                                    &mut CompilationContext {
                                        name: el_name,
                                        context: ctx.context,
                                        tree: ctx.tree,
                                        node_ids: node.children_id(),
                                        slots: &slots,
                                        parent: ctx.parent,
                                        extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                                        raw: true,
                                        spaceless: ctx.spaceless,
                                        verbatim: ctx.verbatim,
                                    },
                                    component_resolver,
                                    result,
                                    Cow::Borrowed(&*components),
                                    transformers,
                                    unique_elements,
                                )?;

                                write!(result, "</{el_name}>")
                                    .expect("writing to a String can't fail");
                            }
                        }
                        Err(e) if matches!(**e, Error::ComponentNotFound { .. }) => {
                            if let Error::ComponentNotFound { name } = (**e).clone() {
                                // Fix span of component not found error
                                let spanned_data = node.spanned_data();
                                return Err(SpannedWithComponent::new(Error::ComponentNotFound {
                                    name,
                                })
                                .with_span(spanned_data.span().clone())
                                .with_file_path(spanned_data.file_path())
                                .with_component_name(ctx.name));
                            }

                            unreachable!();
                        }
                        Err(e) => {
                            // An error occured in a component
                            return Err(e);
                        }
                    }
                } else {
                    // Not component element
                    if unique_elements.contains(&(ctx.name.to_string(), node_index)) {
                        continue;
                    }

                    write!(result, "<{el_name}").expect("writing to a String can't fail");

                    // Attributes
                    for (key, val_blocks) in attrs.iter().chain(
                        ctx.extra_attr_on_all_elements
                            .map(|key| (Spanned::new(Cow::Borrowed(key)), Spanned::new(vec![])))
                            .as_ref(),
                    ) {
                        if (**key == "slot" || **key == "'__p_attr'" || **key == "pochoir-once")
                            && !ctx.raw
                        {
                            // Ignore the `slot`, `'__p_attr` and `pochoir-once` attribute
                            continue;
                        }

                        // We don't care about HTML elements (like slots or components) in attribute values, so we can
                        // just use the render function of the template engine instead of the
                        // render_template_block function
                        let evaluated_value = compile_template_block(
                            ctx,
                            component_resolver,
                            &mut node_index,
                            val_blocks,
                            true,
                            &components,
                            transformers,
                            unique_elements,
                        )?;

                        if evaluated_value == Value::Null
                            || evaluated_value == Value::String(String::new())
                            || evaluated_value == Value::Bool(true)
                        {
                            write!(result, " {}", **key).expect("writing to a String can't fail");
                        } else if evaluated_value == Value::Bool(false) {
                            // Nothing to do, ignore the attribute
                        } else {
                            write!(result, " {}=\"{}\"", **key, evaluated_value)
                                .expect("writing to a String can't fail");
                        }
                    }

                    write!(result, ">").expect("writing to a String can't fail");

                    if attrs.get("pochoir-once").is_some() {
                        unique_elements.insert((ctx.name.to_string(), node_index));
                    }

                    // All nodes in the same component are considered as part of the same
                    // compilation context
                    compile_recursive(
                        &mut CompilationContext {
                            name: ctx.name,
                            context: ctx.context,
                            tree: ctx.tree,
                            node_ids: node.children_id(),
                            slots: ctx.slots,
                            parent: ctx.parent,
                            extra_attr_on_all_elements: ctx.extra_attr_on_all_elements,
                            raw: ctx.raw,
                            spaceless: ctx.spaceless,
                            verbatim: ctx.verbatim,
                        },
                        component_resolver,
                        result,
                        Cow::Borrowed(&*components),
                        transformers,
                        unique_elements,
                    )?;

                    if !EMPTY_HTML_ELEMENTS.contains(&&**el_name) {
                        write!(result, "</{el_name}>").expect("writing to a String can't fail");
                    }
                }
            }
            Node::Comment(_) => (),
            Node::Doctype(doctype) => {
                write!(result, "<!DOCTYPE {doctype}>").expect("writing to a String can't fail");
            }
            Node::TemplateBlock(block) => {
                render_template_block(
                    ctx,
                    component_resolver,
                    &mut node_index,
                    &[Spanned::new(block)
                        .with_span(node.spanned_data().span().clone())
                        .with_file_path(ctx.tree.file_path())],
                    result,
                    &components,
                    transformers,
                    unique_elements,
                )?;
            }
            Node::Root => unreachable!(),
        }
    }

    Ok(())
}