livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
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
//! Turn a component's `.livewire` source into the Jinja template the engine renders.
//!
//! A component file is Blade-flavoured HTML: `<livewire:…>` tags, `@livewire`,
//! `@this`, `@entangle`, `@assets`, `@script`, `@teleport`, `@persist`,
//! `@island`, and the three asset helpers. This module rewrites exactly those
//! constructs and copies every other byte. Jinja tags (`{{ … }}`, `{% … %}`,
//! `{# … #}`) are left untouched, and an `@word` it does not know stays where
//! it is, so Blade control flow such as `@if` survives verbatim.
//!
//! Two framework transforms are injected on request:
//!
//! * Morph markers — `<!--[if BLOCK]><![endif]-->` before an opening
//!   `{% if %}`/`{% for %}` and `<!--[if ENDBLOCK]><![endif]-->` after its
//!   closing tag, matching `SupportMorphAwareBladeCompilation` byte for byte.
//!   A block inside an HTML tag (a conditional class, for example) gets none:
//!   the browser's morph would otherwise see a marker inside an attribute.
//! * Smart wire keys — a nested component with no `wire:key` that sits inside a
//!   loop receives a deterministic key built from the template identity, the
//!   component's position in the source, and each enclosing `loop.index0`.
//!
//! `@island … @endisland` compiles to the `<!--[if FRAGMENT:…]><![endif]-->`
//! marker pair that `js/fragment.js` and `js/island.js` parse, carrying `type`,
//! `name`, `token`, and `mode` as `key=value` pairs.
//!
//! Compilation never fails: truncated input, an unclosed tag, or an unbalanced
//! directive is copied as it stands.

/// Where a component's source came from, which keys its nested components deterministically.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateIdentity {
    /// The component's name, such as `counter`.
    pub name: String,
    /// The view name or inline marker, such as `livewire.counter`.
    pub source: String,
}

impl TemplateIdentity {
    /// A stable, source-derived tag applied to this template's generated keys.
    fn hash(&self) -> String {
        let seed = if self.source.is_empty() {
            self.name.as_str()
        } else {
            self.source.as_str()
        };

        let mut hash: u32 = 0x811c_9dc5;

        for byte in seed.as_bytes() {
            hash ^= u32::from(*byte);
            hash = hash.wrapping_mul(0x0100_0193);
        }

        format!("{hash:08x}")
    }
}

/// What to inject while compiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompileOptions {
    /// Wrap conditionals, loops, and conditional class output in morph comments.
    pub inject_morph_markers: bool,
    /// Derive keys for nested components that have none, inside loops.
    pub smart_wire_keys: bool,
}

/// Translates the component source into the Jinja the engine compiles.
pub fn compile(source: &str, identity: &TemplateIdentity, options: CompileOptions) -> String {
    let mut compiler = Compiler::new(identity.hash(), options, loops_need_aliases(source));

    compiler.translate(source, false)
}

/// The morph marker that opens a block for the browser's morph.
const BLOCK_START: &str = "<!--[if BLOCK]><![endif]-->";

/// The morph marker that closes a block for the browser's morph.
const BLOCK_END: &str = "<!--[if ENDBLOCK]><![endif]-->";

/// One compilation: counters, the loop stack, and the nested regions it recurses into.
struct Compiler {
    /// Whether any loop holds a keyed nested component, so loops need aliases.
    alias_loops: bool,
    /// Recursion guard for nested slots, islands, and attribute values.
    depth: usize,
    /// This template's stable hash, used in keys and island tokens.
    hash: String,
    /// How many islands have been emitted, which distinguishes their tokens.
    island_occurrence: usize,
    /// How many loops have been given an alias.
    loop_occurrence: usize,
    /// The aliases of the loops enclosing the current position, outermost first.
    loops: Vec<String>,
    /// How many nested components have been emitted, which keeps keys distinct.
    occurrence: usize,
    /// The injection options.
    options: CompileOptions,
    /// How many slots have been captured.
    slot_occurrence: usize,
}

impl Compiler {
    /// Prepare one compilation.
    fn new(hash: String, options: CompileOptions, alias_loops: bool) -> Self {
        Self {
            alias_loops,
            depth: 0,
            hash,
            island_occurrence: 0,
            loop_occurrence: 0,
            loops: Vec::new(),
            occurrence: 0,
            options,
            slot_occurrence: 0,
        }
    }

    /// Compile a piece of the template, `in_tag` telling whether it starts inside an HTML tag.
    fn translate(&mut self, text: &str, in_tag: bool) -> String {
        if self.depth > 64 {
            return text.to_string();
        }

        self.depth += 1;

        let result = self.translate_inner(text, in_tag);

        self.depth -= 1;

        result
    }

