summaryrefslogtreecommitdiff
path: root/Hutch/Views/Repositories/ReadmeView.swift
blob: 5742811814af850298802d252a9de618c01474a5 (plain) (blame)
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
import SwiftUI
import WebKit

struct ReadmeView: View {
    let viewModel: RepositoryDetailViewModel

    @Environment(\.colorScheme) private var colorScheme
    @State private var isShowingRepositoryDetails = false

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                headerSection
                metadataSection
                repositoryDetailsSection
                latestChangeSection
                readmeSection
            }
            .padding()
        }
        .task {
            async let readme: () = viewModel.loadReadme()
            async let commits: () = viewModel.loadCommits()
            async let refs: () = viewModel.loadReferences()
            _ = await (readme, commits, refs)
        }
        .navigationDestination(for: CommitSummary.self) { commit in
            CommitDetailView(
                commitSummary: commit,
                repository: viewModel.repository
            )
        }
    }

    @ViewBuilder
    private var headerSection: some View {
        VStack(alignment: .leading, spacing: 6) {
            Text(viewModel.repository.owner.canonicalName)
                .font(.subheadline)
                .foregroundStyle(.secondary)
            Text(viewModel.repository.name)
                .font(.largeTitle.weight(.semibold))
            if let description = viewModel.repository.description, !description.isEmpty {
                Text(description)
                    .font(.body)
            }
        }
    }

    @ViewBuilder
    private var metadataSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            SummaryMetadataRow(
                icon: "arrow.triangle.branch",
                title: viewModel.repository.head?.name ?? repositoryVisibilityLabel(viewModel.repository.visibility)
            )

            if let readmePath = viewModel.readmePath {
                SummaryMetadataRow(
                    icon: "doc.text",
                    title: readmePath
                )
            }
        }
    }

    private var repositoryDetailsSection: some View {
        DisclosureGroup(isExpanded: $isShowingRepositoryDetails) {
            VStack(alignment: .leading, spacing: 12) {
                SummaryDetailRow(label: "Visibility", value: repositoryVisibilityLabel(viewModel.repository.visibility))
                SummaryDetailRow(label: "Read-only", value: repositoryCloneURLs(for: viewModel.repository).readOnly, monospace: true)
                SummaryDetailRow(label: "Read/write", value: repositoryCloneURLs(for: viewModel.repository).readWrite, monospace: true)
                SummaryDetailRow(label: "RID", value: viewModel.repository.rid, monospace: true)
            }
            .padding(.top, 8)
        } label: {
            Text("Repository Details")
                .font(.subheadline.weight(.medium))
        }
    }

    @ViewBuilder
    private var latestChangeSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            if viewModel.isLoadingCommits && viewModel.commits.isEmpty {
                SRHTLoadingStateView(message: "Loading latest change…")
                    .frame(maxWidth: .infinity)
            } else if let commit = viewModel.commits.first {
                NavigationLink(value: commit) {
                    SummaryMetadataRow(
                        icon: "arrow.trianglehead.clockwise",
                        title: commit.title,
                        subtitle: "\(commit.shortId)\(commit.author.name) \(commit.author.time.relativeDescription)"
                    )
                    .contentShape(Rectangle())
                }
                .buttonStyle(.plain)
            } else if let error = viewModel.error, viewModel.commits.isEmpty {
                SRHTErrorStateView(
                    title: "Couldn't Load Latest Change",
                    message: error,
                    retryAction: { await viewModel.loadCommits() }
                )
            } else {
                ContentUnavailableView(
                    "No Recent Commits",
                    systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90",
                    description: Text("This repository does not have any commit history yet.")
                )
            }
        }
    }

    @ViewBuilder
    private var readmeSection: some View {
        if viewModel.isLoadingReadme {
            SRHTLoadingStateView(message: "Loading README…")
        } else if let content = viewModel.readmeContent {
            RenderedMarkupContentView(
                content: sharedReadmeContent(from: content),
                readmePath: viewModel.readmePath,
                colorScheme: colorScheme,
                ownerCanonicalName: viewModel.repository.owner.canonicalName,
                repositoryName: viewModel.repository.name
            )
        } else if let error = viewModel.error, !viewModel.readmeLoaded {
            SRHTErrorStateView(
                title: "Couldn't Load README",
                message: error,
                retryAction: { await viewModel.loadReadme() }
            )
        } else {
            ContentUnavailableView(
                "No README",
                systemImage: "doc.text",
                description: Text("This repository does not have a README file.")
            )
        }
    }

    private func sharedReadmeContent(from content: RepositoryDetailViewModel.ReadmeContent) -> RenderedMarkupContent {
        switch content {
        case .html(let html):
            .html(html)
        case .markdown(let text):
            .markdown(text)
        case .org(let text):
            .org(text)
        case .plainText(let text):
            .plainText(text)
        }
    }
}

enum RenderedMarkupContent: Sendable {
    case html(String)
    case markdown(String)
    case org(String)
    case plainText(String)
}

struct RenderedMarkupContentView: View {
    let content: RenderedMarkupContent
    let readmePath: String?
    let colorScheme: ColorScheme
    let ownerCanonicalName: String
    let repositoryName: String
    var repositoryHost = "git.sr.ht"

    @State private var renderedHTML: String?

    private var cacheKey: String {
        switch content {
        case .html(let html):
            "html:\(readmePath ?? "custom"):\(html)"
        case .markdown(let text):
            "markdown:\(readmePath ?? ""):\(text)"
        case .org(let text):
            "org:\(readmePath ?? ""):\(text)"
        case .plainText(let text):
            "plain:\(readmePath ?? ""):\(text)"
        }
    }