    /// The scanner proper: copies bytes, rewriting the directives it knows.
    fn translate_inner(&mut self, text: &str, start_in_tag: bool) -> String {
        let bytes = text.as_bytes();
        let mut out = String::with_capacity(text.len() + 64);
        let mut index = 0;
        let mut in_tag = start_in_tag;
        let mut quote: Option<u8> = None;
        let mut raw_text: Option<String> = None;
        let mut pending_tag: Option<(String, bool)> = None;

        while index < bytes.len() {
            if let Some(active_quote) = quote {
                if bytes[index] == active_quote {
                    quote = None;
                    out.push(char::from(active_quote));
                    index += 1;
                    continue;
                }

                if bytes[index] == b'@' {
                    if let Some((consumed, replacement)) = self.directive(text, index) {
                        out.push_str(&replacement);
                        index += consumed;
                    } else {
                        out.push('@');
                        index += 1;
                    }
                    continue;
                }

                if bytes[index] == b'{' && starts_jinja(bytes, index) {
                    match jinja_end(text, index) {
                        Some(end) => {
                            out.push_str(&text[index..end]);
                            index = end;
                        }
                        None => {
                            out.push('{');
                            index += 1;
                        }
                    }
                    continue;
                }

                let start = index;
                index += 1;

                while index < bytes.len()
                    && bytes[index] != b'@'
                    && bytes[index] != b'{'
                    && bytes[index] != active_quote
                {
                    index += 1;
                }

                out.push_str(&text[start..index]);
                continue;
            }

            match bytes[index] {
                b'<' if !in_tag => {
                    if let Some(tag) = LivewireTag::parse(text, index) {
                        match tag.compile(self) {
                            Some(compiled) => {
                                out.push_str(&compiled);
                                index = tag.end;
                            }
                            None => {
                                out.push('<');
                                index += 1;
                            }
                        }
                        continue;
                    }

                    let mut cursor = index + 1;
                    let closing = cursor < bytes.len() && bytes[cursor] == b'/';

                    if closing {
                        cursor += 1;
                    }

                    let name_start = cursor;

                    while cursor < bytes.len() && bytes[cursor].is_ascii_alphanumeric() {
                        cursor += 1;
                    }

                    let opens_tag =
                        cursor > name_start || (cursor < bytes.len() && matches!(bytes[cursor], b'!' | b'?'));

                    if opens_tag {
                        in_tag = true;
                        pending_tag = if cursor > name_start {
                            Some((text[name_start..cursor].to_ascii_lowercase(), closing))
                        } else {
                            None
                        };
                    }

                    out.push('<');
                    index += 1;
                }
                b'>' if in_tag => {
                    in_tag = false;

                    if let Some((name, closing)) = pending_tag.take()
                        && (name == "script" || name == "style")
                    {
                        let self_closing = index > 0 && bytes[index - 1] == b'/';

                        if closing {
                            if raw_text.as_deref() == Some(name.as_str()) {
                                raw_text = None;
                            }
                        } else if !self_closing {
                            raw_text = Some(name);
                        }
                    }

                    out.push('>');
                    index += 1;
                }
                b'"' | b'\'' if in_tag => {
                    quote = Some(bytes[index]);
                    out.push(char::from(bytes[index]));
                    index += 1;
                }
                b'{' if starts_jinja(bytes, index) => match jinja_end(text, index) {
                    None => {
                        out.push('{');
                        index += 1;
                    }
                    Some(end) => {
                        let tag = &text[index..end];
                        let keyword = if bytes[index + 1] == b'%' {
                            jinja_keyword(tag)
                        } else {
                            ""
                        };
                        let markers = self.options.inject_morph_markers && !in_tag && raw_text.is_none();

                        if keyword == "raw" {
                            match text.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
                                Some(offset) => {
                                    let stop = end + offset + "{% endraw %}".len();
                                    out.push_str(&text[index..stop]);
                                    index = stop;
                                }
                                None => {
                                    out.push_str(tag);
                                    index = end;
                                }
                            }
                        } else {
                            if keyword == "endfor" && !in_tag && !self.loops.is_empty() {
                                self.loops.pop();
                            }

                            if keyword == "for" && self.options.smart_wire_keys && self.alias_loops && !in_tag {
                                let alias = format!("lw_loop_{}", self.loop_occurrence);
                                self.loop_occurrence += 1;

                                if markers {
                                    out.push_str(BLOCK_START);
                                }

                                out.push_str(tag);
                                out.push_str("{% set ");
                                out.push_str(&alias);
                                out.push_str(" = loop %}");
                                self.loops.push(alias);
                            } else if (keyword == "if" || keyword == "for") && markers {
                                out.push_str(BLOCK_START);
                                out.push_str(tag);
                            } else if (keyword == "endif" || keyword == "endfor") && markers {
                                out.push_str(tag);
                                out.push_str(BLOCK_END);
                            } else {
                                out.push_str(tag);
                            }

                            index = end;
                        }
                    }
                },
                b'@' => match self.directive(text, index) {
                    Some((consumed, replacement)) => {
                        out.push_str(&replacement);
                        index += consumed;
                    }
                    None => {
                        out.push('@');
                        index += 1;
                    }
                },
                _ => {
                    let start = index;
                    index += 1;

                    while index < bytes.len() && !matches!(bytes[index], b'@' | b'<' | b'{' | b'"' | b'\'' | b'>') {
                        index += 1;
                    }

                    out.push_str(&text[start..index]);
                }
            }
        }

        out
    }

    /// Rewrite one `@directive` starting at `at`: what it consumed and what replaces it.
    fn directive(&mut self, text: &str, at: usize) -> Option<(usize, String)> {
        let bytes = text.as_bytes();

        if at > 0 && bytes[at - 1] == b'@' {
            return None;
        }

        let mut word_end = at + 1;

        if word_end >= bytes.len() || !(bytes[word_end].is_ascii_alphabetic() || bytes[word_end] == b'_') {
            return None;
        }

        word_end += 1;

        while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
            word_end += 1;
        }

        let word = &text[at + 1..word_end];
        let mut cursor = word_end;

        while cursor < bytes.len() && (bytes[cursor] == b' ' || bytes[cursor] == b'\t') {
            cursor += 1;
        }

        let mut expression: Option<&str> = None;
        let mut after = word_end;

        if cursor < bytes.len() && bytes[cursor] == b'(' {
            let end = balanced_paren(text, cursor)?;
            expression = Some(&text[cursor + 1..end - 1]);
            after = end;
        }

        let word_consumed = word_end - at;

        match word {
            "this" => Some((word_consumed, "$wire".to_string())),
            "entangle" => {
                let value = expression?;
                let mut replacement = format!("$wire.entangle({})", value.trim());
                let mut consumed = after;

                for suffix in [".live", ".defer"] {
                    if text.get(after..).is_some_and(|rest| rest.starts_with(suffix)) {
                        replacement.push_str(suffix);
                        consumed += suffix.len();
                        break;
                    }
                }

                Some((consumed - at, replacement))
            }
            "livewire" => {
                let arguments = expression?;
                let replacement = self.livewire_expression(arguments)?;

                Some((after - at, replacement))
            }
            "assets" => Some((word_consumed, "{% livewire_assets %}".to_string())),
            "endassets" => Some((word_consumed, "{% endlivewire_assets %}".to_string())),
            "script" => Some((word_consumed, "{% livewire_script %}".to_string())),
            "endscript" => Some((word_consumed, "{% endlivewire_script %}".to_string())),
            "teleport" => {
                let selector = directive_value(expression);
                Some((after - at, format!("<template x-teleport=\"{selector}\">")))
            }
            "endteleport" => Some((word_consumed, "</template>".to_string())),
            "persist" => {
                let name = directive_value(expression);
                Some((after - at, format!("<div x-persist=\"{name}\">")))
            }
            "endpersist" => Some((word_consumed, "</div>".to_string())),
            "island" => self.island(text, at, expression, after),
            "livewireStyles" => Some((word_consumed, "{{ livewire_styles() }}".to_string())),
            "livewireScripts" => Some((word_consumed, "{{ livewire_scripts() }}".to_string())),
            "livewireScriptConfig" => Some((word_consumed, "{{ livewire_script_config() }}".to_string())),
            _ => None,
        }
    }

    /// Compile `@island … @endisland` into the fragment markers the island client parses.
    fn island(&mut self, text: &str, at: usize, expression: Option<&str>, after: usize) -> Option<(usize, String)> {
        let (end_at, end_after) = find_matching_endisland(text, after)?;
        let options = IslandOptions::parse(expression);

        let token = format!("{}-{}", self.hash, self.island_occurrence);
        self.island_occurrence += 1;

        let inner = self.translate(&text[after..end_at], false);

        let name = options.name.clone().unwrap_or_else(|| token.clone());
        let mode = options.mode.clone().unwrap_or_else(|| "morph".to_string());

        let inner = match options.directive() {
            Some(directive) => inject_island_attribute(&inner, directive),
            None => inner,
        };

        let metadata = format!("type=island|name={name}|token={token}|mode={mode}");
        let replacement =
            format!("<!--[if FRAGMENT:{metadata}]><![endif]-->{inner}<!--[if ENDFRAGMENT:{metadata}]><![endif]-->");

        Some((end_after - at, replacement))
    }

    /// Compile `@livewire(…)` into the same expression `<livewire:…>` produces.
    fn livewire_expression(&mut self, expression: &str) -> Option<String> {
        let arguments = split_top_level(expression, ',');
        let name = arguments.first()?.trim();

        if name.is_empty() {
            return None;
        }

        let occurrence = self.occurrence;
        self.occurrence += 1;

        let params = match arguments.get(1) {
            None => "{}".to_string(),
            Some(argument) => convert_params(argument.trim()),
        };

        let mut key: Option<String> = None;

        for argument in arguments.iter().skip(2) {
            let argument = argument.trim();

            if let Some(rest) = argument.strip_prefix("key:") {
                key = Some(rest.trim().to_string());
            } else if let Some(inner) = argument.strip_prefix("key(").and_then(|rest| rest.strip_suffix(')')) {
                key = Some(inner.trim().to_string());
            }
        }

        let key = key.unwrap_or_else(|| self.missing_key(occurrence));

        Some(format!("{{{{ livewire({name}, {params}, {key}) }}}}"))
    }

    /// The key argument for a component whose source declared none.
    fn missing_key(&self, occurrence: usize) -> String {
        if !self.options.smart_wire_keys || self.loops.is_empty() {
            return "none".to_string();
        }

        let mut key = format!("'lw-{}-{}'", self.hash, occurrence);

        for alias in &self.loops {
            key.push_str(" ~ '-' ~ ");
            key.push_str(alias);
            key.push_str(".index0");
        }

        key
    }

    /// Compile an attribute value: direct text stays literal, echos become expressions.
    fn attribute_expression(&mut self, value: &str) -> String {
        if value.is_empty() {
            return "true".to_string();
        }

        let compiled = self.translate(value, true);

        if !compiled.contains("{{") {
            return jinja_string(&compiled);
        }

        interpolate(&compiled)
    }

    /// Compile a nested component into `{{ livewire(name, params, key) }}`.
    fn component_expression(&mut self, name: &str, attributes: &str, slot: Option<&str>) -> String {
        let occurrence = self.occurrence;
        self.occurrence += 1;

        let mut params: Vec<(String, String)> = Vec::new();
        let mut key: Option<String> = None;

        for (attribute, value) in parse_attributes(attributes) {
            match attribute.as_str() {
                "wire:key" | "key" => {
                    key = Some(match value {
                        Some(value) => self.attribute_expression(&value),
                        None => "none".to_string(),
                    });
                    continue;
                }
                _ => {}
            }

            if let Some(bound) = attribute.strip_prefix(':') {
                let value = match value {
                    None => "true".to_string(),
                    Some(value) => {
                        let trimmed = value.trim();

                        match strip_braces(trimmed) {
                            Some(inner) => inner.trim().to_string(),
                            None => trimmed.to_string(),
                        }
                    }
                };

                params.push((bound.to_string(), value));
            } else {
                let value = match value {
                    Some(value) => self.attribute_expression(&value),
                    None => "true".to_string(),
                };

                params.push((attribute, value));
            }
        }

        if let Some(slot) = slot {
            params.push(("slot".to_string(), slot.to_string()));
        }

        let key = key.unwrap_or_else(|| self.missing_key(occurrence));

        let mut expression = String::from("{{ livewire(");
        expression.push_str(&jinja_string(name));
        expression.push_str(", {");

        for (index, (name, value)) in params.iter().enumerate() {
            if index > 0 {
                expression.push_str(", ");
            }

            expression.push_str(&jinja_string(name));
            expression.push_str(": ");
            expression.push_str(value);
        }

        expression.push_str("}, ");
        expression.push_str(&key);
        expression.push_str(") }}");

        expression
    }
}

/// A `<livewire:…>` tag found in the source.
struct LivewireTag<'a> {
    /// The attributes between the name and the closing bracket.
    attributes: &'a str,
    /// Where the tag ends, which for a paired tag is past its closing tag.
    end: usize,
    /// The slot content of a paired tag.
    inner: Option<&'a str>,
    /// The component name, without the `livewire:` prefix.
    name: &'a str,
    /// Whether the tag closed on itself.
    self_closing: bool,
}

impl<'a> LivewireTag<'a> {
    /// Parse a tag at `at`, or nothing when this is not a well-formed Livewire tag.
    fn parse(text: &'a str, at: usize) -> Option<Self> {
        let bounds = livewire_tag_bounds(text, at)?;

        if bounds.self_closing {
            return Some(Self {
                attributes: &text[bounds.name_end..bounds.attributes_end],
                end: bounds.tag_end,
                inner: None,
                name: &text[bounds.name_start..bounds.name_end],
                self_closing: true,
            });
        }

        let name = &text[bounds.name_start..bounds.name_end];
        let closing = format!("</livewire:{name}>");
        let close_offset = text.get(bounds.tag_end..)?.find(&closing)?;
        let close_start = bounds.tag_end + close_offset;
        let end = close_start + closing.len();

        Some(Self {
            attributes: &text[bounds.name_end..bounds.attributes_end],
            end,
            inner: Some(&text[bounds.tag_end..close_start]),
            name,
            self_closing: false,
        })
    }