    var body: some View {
        Group {
            switch content {
            case .html(let html):
                HTMLWebView(html: html, colorScheme: colorScheme)
            case .markdown, .org:
                if let renderedHTML {
                    HTMLWebView(html: renderedHTML, colorScheme: colorScheme)
                } else {
                    SRHTLoadingStateView(message: "Preparing README…")
                }
            case .plainText(let text):
                Text(text)
                    .font(.system(.body, design: .monospaced))
                    .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
        .task(id: cacheKey) {
            await prepareHTMLIfNeeded()
        }
    }

    private func prepareHTMLIfNeeded() async {
        switch content {
        case .html, .plainText:
            renderedHTML = nil
        case .markdown(let text):
            if let cached = RenderedReadmeHTMLCache.shared.html(forKey: cacheKey) {
                renderedHTML = cached
                return
            }
            let html = await Task.detached(priority: .userInitiated) {
                markdownToHTML(text) { source in
                    resolveRepositoryAssetURL(
                        source,
                        owner: ownerCanonicalName,
                        repositoryName: repositoryName,
                        readmePath: readmePath
                    )?
                    .replacingOccurrences(of: "git.sr.ht", with: repositoryHost)
                }
            }.value
            RenderedReadmeHTMLCache.shared.setHTML(html, forKey: cacheKey)
            guard !Task.isCancelled else { return }
            renderedHTML = html
        case .org(let text):
            if let cached = RenderedReadmeHTMLCache.shared.html(forKey: cacheKey) {
                renderedHTML = cached
                return
            }
            let html = await Task.detached(priority: .userInitiated) {
                orgToHTML(text) { source in
                    resolveRepositoryAssetURL(
                        source,
                        owner: ownerCanonicalName,
                        repositoryName: repositoryName,
                        readmePath: readmePath
                    )?
                    .replacingOccurrences(of: "git.sr.ht", with: repositoryHost)
                }
            }.value
            RenderedReadmeHTMLCache.shared.setHTML(html, forKey: cacheKey)
            guard !Task.isCancelled else { return }
            renderedHTML = html
        }
    }
}

private final class RenderedReadmeHTMLCache: @unchecked Sendable {
    static let shared = RenderedReadmeHTMLCache()

    private let storage = NSCache<NSString, NSString>()

    func html(forKey key: String) -> String? {
        storage.object(forKey: key as NSString) as String?
    }

    func setHTML(_ html: String, forKey key: String) {
        storage.setObject(html as NSString, forKey: key as NSString)
    }

    func removeAll() {
        storage.removeAllObjects()
    }
}

@MainActor
func clearWebContentRenderCaches() {
    RenderedReadmeHTMLCache.shared.removeAll()
    HTMLWebViewCoordinator.heightCache.removeAllObjects()
}

// MARK: - Markdown to HTML

nonisolated func processInline(_ text: String, imageURLResolver: ((String) -> String?)? = nil) -> String {

    var protectedFragments: [String: String] = [:]
    var result = protectMatches(
        in: text,
        pattern: #"</?[A-Za-z][^>]*?>"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let rawTag = nsText.substring(with: match.range)
        return sanitizedMarkdownHTMLTag(rawTag) ?? escapeHTML(rawTag)
    }

    result = escapeHTML(result)

    // Images: ![alt](url)
    result = replaceMatches(in: result, pattern: #"!\[([^\]]*)\]\(([^)]+)\)"#) { match, nsText in
        let alt = nsText.substring(with: match.range(at: 1))
        let source = decodeHTMLEntities(nsText.substring(with: match.range(at: 2)))
        let resolvedSource = imageURLResolver?(source) ?? source
        guard let sanitizedSource = sanitizedReadmeImageURLString(resolvedSource) else {
            return escapeHTML(alt)
        }
        return #"<img src="\#(sanitizedSource)" alt="\#(escapeHTMLAttribute(alt))">"#
    }
    // Links: [text](url)
    result = replaceMatches(in: result, pattern: #"\[([^\]]+)\]\(([^)]+)\)"#) { match, nsText in
        let label = nsText.substring(with: match.range(at: 1))
        let rawURL = decodeHTMLEntities(nsText.substring(with: match.range(at: 2)))
        guard let sanitizedURL = sanitizedReadmeLinkURLString(rawURL) else {
            return label
        }
        return #"<a href="\#(sanitizedURL)">\#(label)</a>"#
    }
    // Plain email autolinks
    result = replaceMatches(
        in: result,
        pattern: #"(?i)(?<![\w.%+\-])([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})(?![\w\-])"#
    ) { match, nsText in
        guard !isInsideHTMLTag(nsText, range: match.range) else {
            return nsText.substring(with: match.range)
        }
        let email = nsText.substring(with: match.range(at: 1))
        let href = escapeHTMLAttribute("mailto:\(email)")
        return #"<a href="\#(href)">\#(email)</a>"#
    }
    // Strikethrough: ~~text~~
    result = result.replacingOccurrences(
        of: #"~~(.+?)~~"#,
        with: "<del>$1</del>",
        options: .regularExpression
    )
    // Bold: **text**
    result = result.replacingOccurrences(
        of: #"\*\*(.+?)\*\*"#,
        with: "<strong>$1</strong>",
        options: .regularExpression
    )
    // Italic: *text*
    result = result.replacingOccurrences(
        of: #"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)"#,
        with: "<em>$1</em>",
        options: .regularExpression
    )
    // Italic: _text_
    result = result.replacingOccurrences(
        of: #"(?<!\w)_(.+?)_(?!\w)"#,
        with: "<em>$1</em>",
        options: .regularExpression
    )
    // Inline code: `text`
    result = result.replacingOccurrences(
        of: #"`([^`]+)`"#,
        with: "<code>$1</code>",
        options: .regularExpression
    )

    for (token, fragment) in protectedFragments {
        result = result.replacingOccurrences(of: token, with: fragment)
    }

    return result
}

// MARK: - Org-mode to HTML

nonisolated func orgToHTML(_ text: String, imageURLResolver: ((String) -> String?)? = nil) -> String {
    let normalizedText = text
        .replacingOccurrences(of: "\r\n", with: "\n")
        .replacingOccurrences(of: "\r", with: "\n")
    let rawLines = normalizedText.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
    var title: String?
    var author: String?
    var date: String?
    let lines = rawLines.filter { line in
        let trimmed = line.trimmingCharacters(in: .whitespaces)
        guard let directive = orgKeywordDirective(in: trimmed) else {
            return true
        }
        switch directive.keyword {
        case "title":
            title = directive.value
            return false
        case "author":
            author = directive.value
            return false
        case "date":
            date = directive.value
            return false
        default:
            return true
        }
    }
    var html = ""
    var listType: OrgListType?
    var inQuoteBlock = false
    var inPropertyDrawer = false
    var srcLanguage: String?
    var inExampleBlock = false
    var inCenterBlock = false
    var inVerseBlock = false
    var currentListItemLines: [String] = []
    var paragraph: [String] = []
    var tableRows: [[String]] = []
    var propertyRows: [(String, String)] = []
    var verseLines: [String] = []
    var pendingBlockName: String?
    var pendingBlockCaption: String?
    var activeBlockCaption: String?
    var isWrappingBlockFigure = false

    func beginPendingBlockWrapperIfNeeded() {
        guard pendingBlockName != nil || pendingBlockCaption != nil else { return }
        let idAttribute = pendingBlockName.map { #" id="\#(escapeHTMLAttribute($0))""# } ?? ""
        html += #"<figure class="org-block"\#(idAttribute)>"# + "\n"
        activeBlockCaption = pendingBlockCaption
        isWrappingBlockFigure = true
        pendingBlockName = nil
        pendingBlockCaption = nil
    }

    func closePendingBlockWrapper() {
        guard isWrappingBlockFigure else { return }
        if let activeBlockCaption {
            html += "<figcaption>" + processOrgInline(activeBlockCaption, imageURLResolver: imageURLResolver) + "</figcaption>\n"
        }
        html += "</figure>\n"
        activeBlockCaption = nil
        isWrappingBlockFigure = false
    }

    func flushParagraph() {
        if !paragraph.isEmpty {
            let normalizedParagraph = paragraph
                .map { $0.trimmingCharacters(in: .whitespaces) }
                .joined(separator: " ")
            html += "<p>" + processOrgInline(normalizedParagraph, imageURLResolver: imageURLResolver) + "</p>\n"
            paragraph = []
        }
    }

    func flushListItem() {
        guard !currentListItemLines.isEmpty else { return }
        html += "<li>" + renderOrgListItemBody(
            currentListItemLines,
            imageURLResolver: imageURLResolver
        ) + "</li>\n"
        currentListItemLines = []
    }

    func closeList() {
        flushListItem()
        switch listType {
        case .unordered:
            html += "</ul>\n"
        case .ordered:
            html += "</ol>\n"
        case nil:
            break
        }
        listType = nil
    }

    func flushTable() {
        guard !tableRows.isEmpty else { return }
        beginPendingBlockWrapperIfNeeded()
        html += renderHTMLTable(
            rows: tableRows,
            inlineRenderer: { processOrgInline($0, imageURLResolver: imageURLResolver) }
        )
        closePendingBlockWrapper()
        tableRows = []
    }

    func flushPropertyDrawer() {
        guard !propertyRows.isEmpty else { return }
        html += "<dl class=\"org-properties\">\n"
        for (key, value) in propertyRows {
            html += "<dt>" + escapeHTML(key) + "</dt>"
            html += "<dd>" + processOrgInline(value, imageURLResolver: imageURLResolver) + "</dd>\n"
        }
        html += "</dl>\n"
        propertyRows = []
    }

    func closeQuoteBlock() {
        if inQuoteBlock {
            flushParagraph()
            html += "</blockquote>\n"
            inQuoteBlock = false
        }
    }

    func closeSourceBlock() {
        if srcLanguage != nil {
            html += "</code></pre>\n"
            srcLanguage = nil
            closePendingBlockWrapper()
        }
    }

    func closeExampleBlock() {
        if inExampleBlock {
            html += "</code></pre>\n"
            inExampleBlock = false
            closePendingBlockWrapper()
        }
    }

    func closeCenterBlock() {
        if inCenterBlock {
            flushParagraph()
            html += "</div>\n"
            inCenterBlock = false
            closePendingBlockWrapper()
        }
    }

    func closeVerseBlock() {
        if inVerseBlock {
            let content = verseLines
                .map { processOrgInline($0, imageURLResolver: imageURLResolver) }
                .joined(separator: "\n")
            html += #"<blockquote class="org-verse">"# + "\n"
            html += content + "\n"
            html += "</blockquote>\n"
            verseLines = []
            inVerseBlock = false
            closePendingBlockWrapper()
        }
    }

    func flushBlockState() {
        flushParagraph()
        closeList()
        flushTable()
        flushPropertyDrawer()
    }

    if title != nil || author != nil || date != nil {
        html += "<div class=\"org-metadata\">\n"
        if let title {
            html += "<h1 class=\"org-title\">" + escapeHTML(title) + "</h1>\n"
        }
        if let author {
            html += "<p class=\"org-author\">" + escapeHTML(author) + "</p>\n"
        }
        if let date {
            html += "<p class=\"org-date\">" + escapeHTML(date) + "</p>\n"
        }
        html += "</div>\n"
    }

    for line in lines {
        let trimmed = line.trimmingCharacters(in: .whitespaces)

        if srcLanguage != nil {
            if trimmed.lowercased() == "#+end_src" {
                closeSourceBlock()
            } else {
                html += escapeHTML(line) + "\n"
            }
            continue
        }

        if inExampleBlock {
            if trimmed.lowercased() == "#+end_example" {
                closeExampleBlock()
            } else {
                html += escapeHTML(line) + "\n"
            }
            continue
        }

        if inVerseBlock {
            if trimmed.lowercased() == "#+end_verse" {
                closeVerseBlock()
            } else {
                verseLines.append(line)
            }
            continue
        }

        if inQuoteBlock, trimmed.lowercased() == "#+end_quote" {
            closeQuoteBlock()
            continue
        }

        if inCenterBlock {
            if trimmed.lowercased() == "#+end_center" {
                closeCenterBlock()
            } else if trimmed.isEmpty {
                flushParagraph()
            } else {
                paragraph.append(line)
            }
            continue
        }

        if trimmed == "#" || trimmed.hasPrefix("# ") {
            continue
        }

        if let directive = orgKeywordDirective(in: trimmed) {
            switch directive.keyword {
            case "caption":
                pendingBlockCaption = directive.value
                continue
            case "name":
                pendingBlockName = directive.value
                continue
            case "options", "property":
                continue
            default:
                break
            }
        }

        if trimmed.lowercased().hasPrefix("#+begin_src") {
            closeQuoteBlock()
            flushBlockState()
            beginPendingBlockWrapperIfNeeded()
            let language = trimmed
                .split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true)
                .dropFirst()
                .first
                .map(String.init)?
                .trimmingCharacters(in: .whitespacesAndNewlines)
            let classAttribute = language.map { " class=\"language-\(escapeHTMLAttribute($0))\"" } ?? ""
            html += "<pre><code\(classAttribute)>"
            srcLanguage = language ?? ""
            continue
        }

        if trimmed.lowercased() == "#+begin_example" {
            closeQuoteBlock()
            flushBlockState()
            beginPendingBlockWrapperIfNeeded()
            html += "<pre><code>"
            inExampleBlock = true
            continue
        }

        if trimmed.lowercased() == "#+begin_quote" {
            flushBlockState()
            beginPendingBlockWrapperIfNeeded()
            html += "<blockquote>\n"
            inQuoteBlock = true
            continue
        }

        if trimmed.lowercased() == "#+begin_center" {
            closeQuoteBlock()
            flushBlockState()
            beginPendingBlockWrapperIfNeeded()
            html += "<div style=\"text-align:center\">\n"
            inCenterBlock = true
            continue
        }

        if trimmed.lowercased() == "#+begin_verse" {
            closeQuoteBlock()
            flushBlockState()
            beginPendingBlockWrapperIfNeeded()
            verseLines = []
            inVerseBlock = true
            continue
        }

        if trimmed == ":PROPERTIES:" {
            closeQuoteBlock()
            flushBlockState()
            inPropertyDrawer = true
            continue
        }

        if trimmed == ":END:", inPropertyDrawer {
            flushPropertyDrawer()
            inPropertyDrawer = false
            continue
        }

        if inPropertyDrawer,
           trimmed.hasPrefix(":"),
           let secondColonIndex = trimmed.dropFirst().firstIndex(of: ":") {
            let keyStart = trimmed.index(after: trimmed.startIndex)
            let key = String(trimmed[keyStart..<secondColonIndex]).trimmingCharacters(in: .whitespaces)
            let valueStart = trimmed.index(after: secondColonIndex)
            let value = String(trimmed[valueStart...]).trimmingCharacters(in: .whitespaces)
            if !key.isEmpty {
                propertyRows.append((key, value))
                continue
            }
        }

        if isTableLine(trimmed) {
            closeQuoteBlock()
            flushParagraph()
            closeList()
            tableRows.append(parseTableRow(trimmed))
            continue
        } else {
            flushTable()
        }

        if isOrgHorizontalRule(trimmed) {
            closeQuoteBlock()
            flushBlockState()
            html += "<hr>\n"
            continue
        }

        // Org headings: * heading, ** heading, *** heading
        if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) {
            closeQuoteBlock()
            flushBlockState()
            let level = match.1.count
            let content = processOrgInline(String(match.2), imageURLResolver: imageURLResolver)
            html += "<h\(level)>" + content + "</h\(level)>\n"
            continue
        }

        if listType != nil && isIndentedContinuationLine(line) {
            currentListItemLines.append(line)
            continue
        }

        // List items: - item
        if !isIndentedContinuationLine(line), trimmed.hasPrefix("- ") {
            flushParagraph()
            flushPropertyDrawer()
            if listType != .unordered {
                closeList()
                html += "<ul>\n"
                listType = .unordered
            }
            flushListItem()
            currentListItemLines = [String(trimmed.dropFirst(2))]
            continue
        }

        if !isIndentedContinuationLine(line), let orderedItem = orderedListItem(in: trimmed) {
            flushParagraph()
            flushPropertyDrawer()
            if listType != .ordered {
                closeList()
                html += "<ol>\n"
                listType = .ordered
            }
            flushListItem()
            currentListItemLines = [orderedItem]
            continue
        }

        // Blank line
        if trimmed.isEmpty {
            if inQuoteBlock {
                flushParagraph()
            } else {
                flushBlockState()
            }
            continue
        }

        // Regular text
        if pendingBlockName != nil || pendingBlockCaption != nil {
            pendingBlockName = nil
            pendingBlockCaption = nil
        }
        paragraph.append(line)
    }

    closeSourceBlock()
    closeExampleBlock()
    closeCenterBlock()
    closeVerseBlock()
    closeQuoteBlock()
    flushBlockState()

    return html
}

nonisolated private func processOrgInline(_ text: String, imageURLResolver: ((String) -> String?)? = nil) -> String {
    var result = escapeHTML(text)
    var protectedFragments: [String: String] = [:]

    result = protectMatches(
        in: result,
        pattern: #"\[\[([^\]]+)\]\[\[([^\]]+)\]\]\]"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let destination = nsText.substring(with: match.range(at: 1))
        let source = nsText.substring(with: match.range(at: 2))
        guard let imageHTML = makeOrgImageHTML(
            source: source,
            alt: nil,
            imageURLResolver: imageURLResolver
        ) else {
            return source
        }
        guard let sanitizedURL = sanitizedReadmeLinkURLString(destination) else {
            return imageHTML
        }
        return #"<a href="\#(sanitizedURL)">\#(imageHTML)</a>"#
    }

    result = protectOrgLinks(in: result, protectedFragments: &protectedFragments, imageURLResolver: imageURLResolver)
    result = protectMatches(
        in: result,
        pattern: #"(?<!\S)~(.+?)~(?=\s|$|[.,;:!?])|(?<!\S)=(.+?)=(?=\s|$|[.,;:!?])"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let tildeRange = match.range(at: 1)
        let equalsRange = match.range(at: 2)
        let codeText: String
        if tildeRange.location != NSNotFound {
            codeText = nsText.substring(with: tildeRange)
        } else {
            codeText = nsText.substring(with: equalsRange)
        }
        return "<code>\(codeText)</code>"
    }
    result = protectMatches(
        in: result,
        pattern: #"(?<!\S)\+(.+?)\+(?=\s|$|[.,;:!?])"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let value = nsText.substring(with: match.range(at: 1))
        return "<del>\(value)</del>"
    }
    result = protectMatches(
        in: result,
        pattern: #"(?<!\S)_(.+?)_(?=\s|$|[.,;:!?])"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let value = nsText.substring(with: match.range(at: 1))
        return "<u>\(value)</u>"
    }

    // Bold: *text*
    result = result.replacingOccurrences(
        of: #"(?<!\S)\*(.+?)\*(?=\s|$|[.,;:!?])"#,
        with: "<strong>$1</strong>",
        options: .regularExpression
    )
    // Italic: /text/
    result = result.replacingOccurrences(
        of: #"(?<!\S)/(.+?)/(?=\s|$|[.,;:!?])"#,
        with: "<em>$1</em>",
        options: .regularExpression
    )
    result = replaceMatches(
        in: result,
        pattern: #"(?i)(?<![\w.%+\-])([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})(?![\w\-])"#
    ) { match, nsText in
        guard !isInsideHTMLTag(nsText, range: match.range) else {
            return nsText.substring(with: match.range)
        }
        let email = nsText.substring(with: match.range(at: 1))
        let href = escapeHTMLAttribute("mailto:\(email)")
        return #"<a href="\#(href)">\#(email)</a>"#
    }

    for (token, fragment) in protectedFragments {
        result = result.replacingOccurrences(of: token, with: fragment)
    }

    return result
}

// MARK: - HTML Escaping

nonisolated func escapeHTML(_ text: String) -> String {
    text.replacingOccurrences(of: "&", with: "&amp;")
        .replacingOccurrences(of: "<", with: "&lt;")
        .replacingOccurrences(of: ">", with: "&gt;")
        .replacingOccurrences(of: "\"", with: "&quot;")
}

nonisolated func escapeHTMLAttribute(_ text: String) -> String {
    escapeHTML(text).replacingOccurrences(of: "'", with: "&#39;")
}

nonisolated func sanitizedReadmeLinkURLString(_ rawURL: String) -> String? {
    sanitizeReadmeURLString(
        rawURL,
        allowedSchemes: ["http", "https", "mailto"],
        allowsFragmentOnly: true
    )
}

nonisolated func sanitizedReadmeImageURLString(_ rawURL: String) -> String? {
    sanitizeReadmeURLString(
        rawURL,
        allowedSchemes: ["http", "https"],
        allowsFragmentOnly: false
    )
}

nonisolated func isAllowedReadmeNavigationURL(_ url: URL) -> Bool {
    guard let scheme = url.scheme?.lowercased() else {
        return false
    }
    if scheme == "about" || scheme == "data" {
        return true
    }
    guard let sanitizedURL = sanitizedReadmeLinkURLString(url.absoluteString) else {
        return false
    }
    return sanitizedURL == escapeHTMLAttribute(url.absoluteString)
}

nonisolated private func sanitizeReadmeURLString(
    _ rawURL: String,
    allowedSchemes: Set<String>,
    allowsFragmentOnly: Bool
) -> String? {
    let trimmedURL = rawURL.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !trimmedURL.isEmpty else { return nil }

    if allowsFragmentOnly, trimmedURL.hasPrefix("#"), trimmedURL.count > 1 {
        return escapeHTMLAttribute(trimmedURL)
    }

    guard let components = URLComponents(string: trimmedURL),
          let scheme = components.scheme?.lowercased(),
          allowedSchemes.contains(scheme),
          let sanitizedURL = components.url?.absoluteString else {
        return nil
    }

    return escapeHTMLAttribute(sanitizedURL)
}

nonisolated private func isTableLine(_ line: String) -> Bool {
    line.hasPrefix("|") && line.hasSuffix("|")
}

nonisolated private func parseTableRow(_ line: String) -> [String] {
    line
        .split(separator: "|", omittingEmptySubsequences: false)
        .dropFirst()
        .dropLast()
        .map { String($0).trimmingCharacters(in: .whitespaces) }
}

nonisolated private func parseOrgTableSeparatorRow(_ line: String) -> [String] {
    var content = line.trimmingCharacters(in: .whitespaces)
    if content.hasPrefix("|") {
        content.removeFirst()
    }
    if content.hasSuffix("|") {
        content.removeLast()
    }
    return content
        .split(separator: "+", omittingEmptySubsequences: false)
        .map { String($0).trimmingCharacters(in: .whitespaces) }
}

nonisolated private func isTableSeparatorCell(_ cell: String) -> Bool {
    tableAlignment(for: cell) != nil
}

nonisolated private func tableAlignment(for cell: String) -> String? {
    let trimmed = cell.trimmingCharacters(in: .whitespaces)
    guard !trimmed.isEmpty else { return nil }

    let core = trimmed.replacingOccurrences(of: ":", with: "")
    guard !core.isEmpty, core.allSatisfy({ $0 == "-" || $0 == "+" }) else {
        return nil
    }

    let isLeftAligned = trimmed.hasPrefix(":")
    let isRightAligned = trimmed.hasSuffix(":")
    switch (isLeftAligned, isRightAligned) {
    case (true, true):
        return "center"
    case (true, false):
        return "left"
    case (false, true):
        return "right"
    case (false, false):
        return ""
    }
}

nonisolated private func renderHTMLTable(
    rows: [[String]],
    inlineRenderer: (String) -> String
) -> String {
    guard !rows.isEmpty else { return "" }
    let separatorCells: [String]
    if rows.count > 1, rows[1].count == 1 {
        separatorCells = parseOrgTableSeparatorRow(rows[1][0])
    } else {
        separatorCells = rows.count > 1 ? rows[1] : []
    }
    let hasHeaderSeparator = rows.count > 1 && !separatorCells.isEmpty && separatorCells.allSatisfy(isTableSeparatorCell)
    let headerRow = rows.first ?? []
    let bodyRows = hasHeaderSeparator ? Array(rows.dropFirst(2)) : rows
    let columnAlignments = hasHeaderSeparator ? separatorCells.map(tableAlignment) : []
    var html = "<table>\n"

    if hasHeaderSeparator {
        html += "<thead><tr>"
        for (index, cell) in headerRow.enumerated() {
            html += "<th" + tableAlignmentStyleAttribute(columnAlignment(at: index, in: columnAlignments)) + ">" + inlineRenderer(cell) + "</th>"
        }
        html += "</tr></thead>\n"
    }

    html += "<tbody>\n"
    for row in bodyRows {
        html += "<tr>"
        for (index, cell) in row.enumerated() {
            html += "<td" + tableAlignmentStyleAttribute(columnAlignment(at: index, in: columnAlignments)) + ">" + inlineRenderer(cell) + "</td>"
        }
        html += "</tr>\n"
    }
    html += "</tbody>\n"
    html += "</table>\n"
    return html
}

nonisolated private func columnAlignment(at index: Int, in alignments: [String?]) -> String? {
    guard alignments.indices.contains(index) else { return nil }
    return alignments[index]
}

nonisolated private func tableAlignmentStyleAttribute(_ alignment: String?) -> String {
    guard let alignment, !alignment.isEmpty else { return "" }
    return #" style="text-align: \#(alignment);""#
}

private enum OrgListType: Equatable {
    case unordered
    case ordered
}

nonisolated private func orderedListItem(in line: String) -> String? {
    guard let match = line.firstMatch(of: /^(\d+)\.\s+(.+)$/) else { return nil }
    return String(match.2)
}

nonisolated private func renderOrgListItemBody(
    _ lines: [String],
    imageURLResolver: ((String) -> String?)? = nil
) -> String {
    guard let firstLine = lines.first else { return "" }

    var contentLines: [String] = [firstLine.trimmingCharacters(in: .whitespaces)]
    var nestedLines: [String] = []

    for line in lines.dropFirst() {
        let trimmed = line.trimmingCharacters(in: .whitespaces)
        if trimmed.isEmpty {
            continue
        }

        if isIndentedListItemLine(line) {
            nestedLines.append(outdentOrgListLine(line))
        } else {
            contentLines.append(trimmed)
        }
    }

    var html = renderTaskListItem(
        contentLines.joined(separator: " "),
        inlineRenderer: { processOrgInline($0, imageURLResolver: imageURLResolver) }
    )
    if !nestedLines.isEmpty {
        html += "\n" + renderNestedOrgListHTML(nestedLines, imageURLResolver: imageURLResolver)
    }
    return html
}

nonisolated private func renderNestedOrgListHTML(
    _ lines: [String],
    imageURLResolver: ((String) -> String?)? = nil
) -> String {
    var html = ""
    var listType: OrgListType?
    var currentItemLines: [String] = []

    func flushNestedItem() {
        guard !currentItemLines.isEmpty else { return }
        html += "<li>" + renderOrgListItemBody(currentItemLines, imageURLResolver: imageURLResolver) + "</li>\n"
        currentItemLines = []
    }

    func closeNestedList() {
        flushNestedItem()
        switch listType {
        case .unordered:
            html += "</ul>\n"
        case .ordered:
            html += "</ol>\n"
        case nil:
            break
        }
        listType = nil
    }

    for line in lines {
        let trimmed = line.trimmingCharacters(in: .whitespaces)
        if trimmed.hasPrefix("- ") {
            if listType != .unordered {
                closeNestedList()
                html += "<ul>\n"
                listType = .unordered
            }
            flushNestedItem()
            currentItemLines = [String(trimmed.dropFirst(2))]
            continue
        }

        if let orderedItem = orderedListItem(in: trimmed) {
            if listType != .ordered {
                closeNestedList()
                html += "<ol>\n"
                listType = .ordered
            }
            flushNestedItem()
            currentItemLines = [orderedItem]
            continue
        }

        if listType != nil {
            currentItemLines.append(line)
        }
    }

    closeNestedList()
    return html
}

nonisolated private func protectOrgLinks(
    in text: String,
    protectedFragments: inout [String: String],
    imageURLResolver: ((String) -> String?)? = nil
) -> String {
    var result = text

    while let range = result.range(of: "[[") {
        guard let parsed = parseOrgLink(in: result, from: range.lowerBound) else {
            break
        }
        let token = "ZZPROTECTED\(protectedFragments.count)ZZ"
        protectedFragments[token] = renderOrgLink(
            destination: parsed.destination,
            label: parsed.label,
            imageURLResolver: imageURLResolver
        )
        result.replaceSubrange(parsed.range, with: token)
    }

    return result
}

nonisolated private func parseOrgLink(
    in text: String,
    from start: String.Index
) -> (range: Range<String.Index>, destination: String, label: String?)? {
    guard text[start...].hasPrefix("[[") else { return nil }

    var index = text.index(start, offsetBy: 2)
    guard let destinationEnd = text[index...].range(of: "][" )?.lowerBound else {
        guard let end = text[index...].range(of: "]]")?.lowerBound else { return nil }
        return (start..<text.index(end, offsetBy: 2), String(text[index..<end]), nil)
    }

    let destination = String(text[index..<destinationEnd])
    index = text.index(destinationEnd, offsetBy: 2)
    let labelStart = index
    var depth = 0

    while index < text.endIndex {
        if text[index...].hasPrefix("[[") {
            depth += 1
            index = text.index(index, offsetBy: 2)
            continue
        }
        if text[index...].hasPrefix("]]") {
            if depth == 0 {
                let end = text.index(index, offsetBy: 2)
                return (start..<end, destination, String(text[labelStart..<index]))
            }
            depth -= 1
            index = text.index(index, offsetBy: 2)
            continue
        }
        index = text.index(after: index)
    }

    return nil
}

nonisolated private func renderOrgLink(
    destination: String,
    label: String?,
    imageURLResolver: ((String) -> String?)? = nil
) -> String {
    if let label, label.hasPrefix("[["), label.hasSuffix("]]") {
        let source = String(label.dropFirst(2).dropLast(2))
        if let imageHTML = makeOrgImageHTML(source: source, alt: nil, imageURLResolver: imageURLResolver) {
            guard let sanitizedURL = sanitizedReadmeLinkURLString(destination) else {
                return imageHTML
            }
            return #"<a href="\#(sanitizedURL)">\#(imageHTML)</a>"#
        }
    }

    if let imageHTML = makeOrgImageHTML(
        source: destination,
        alt: label,
        imageURLResolver: imageURLResolver
    ) {
        return imageHTML
    }

    guard let sanitizedURL = sanitizedReadmeLinkURLString(destination) else {
        return label ?? destination
    }

    let renderedLabel = label.map { processOrgInline($0, imageURLResolver: imageURLResolver) } ?? destination
    return #"<a href="\#(sanitizedURL)">\#(renderedLabel)</a>"#
}

nonisolated private func orgKeywordDirective(in line: String) -> (keyword: String, value: String)? {
    guard let match = line.firstMatch(of: /^#\+([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/) else {
        return nil
    }
    return (
        keyword: String(match.1).lowercased(),
        value: String(match.2).trimmingCharacters(in: .whitespaces)
    )
}


nonisolated private func isOrgHorizontalRule(_ line: String) -> Bool {
    matchesRegex(line, pattern: #"^\s*-{5,}\s*$"#)
}

nonisolated private func matchesRegex(_ text: String, pattern: String) -> Bool {
    guard let regex = try? NSRegularExpression(pattern: pattern) else { return false }
    let range = NSRange(location: 0, length: (text as NSString).length)
    return regex.firstMatch(in: text, range: range) != nil
}

nonisolated private func isInsideHTMLTag(_ text: NSString, range: NSRange) -> Bool {
    guard range.location != NSNotFound else { return false }
    let prefix = text.substring(to: range.location)
    guard let lastOpen = prefix.lastIndex(of: "<") else { return false }
    guard let lastClose = prefix.lastIndex(of: ">") else { return true }
    return lastOpen > lastClose
}

nonisolated private func isIndentedContinuationLine(_ line: String) -> Bool {
    guard !line.trimmingCharacters(in: .whitespaces).isEmpty else { return false }
    guard let first = line.first else { return false }
    return first == " " || first == "\t"
}

nonisolated private func isIndentedListItemLine(_ line: String) -> Bool {
    guard isIndentedContinuationLine(line) else { return false }
    let trimmed = line.trimmingCharacters(in: .whitespaces)
    return trimmed.hasPrefix("- ") || orderedListItem(in: trimmed) != nil
}

nonisolated private func outdentOrgListLine(_ line: String) -> String {
    var result = line
    while result.first == " " || result.first == "\t" {
        result.removeFirst()
    }
    return result
}

private extension Array {
    subscript(safe index: Int) -> Element? {
        guard indices.contains(index) else { return nil }
        return self[index]
    }
}


nonisolated func decodeHTMLEntities(_ text: String) -> String {
    text
        .replacingOccurrences(of: "&amp;", with: "&")
        .replacingOccurrences(of: "&quot;", with: "\"")
        .replacingOccurrences(of: "&#39;", with: "'")
        .replacingOccurrences(of: "&lt;", with: "<")
        .replacingOccurrences(of: "&gt;", with: ">")
}

nonisolated func sanitizedMarkdownHTMLBlock(_ rawHTML: String) -> String? {
    var protectedFragments: [String: String] = [:]
    var foundUnsafeMarkup = false
    let protected = protectMatches(
        in: rawHTML,
        pattern: #"(?s)<!--.*?-->|</?[A-Za-z][^>]*?>"#,
        protectedFragments: &protectedFragments
    ) { match, nsText in
        let rawTag = nsText.substring(with: match.range)
        guard let sanitizedTag = sanitizedMarkdownHTMLTag(rawTag) else {
            foundUnsafeMarkup = true
            return ""
        }
        return sanitizedTag
    }

    guard !foundUnsafeMarkup else { return nil }

    var sanitized = escapeHTML(protected)
    sanitized = replaceMatches(in: sanitized, pattern: #"ZZPROTECTED\d+ZZ"#) { match, nsText in
        let token = nsText.substring(with: match.range)
        return protectedFragments[token] ?? ""
    }

    return sanitized.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : sanitized
}

nonisolated func sanitizedMarkdownHTMLTag(_ rawTag: String) -> String? {
    let trimmed = rawTag.trimmingCharacters(in: .whitespacesAndNewlines)
    guard trimmed.hasPrefix("<"), trimmed.hasSuffix(">") else { return nil }
    guard !trimmed.lowercased().hasPrefix("<!--") else { return nil }

    let selfClosing = trimmed.hasSuffix("/>")
    let contentStart = trimmed.index(after: trimmed.startIndex)
    let contentEnd = trimmed.index(trimmed.endIndex, offsetBy: selfClosing ? -2 : -1)
    let inner = trimmed[contentStart..<contentEnd].trimmingCharacters(in: .whitespacesAndNewlines)
    let isClosing = inner.hasPrefix("/")
    let body = isClosing ? inner.dropFirst().trimmingCharacters(in: .whitespacesAndNewlines) : inner
    let parts = body.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true)
    guard let rawName = parts.first else { return nil }
    let tagName = rawName.lowercased()
    let allowedTags: Set<String> = [
        "a", "abbr", "b", "blockquote", "br", "code", "del", "div", "em",
        "hr", "i", "img", "li", "ol", "p", "pre", "span", "strong", "sub",
        "sup", "u", "ul"
    ]
    guard allowedTags.contains(tagName) else { return nil }

    if isClosing {
        return "</\(tagName)>"
    }

    let attributePortion = parts.count > 1 ? String(parts[1]) : ""
    let attributes = parseHTMLAttributes(attributePortion)
    var renderedAttributes: [String] = []

    for (name, value) in attributes {
        switch (tagName, name.lowercased()) {
        case ("a", "href"):
            if let sanitized = sanitizedReadmeLinkURLString(decodeHTMLEntities(value)) {
                renderedAttributes.append(#"href="\#(sanitized)""#)
            }
        case ("img", "src"):
            if let sanitized = sanitizedReadmeImageURLString(decodeHTMLEntities(value)) {
                renderedAttributes.append(#"src="\#(sanitized)""#)
            }
        case ("img", "alt"), (_, "title"), (_, "class"):
            renderedAttributes.append(#"\#(name)="\#(escapeHTMLAttribute(value))""#)
        default:
            continue
        }
    }

    let suffix = selfClosing || tagName == "br" || tagName == "hr" || tagName == "img" ? " /" : ""
    let attributeText = renderedAttributes.isEmpty ? "" : " " + renderedAttributes.joined(separator: " ")
    return "<\(tagName)\(attributeText)\(suffix)>"
}

nonisolated private func parseHTMLAttributes(_ text: String) -> [(String, String)] {
    guard let regex = try? NSRegularExpression(pattern: #"([A-Za-z_:][A-Za-z0-9:._-]*)\s*=\s*"([^"]*)""#) else {
        return []
    }
    let nsText = text as NSString
    return regex.matches(in: text, range: NSRange(location: 0, length: nsText.length)).map { match in
        let name = nsText.substring(with: match.range(at: 1))
        let value = nsText.substring(with: match.range(at: 2))
        return (name, value)
    }
}

nonisolated private func protectMatches(
    in text: String,
    pattern: String,
    protectedFragments: inout [String: String],
    transform: (NSTextCheckingResult, NSString) -> String
) -> String {
    guard let regex = try? NSRegularExpression(pattern: pattern) else { return text }
    var result = text
    let matches = regex.matches(in: result, range: NSRange(location: 0, length: (result as NSString).length))

    for match in matches.reversed() {
        let token = "ZZPROTECTED\(protectedFragments.count)ZZ"
        let nsText = result as NSString
        protectedFragments[token] = transform(match, nsText)
        result = nsText.replacingCharacters(in: match.range, with: token)
    }

    return result
}

nonisolated private func replaceMatches(
    in text: String,
    pattern: String,
    transform: (NSTextCheckingResult, NSString) -> String
) -> String {
    guard let regex = try? NSRegularExpression(pattern: pattern) else { return text }
    var result = text
    let matches = regex.matches(in: result, range: NSRange(location: 0, length: (result as NSString).length))

    for match in matches.reversed() {
        let nsText = result as NSString
        let replacement = transform(match, nsText)
        result = nsText.replacingCharacters(in: match.range, with: replacement)
    }

    return result
}

nonisolated private func makeOrgImageHTML(
    source: String,
    alt: String?,
    imageURLResolver: ((String) -> String?)?
) -> String? {
    guard isRenderableImageSource(source) else { return nil }
    let resolvedSource = imageURLResolver?(source) ?? source
    guard let sanitizedSource = sanitizedReadmeImageURLString(resolvedSource) else { return nil }
    let altText = escapeHTMLAttribute(alt ?? "")
    return #"<img src="\#(sanitizedSource)" alt="\#(altText)">"#
}

nonisolated private func isRenderableImageSource(_ source: String) -> Bool {
    let lowercased = source.lowercased()
    return [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".heic"]
        .contains(where: { lowercased.hasSuffix($0) })
}

nonisolated func resolveRepositoryAssetURL(
    _ source: String,
    owner: String,
    repositoryName: String,
    readmePath: String?
) -> String? {
    let trimmedSource = source.trimmingCharacters(in: .whitespacesAndNewlines)
    guard !trimmedSource.isEmpty else { return nil }

    if trimmedSource.hasPrefix("http://") || trimmedSource.hasPrefix("https://") || trimmedSource.hasPrefix("data:") {
        return trimmedSource
    }

    let relativePath: String
    if trimmedSource.hasPrefix("/") {
        relativePath = String(trimmedSource.dropFirst())
    } else {
        let readmeDirectory = (readmePath as NSString?)?.deletingLastPathComponent ?? ""
        relativePath = normalizeRepositoryPath(
            (readmeDirectory as NSString).appendingPathComponent(trimmedSource)
        )
    }

    guard !relativePath.isEmpty else { return nil }
    var components = URLComponents()
    components.scheme = "https"
    components.host = "git.sr.ht"
    let encodedOwner = owner.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? owner
    let encodedRepository = repositoryName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? repositoryName
    let encodedRelativePath = relativePath
        .split(separator: "/", omittingEmptySubsequences: false)
        .map { segment in
            String(segment).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? String(segment)
        }
        .joined(separator: "/")
    components.percentEncodedPath = "/\(encodedOwner)/\(encodedRepository)/blob/HEAD/\(encodedRelativePath)"
    return components.string
}

nonisolated private func normalizeRepositoryPath(_ path: String) -> String {
    var components: [String] = []

    for part in path.split(separator: "/") {
        switch part {
        case ".":
            continue
        case "..":
            if !components.isEmpty {
                components.removeLast()
            }
        default:
            components.append(String(part))
        }
    }

    return components.joined(separator: "/")
}

nonisolated private func renderTaskListItem(
    _ text: String,
    inlineRenderer: (String) -> String
) -> String {
    let trimmed = text.trimmingCharacters(in: .whitespaces)
    guard trimmed.count >= 4 else {
        return inlineRenderer(text)
    }

    let prefix = String(trimmed.prefix(4))
    let remainder = String(trimmed.dropFirst(4)).trimmingCharacters(in: .whitespaces)

    switch prefix {
    case "[ ] ":
        return #"<span class="task-list-item"><input type="checkbox" disabled> \#(inlineRenderer(remainder))</span>"#
    case "[x] ", "[X] ":
        return #"<span class="task-list-item"><input type="checkbox" checked disabled> \#(inlineRenderer(remainder))</span>"#
    default:
        return inlineRenderer(text)
    }
}

// MARK: - WKWebView Wrapper

/// A WKWebView wrapper that renders HTML inline and grows to fit its content.
struct HTMLWebView: View {
    let html: String
    let colorScheme: ColorScheme
    var style: HTMLWebViewStyle = .readme
    var baseURL: URL? = nil
    var onInterceptURL: ((URL) -> Bool)? = nil
    @Environment(\.openURL) private var openURL
    @State private var contentHeight: CGFloat = 1
    @State private var loadError: String?
    @State private var reloadToken = 0

    var body: some View {
        Group {
            if let loadError {
                SRHTErrorStateView(
                    title: "Couldn't Render Content",
                    message: loadError,
                    retryAction: {
                        await MainActor.run {
                            self.loadError = nil
                            reloadToken += 1
                        }
                    }
                )
            } else {
                HTMLWebViewRepresentable(
                    html: html,
                    colorScheme: colorScheme,
                    style: style,
                    baseURL: baseURL,
                    onInterceptURL: onInterceptURL,
                    openURL: openURL,
                    dynamicHeight: $contentHeight,
                    loadError: $loadError,
                    reloadToken: reloadToken
                )
                .frame(height: max(contentHeight, 1))
            }
        }
    }
}

struct HTMLWebViewStyle: Sendable {
    let bodyFontSize: Int
    let lineHeight: Double
    let codeFontSize: Int
    let viewport: String

    static let readme = HTMLWebViewStyle(
        bodyFontSize: 16,
        lineHeight: 1.6,
        codeFontSize: 13,
        viewport: "width=device-width, initial-scale=1, maximum-scale=1"
    )

    static let commentPreview = HTMLWebViewStyle(
        bodyFontSize: 15,
        lineHeight: 1.5,
        codeFontSize: 12,
        viewport: "width=device-width, initial-scale=1, user-scalable=no"
    )
}

private struct HTMLWebViewRepresentable: UIViewRepresentable {
    let html: String
    let colorScheme: ColorScheme
    let style: HTMLWebViewStyle
    let baseURL: URL?
    let onInterceptURL: ((URL) -> Bool)?
    let openURL: OpenURLAction
    @Binding var dynamicHeight: CGFloat
    @Binding var loadError: String?
    let reloadToken: Int

    func makeCoordinator() -> HTMLWebViewCoordinator {
        HTMLWebViewCoordinator(parent: self)
    }

    func makeUIView(context: Context) -> WKWebView {
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences.allowsContentJavaScript = false
        config.websiteDataStore = HTMLWebViewCoordinator.websiteDataStore
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.clipsToBounds = false
        webView.allowsLinkPreview = false
        webView.scrollView.isScrollEnabled = false
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        webView.scrollView.clipsToBounds = false
        webView.navigationDelegate = context.coordinator
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        context.coordinator.parent = self
        let textColor = colorScheme == .dark ? "#fff" : "#000"
        let linkColor = colorScheme == .dark ? "#58a6ff" : "#0066cc"

        let wrapped = """
        <!DOCTYPE html>
        <html>
        <head>
        <meta name="viewport" content="\(style.viewport)">
        <style>
            body {
                font-family: -apple-system, system-ui, sans-serif;
                font-size: \(style.bodyFontSize)px;
                line-height: \(style.lineHeight);
                padding: 0;
                margin: 0;
                color: \(textColor);
                background: transparent;
                word-wrap: break-word;
                overflow-wrap: break-word;
                max-width: 100%;
            }
            * { box-sizing: border-box; }
            h1, h2, h3, h4, h5, h6 { line-height: 1.25; }
            p:first-child { margin-top: 0; }
            p:last-child { margin-bottom: 0; }
            pre, code {
                font-family: ui-monospace, Menlo, monospace;
                font-size: \(style.codeFontSize)px;
                background: rgba(128, 128, 128, 0.15);
                padding: 2px 4px;
                border-radius: 3px;
            }
            pre code { padding: 0; background: none; }
            pre {
                padding: 8px;
                overflow-x: auto;
                white-space: pre;
                word-break: normal;
                overflow-wrap: normal;
            }
            img { max-width: 100%; height: auto; }
            svg {
                max-width: 100%;
                height: auto;
            }
            input[type="checkbox"] {
                margin-right: 0.45rem;
                vertical-align: middle;
            }
            .task-list-item {
                display: inline-flex;
                align-items: center;
                gap: 0.1rem;
            }
            a { color: \(linkColor); }
            table { border-collapse: collapse; width: 100%; }
            td, th { border: 1px solid #ccc; padding: 4px 8px; }
            blockquote {
                border-left: 3px solid rgba(128, 128, 128, 0.5);
                margin: 0.5em 0;
                padding: 0.25em 0 0.25em 1em;
                color: inherit;
                opacity: 0.85;
            }
            .org-verse {
                white-space: pre-wrap;
            }
            hr {
                border: none;
                border-top: 1px solid rgba(128, 128, 128, 0.35);
                margin: 1em 0;
            }
            table {
                border-collapse: collapse;
                width: 100%;
                margin: 0.75em 0;
                font-size: 0.95em;
            }
            th {
                background: rgba(128, 128, 128, 0.15);
                font-weight: 600;
                text-align: left;
            }
            td, th {
                border: 1px solid rgba(128, 128, 128, 0.3);
                padding: 6px 10px;
            }
            dl.org-properties {
                margin: 0.5em 0;
                display: grid;
                grid-template-columns: max-content 1fr;
                gap: 2px 12px;
            }
            dt {
                font-weight: 600;
                font-family: ui-monospace, Menlo, monospace;
                font-size: 0.9em;
            }
            dd { margin: 0; }
            .org-metadata { margin-bottom: 1em; }
            figure.org-block {
                margin: 0.75em 0;
            }
            figure.org-block figcaption {
                margin-top: 0.4em;
                color: rgba(128, 128, 128, 0.85);
                font-size: 0.9em;
            }
            .btn {
                display: inline-flex;
                align-items: center;
                gap: 0.4em;
            }
            .icon {
                display: inline-flex;
                align-items: center;
                vertical-align: middle;
            }
            .icon svg {
                width: 0.65em;
                height: 0.65em;
                display: block;
                fill: currentColor;
            }
            .org-title { margin: 0 0 0.25em; }
            .org-author, .org-date {
                margin: 0;
                color: rgba(128, 128, 128, 0.85);
                font-size: 0.9em;
            }
            del { opacity: 0.7; }
        </style>
        </head>
        <body>\(html)</body>
        </html>
        """

        if let cachedHeight = HTMLWebViewCoordinator.heightCache.object(forKey: wrapped as NSString)?.doubleValue {
            let height = CGFloat(cachedHeight)
            if abs(dynamicHeight - height) > 0.5 {
                DispatchQueue.main.async {
                    if abs(self.dynamicHeight - height) > 0.5 {
                        self.dynamicHeight = height
                    }
                }
            }
        }

        guard context.coordinator.lastHTML != wrapped || context.coordinator.lastReloadToken != reloadToken else { return }
        context.coordinator.lastHTML = wrapped
        context.coordinator.lastReloadToken = reloadToken
        if loadError != nil {
            DispatchQueue.main.async {
                self.loadError = nil
            }
        }
        webView.loadHTMLString(wrapped, baseURL: baseURL)
    }
}

private final class HTMLWebViewCoordinator: NSObject, WKNavigationDelegate, @unchecked Sendable {
    static let websiteDataStore = WKWebsiteDataStore.nonPersistent()
    static let heightCache = NSCache<NSString, NSNumber>()

    var parent: HTMLWebViewRepresentable
    var lastHTML: String?
    var lastReloadToken = 0

    init(parent: HTMLWebViewRepresentable) {
        self.parent = parent
    }

    func webView(_ webView: WKWebView, didFinish _: WKNavigation!) {
        DispatchQueue.main.async {
            self.parent.loadError = nil
        }
        updateHeight(for: webView)
    }

    func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
        handleLoadFailure(error)
    }

    func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
        handleLoadFailure(error)
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
    ) {
        guard let requestURL = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }

        if navigationAction.navigationType == .linkActivated {
            if isSameDocumentFragmentNavigation(requestURL) {
                decisionHandler(.allow)
                return
            }
            if let intercept = parent.onInterceptURL, intercept(requestURL) {
                decisionHandler(.cancel)
                return
            }
            if isAllowedReadmeNavigationURL(requestURL) {
                parent.openURL(requestURL)
            }
            decisionHandler(.cancel)
            return
        }

        if isAllowedReadmeNavigationURL(requestURL) {
            decisionHandler(.allow)
        } else {
            decisionHandler(.cancel)
        }
    }

    private func handleLoadFailure(_ error: Error) {
        let nsError = error as NSError
        guard nsError.code != NSURLErrorCancelled else { return }
        DispatchQueue.main.async {
            self.parent.loadError = "The content could not be displayed right now."
        }
    }

    private func updateHeight(for webView: WKWebView) {
        webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] result, _ in
            guard let self else { return }
            guard let heightValue = result as? NSNumber else { return }
            let height = CGFloat(heightValue.doubleValue)
            guard height > 0 else { return }
            let rounded = ceil(height) + 4
            DispatchQueue.main.async {
                if let html = self.lastHTML {
                    Self.heightCache.setObject(NSNumber(value: Double(rounded)), forKey: html as NSString)
                }
                if abs(self.parent.dynamicHeight - rounded) > 0.5 {
                    self.parent.dynamicHeight = rounded
                }
            }
        }
    }

    private func isSameDocumentFragmentNavigation(_ url: URL) -> Bool {
        guard url.fragment != nil,
              let baseURL = parent.baseURL else {
            return false
        }

        guard var destination = URLComponents(url: url, resolvingAgainstBaseURL: false),
              var base = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {
            return false
        }

        destination.fragment = nil
        base.fragment = nil
        return destination.url == base.url
    }
}