    /// Compile this tag, or nothing when it should stay as written.
    fn compile(&self, compiler: &mut Compiler) -> Option<String> {
        match self.name {
            "styles" => return Some("{{ livewire_styles() }}".to_string()),
            "scripts" => return Some("{{ livewire_scripts() }}".to_string()),
            _ => {}
        }

        if self.self_closing {
            return Some(compiler.component_expression(self.name, self.attributes, None));
        }

        let inner = self.inner?;
        let inner = compiler.translate(inner, false);

        let variable = format!("lw_slot_{}", compiler.slot_occurrence);
        compiler.slot_occurrence += 1;

        let expression = compiler.component_expression(self.name, self.attributes, Some(&variable));

        Some(format!("{{% set {variable} %}}{inner}{{% endset %}}{expression}"))
    }
}

/// Where a `<livewire:name …>` tag starts and ends in the source.
struct TagBounds {
    /// The byte just past the closing `>`.
    attributes_end: usize,
    /// The byte where the name ends.
    name_end: usize,
    /// The byte where the component name starts.
    name_start: usize,
    /// Whether the tag closed on itself.
    self_closing: bool,
    /// The byte just past the whole tag.
    tag_end: usize,
}

/// Find the bounds of a `<livewire:name …>` tag at `at`.
fn livewire_tag_bounds(text: &str, at: usize) -> Option<TagBounds> {
    let prefix = "<livewire:";

    if !text.get(at..)?.starts_with(prefix) {
        return None;
    }

    let bytes = text.as_bytes();
    let mut cursor = at + prefix.len();
    let name_start = cursor;

    while cursor < bytes.len()
        && (bytes[cursor].is_ascii_alphanumeric() || matches!(bytes[cursor], b'_' | b'.' | b'-' | b':'))
    {
        cursor += 1;
    }

    if cursor == name_start {
        return None;
    }

    let name_end = cursor;
    let mut quote: Option<u8> = None;

    while cursor < bytes.len() {
        let byte = bytes[cursor];

        if let Some(active) = quote {
            if byte == active {
                quote = None;
            }
            cursor += 1;
            continue;
        }

        match byte {
            b'"' | b'\'' => quote = Some(byte),
            b'>' => {
                let self_closing = cursor > name_end && bytes[cursor - 1] == b'/';
                let attributes_end = if self_closing { cursor - 1 } else { cursor };

                return Some(TagBounds {
                    attributes_end,
                    name_end,
                    name_start,
                    self_closing,
                    tag_end: cursor + 1,
                });
            }
            _ => {}
        }

        cursor += 1;
    }

    None
}

/// Whether the attributes of a tag carry an explicit key.
fn attributes_have_key(attributes: &str) -> bool {
    parse_attributes(attributes)
        .iter()
        .any(|(name, _)| name == "wire:key" || name == "key")
}

/// Parse a tag's attributes into their names and values.
fn parse_attributes(attributes: &str) -> Vec<(String, Option<String>)> {
    let bytes = attributes.as_bytes();
    let mut parsed = Vec::new();
    let mut index = 0;

    while index < bytes.len() {
        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
            index += 1;
        }

        if index >= bytes.len() {
            break;
        }

        if bytes[index] == b'/' {
            index += 1;
            continue;
        }

        let name_start = index;

        while index < bytes.len() && !bytes[index].is_ascii_whitespace() && !matches!(bytes[index], b'=' | b'/' | b'>')
        {
            index += 1;
        }

        if index == name_start {
            index += 1;
            continue;
        }

        let name = attributes[name_start..index].to_string();

        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
            index += 1;
        }

        let mut value = None;

        if index < bytes.len() && bytes[index] == b'=' {
            index += 1;

            while index < bytes.len() && bytes[index].is_ascii_whitespace() {
                index += 1;
            }

            if index < bytes.len() && (bytes[index] == b'"' || bytes[index] == b'\'') {
                let quote = bytes[index];
                index += 1;
                let start = index;

                while index < bytes.len() && bytes[index] != quote {
                    index += 1;
                }

                value = Some(attributes[start..index].to_string());

                if index < bytes.len() {
                    index += 1;
                }
            } else {
                let start = index;

                while index < bytes.len() && !bytes[index].is_ascii_whitespace() {
                    index += 1;
                }

                value = Some(attributes[start..index].to_string());
            }
        }

        parsed.push((name, value));
    }

    parsed
}

/// The options `@island(…)` accepts at compile time.
struct IslandOptions {
    /// Defer the island until the browser reaches it.
    defer: bool,
    /// Load the island when it scrolls into view.
    lazy: bool,
    /// The update mode, which is `morph` unless the source says `append` or `prepend`.
    mode: Option<String>,
    /// The island's name, used by `wire:island`.
    name: Option<String>,
}

impl IslandOptions {
    /// Read the directive's named arguments.
    fn parse(expression: Option<&str>) -> Self {
        let mut options = Self {
            defer: false,
            lazy: false,
            mode: None,
            name: None,
        };

        if let Some(expression) = expression {
            for part in split_top_level(expression, ',') {
                let Some((key, value)) = part.split_once(':') else {
                    continue;
                };

                let key = key.trim();
                let value = value.trim();

                match key {
                    "name" => options.name = Some(unquote(value).unwrap_or(value).to_string()),
                    "mode" => options.mode = Some(unquote(value).unwrap_or(value).to_string()),
                    "lazy" => options.lazy = value == "true",
                    "defer" => options.defer = value == "true",
                    _ => {}
                }
            }
        }

        options
    }

    /// The lazy-loading attribute the island's first element carries, if any.
    fn directive(&self) -> Option<&'static str> {
        if self.lazy {
            Some("wire:intersect.once=\"__lazyLoadIsland\"")
        } else if self.defer {
            Some("wire:init=\"__lazyLoadIsland\"")
        } else {
            None
        }
    }
}

/// Find the `@endisland` matching an `@island` that ends at `from`.
fn find_matching_endisland(text: &str, from: usize) -> Option<(usize, usize)> {
    let bytes = text.as_bytes();
    let mut index = from;
    let mut depth = 0usize;

    while index < bytes.len() {
        if bytes[index] == b'{' && starts_jinja(bytes, index) {
            index = jinja_end(text, index)?;
            continue;
        }

        if bytes[index] == b'@' {
            let mut word_end = index + 1;

            while word_end < bytes.len() && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_') {
                word_end += 1;
            }

            match &text[index + 1..word_end] {
                "island" => {
                    depth += 1;
                    index = word_end;
                    continue;
                }
                "endisland" if depth == 0 => return Some((index, word_end)),
                "endisland" => {
                    depth -= 1;
                    index = word_end;
                    continue;
                }
                _ => {}
            }

            index = word_end;
            continue;
        }

        index += 1;
    }

    None
}

/// Whether any loop holds a nested component that needs a generated key.
fn loops_need_aliases(source: &str) -> bool {
    let bytes = source.as_bytes();
    let mut index = 0;
    let mut depth = 0usize;

    while index < bytes.len() {
        if bytes[index] == b'{'
            && starts_jinja(bytes, index)
            && let Some(end) = jinja_end(source, index)
        {
            let keyword = if bytes[index + 1] == b'%' {
                jinja_keyword(&source[index..end])
            } else {
                ""
            };

            match keyword {
                "for" => depth += 1,
                "endfor" => depth = depth.saturating_sub(1),
                "raw" => {
                    if let Some(offset) = source.get(end..).and_then(|rest| rest.find("{% endraw %}")) {
                        index = end + offset + "{% endraw %}".len();
                        continue;
                    }
                }
                _ => {}
            }

            index = end;
            continue;
        }

        if bytes[index] == b'<'
            && let Some(bounds) = livewire_tag_bounds(source, index)
        {
            if depth > 0 && !attributes_have_key(&source[bounds.name_end..bounds.attributes_end]) {
                return true;
            }

            index = bounds.tag_end;
            continue;
        }

        index += 1;
    }

    false
}

/// Insert an island lazy-loading attribute into the first element of `html`.
fn inject_island_attribute(html: &str, attribute: &str) -> String {
    let bytes = html.as_bytes();
    let mut index = 0;

    while index + 1 < bytes.len() {
        if bytes[index] == b'<' && bytes[index + 1].is_ascii_alphabetic() {
            let mut cursor = index + 2;

            while cursor < bytes.len() && (bytes[cursor].is_ascii_alphanumeric() || bytes[cursor] == b'-') {
                cursor += 1;
            }

            let mut out = String::with_capacity(html.len() + attribute.len() + 1);
            out.push_str(&html[..cursor]);
            out.push(' ');
            out.push_str(attribute);
            out.push_str(&html[cursor..]);

            return out;
        }

        index += 1;
    }

    format!("<span {attribute}>{html}</span>")
}

/// Turn a directive's expression into an attribute value.
fn directive_value(expression: Option<&str>) -> String {
    match expression {
        None => String::new(),
        Some(expression) => {
            let trimmed = expression.trim();

            if let Some(inner) = unquote(trimmed) {
                escape_attribute(inner)
            } else if trimmed.starts_with("{{") {
                trimmed.to_string()
            } else {
                format!("{{{{ {trimmed} }}}}")
            }
        }
    }
}

/// Escape a value for a double-quoted HTML attribute.
fn escape_attribute(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());

    for character in value.chars() {
        match character {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            other => escaped.push(other),
        }
    }

    escaped
}

/// Convert a component's `params` argument into a Jinja map.
fn convert_params(value: &str) -> String {
    if value.is_empty() {
        return "{}".to_string();
    }

    if value.starts_with('[') && value.ends_with(']') {
        return convert_php_array(&value[1..value.len() - 1]);
    }

    if value.starts_with('{') && value.ends_with('}') {
        return convert_object(&value[1..value.len() - 1]);
    }

    if let Some(inner) = value.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
        return convert_php_array(inner);
    }

    value.to_string()
}

/// Convert the body of a PHP array literal into a Jinja map or list.
fn convert_php_array(inner: &str) -> String {
    let mut pairs: Vec<(Option<String>, String)> = Vec::new();

    for entry in split_top_level(inner, ',') {
        let entry = entry.trim();

        if entry.is_empty() {
            continue;
        }

        if let Some(position) = find_top_level(entry, "=>") {
            let key = entry[..position].trim();
            let value = entry[position + 2..].trim();

            pairs.push((Some(unquote(key).unwrap_or(key).to_string()), convert_value(value)));
        } else {
            pairs.push((None, convert_value(entry)));
        }
    }

    if pairs.is_empty() {
        return "{}".to_string();
    }

    if pairs.iter().any(|(key, _)| key.is_some()) {
        let mut out = String::from("{");

        for (index, (key, value)) in pairs.iter().enumerate() {
            if index > 0 {
                out.push_str(", ");
            }

            let key = key.clone().unwrap_or_else(|| index.to_string());
            out.push_str(&jinja_string(&key));
            out.push_str(": ");
            out.push_str(value);
        }

        out.push('}');

        return out;
    }

    let values: Vec<String> = pairs.into_iter().map(|(_, value)| value).collect();

    format!("[{}]", values.join(", "))
}

/// Convert the body of a JSON-style object into a Jinja map.
fn convert_object(inner: &str) -> String {
    let mut pairs: Vec<(String, String)> = Vec::new();

    for entry in split_top_level(inner, ',') {
        let entry = entry.trim();

        if entry.is_empty() {
            continue;
        }

        let Some(position) = find_top_level(entry, ":") else {
            return format!("{{{inner}}}");
        };

        let key = entry[..position].trim();
        let value = entry[position + 1..].trim();

        pairs.push((unquote(key).unwrap_or(key).to_string(), convert_value(value)));
    }

    let mut out = String::from("{");

    for (index, (key, value)) in pairs.iter().enumerate() {
        if index > 0 {
            out.push_str(", ");
        }

        out.push_str(&jinja_string(key));
        out.push_str(": ");
        out.push_str(value);
    }

    out.push('}');

    out
}

/// Convert one value inside a literal: nested array literals become Jinja collections.
fn convert_value(value: &str) -> String {
    let trimmed = value.trim();

    if trimmed.starts_with('[') && trimmed.ends_with(']') && trimmed.len() >= 2 {
        return convert_php_array(&trimmed[1..trimmed.len() - 1]);
    }

    if trimmed.starts_with('{') && trimmed.ends_with('}') && trimmed.len() >= 2 {
        return convert_object(&trimmed[1..trimmed.len() - 1]);
    }

    if let Some(inner) = trimmed.strip_prefix("array(").and_then(|rest| rest.strip_suffix(')')) {
        return convert_php_array(inner);
    }

    trimmed.to_string()
}

/// Turn compiled attribute text into a Jinja expression, echos becoming values.
fn interpolate(compiled: &str) -> String {
    let bytes = compiled.as_bytes();
    let mut parts: Vec<(bool, &str)> = Vec::new();
    let mut index = 0;
    let mut literal_start = 0;

    while index + 1 < bytes.len() {
        if bytes[index] == b'{'
            && bytes[index + 1] == b'{'
            && let Some(end) = jinja_end(compiled, index)
        {
            if index > literal_start {
                parts.push((false, &compiled[literal_start..index]));
            }

            parts.push((true, &compiled[index + 2..end - 2]));
            index = end;
            literal_start = end;
            continue;
        }

        index += 1;
    }

    if literal_start < compiled.len() {
        parts.push((false, &compiled[literal_start..]));
    }

    match parts.as_slice() {
        [] => "''".to_string(),
        [(true, expression)] => expression.trim().to_string(),
        [(false, literal)] => jinja_string(literal),
        _ => {
            let mut out = String::new();

            for (index, (is_expression, part)) in parts.iter().enumerate() {
                if index > 0 {
                    out.push_str(" ~ ");
                }

                if *is_expression {
                    out.push('(');
                    out.push_str(part.trim());
                    out.push(')');
                } else if part.is_empty() {
                    out.push_str("''");
                } else {
                    out.push_str(&jinja_string(part));
                }
            }

            out
        }
    }
}

/// Quote `value` as a Jinja string literal.
fn jinja_string(value: &str) -> String {
    let mut quoted = String::with_capacity(value.len() + 2);
    quoted.push('\'');

    for character in value.chars() {
        match character {
            '\\' => quoted.push_str("\\\\"),
            '\'' => quoted.push_str("\\'"),
            other => quoted.push(other),
        }
    }

    quoted.push('\'');

    quoted
}

/// Strip matching single or double quotes from `value`.
fn unquote(value: &str) -> Option<&str> {
    let bytes = value.as_bytes();

    if bytes.len() < 2 {
        return None;
    }

    let first = bytes[0];
    let last = bytes[bytes.len() - 1];

    if first != last || !matches!(first, b'"' | b'\'') {
        return None;
    }

    Some(&value[1..value.len() - 1])
}

/// Strip `{{ }}` from a value that is exactly one echo.
fn strip_braces(value: &str) -> Option<&str> {
    value.strip_prefix("{{")?.strip_suffix("}}")
}

/// Whether a Jinja tag starts at `index`.
fn starts_jinja(bytes: &[u8], index: usize) -> bool {
    index + 1 < bytes.len() && matches!(bytes[index + 1], b'{' | b'%' | b'#')
}

/// The byte just past the Jinja tag starting at `start`.
fn jinja_end(text: &str, start: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    let closer: &[u8] = match bytes.get(start + 1) {
        Some(b'{') => b"}}",
        Some(b'%') => b"%}",
        Some(b'#') => b"#}",
        _ => return None,
    };

    let mut index = start + 2;
    let mut quote: Option<u8> = None;

    while index < bytes.len() {
        if let Some(active) = quote {
            if bytes[index] == b'\\' {
                index = (index + 2).min(bytes.len());
                continue;
            }

            if bytes[index] == active {
                quote = None;
            }

            index += 1;
            continue;
        }

        match bytes[index] {
            b'"' | b'\'' => quote = Some(bytes[index]),
            _ => {
                if bytes[index..].starts_with(closer) {
                    return Some(index + closer.len());
                }
            }
        }

        index += 1;
    }

    None
}

/// The keyword a `{% … %}` tag starts with, `-` whitespace control included.
fn jinja_keyword(tag: &str) -> &str {
    let inner = tag.strip_prefix("{%").unwrap_or(tag);
    let inner = inner.strip_suffix("%}").unwrap_or(inner);
    let inner = inner.trim().trim_start_matches('-').trim_start();

    let end = inner
        .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
        .unwrap_or(inner.len());

    &inner[..end]
}

/// The byte just past the `)` matching the `(` at `open`.
fn balanced_paren(text: &str, open: usize) -> Option<usize> {
    let bytes = text.as_bytes();
    let mut index = open;
    let mut depth = 0usize;
    let mut quote: Option<u8> = None;

    while index < bytes.len() {
        if let Some(active) = quote {
            if bytes[index] == b'\\' {
                index = (index + 2).min(bytes.len());
                continue;
            }

            if bytes[index] == active {
                quote = None;
            }

            index += 1;
            continue;
        }

        match bytes[index] {
            b'"' | b'\'' => quote = Some(bytes[index]),
            b'(' => depth += 1,
            b')' => {
                depth -= 1;

                if depth == 0 {
                    return Some(index + 1);
                }
            }
            _ => {}
        }

        index += 1;
    }

    None
}

/// Split `value` on `separator` where it is not inside quotes, brackets, or braces.
fn split_top_level(value: &str, separator: char) -> Vec<&str> {
    let bytes = value.as_bytes();
    let separator = separator as u8;
    let mut parts = Vec::new();
    let mut start = 0;
    let mut index = 0;
    let mut depth = 0usize;
    let mut quote: Option<u8> = None;

    while index < bytes.len() {
        if let Some(active) = quote {
            if bytes[index] == b'\\' {
                index = (index + 2).min(bytes.len());
                continue;
            }

            if bytes[index] == active {
                quote = None;
            }

            index += 1;
            continue;
        }

        match bytes[index] {
            b'"' | b'\'' => quote = Some(bytes[index]),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            byte if byte == separator && depth == 0 => {
                parts.push(&value[start..index]);
                start = index + 1;
            }
            _ => {}
        }

        index += 1;
    }

    parts.push(&value[start..]);

    parts
}

/// Find `needle` in `value` where it is not inside quotes, brackets, or braces.
fn find_top_level(value: &str, needle: &str) -> Option<usize> {
    let bytes = value.as_bytes();
    let mut index = 0;
    let mut depth = 0usize;
    let mut quote: Option<u8> = None;

    while index < bytes.len() {
        if let Some(active) = quote {
            if bytes[index] == b'\\' {
                index = (index + 2).min(bytes.len());
                continue;
            }

            if bytes[index] == active {
                quote = None;
            }

            index += 1;
            continue;
        }

        match bytes[index] {
            b'"' | b'\'' => quote = Some(bytes[index]),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            _ => {
                if depth == 0 && value[index..].starts_with(needle) {
                    return Some(index);
                }
            }
        }

        index += 1;
    }

    None
}

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

    const NO_OPTIONS: CompileOptions = CompileOptions {
        inject_morph_markers: false,
        smart_wire_keys: false,
    };
    const MORPH: CompileOptions = CompileOptions {
        inject_morph_markers: true,
        smart_wire_keys: false,
    };
    const KEYS: CompileOptions = CompileOptions {
        inject_morph_markers: false,
        smart_wire_keys: true,
    };
    const ALL: CompileOptions = CompileOptions {
        inject_morph_markers: true,
        smart_wire_keys: true,
    };

    fn identity() -> TemplateIdentity {
        TemplateIdentity {
            name: "counter".to_string(),
            source: "livewire.counter".to_string(),
        }
    }

    fn hash() -> String {
        identity().hash()
    }

    fn run(source: &str, options: CompileOptions) -> String {
        compile(source, &identity(), options)
    }

    #[test]
    fn a_self_closing_tag_becomes_the_livewire_expression() {
        let source = r#"<div><livewire:post-row :post="post" wire:key="row-1" class="p-4" /></div>"#;

        assert_eq!(
            run(source, NO_OPTIONS),
            r#"<div>{{ livewire('post-row', {'post': post, 'class': 'p-4'}, 'row-1') }}</div>"#
        );
    }

    #[test]
    fn a_paired_tag_compiles_its_slot() {
        assert_eq!(
            run("<livewire:counter>Hello</livewire:counter>", NO_OPTIONS),
            "{% set lw_slot_0 %}Hello{% endset %}{{ livewire('counter', {'slot': lw_slot_0}, none) }}"
        );
    }

    #[test]
    fn slot_content_is_compiled_too() {
        assert_eq!(
            run(
                "<livewire:counter>@this.now() @entangle('open')</livewire:counter>",
                NO_OPTIONS
            ),
            "{% set lw_slot_0 %}$wire.now() $wire.entangle('open'){% endset %}\
             {{ livewire('counter', {'slot': lw_slot_0}, none) }}"
        );
    }

    #[test]
    fn the_livewire_directive_accepts_php_arrays_keys_and_json_objects() {
        assert_eq!(
            run("@livewire('counter', ['step' => 2], key: 'c1')", NO_OPTIONS),
            "{{ livewire('counter', {'step': 2}, 'c1') }}"
        );

        assert_eq!(
            run(r#"@livewire("counter", {"step": 2})"#, NO_OPTIONS),
            r#"{{ livewire("counter", {'step': 2}, none) }}"#
        );

        assert_eq!(
            run("@livewire('counter', [], key('c2'))", NO_OPTIONS),
            "{{ livewire('counter', {}, 'c2') }}"
        );
    }

    #[test]
    fn the_livewire_directive_converts_nested_arrays() {
        assert_eq!(
            run("@livewire('x', ['a' => ['b' => 1], 'list' => [1, 2]])", NO_OPTIONS),
            "{{ livewire('x', {'a': {'b': 1}, 'list': [1, 2]}, none) }}"
        );
    }

    #[test]
    fn this_becomes_wire() {
        assert_eq!(
            run(r#"<button wire:click="@this.increment">Go</button>"#, NO_OPTIONS),
            r#"<button wire:click="$wire.increment">Go</button>"#
        );
    }

    #[test]
    fn entangle_becomes_wire_entangle_with_its_modifier() {
        assert_eq!(
            run(r#"<div x-data="{ open: @entangle('open') }"></div>"#, NO_OPTIONS),
            r#"<div x-data="{ open: $wire.entangle('open') }"></div>"#
        );

        assert_eq!(run("@entangle('open').live", NO_OPTIONS), "$wire.entangle('open').live");
        assert_eq!(
            run("@entangle('open').defer", NO_OPTIONS),
            "$wire.entangle('open').defer"
        );
    }

    #[test]
    fn assets_and_scripts_become_jinja_blocks() {
        assert_eq!(
            run("@assets<script src=\"/a.js\"></script>@endassets", NO_OPTIONS),
            "{% livewire_assets %}<script src=\"/a.js\"></script>{% endlivewire_assets %}"
        );

        assert_eq!(
            run("@script console.log('a') @endscript", NO_OPTIONS),
            "{% livewire_script %} console.log('a') {% endlivewire_script %}"
        );
    }

    #[test]
    fn teleport_becomes_a_template() {
        assert_eq!(
            run("@teleport('#modal')<div>x</div>@endteleport", NO_OPTIONS),
            "<template x-teleport=\"#modal\"><div>x</div></template>"
        );
    }

    #[test]
    fn persist_becomes_a_div() {
        assert_eq!(
            run("@persist('player')<div>x</div>@endpersist", NO_OPTIONS),
            "<div x-persist=\"player\"><div>x</div></div>"
        );
    }

    #[test]
    fn an_island_emits_fragment_markers() {
        let named = format!("{}-0", hash());

        assert_eq!(
            run("@island(name: 'timer')<p>t</p>@endisland", NO_OPTIONS),
            format!(
                "<!--[if FRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->\
                 <p>t</p>\
                 <!--[if ENDFRAGMENT:type=island|name=timer|token={named}|mode=morph]><![endif]-->"
            )
        );

        assert_eq!(
            run("@island<p>t</p>@endisland", NO_OPTIONS),
            format!(
                "<!--[if FRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->\
                 <p>t</p>\
                 <!--[if ENDFRAGMENT:type=island|name={named}|token={named}|mode=morph]><![endif]-->"
            )
        );
    }

    #[test]
    fn islands_nest_with_distinct_tokens() {
        let output = run(
            "@island(name: 'outer')<div>@island(name: 'inner')x@endisland</div>@endisland",
            NO_OPTIONS,
        );

        assert!(output.contains(&format!("name=outer|token={}-0", hash())));
        assert!(output.contains(&format!("name=inner|token={}-1", hash())));

        let inner_end = output.find("ENDFRAGMENT:type=island|name=inner").unwrap();
        let outer_end = output.rfind("ENDFRAGMENT:type=island|name=outer").unwrap();

        assert!(inner_end < outer_end);
    }

    #[test]
    fn an_island_carries_its_mode() {
        assert!(run("@island(name: 'feed', mode: 'append')x@endisland", NO_OPTIONS).contains("mode=append"));
    }

    #[test]
    fn a_lazy_island_gets_a_load_attribute() {
        assert!(
            run("@island(defer: true)<p>x</p>@endisland", NO_OPTIONS)
                .contains(r#"<p wire:init="__lazyLoadIsland">x</p>"#)
        );

        assert!(
            run("@island(lazy: true)plain@endisland", NO_OPTIONS)
                .contains(r#"<span wire:intersect.once="__lazyLoadIsland">plain</span>"#)
        );
    }

    #[test]
    fn the_asset_helpers_become_expressions() {
        assert_eq!(
            run("@livewireStyles@livewireScripts@livewireScriptConfig", NO_OPTIONS),
            "{{ livewire_styles() }}{{ livewire_scripts() }}{{ livewire_script_config() }}"
        );
    }

    #[test]
    fn unknown_directives_pass_through_byte_for_byte() {
        for source in [
            "@if ($show) <p>@endif</p>",
            "user@example.com",
            "@unknownDirective('x')",
            "@@livewire('counter')",
            "@foreach($items as $item)@endforeach",
        ] {
            assert_eq!(run(source, ALL), source, "source: {source}");
        }
    }

    #[test]
    fn morph_markers_wrap_conditionals_and_loops() {
        assert_eq!(
            run("{% if show %}a{% endif %}", MORPH),
            format!("{BLOCK_START}{{% if show %}}a{{% endif %}}{BLOCK_END}")
        );

        assert_eq!(
            run("{%- for x in y -%}a{%- endfor -%}", MORPH),
            format!("{BLOCK_START}{{%- for x in y -%}}a{{%- endfor -%}}{BLOCK_END}")
        );
    }

    #[test]
    fn morph_markers_nest() {
        assert_eq!(
            run("{% if a %}{% for x in y %}z{% endfor %}{% endif %}", MORPH),
            format!(
                "{BLOCK_START}{{% if a %}}{BLOCK_START}{{% for x in y %}}z{{% endfor %}}{BLOCK_END}{{% endif %}}{BLOCK_END}"
            )
        );
    }

    #[test]
    fn a_block_inside_an_attribute_gets_no_marker() {
        let source = r#"<div class="{% if active %}on{% endif %}">x</div>"#;

        assert_eq!(run(source, MORPH), source);
    }

    #[test]
    fn script_contents_carry_no_morph_markers() {
        let source = "<script>{% if a %}x{% endif %}</script>";

        assert_eq!(run(source, MORPH), source);
    }

    #[test]
    fn smart_keys_use_the_enclosing_loop() {
        let output = run(
            r#"<div>{% for post in posts %}<livewire:post-row :post="post" />{% endfor %}</div>"#,
            KEYS,
        );

        assert!(output.contains("{% set lw_loop_0 = loop %}"));
        assert!(output.contains(&format!("'lw-{}-0' ~ '-' ~ lw_loop_0.index0", hash())));
        assert!(output.contains("{{ livewire('post-row', {'post': post}, "));
        assert!(!output.contains(BLOCK_START));
    }

    #[test]
    fn nested_loops_give_distinct_keys() {
        let output = run(
            "{% for a in xs %}{% for b in ys %}<livewire:row />{% endfor %}{% endfor %}",
            KEYS,
        );

        assert!(output.contains("{% set lw_loop_0 = loop %}"));
        assert!(output.contains("{% set lw_loop_1 = loop %}"));
        assert!(output.contains(&format!(
            "'lw-{}-0' ~ '-' ~ lw_loop_0.index0 ~ '-' ~ lw_loop_1.index0",
            hash()
        )));
    }

    #[test]
    fn both_options_off_leave_keys_and_comments_out() {
        assert_eq!(
            run("{% for a in xs %}<livewire:row />{% endfor %}", NO_OPTIONS),
            "{% for a in xs %}{{ livewire('row', {}, none) }}{% endfor %}"
        );

        assert_eq!(run("{% if a %}b{% endif %}", NO_OPTIONS), "{% if a %}b{% endif %}");
    }

    #[test]
    fn an_explicit_key_always_wins() {
        assert_eq!(
            run(
                "{% for p in ps %}<livewire:row wire:key=\"k-{{ p.id }}\" />{% endfor %}",
                KEYS
            ),
            "{% for p in ps %}{{ livewire('row', {}, 'k-' ~ (p.id)) }}{% endfor %}"
        );
    }

    #[test]
    fn existing_jinja_is_untouched() {
        let source = "{% set x = 1 %}{{ x }}{# note #}";

        assert_eq!(run(source, ALL), source);
    }

    #[test]
    fn wire_island_attributes_pass_through() {
        let source = r#"<button wire:click="increment" wire:island="foo">Go</button>"#;

        assert_eq!(run(source, ALL), source);
    }

    #[test]
    fn truncated_input_is_left_as_it_stands() {
        for source in [
            "@island",
            "@island(",
            "@endisland",
            "@livewire(",
            "@teleport(",
            "@entangle(",
            "<livewire:counter",
            "<livewire:counter>",
            "{% if x",
            "{{ x",
        ] {
            assert_eq!(run(source, ALL), source, "source: {source}");
        }
    }

    #[test]
    fn compiling_the_same_source_twice_gives_the_same_string() {
        let source = "<livewire:row />@island(name: 'a')x@endisland";

        assert_eq!(run(source, ALL), run(source, ALL));
    }
}