1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2024 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import Markdown
import SymbolKit
/// A visitor which converts a semantic model into a render node.
///
/// The translator visits the contents of a ``DocumentationNode``'s ``Semantic`` model and creates a ``RenderNode``.
/// The translation is lossy, meaning that translating a ``RenderNode`` back to a ``Semantic`` is not possible with full fidelity.
/// For example, source markup syntax is not preserved during the translation.
public struct RenderNodeTranslator: SemanticVisitor {
/// Resolved topic references that were seen by the visitor. These should be used to populate the references dictionary.
var collectedTopicReferences: [ResolvedTopicReference] = []
/// Unresolvable topic references outside the current bundle.
var collectedUnresolvedTopicReferences: [UnresolvedTopicReference] = []
/// Any collected constraints to symbol relationships.
var collectedConstraints: [TopicReference: [SymbolGraph.Symbol.Swift.GenericConstraint]] = [:]
/// A context containing pre-rendered content.
let renderContext: RenderContext?
/// A collection of functions that render pieces of documentation content.
let contentRenderer: DocumentationContentRenderer
/// Whether the documentation converter should include source file
/// location metadata in any render nodes representing symbols it creates.
///
/// Before setting this value to `true` please confirm that your use case doesn't
/// include public distribution of any created render nodes as there are filesystem privacy and security
/// concerns with distributing this data.
var shouldEmitSymbolSourceFileURIs: Bool
/// Whether the documentation converter should include access level information for symbols.
var shouldEmitSymbolAccessLevels: Bool
/// Whether tutorials that are not curated in a tutorials overview should be translated.
var shouldRenderUncuratedTutorials: Bool = false
/// The source repository where the documentation's sources are hosted.
var sourceRepository: SourceRepository?
var symbolIdentifiersWithExpandedDocumentation: [String]? = nil
public mutating func visitCode(_ code: Code) -> RenderTree? {
let fileType = NSString(string: code.fileName).pathExtension
guard let fileIdentifier = context.identifier(forAssetName: code.fileReference.path, in: identifier) else {
return nil
}
let fileReference = ResourceReference(bundleIdentifier: code.fileReference.bundleIdentifier, path: fileIdentifier)
guard let fileContents = fileContents(with: fileReference) else {
return nil
}
let assetReference = RenderReferenceIdentifier(fileReference.path)
fileReferences[fileReference.path] = FileReference(
identifier: assetReference,
fileName: code.fileName,
fileType: fileType,
syntax: fileType,
content: fileContents.splitByNewlines
)
return assetReference
}
private func fileContents(with fileReference: ResourceReference) -> String? {
// Check if the file is a local asset that can be read directly from the context
if let fileData = try? context.resource(with: fileReference) {
return String(data: fileData, encoding: .utf8)
}
// Check if the file needs to be resolved to read its content
else if let asset = context.resolveAsset(named: fileReference.path, in: identifier) {
return try? String(contentsOf: asset.data(bestMatching: DataTraitCollection()).url, encoding: .utf8)
}
// Couldn't find the file reference's content
else {
return nil
}
}
public mutating func visitSteps(_ steps: Steps) -> RenderTree? {
let stepsContent = steps.content.flatMap { child -> [RenderBlockContent] in
return visit(child) as! [RenderBlockContent]
}
return stepsContent
}
public mutating func visitStep(_ step: Step) -> RenderTree? {
let renderBlock = visitMarkupContainer(MarkupContainer(step.content)) as! [RenderBlockContent]
let caption = visitMarkupContainer(MarkupContainer(step.caption)) as! [RenderBlockContent]
let mediaReference = step.media.map { visit($0) } as? RenderReferenceIdentifier
let codeReference = step.code.map { visitCode($0) } as? RenderReferenceIdentifier
let previewReference = step.code?.preview.flatMap {
createAndRegisterRenderReference(forMedia: $0.source, altText: ($0 as? ImageMedia)?.altText)
}
let result = [RenderBlockContent.step(.init(content: renderBlock, caption: caption, media: mediaReference, code: codeReference, runtimePreview: previewReference))]
return result
}
public mutating func visitTutorialSection(_ tutorialSection: TutorialSection) -> RenderTree? {
let introduction = contentLayouts(tutorialSection.introduction)
let stepsContent: [RenderBlockContent]
if let steps = tutorialSection.stepsContent {
stepsContent = visit(steps) as! [RenderBlockContent]
} else {
stepsContent = []
}
let highlightsPerFile = LineHighlighter(context: context, tutorialSection: tutorialSection, tutorialReference: identifier).highlights
// Add the highlights to the file references.
for result in highlightsPerFile {
fileReferences[result.file.path]?.highlights = result.highlights
}
return TutorialSectionsRenderSection.Section(title: tutorialSection.title, contentSection: introduction, stepsSection: stepsContent, anchor: urlReadableFragment(tutorialSection.title))
}
public mutating func visitTutorial(_ tutorial: Tutorial) -> RenderTree? {
var node = RenderNode(identifier: identifier, kind: .tutorial)
var hierarchyTranslator = RenderHierarchyTranslator(context: context, bundle: bundle)
if let hierarchy = hierarchyTranslator.visitTechnologyNode(identifier) {
let technology = try! context.entity(with: hierarchy.technology).semantic as! Technology
node.hierarchy = hierarchy.hierarchy
node.metadata.category = technology.name
node.metadata.categoryPathComponent = hierarchy.technology.url.lastPathComponent
} else if !context.allowsRegisteringArticlesWithoutTechnologyRoot {
// This tutorial is not curated, so we don't generate a render node.
// We've warned about this during semantic analysis.
return nil
}
node.metadata.title = tutorial.intro.title
node.metadata.role = DocumentationContentRenderer.role(for: .tutorial).rawValue
collectedTopicReferences.append(contentsOf: hierarchyTranslator.collectedTopicReferences)
let documentationNode = try! context.entity(with: identifier)
node.variants = variants(for: documentationNode)
var intro = visitIntro(tutorial.intro) as! IntroRenderSection
intro.estimatedTimeInMinutes = tutorial.durationMinutes
if let chapterReference = context.parents(of: identifier).first {
intro.chapter = context.title(for: chapterReference)
}
// Add an Xcode requirement to the tutorial intro if one is provided.
if let requirement = tutorial.requirements.first {
let identifier = RenderReferenceIdentifier(requirement.title)
let requirementReference = XcodeRequirementReference(identifier: identifier, title: requirement.title, url: requirement.destination)
requirementReferences[identifier.identifier] = requirementReference
intro.xcodeRequirement = identifier
}
if let projectFiles = tutorial.projectFiles {
intro.projectFiles = createAndRegisterRenderReference(forMedia: projectFiles, assetContext: .download)
}
node.sections.append(intro)
var tutorialSections = TutorialSectionsRenderSection(sections: tutorial.sections.map { visitTutorialSection($0) as! TutorialSectionsRenderSection.Section })
// Attach anchors to tutorial sections.
// Find the reference associated with the section, by searching the tutorial's children for a node that has a matching title.
// This assumes that the rendered `tasks` are in the same order as `tutorial.sections`.
let sectionReferences = context.children(of: identifier, kind: .onPageLandmark)
tutorialSections.tasks = tutorialSections.tasks.enumerated().map { (index, section) in
var section = section
section.anchor = sectionReferences[index].reference.fragment ?? ""
return section
}
node.sections.append(tutorialSections)
if let assessments = tutorial.assessments {
node.sections.append(visitAssessments(assessments) as! TutorialAssessmentsRenderSection)
}
// We guarantee there will be at least 1 path with at least 4 nodes in that path if the tutorial is curated.
// The way to curate tutorials is to link them from a Technology page and that generates the following hierarchy:
// technology -> volume -> chapter -> tutorial.
let technologyPath = context.finitePaths(to: identifier, options: [.preferTechnologyRoot])[0]
if technologyPath.count >= 2 {
let volume = technologyPath[technologyPath.count - 2]
if let cta = callToAction(with: tutorial.callToActionImage, volume: volume) {
node.sections.append(cta)
}
}
node.references = createTopicRenderReferences()
addReferences(fileReferences, to: &node)
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
addReferences(requirementReferences, to: &node)
addReferences(downloadReferences, to: &node)
addReferences(linkReferences, to: &node)
addReferences(hierarchyTranslator.linkReferences, to: &node)
return node
}
/// Creates a CTA for tutorials and tutorial articles.
private mutating func callToAction(with callToActionImage: ImageMedia?, volume: ResolvedTopicReference) -> CallToActionSection? {
// Get all the tutorials and tutorial articles in the learning path, ordered.
var surroundingTopics = [(reference: ResolvedTopicReference, kind: DocumentationNode.Kind)]()
for node in context.breadthFirstSearch(from: volume) where node.kind == .tutorial || node.kind == .tutorialArticle {
surroundingTopics.append((node.reference, node.kind))
}
// Find the tutorial or article that comes after the current page, if one exists.
let nextTopicIndex = surroundingTopics.firstIndex(where: { $0.reference == identifier }).map { $0 + 1 }
if let nextTopicIndex, nextTopicIndex < surroundingTopics.count {
let nextTopicReference = surroundingTopics[nextTopicIndex]
let nextTopicReferenceIdentifier = visitResolvedTopicReference(nextTopicReference.reference) as! RenderReferenceIdentifier
let nextTopic = try! context.entity(with: nextTopicReference.reference).semantic as! Abstracted & Titled
let image = callToActionImage.map { visit($0) as! RenderReferenceIdentifier }
return createCallToAction(reference: nextTopicReferenceIdentifier, kind: nextTopicReference.kind, title: nextTopic.title ?? "", abstract: inlineAbstractContentInTopic(nextTopic), image: image)
}
return nil
}
private mutating func createCallToAction(reference: RenderReferenceIdentifier, kind: DocumentationNode.Kind, title: String, abstract: [RenderInlineContent], image: RenderReferenceIdentifier?) -> CallToActionSection {
let overridingTitle: String
let eyebrow: String
switch kind {
case .tutorial:
overridingTitle = "Get started"
eyebrow = "Tutorial"
case .tutorialArticle:
overridingTitle = "Read article"
eyebrow = "Article"
default:
fatalError("Unexpected kind '\(kind)', only tutorials and tutorial articles may be CTA destinations.")
}
let action = RenderInlineContent.reference(identifier: reference, isActive: true, overridingTitle: overridingTitle, overridingTitleInlineContent: [.text(overridingTitle)])
return CallToActionSection(title: title, abstract: abstract, media: image, action: action, featuredEyebrow: eyebrow)
}
private mutating func inlineAbstractContentInTopic(_ topic: Abstracted) -> [RenderInlineContent] {
if let abstract = topic.abstract {
return (visitMarkupContainer(MarkupContainer(abstract)) as! [RenderBlockContent]).firstParagraph
}
return []
}
public mutating func visitIntro(_ intro: Intro) -> RenderTree? {
var section = IntroRenderSection(title: intro.title)
section.content = visitMarkupContainer(intro.content) as! [RenderBlockContent]
section.image = intro.image.map { visit($0) } as? RenderReferenceIdentifier
section.video = intro.video.map { visit($0) } as? RenderReferenceIdentifier
// Set the Intro's background image to the video's poster image.
section.backgroundImage = intro.video?.poster.flatMap { createAndRegisterRenderReference(forMedia: $0) }
?? intro.image.flatMap { createAndRegisterRenderReference(forMedia: $0.source) }
return section
}
/// Add a requirement reference and return its identifier.
public mutating func visitXcodeRequirement(_ requirement: XcodeRequirement) -> RenderTree? {
fatalError("TODO")
}
public mutating func visitAssessments(_ assessments: Assessments) -> RenderTree? {
let renderSectionAssessments: [TutorialAssessmentsRenderSection.Assessment] = assessments.questions.map { question in
return self.visitMultipleChoice(question) as! TutorialAssessmentsRenderSection.Assessment
}
return TutorialAssessmentsRenderSection(assessments: renderSectionAssessments, anchor: RenderHierarchyTranslator.assessmentsAnchor)
}
public mutating func visitMultipleChoice(_ multipleChoice: MultipleChoice) -> RenderTree? {
let questionPhrasing = visit(multipleChoice.questionPhrasing) as! [RenderBlockContent]
let content = visitMarkupContainer(multipleChoice.content) as! [RenderBlockContent]
return TutorialAssessmentsRenderSection.Assessment(title: questionPhrasing, content: content, choices: multipleChoice.choices.map { visitChoice($0) } as! [TutorialAssessmentsRenderSection.Assessment.Choice])
}
public mutating func visitChoice(_ choice: Choice) -> RenderTree? {
return TutorialAssessmentsRenderSection.Assessment.Choice(
content: visitMarkupContainer(choice.content) as! [RenderBlockContent],
isCorrect: choice.isCorrect,
justification: (visitJustification(choice.justification) as! [RenderBlockContent]),
reaction: choice.justification.reaction
)
}
public mutating func visitJustification(_ justification: Justification) -> RenderTree? {
return visitMarkupContainer(justification.content) as! [RenderBlockContent]
}
// Visits a container and expects the elements to be block level elements
public mutating func visitMarkupContainer(_ markupContainer: MarkupContainer) -> RenderTree? {
var contentCompiler = RenderContentCompiler(context: context, bundle: bundle, identifier: identifier)
let content = markupContainer.elements.reduce(into: [], { result, item in result.append(contentsOf: contentCompiler.visit(item))}) as! [RenderBlockContent]
collectedTopicReferences.append(contentsOf: contentCompiler.collectedTopicReferences)
// Copy all the image references found in the markup container.
imageReferences.merge(contentCompiler.imageReferences) { (_, new) in new }
videoReferences.merge(contentCompiler.videoReferences) { (_, new) in new }
linkReferences.merge(contentCompiler.linkReferences) { (_, new) in new }
return content
}
// Visits a collection of inline markup elements.
public mutating func visitMarkup(_ markup: [Markup]) -> RenderTree? {
var contentCompiler = RenderContentCompiler(context: context, bundle: bundle, identifier: identifier)
let content = markup.reduce(into: [], { result, item in result.append(contentsOf: contentCompiler.visit(item))}) as! [RenderInlineContent]
collectedTopicReferences.append(contentsOf: contentCompiler.collectedTopicReferences)
// Copy all the image references.
imageReferences.merge(contentCompiler.imageReferences) { (_, new) in new }
videoReferences.merge(contentCompiler.videoReferences) { (_, new) in new }
return content
}
// Visits a single inline markup element.
public mutating func visitMarkup(_ markup: Markup) -> RenderTree? {
return visitMarkup(Array(markup.children))
}
private func firstTutorial(ofTechnology technology: ResolvedTopicReference) -> (reference: ResolvedTopicReference, kind: DocumentationNode.Kind)? {
guard let volume = (context.children(of: technology, kind: .volume)).first,
let firstChapter = (context.children(of: volume.reference)).first,
let firstTutorial = (context.children(of: firstChapter.reference)).first else
{
return nil
}
return firstTutorial
}
/// Returns a description of the total estimated duration to complete the tutorials of the given technology.
/// - Returns: The estimated duration, or `nil` if there are no tutorials with time estimates.
private func totalEstimatedDuration(for technology: Technology) -> String? {
var totalDurationMinutes: Int? = nil
for node in context.breadthFirstSearch(from: identifier) {
guard let entity = try? context.entity(with: node.reference),
let durationMinutes = (entity.semantic as? Timed)?.durationMinutes
else {
continue
}
if totalDurationMinutes == nil {
totalDurationMinutes = 0
}
totalDurationMinutes! += durationMinutes
}
return totalDurationMinutes.flatMap(contentRenderer.formatEstimatedDuration(minutes:))
}
public mutating func visitTechnology(_ technology: Technology) -> RenderTree? {
var node = RenderNode(identifier: identifier, kind: .overview)
node.metadata.title = technology.intro.title
node.metadata.category = technology.name
node.metadata.categoryPathComponent = identifier.url.lastPathComponent
node.metadata.estimatedTime = totalEstimatedDuration(for: technology)
node.metadata.role = DocumentationContentRenderer.role(for: .technology).rawValue
let documentationNode = try! context.entity(with: identifier)
node.variants = variants(for: documentationNode)
var intro = visitIntro(technology.intro) as! IntroRenderSection
if let firstTutorial = self.firstTutorial(ofTechnology: identifier) {
intro.action = visitLink(firstTutorial.reference.url, defaultTitle: "Get started")
}
node.sections.append(intro)
node.sections.append(contentsOf: technology.volumes.map { visitVolume($0) as! VolumeRenderSection })
if let resources = technology.resources {
node.sections.append(visitResources(resources) as! ResourcesRenderSection)
}
var hierarchyTranslator = RenderHierarchyTranslator(context: context, bundle: bundle)
node.hierarchy = hierarchyTranslator
.visitTechnologyNode(identifier, omittingChapters: true)!
.hierarchy
collectedTopicReferences.append(contentsOf: hierarchyTranslator.collectedTopicReferences)
node.references = createTopicRenderReferences()
addReferences(fileReferences, to: &node)
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
addReferences(linkReferences, to: &node)
return node
}
private mutating func createTopicRenderReferences() -> [String: RenderReference] {
var renderReferences: [String: RenderReference] = [:]
let renderer = DocumentationContentRenderer(documentationContext: context, bundle: bundle)
for reference in collectedTopicReferences {
var renderReference: TopicRenderReference
var dependencies: RenderReferenceDependencies
if let renderContext, let prerendered = renderContext.store.content(for: reference)?.renderReference as? TopicRenderReference,
let renderReferenceDependencies = renderContext.store.content(for: reference)?.renderReferenceDependencies {
renderReference = prerendered
dependencies = renderReferenceDependencies
} else {
dependencies = RenderReferenceDependencies()
renderReference = renderer.renderReference(for: reference, dependencies: &dependencies)
}
for link in dependencies.linkReferences {
linkReferences[link.identifier.identifier] = link
}
for imageReference in dependencies.imageReferences {
imageReferences[imageReference.identifier.identifier] = imageReference
}
for dependencyReference in dependencies.topicReferences {
var dependencyRenderReference: TopicRenderReference
if let renderContext, let prerendered = renderContext.store.content(for: dependencyReference)?.renderReference as? TopicRenderReference {
dependencyRenderReference = prerendered
} else {
var dependencies = RenderReferenceDependencies()
dependencyRenderReference = renderer.renderReference(for: dependencyReference, dependencies: &dependencies)
}
renderReferences[dependencyReference.absoluteString] = dependencyRenderReference
}
// Add any conformance constraints to the reference, if any are present.
if let conformanceSection = renderer.conformanceSectionFor(reference, collectedConstraints: collectedConstraints) {
renderReference.conformance = conformanceSection
}
renderReferences[reference.absoluteString] = renderReference
}
for unresolved in collectedUnresolvedTopicReferences {
let renderReference = UnresolvedRenderReference(
identifier: RenderReferenceIdentifier(unresolved.topicURL.absoluteString),
title: unresolved.title ?? unresolved.topicURL.absoluteString
)
renderReferences[renderReference.identifier.identifier] = renderReference
}
return renderReferences
}
private func addReferences(_ references: [String: some RenderReference], to node: inout RenderNode) {
node.references.merge(references) { _, new in new }
}
public mutating func visitVolume(_ volume: Volume) -> RenderTree? {
var volumeSection = VolumeRenderSection(name: volume.name)
volumeSection.image = volume.image.map { visit($0) as! RenderReferenceIdentifier }
volumeSection.content = volume.content.map { visitMarkupContainer($0) as! [RenderBlockContent] }
volumeSection.chapters = volume.chapters.compactMap { visitChapter($0) } as? [VolumeRenderSection.Chapter] ?? []
return volumeSection
}
public mutating func visitImageMedia(_ imageMedia: ImageMedia) -> RenderTree? {
return createAndRegisterRenderReference(forMedia: imageMedia.source, altText: imageMedia.altText)
}
public mutating func visitVideoMedia(_ videoMedia: VideoMedia) -> RenderTree? {
return createAndRegisterRenderReference(
forMedia: videoMedia.source,
poster: videoMedia.poster,
altText: videoMedia.altText
)
}
public mutating func visitChapter(_ chapter: Chapter) -> RenderTree? {
guard !chapter.topicReferences.isEmpty else {
// If the chapter has no tutorials, return `nil`.
return nil
}
var renderChapter = VolumeRenderSection.Chapter(name: chapter.name)
renderChapter.content = visitMarkupContainer(chapter.content) as! [RenderBlockContent]
renderChapter.tutorials = chapter.topicReferences.map { visitTutorialReference($0) } as! [RenderReferenceIdentifier]
renderChapter.image = chapter.image.map { visit($0) } as? RenderReferenceIdentifier
return renderChapter
}
public mutating func visitContentAndMedia(_ contentAndMedia: ContentAndMedia) -> RenderTree? {
var layout: ContentAndMediaSection.Layout? {
switch contentAndMedia.layout {
case .horizontal: return .horizontal
case .vertical: return .vertical
case nil: return nil
}
}
let mediaReference = contentAndMedia.media.map { visit($0) } as? RenderReferenceIdentifier
var section = ContentAndMediaSection(layout: layout, title: contentAndMedia.title, media: mediaReference, mediaPosition: contentAndMedia.mediaPosition)
section.eyebrow = contentAndMedia.eyebrow
section.content = visitMarkupContainer(contentAndMedia.content) as! [RenderBlockContent]
return section
}
public mutating func visitTutorialReference(_ tutorialReference: TutorialReference) -> RenderTree? {
switch context.resolve(tutorialReference.topic, in: bundle.rootReference) {
case let .failure(reference, _):
return RenderReferenceIdentifier(reference.topicURL.absoluteString)
case let .success(resolved):
return visitResolvedTopicReference(resolved)
}
}
public mutating func visitResolvedTopicReference(_ resolvedTopicReference: ResolvedTopicReference) -> RenderTree {
collectedTopicReferences.append(resolvedTopicReference)
return RenderReferenceIdentifier(resolvedTopicReference.absoluteString)
}
public mutating func visitResources(_ resources: Resources) -> RenderTree? {
let tiles = resources.tiles.map { visitTile($0) as! RenderTile }
let content = visitMarkupContainer(resources.content) as! [RenderBlockContent]
return ResourcesRenderSection(tiles: tiles, content: content)
}
public mutating func visitLink(_ link: URL, defaultTitle overridingTitle: String?) -> RenderInlineContent {
let overridingTitleInlineContent: [RenderInlineContent]? = overridingTitle.map { [RenderInlineContent.text($0)] }
let action: RenderInlineContent
// We expect, at this point of the rendering, this API to be called with valid URLs, otherwise crash.
if let resolved = context.referenceIndex[link.absoluteString] {
action = RenderInlineContent.reference(identifier: RenderReferenceIdentifier(resolved.absoluteString),
isActive: true,
overridingTitle: overridingTitle,
overridingTitleInlineContent: overridingTitleInlineContent)
collectedTopicReferences.append(resolved)
} else if !ResolvedTopicReference.urlHasResolvedTopicScheme(link) {
// This is an external link
let externalLinkIdentifier = RenderReferenceIdentifier(forExternalLink: link.absoluteString)
if linkReferences.keys.contains(externalLinkIdentifier.identifier) {
// If we've already seen this link, return the existing reference with an overridden title.
action = RenderInlineContent.reference(identifier: externalLinkIdentifier,
isActive: true,
overridingTitle: overridingTitle,
overridingTitleInlineContent: overridingTitleInlineContent)
} else {
// Otherwise, create and save a new link reference.
let linkReference = LinkReference(identifier: externalLinkIdentifier,
title: overridingTitle ?? link.absoluteString,
titleInlineContent: overridingTitleInlineContent ?? [.text(link.absoluteString)],
url: link.absoluteString)
linkReferences[externalLinkIdentifier.identifier] = linkReference
action = RenderInlineContent.reference(identifier: externalLinkIdentifier, isActive: true, overridingTitle: nil, overridingTitleInlineContent: nil)
}
} else {
// This is an unresolved doc: URL. We render the link inactive by converting it to plain text,
// as it may break routing or other downstream uses of the URL.
action = RenderInlineContent.text(link.path)
}
return action
}
public mutating func visitTile(_ tile: Tile) -> RenderTree? {
let action = tile.destination.map { visitLink($0, defaultTitle: RenderTile.defaultCallToActionTitle(for: tile.identifier)) }
var section = RenderTile(identifier: .init(tileIdentifier: tile.identifier), title: tile.title, action: action, media: nil)
section.content = visitMarkupContainer(tile.content) as! [RenderBlockContent]
return section
}
public mutating func visitArticle(_ article: Article) -> RenderTree? {
var node = RenderNode(identifier: identifier, kind: .article)
// Contains symbol references declared in the Topics section.
var topicSectionContentCompiler = RenderContentCompiler(context: context, bundle: bundle, identifier: identifier)
node.metadata.title = article.title!.plainText
// Detect the article modules from its breadcrumbs.
var modules = Set<ResolvedTopicReference>()
for reference in context.topicGraph.reverseEdgesGraph.breadthFirstSearch(from: identifier) {
if let moduleReference = (try? context.entity(with: reference).semantic as? Symbol)?.moduleReference {
modules.insert(moduleReference)
}
}
let moduleNames = modules.compactMap { reference -> String? in
guard let node = try? context.entity(with: reference) else { return nil }
switch node.name {
case .conceptual(let title):
return title
case .symbol(let declaration):
return declaration.tokens.map { $0.description }.joined(separator: " ")
}
}
if !moduleNames.isEmpty {
node.metadata.modules = moduleNames.map({
return RenderMetadata.Module(name: $0, relatedModules: nil)
})
}
let documentationNode = try! context.entity(with: identifier)
var hierarchyTranslator = RenderHierarchyTranslator(context: context, bundle: bundle)
let hierarchy = hierarchyTranslator.visitArticle(identifier)
collectedTopicReferences.append(contentsOf: hierarchyTranslator.collectedTopicReferences)
node.hierarchy = hierarchy
// Emit variants only if we're not compiling an article-only catalog to prevent renderers from
// advertising the page as "Swift", which is the language DocC assigns to pages in article only pages.
// (github.com/apple/swift-docc/issues/240).
if let topLevelModule = context.soleRootModuleReference,
try! context.entity(with: topLevelModule).kind.isSymbol
{
node.variants = variants(for: documentationNode)
}
if let abstract = article.abstractSection,
let abstractContent = visitMarkup(abstract.content) as? [RenderInlineContent] {
node.abstract = abstractContent
}
if let discussion = article.discussion,
let discussionContent = visitMarkupContainer(MarkupContainer(discussion.content)) as? [RenderBlockContent] {
var title: String?
if let first = discussionContent.first, case RenderBlockContent.heading = first {
title = nil
} else if shouldCreateAutomaticArticleSubheading(for: documentationNode) {
// For articles hardcode an overview title unless the user explicitly
// opts-out with the `@AutomaticArticleSubheading` directive.
title = "Overview"
}
node.primaryContentSections.append(ContentRenderSection(kind: .content, content: discussionContent, heading: title))
}
node.topicSectionsVariants = VariantCollection<[TaskGroupRenderSection]>(
from: documentationNode.availableVariantTraits,
fallbackDefaultValue: []
) { trait in
let allowedTraits = documentationNode.availableVariantTraits.traitsCompatible(with: trait)
var sections = [TaskGroupRenderSection]()
if let topics = article.topics, !topics.taskGroups.isEmpty {
// Don't set an eyebrow as collections and groups don't have one; append the authored Topics section
sections.append(
contentsOf: renderGroups(
topics,
allowExternalLinks: false,
allowedTraits: allowedTraits,
availableTraits: documentationNode.availableVariantTraits,
contentCompiler: &topicSectionContentCompiler
)
)
}
// Place "top" rendering preference automatic task groups
// after any user-defined task groups but before automatic curation.
if !article.automaticTaskGroups.isEmpty {
sections.append(
contentsOf: renderAutomaticTaskGroupsSection(
article.automaticTaskGroups.filter { $0.renderPositionPreference == .top },
contentCompiler: &topicSectionContentCompiler
)
)
}
// If there are no manually curated topics, and no automatic groups, try generating automatic groups by
// child kind.
if (article.topics == nil || article.topics?.taskGroups.isEmpty == true) &&
article.automaticTaskGroups.isEmpty {
// If there are no authored child topics in docs or markdown,
// inspect the topic graph, find this node's children, and
// for the ones found curate them automatically in task groups.
// Automatic groups are named after the child's kind, e.g.
// "Methods", "Variables", etc.
let alreadyCurated = Set(node.topicSections.flatMap { $0.identifiers })
let groups = try! AutomaticCuration.topics(
for: documentationNode,
withTraits: allowedTraits,
context: context
).compactMap { group -> AutomaticCuration.TaskGroup? in
// Remove references that have been already curated.
let newReferences = group.references.filter { !alreadyCurated.contains($0.absoluteString) }
// Remove groups that have no uncurated references
guard !newReferences.isEmpty else { return nil }
return (title: group.title, references: newReferences)
}
// Collect all child topic references.
topicSectionContentCompiler.collectedTopicReferences.append(contentsOf: groups.flatMap(\.references))
// Add the final groups to the node.
sections.append(contentsOf: groups.map(TaskGroupRenderSection.init(taskGroup:)))
}
// Place "bottom" rendering preference automatic task groups
// after any user-defined task groups but before automatic curation.
if !article.automaticTaskGroups.isEmpty {
sections.append(
contentsOf: renderAutomaticTaskGroupsSection(
article.automaticTaskGroups.filter { $0.renderPositionPreference == .bottom },
contentCompiler: &topicSectionContentCompiler
)
)
}
return sections
} ?? .init(defaultValue: [])
node.topicSectionsStyle = topicsSectionStyle(for: documentationNode)
if shouldCreateAutomaticRoleHeading(for: documentationNode) {
let role = DocumentationContentRenderer.roleForArticle(article, nodeKind: documentationNode.kind)
node.metadata.role = role.rawValue
switch role {
case .article:
// If there are no links to other nodes from the article,
// set the eyebrow for articles.
node.metadata.roleHeading = "Article"
case .collectionGroup:
// If the article links to other nodes, set the eyebrow for
// API Collections if any linked node is a symbol.
//
// If none of the linked nodes are symbols (it's a plain collection),
// don't display anything as the eyebrow title.
let curatesSymbols = topicSectionContentCompiler.collectedTopicReferences.contains { topicReference in
context.topicGraph.nodeWithReference(topicReference)?.kind.isSymbol ?? false
}
if curatesSymbols {
node.metadata.roleHeading = "API Collection"
}
default:
break
}
}
if let pageImages = documentationNode.metadata?.pageImages {
node.metadata.images = pageImages.compactMap { pageImage -> TopicImage? in
let renderReference = createAndRegisterRenderReference(forMedia: pageImage.source)
return renderReference.map {
TopicImage(pageImagePurpose: pageImage.purpose, identifier: $0)
}
}
}
if let pageColor = documentationNode.metadata?.pageColor {
node.metadata.color = TopicColor(standardColorIdentifier: pageColor.rawValue)
}
var metadataCustomDictionary : [String: String] = [:]
if let customMetadatas = documentationNode.metadata?.customMetadata {
for elem in customMetadatas {
metadataCustomDictionary[elem.key] = elem.value
}
}
node.metadata.customMetadata = metadataCustomDictionary
node.seeAlsoSectionsVariants = VariantCollection<[TaskGroupRenderSection]>(
from: documentationNode.availableVariantTraits,
fallbackDefaultValue: []
) { trait in
let allowedTraits = documentationNode.availableVariantTraits.traitsCompatible(with: trait)
var seeAlsoSections = [TaskGroupRenderSection]()
// Authored See Also section
if let seeAlso = article.seeAlso, !seeAlso.taskGroups.isEmpty {
seeAlsoSections.append(
contentsOf: renderGroups(
seeAlso,
allowExternalLinks: true,
allowedTraits: allowedTraits,
availableTraits: documentationNode.availableVariantTraits,
contentCompiler: &topicSectionContentCompiler
)
)
}
// Automatic See Also section
if let seeAlso = AutomaticCuration.seeAlso(
for: documentationNode,
withTraits: allowedTraits,
context: context,
bundle: bundle,
renderContext: renderContext,
renderer: contentRenderer
) {
topicSectionContentCompiler.collectedTopicReferences.append(contentsOf: seeAlso.references)
seeAlsoSections.append(TaskGroupRenderSection(taskGroup: seeAlso))
}
return seeAlsoSections
} ?? .init(defaultValue: [])
if let callToAction = article.metadata?.callToAction {
if let url = callToAction.url {
let downloadIdentifier = RenderReferenceIdentifier(url.description)
node.sampleDownload = .init(
action: .reference(
identifier: downloadIdentifier,
isActive: true,
overridingTitle: callToAction.buttonLabel(for: article.metadata?.pageKind?.kind),
overridingTitleInlineContent: nil))
downloadReferences[url.description] = DownloadReference(identifier: downloadIdentifier, verbatimURL: url, checksum: nil)
} else if let fileReference = callToAction.file,
let downloadIdentifier = createAndRegisterRenderReference(forMedia: fileReference, assetContext: .download)
{
node.sampleDownload = .init(action: .reference(
identifier: downloadIdentifier,
isActive: true,
overridingTitle: callToAction.buttonLabel(for: article.metadata?.pageKind?.kind),
overridingTitleInlineContent: nil
))
}
}
if let availability = article.metadata?.availability, !availability.isEmpty {
let renderAvailability = availability.compactMap({
let currentPlatform = PlatformName(metadataPlatform: $0.platform).flatMap { name in
context.externalMetadata.currentPlatforms?[name.displayName]
}
return .init($0, current: currentPlatform)
}).sorted(by: AvailabilityRenderOrder.compare)
if !renderAvailability.isEmpty {
node.metadata.platformsVariants = .init(defaultValue: renderAvailability)
}
}
if let pageKind = article.metadata?.pageKind {
node.metadata.role = pageKind.kind.renderRole.rawValue
node.metadata.roleHeading = pageKind.kind.titleHeading
}
if let titleHeading = article.metadata?.titleHeading {
node.metadata.roleHeading = titleHeading.heading
}
collectedTopicReferences.append(contentsOf: topicSectionContentCompiler.collectedTopicReferences)
node.references = createTopicRenderReferences()
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
addReferences(linkReferences, to: &node)
addReferences(downloadReferences, to: &node)
// See Also can contain external links, we need to separately transfer
// link references from the content compiler
addReferences(topicSectionContentCompiler.linkReferences, to: &node)
return node
}
public mutating func visitTutorialArticle(_ article: TutorialArticle) -> RenderTree? {
var node = RenderNode(identifier: identifier, kind: .article)
var hierarchyTranslator = RenderHierarchyTranslator(context: context, bundle: bundle)
guard let hierarchy = hierarchyTranslator.visitTechnologyNode(identifier) else {
// This tutorial article is not curated, so we don't generate a render node.
// We've warned about this during semantic analysis.
return nil
}
let technology = try! context.entity(with: hierarchy.technology).semantic as! Technology
node.metadata.title = article.title
node.metadata.category = technology.name
node.metadata.categoryPathComponent = hierarchy.technology.url.lastPathComponent
node.metadata.role = DocumentationContentRenderer.role(for: .tutorialArticle).rawValue
// Unlike for other pages, in here we use `RenderHierarchyTranslator` to crawl the technology
// and produce the list of modules for the render hierarchy to display in the tutorial local navigation.
node.hierarchy = hierarchy.hierarchy
let documentationNode = try! context.entity(with: identifier)
node.variants = variants(for: documentationNode)
collectedTopicReferences.append(contentsOf: hierarchyTranslator.collectedTopicReferences)
var intro: IntroRenderSection
if let articleIntro = article.intro {
intro = visitIntro(articleIntro) as! IntroRenderSection
} else {
// Create a default intro section so that it's not an error to skip writing one.
intro = IntroRenderSection(title: "")
}
if let time = article.durationMinutes {
intro.estimatedTimeInMinutes = time
}
// Guaranteed to have at least one path
let technologyPath = context.finitePaths(to: identifier, options: [.preferTechnologyRoot])[0]
node.sections.append(intro)
let layouts = contentLayouts(article.content)
let articleSection = TutorialArticleSection(content: layouts)
node.sections.append(articleSection)
if let assessments = article.assessments {
node.sections.append(visitAssessments(assessments) as! TutorialAssessmentsRenderSection)
}
if technologyPath.count >= 2 {
let volume = technologyPath[technologyPath.count - 2]
if let cta = callToAction(with: article.callToActionImage, volume: volume) {
node.sections.append(cta)
}
}
node.references = createTopicRenderReferences()
addReferences(fileReferences, to: &node)
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
addReferences(requirementReferences, to: &node)
addReferences(downloadReferences, to: &node)
addReferences(linkReferences, to: &node)
return node
}
private mutating func contentLayouts(_ markupLayouts: some Sequence<MarkupLayout>) -> [ContentLayout] {
return markupLayouts.map { content in
switch content {
case .markup(let markup):
return .fullWidth(content: visitMarkupContainer(markup) as! [RenderBlockContent])
case .contentAndMedia(let contentAndMedia):
return .contentAndMedia(content: visitContentAndMedia(contentAndMedia) as! ContentAndMediaSection)
case .stack(let stack):
return .columns(content: self.visitStack(stack) as! [ContentAndMediaSection])
}
}
}
public mutating func visitStack(_ stack: Stack) -> RenderTree? {
return stack.contentAndMedia.map { self.visitContentAndMedia($0) as! ContentAndMediaSection } as [ContentAndMediaSection]
}
public mutating func visitComment(_ comment: Comment) -> RenderTree? {
return nil
}
public mutating func visitDeprecationSummary(_ summary: DeprecationSummary) -> RenderTree? {
return nil
}
/// The current module context for symbols.
private var currentSymbolModuleName: String? = nil
/// The current symbol context.
private var currentSymbol: ResolvedTopicReference? = nil
/// Renders automatically generated task groups
private mutating func renderAutomaticTaskGroupsSection(_ taskGroups: [AutomaticTaskGroupSection], contentCompiler: inout RenderContentCompiler) -> [TaskGroupRenderSection] {
return taskGroups.map { group in
contentCompiler.collectedTopicReferences.append(contentsOf: group.references)
return TaskGroupRenderSection(
title: group.title,
abstract: nil,
discussion: nil,
identifiers: group.references.map(\.url.absoluteString),
generated: true,
anchor: urlReadableFragment(group.title)
)
}
}
/// Renders a list of topic groups.
///
/// When rendering topic groups for a page that is available in multiple languages,
/// you can provide the total available traits the parent page will be available in,
/// as well as the _specific_ traits this particular render section should be created for.
/// Any referenced pages that are included in the _available_ traits
/// but excluded from the _allowed_ traits will be filtered out.
///
/// This behavior is designed to ensure that all items in the task group will be rendered
/// in _some_ task group of the parent page, whether in the currently provided allowed traits,
/// or in a different subset of the page's available traits.
/// However, if a task-group item's language isn't included in any of the available traits,
/// it will _not_ be filtered out since otherwise it would be invisible to the reader
/// of the documentation regardless of which of the available traits they view.
///
/// - Parameters:
/// - topics: The topic groups to be rendered.
///
/// - allowExternalLinks: Whether or not external links should be included in the
/// rendered task groups.
///
/// - allowedTraits: The traits that the returned render section should filter for.
///
/// These traits should be a _subset_ of the given available traits.
///
/// - availableTraits: The traits that are available in the parent page that this render
/// section belongs to.
///
/// This method will only filter for allowed traits that are also explicitly available.
///
/// - contentCompiler: The current render content compiler.
private mutating func renderGroups(
_ topics: GroupedSection,
allowExternalLinks: Bool,
allowedTraits: Set<DocumentationDataVariantsTrait>,
availableTraits: Set<DocumentationDataVariantsTrait>,
contentCompiler: inout RenderContentCompiler
) -> [TaskGroupRenderSection] {
return topics.taskGroups.compactMap { group in
let supportedLanguages = group.directives[SupportedLanguage.directiveName]?.compactMap {
SupportedLanguage(from: $0, source: nil, for: bundle, in: context)?.language
}
// If the task group has a set of supported languages, see if it should render for the allowed traits.
if supportedLanguages?.matchesOneOf(traits: allowedTraits) == false {
return nil
}
let abstractContent = group.abstract.map {
return visitMarkup($0.content) as! [RenderInlineContent]
}
let discussion = group.discussion.map { discussion -> ContentRenderSection in
let discussionContent = visitMarkupContainer(MarkupContainer(discussion.content)) as! [RenderBlockContent]
return ContentRenderSection(kind: .content, content: discussionContent, heading: "Discussion")
}
/// Returns whether the topic with the given identifier is available in one of the traits in `allowedTraits`.
func isTopicAvailableInAllowedTraits(identifier topicIdentifier: String) -> Bool {
guard let reference = contentCompiler.collectedTopicReferences[topicIdentifier] else {
// If there's no reference in `contentCompiler.collectedTopicReferences`, the reference refers to
// a non-documentation URL (e.g., 'https://' URL), in which case it is available in all traits.
return true
}
guard context.isSymbol(reference: reference) else {
// If the reference corresponds to any kind except Symbol
// (e.g., Article, Tutorial, SampleCode...), allow the topic
// to appear independently of the source language it belongs to.
return true
}
let referenceSourceLanguageIDs = Set(context.sourceLanguages(for: reference).map(\.id))
let availableSourceLanguageTraits = Set(availableTraits.compactMap(\.interfaceLanguage))
if availableSourceLanguageTraits.isDisjoint(with: referenceSourceLanguageIDs) {
// The set of available source language traits has no members in common with the
// set of source languages the given reference is available in.
//
// Since we should only filter for traits that are available in the parent page,
// just return true. (See the documentation of this method for more details).
return true
}
return referenceSourceLanguageIDs.contains { sourceLanguageID in
allowedTraits.contains { trait in
trait.interfaceLanguage == sourceLanguageID
}
}
}
let taskGroupRenderSection = TaskGroupRenderSection(
title: group.heading?.plainText,
abstract: abstractContent,
discussion: discussion,
identifiers: group.links.compactMap { link in
switch link {
case let link as Link:
if !allowExternalLinks {
// For links require documentation scheme
guard let _ = link.destination.flatMap(ValidatedURL.init(parsingAuthoredLink:))?.requiring(scheme: ResolvedTopicReference.urlScheme) else {
return nil
}
}
if let referenceInlines = contentCompiler.visitLink(link) as? [RenderInlineContent],
let renderReference = referenceInlines.first(where: { inline in
switch inline {
case .reference(_,_,_,_):
return true
default:
return false
}
}),
case let RenderInlineContent.reference(
identifier: identifier,
isActive: _,
overridingTitle: _,
overridingTitleInlineContent: _
) = renderReference
{
return isTopicAvailableInAllowedTraits(identifier: identifier.identifier)
? identifier.identifier : nil
}
case let link as SymbolLink:
if let referenceInlines = contentCompiler.visitSymbolLink(link) as? [RenderInlineContent],
let renderReference = referenceInlines.first(where: { inline in
switch inline {
case .reference:
return true
default:
return false
}
}),
case let RenderInlineContent.reference(
identifier: identifier,
isActive: _,
overridingTitle: _,
overridingTitleInlineContent: _
) = renderReference
{
return isTopicAvailableInAllowedTraits(identifier: identifier.identifier)
? identifier.identifier : nil
}
default: break
}
return nil
},
anchor: group.heading.map { urlReadableFragment($0.plainText) } ?? "Topics"
)
// rdar://74617294 If a task group doesn't have any symbol or external links it shouldn't be rendered
guard !taskGroupRenderSection.identifiers.isEmpty else {
return nil
}
return taskGroupRenderSection
}
}
@discardableResult
private mutating func collectUnresolvableSymbolReference(destination: UnresolvedTopicReference, title: String) -> UnresolvedTopicReference? {
guard let url = ValidatedURL(destination.topicURL.url) else {
return nil
}
let reference = UnresolvedTopicReference(topicURL: url, title: title)
collectedUnresolvedTopicReferences.append(reference)
return reference
}
private func shouldCreateAutomaticRoleHeading(for node: DocumentationNode) -> Bool {
return node.options?.automaticTitleHeadingEnabled
?? context.options?.automaticTitleHeadingEnabled
?? true
}
private func shouldCreateAutomaticArticleSubheading(for node: DocumentationNode) -> Bool {
return node.options?.automaticArticleSubheadingEnabled
?? context.options?.automaticArticleSubheadingEnabled
?? true
}
private func topicsSectionStyle(for node: DocumentationNode) -> RenderNode.TopicsSectionStyle {
let topicsVisualStyleOption: TopicsVisualStyle.Style
if let topicsSectionStyleOption = node.options?.topicsVisualStyle
?? context.options?.topicsVisualStyle
{
topicsVisualStyleOption = topicsSectionStyleOption
} else {
topicsVisualStyleOption = .list
}
switch topicsVisualStyleOption {
case .list:
return .list
case .compactGrid:
return .compactGrid
case .detailedGrid:
return .detailedGrid
case .hidden:
return .hidden
}
}
public mutating func visitSymbol(_ symbol: Symbol) -> RenderTree? {
let documentationNode = try! context.entity(with: identifier)
let identifier = identifier.addingSourceLanguages(documentationNode.availableSourceLanguages)
var node = RenderNode(identifier: identifier, kind: .symbol)
var contentCompiler = RenderContentCompiler(context: context, bundle: bundle, identifier: identifier)
currentSymbol = identifier
/*
FIXME: We shouldn't be doing this kind of crawling here.
We should be doing a graph search to build up a breadcrumb and pass that to the translator, giving
a definitive hierarchy before we even begin to build a RenderNode.
*/
var ref = documentationNode.reference
while let grandparent = context.parents(of: ref).first {
ref = grandparent
}
let moduleName = context.moduleName(forModuleReference: symbol.moduleReference)
if let crossImportOverlayModule = symbol.crossImportOverlayModule {
node.metadata.modulesVariants = VariantCollection(defaultValue: [RenderMetadata.Module(name: crossImportOverlayModule.declaringModule, relatedModules: crossImportOverlayModule.bystanderModules)])
} else if let moduleVariants = VariantCollection<[RenderMetadata.Module]?>(
from: symbol.extendedModuleVariants,
transform: { (_, value) in
let relatedModules: [String]?
// Don't add the module name of extensions made in the compiled module.
if (value != moduleName.displayName) && (value != moduleName.symbolName) {
relatedModules = [value]
} else {
relatedModules = nil
}
return [
RenderMetadata.Module(name: moduleName.displayName, relatedModules: relatedModules)
]
}
) {
node.metadata.modulesVariants = moduleVariants
} else {
node.metadata.modulesVariants = VariantCollection(defaultValue: [RenderMetadata.Module(name: moduleName.displayName, relatedModules: nil)])
}
node.metadata.extendedModuleVariants = VariantCollection<String?>(from: symbol.extendedModuleVariants)
node.metadata.platformsVariants = VariantCollection<[AvailabilityRenderItem]?>(from: symbol.availabilityVariants) { _, availability in
availability.availability
.compactMap { availability -> AvailabilityRenderItem? in
// Filter items with insufficient availability data
guard availability.introducedVersion != nil else {
return nil
}
guard let name = availability.domain.map({ PlatformName(operatingSystemName: $0.rawValue) }),
let currentPlatform = context.externalMetadata.currentPlatforms?[name.displayName] else {
// No current platform provided by the context
return AvailabilityRenderItem(availability, current: nil)
}
return AvailabilityRenderItem(availability, current: currentPlatform)
}
.filter({ !($0.unconditionallyUnavailable == true) })
.sorted(by: AvailabilityRenderOrder.compare)
} ?? .init(defaultValue:
defaultAvailability(for: bundle, moduleName: moduleName.symbolName, currentPlatforms: context.externalMetadata.currentPlatforms)?
.filter({ !($0.unconditionallyUnavailable == true) })
.sorted(by: AvailabilityRenderOrder.compare)
)
if let availability = documentationNode.metadata?.availability, !availability.isEmpty {
let renderAvailability = availability.compactMap({
let currentPlatform = PlatformName(metadataPlatform: $0.platform).flatMap { name in
context.externalMetadata.currentPlatforms?[name.displayName]
}
return .init($0, current: currentPlatform)
}).sorted(by: AvailabilityRenderOrder.compare)
if !renderAvailability.isEmpty {
node.metadata.platformsVariants.defaultValue = renderAvailability
}
}
node.metadata.requiredVariants = VariantCollection<Bool>(from: symbol.isRequiredVariants) ?? .init(defaultValue: false)
node.metadata.role = DocumentationContentRenderer.role(for: documentationNode.kind).rawValue
node.metadata.titleVariants = VariantCollection<String?>(from: symbol.titleVariants)
node.metadata.externalIDVariants = VariantCollection<String?>(from: symbol.externalIDVariants)
if shouldCreateAutomaticRoleHeading(for: documentationNode) {
node.metadata.roleHeadingVariants = VariantCollection<String?>(from: symbol.roleHeadingVariants)
}
if let titleHeading = documentationNode.metadata?.titleHeading {
node.metadata.roleHeadingVariants = VariantCollection<String?>(defaultValue: titleHeading.heading)
}
node.metadata.symbolKindVariants = VariantCollection<String?>(from: symbol.kindVariants) { _, kindVariants in
kindVariants.identifier.renderingIdentifier
} ?? .init(defaultValue: nil)
node.metadata.conformance = contentRenderer.conformanceSectionFor(identifier, collectedConstraints: collectedConstraints)
node.metadata.fragmentsVariants = contentRenderer.subHeadingFragments(for: documentationNode)
node.metadata.navigatorTitleVariants = contentRenderer.navigatorFragments(for: documentationNode)
if let pageImages = documentationNode.metadata?.pageImages {
node.metadata.images = pageImages.compactMap { pageImage -> TopicImage? in
let renderReference = createAndRegisterRenderReference(forMedia: pageImage.source)
return renderReference.map {
TopicImage(pageImagePurpose: pageImage.purpose, identifier: $0)
}
}
}
if let pageColor = documentationNode.metadata?.pageColor {
node.metadata.color = TopicColor(standardColorIdentifier: pageColor.rawValue)
}
var metadataCustomDictionary : [String: String] = [:]
if let customMetadatas = documentationNode.metadata?.customMetadata {
for elem in customMetadatas {
metadataCustomDictionary[elem.key] = elem.value
}
}
node.metadata.customMetadata = metadataCustomDictionary
node.variants = variants(for: documentationNode)
collectedTopicReferences.append(identifier)
let contentRenderer = DocumentationContentRenderer(documentationContext: context, bundle: bundle)
node.metadata.tags = contentRenderer.tags(for: identifier)
var hierarchyTranslator = RenderHierarchyTranslator(context: context, bundle: bundle)
let hierarchy = hierarchyTranslator.visitSymbol(identifier)
collectedTopicReferences.append(contentsOf: hierarchyTranslator.collectedTopicReferences)
node.hierarchy = hierarchy
// In case `inheritDocs` is disabled and there is actually origin data for the symbol, then include origin information as abstract.
// Generate the placeholder abstract only in case there isn't an authored abstract coming from a doc extension.
if !context.externalMetadata.inheritDocs, let origin = (documentationNode.semantic as! Symbol).origin, symbol.abstractSection == nil {
// Create automatic abstract for inherited symbols.
node.abstract = [.text("Inherited from "), .codeVoice(code: origin.displayName), .text(".")]
} else {
node.abstractVariants = VariantCollection<[RenderInlineContent]?>(
from: symbol.abstractSectionVariants
) { _, abstractSection in
// Create an abstract as usual.
let abstract = abstractSection.content
if let abstractContent = visitMarkup(abstract) as? [RenderInlineContent] {
return abstractContent
} else {
return nil
}
} ?? .init(defaultValue: nil)
}
node.primaryContentSectionsVariants.append(
contentsOf: createRenderSections(
for: symbol,
renderNode: &node,
translators: [
DeclarationsSectionTranslator(),
HTTPEndpointSectionTranslator(endpointType: .production),
HTTPEndpointSectionTranslator(endpointType: .sandbox),
ParametersSectionTranslator(),
HTTPParametersSectionTranslator(parameterSource: .path),
HTTPParametersSectionTranslator(parameterSource: .query),
HTTPParametersSectionTranslator(parameterSource: .cookie),
HTTPParametersSectionTranslator(parameterSource: .header),
HTTPBodySectionTranslator(),
HTTPResponsesSectionTranslator(),
DictionaryKeysSectionTranslator(),
AttributesSectionTranslator(),
ReturnsSectionTranslator(),
MentionsSectionTranslator(referencingSymbol: identifier),
DiscussionSectionTranslator(),
]
)
)
var sourceRepository = sourceRepository
if shouldEmitSymbolSourceFileURIs {
node.metadata.sourceFileURIVariants = VariantCollection<String?>(
from: symbol.locationVariants
) { _, location in
location.uri
} ?? .init(defaultValue: nil)
// If a source repository is not set, set the device's
// filesystem as the source repository. This causes
// the `metadata.remoteSource` property to link to the
// file's location on disk.
if sourceRepository == nil {
sourceRepository = .localFilesystem()
}
}
if let sourceRepository {
node.metadata.remoteSourceVariants = VariantCollection<RenderMetadata.RemoteSource?>(
from: symbol.locationVariants
) { _, location in
guard let locationURL = location.url(),
let url = sourceRepository.format(
sourceFileURL: locationURL,
lineNumber: location.position.line + 1
)
else {
return nil
}
return RenderMetadata.RemoteSource(
fileName: locationURL.lastPathComponent,
url: url
)
} ?? .init(defaultValue: nil)
}
if shouldEmitSymbolAccessLevels {
node.metadata.symbolAccessLevelVariants = VariantCollection<String?>(from: symbol.accessLevelVariants)
}
if let externalID = symbol.externalID,
let symbolIdentifiersWithExpandedDocumentation
{
node.metadata.hasNoExpandedDocumentation = !symbolIdentifiersWithExpandedDocumentation.contains(externalID)
}
node.relationshipSectionsVariants = VariantCollection<[RelationshipsRenderSection]>(
from: documentationNode.availableVariantTraits,
fallbackDefaultValue: []
) { trait in
guard let relationships = symbol.relationshipsVariants[trait], !relationships.groups.isEmpty else {
return []
}
var groupSections = [RelationshipsRenderSection]()
let eligibleGroups = relationships.groups.sorted(by: \.sectionOrder)
for group in eligibleGroups {
// destination url → symbol title
var destinationsMap = [TopicReference: String]()
for destination in group.destinations {
if let constraints = relationships.constraints[destination] {
collectedConstraints[destination] = constraints
}
switch destination {
case .resolved(.success(let resolved)):
if let node = context.documentationCache[resolved] {
let resolver = LinkTitleResolver(context: context, source: resolved.url)
let resolvedTitle = resolver.title(for: node)
destinationsMap[destination] = resolvedTitle?[trait]
let dropLink = context.topicGraph.nodeWithReference(resolved)?.isEmptyExtension ?? false
if !dropLink {
// Add relationship to render references
collectedTopicReferences.append(resolved)
} else if let topicUrl = ValidatedURL(resolved.url) {
// If the topic isn't linkable (e.g. an extended type), then we shouldn't
// add a resolved relationship - deconstruct the resolved reference so
// we can still display it, though
let title = resolvedTitle?[trait] ?? resolved.lastPathComponent
let reference = UnresolvedTopicReference(topicURL: topicUrl, title: title)
collectedUnresolvedTopicReferences.append(reference)
}
} else if let entity = context.externalCache[resolved] {
collectedTopicReferences.append(resolved)
destinationsMap[destination] = entity.topicRenderReference.title
} else {
fatalError("A successfully resolved reference should have either local or external content.")
}
case .unresolved(let unresolved), .resolved(.failure(let unresolved, _)):
// Try creating a render reference anyway
if let title = relationships.targetFallbacks[destination],
let reference = collectUnresolvableSymbolReference(destination: unresolved, title: title) {
destinationsMap[destination] = reference.title
}
}
}
// Links section
var orderedDestinations = Array(destinationsMap.keys)
orderedDestinations.sort { destination1, destination2 -> Bool in
return destinationsMap[destination1]! <= destinationsMap[destination2]!
}
let groupSection = RelationshipsRenderSection(type: group.kind.rawValue, title: group.heading.plainText, identifiers: orderedDestinations.map({ $0.url!.absoluteString }))
groupSections.append(groupSection)
}
return groupSections
} ?? .init(defaultValue: [])
// Build up the topic section variants by iterating over all available
// variant traits.
//
// We can't just iterate over the traits of the existing
// topics section or automatic task groups, because it's important
// for automatic curation to consider _all_ variants this node is available in.
node.topicSectionsVariants = VariantCollection<[TaskGroupRenderSection]>(
from: documentationNode.availableVariantTraits,
fallbackDefaultValue: []
) { trait in
let allowedTraits = documentationNode.availableVariantTraits.traitsCompatible(with: trait)
let automaticTaskGroups = symbol.automaticTaskGroupsVariants[trait] ?? []
let topics = symbol.topicsVariants[trait]
var sections = [TaskGroupRenderSection]()
if let topics, !topics.taskGroups.isEmpty {
// Allowed symbol traits should be all traits except the reverse of the objc/swift pairing
sections.append(
contentsOf: renderGroups(
topics,
allowExternalLinks: false,
allowedTraits: allowedTraits,
availableTraits: documentationNode.availableVariantTraits,
contentCompiler: &contentCompiler
)
)
}
// Place "top" rendering preference automatic task groups
// after any user-defined task groups but before automatic curation.
if !automaticTaskGroups.isEmpty {
sections.append(
contentsOf: renderAutomaticTaskGroupsSection(
automaticTaskGroups.filter({ $0.renderPositionPreference == .top }),
contentCompiler: &contentCompiler
)
)
}
// Children of the current symbol that have not been curated manually in a task group will all
// be automatically curated in task groups after their symbol kind: "Properties", "Enumerations", etc.
let alreadyCurated = Set(sections.flatMap { $0.identifiers })
let groups = try! AutomaticCuration.topics(for: documentationNode, withTraits: allowedTraits, context: context)
sections.append(contentsOf: groups.compactMap { group in
let newReferences = group.references.filter { !alreadyCurated.contains($0.absoluteString) }
guard !newReferences.isEmpty else { return nil }
contentCompiler.collectedTopicReferences.append(contentsOf: newReferences)
return TaskGroupRenderSection(taskGroup: (title: group.title, references: newReferences))
})
// Place "bottom" rendering preference automatic task groups
// after any user-defined task groups but before automatic curation.
if !automaticTaskGroups.isEmpty {
sections.append(
contentsOf: renderAutomaticTaskGroupsSection(
automaticTaskGroups.filter({ $0.renderPositionPreference == .bottom }),
contentCompiler: &contentCompiler
)
)
}
return sections
} ?? .init(defaultValue: [])
node.topicSectionsStyle = topicsSectionStyle(for: documentationNode)
node.defaultImplementationsSectionsVariants = VariantCollection<[TaskGroupRenderSection]>(
from: symbol.defaultImplementationsVariants,
symbol.relationshipsVariants
) { _, defaultImplementations, relationships in
guard !symbol.defaultImplementations.groups.isEmpty else {
return []
}
for imp in defaultImplementations.implementations {
let resolved: ResolvedTopicReference
switch imp.reference {
case .resolved(.success(let reference)):
resolved = reference
case .unresolved(let unresolved), .resolved(.failure(let unresolved, _)):
// Try creating a render reference anyway
if let title = defaultImplementations.targetFallbacks[imp.reference],
let reference = collectUnresolvableSymbolReference(destination: unresolved, title: title),
let constraints = relationships.constraints[imp.reference] {
collectedConstraints[.unresolved(reference)] = constraints
}
continue
}
// Add implementation to render references
collectedTopicReferences.append(resolved)
if let constraints = relationships.constraints[imp.reference] {
collectedConstraints[.successfullyResolved(resolved)] = constraints
}
}
return defaultImplementations.groups.map { group in
TaskGroupRenderSection(
title: group.heading,
abstract: nil,
discussion: nil,
identifiers: group.references.map({ $0.url!.absoluteString }),
anchor: urlReadableFragment(group.heading)
)
}
} ?? .init(defaultValue: [])
node.seeAlsoSectionsVariants = VariantCollection<[TaskGroupRenderSection]>(
from: documentationNode.availableVariantTraits,
fallbackDefaultValue: []
) { trait in
let allowedTraits = documentationNode.availableVariantTraits.traitsCompatible(with: trait)
// If the symbol contains an authored See Also section from the documentation extension,
// add it as the first section under See Also.
var seeAlsoSections = [TaskGroupRenderSection]()
if let seeAlso = symbol.seeAlsoVariants[trait] {
seeAlsoSections.append(
contentsOf: renderGroups(
seeAlso,
allowExternalLinks: true,
allowedTraits: allowedTraits,
availableTraits: documentationNode.availableVariantTraits,
contentCompiler: &contentCompiler
)
)
}
// Curate the current node's siblings as further See Also groups.
if let seeAlso = AutomaticCuration.seeAlso(
for: documentationNode,
withTraits: allowedTraits,
context: context,
bundle: bundle,
renderContext: renderContext,
renderer: contentRenderer
), !seeAlso.references.isEmpty {
contentCompiler.collectedTopicReferences.append(contentsOf: seeAlso.references)
seeAlsoSections.append(
TaskGroupRenderSection(taskGroup: seeAlso)
)
}
return seeAlsoSections
} ?? .init(defaultValue: [])
node.deprecationSummaryVariants = VariantCollection<[RenderBlockContent]?>(
from: symbol.deprecatedSummaryVariants
) { _, deprecatedSummary in
// If there is a deprecation summary in a documentation extension file add it to the render node
visitMarkupContainer(MarkupContainer(deprecatedSummary.content)) as? [RenderBlockContent]
} ?? .init(defaultValue: nil)
collectedTopicReferences.append(contentsOf: contentCompiler.collectedTopicReferences)
node.references = createTopicRenderReferences()
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
// See Also can contain external links, we need to separately transfer
// link references from the content compiler
addReferences(contentCompiler.linkReferences, to: &node)
addReferences(linkReferences, to: &node)
currentSymbol = nil
return node
}
/// Creates a render reference for the given media and registers the reference to include it in the `references` dictionary.
mutating func createAndRegisterRenderReference(forMedia media: ResourceReference?, poster: ResourceReference? = nil, altText: String? = nil, assetContext: DataAsset.Context = .display) -> RenderReferenceIdentifier? {
guard let oldMedia = media,
let mediaIdentifier = context.identifier(forAssetName: oldMedia.path, in: identifier) else {
return nil
}
let media = ResourceReference(bundleIdentifier: oldMedia.bundleIdentifier, path: mediaIdentifier)
guard let resolvedAssets = renderContext?.store.content(forAssetNamed: media.path, bundleIdentifier: identifier.bundleIdentifier)
?? context.resolveAsset(named: media.path, in: identifier)
else {
return nil
}
let fileExtension: String = {
let identifierFileExtension = NSString(string: media.path).pathExtension
if !identifierFileExtension.isEmpty {
return identifierFileExtension
}
return resolvedAssets.data(bestMatching: DataTraitCollection()).url.pathExtension
}()
// Check if media is a supported image.
if DocumentationContext.isFileExtension(fileExtension, supported: .image) {
let mediaReference = RenderReferenceIdentifier(media.path)
imageReferences[media.path] = ImageReference(
identifier: mediaReference,
// If no alt text has been provided and this image has been registered previously, use the registered alt text.
altText: altText ?? imageReferences[media.path]?.altText,
imageAsset: resolvedAssets
)
return mediaReference
}
if DocumentationContext.isFileExtension(fileExtension, supported: .video) {
let mediaReference = RenderReferenceIdentifier(media.path)
let poster = poster.flatMap { createAndRegisterRenderReference(forMedia: $0) }
videoReferences[media.path] = VideoReference(identifier: mediaReference, altText: altText, videoAsset: resolvedAssets, poster: poster)
return mediaReference
}
if assetContext == DataAsset.Context.download {
let mediaReference = RenderReferenceIdentifier(media.path)
// Create a download reference if possible.
let downloadReference: DownloadReference
do {
let downloadURL = resolvedAssets.variants.first!.value
let downloadData = try context.dataProvider.contentsOfURL(downloadURL, in: bundle)
downloadReference = DownloadReference(identifier: mediaReference,
renderURL: downloadURL,
checksum: Checksum.sha512(of: downloadData))
} catch {
// It seems this is the way to error out of here.
return nil
}
// Add the file to the download references.
downloadReferences[media.path] = downloadReference
return mediaReference
}
return nil
}
var context: DocumentationContext
var bundle: DocumentationBundle
var identifier: ResolvedTopicReference
var source: URL?
var imageReferences: [String: ImageReference] = [:]
var videoReferences: [String: VideoReference] = [:]
var fileReferences: [String: FileReference] = [:]
var linkReferences: [String: LinkReference] = [:]
var requirementReferences: [String: XcodeRequirementReference] = [:]
var downloadReferences: [String: DownloadReference] = [:]
private var bundleAvailability: [BundleModuleIdentifier: [AvailabilityRenderItem]] = [:]
/// Given module availability and the current platforms we're building against return if the module is a beta framework.
private func isModuleBeta(moduleAvailability: DefaultAvailability.ModuleAvailability, currentPlatforms: [String: PlatformVersion]) -> Bool {
guard let introducedVersion = moduleAvailability.introducedVersion else { return false }
guard
// Check if we have a symbol availability version and a target platform version
let moduleVersion = Version(versionString: introducedVersion),
// We require at least two components for a platform version (e.g. 10.15 or 10.15.1)
moduleVersion.count >= 2,
// Verify we're building against this platform
let targetPlatformVersion = currentPlatforms[moduleAvailability.platformName.displayName],
// Verify the target platform version is in beta
targetPlatformVersion.beta else {
return false
}
// Build a module availability version, defaulting the patch number to 0 if not provided (e.g. 10.15)
let moduleVersionTriplet = VersionTriplet(moduleVersion[0], moduleVersion[1], moduleVersion.count > 2 ? moduleVersion[2] : 0)
return moduleVersionTriplet == targetPlatformVersion.version
}
/// The default availability for modules in a given bundle and module.
mutating func defaultAvailability(for bundle: DocumentationBundle, moduleName: String, currentPlatforms: [String: PlatformVersion]?) -> [AvailabilityRenderItem]? {
let identifier = BundleModuleIdentifier(bundle: bundle, moduleName: moduleName)
// Cached availability
if let availability = bundleAvailability[identifier] {
return availability
}
// Find default module availability if existing
guard let bundleDefaultAvailability = bundle.info.defaultAvailability,
let moduleAvailability = bundleDefaultAvailability.modules[moduleName] else {
return nil
}
// Prepare for rendering
let renderedAvailability = moduleAvailability
.filter({ $0.versionInformation != .unavailable })
.compactMap({ availability -> AvailabilityRenderItem? in
guard let availabilityIntroducedVersion = availability.introducedVersion else { return nil }
return AvailabilityRenderItem(
name: availability.platformName.displayName,
introduced: availabilityIntroducedVersion,
isBeta: currentPlatforms.map({ isModuleBeta(moduleAvailability: availability, currentPlatforms: $0) }) ?? false
)
})
// Cache the availability to use for further symbols
bundleAvailability[identifier] = renderedAvailability
// Return the availability
return renderedAvailability
}
mutating func createRenderSections(
for symbol: Symbol,
renderNode: inout RenderNode,
translators: [RenderSectionTranslator]
) -> [VariantCollection<CodableContentSection?>] {
translators.compactMap { translator in
translator.translateSection(for: symbol, renderNode: &renderNode, renderNodeTranslator: &self)
}
}
private func variants(for documentationNode: DocumentationNode) -> [RenderNode.Variant] {
let generator = PresentationURLGenerator(context: context, baseURL: bundle.baseURL)
return documentationNode.availableSourceLanguages
.sorted(by: { language1, language2 in
// Emit Swift first, then alphabetically.
switch (language1, language2) {
case (.swift, _): return true
case (_, .swift): return false
default: return language1.id < language2.id
}
})
.map { sourceLanguage in
RenderNode.Variant(
traits: [.interfaceLanguage(sourceLanguage.id)],
paths: [
generator.presentationURLForReference(identifier).path
]
)
}
}
private mutating func convertFragments(_ fragments: [SymbolGraph.Symbol.DeclarationFragments.Fragment]) -> [DeclarationRenderSection.Token] {
return fragments.map { token -> DeclarationRenderSection.Token in
let reference: ResolvedTopicReference?
if let preciseIdentifier = token.preciseIdentifier,
let resolved = self.context.localOrExternalReference(symbolID: preciseIdentifier)
{
reference = resolved
// Add relationship to render references
self.collectedTopicReferences.append(resolved)
} else {
reference = nil
}
// Add the declaration token
return DeclarationRenderSection.Token(fragment: token, identifier: reference?.absoluteString)
}
}
/// Generate a RenderProperty object from markup content and symbol data.
mutating func createRenderProperty(name: String, contents: [Markup], required: Bool, symbol: SymbolGraph.Symbol?) -> RenderProperty {
let parameterContent = self.visitMarkupContainer(
MarkupContainer(contents)
) as! [RenderBlockContent]
var renderedTokens: [DeclarationRenderSection.Token]? = nil
var attributes: [RenderAttribute] = []
var isReadOnly: Bool? = nil
var deprecated: Bool? = nil
var introducedVersion: String? = nil
var typeDetails: [TypeDetails]? = nil
if let symbol {
// Convert the dictionary key's declaration into section tokens
if let fragments = symbol.declarationFragments {
renderedTokens = convertFragments(fragments)
}
// Populate attributes
if let constraint = symbol.defaultValue {
attributes.append(RenderAttribute.default(String(constraint)))
}
if let constraint = symbol.minimum {
attributes.append(RenderAttribute.minimum(String(constraint)))
}
if let constraint = symbol.maximum {
attributes.append(RenderAttribute.maximum(String(constraint)))
}
if let constraint = symbol.minimumExclusive {
attributes.append(RenderAttribute.minimumExclusive(String(constraint)))
}
if let constraint = symbol.maximumExclusive {
attributes.append(RenderAttribute.maximumExclusive(String(constraint)))
}
if let constraint = symbol.allowedValues {
attributes.append(RenderAttribute.allowedValues(constraint.map{String($0)}))
}
if let constraint = symbol.isReadOnly {
isReadOnly = constraint
}
if let constraint = symbol.minimumLength {
attributes.append(RenderAttribute.minimumLength(String(constraint)))
}
if let constraint = symbol.maximumLength {
attributes.append(RenderAttribute.maximumLength(String(constraint)))
}
if let constraint = symbol.typeDetails, constraint.count > 0 {
// Pull out the base-type details.
typeDetails = constraint.filter { $0.baseType != nil }
.map { TypeDetails(baseType: $0.baseType, arrayMode: $0.arrayMode) }
// Pull out the allowed-type declarations.
// If there is only 1 type declaration found, it would be redundant with declaration, so skip it.
let typeDeclarations = constraint.compactMap { $0.fragments }
if typeDeclarations.count > 1 {
let allowedTypes = typeDeclarations.map { convertFragments($0) }
attributes.append(RenderAttribute.allowedTypes(allowedTypes))
}
}
// Extract the availability information
if let availabilityItems = symbol.availability, availabilityItems.count > 0 {
availabilityItems.forEach { item in
if deprecated == nil && (item.isUnconditionallyDeprecated || item.deprecatedVersion != nil) {
deprecated = true
}
if let intro = item.introducedVersion, introducedVersion == nil {
introducedVersion = "\(intro)"
}
}
}
}
return RenderProperty(
name: name,
type: renderedTokens ?? [],
typeDetails: typeDetails,
content: parameterContent,
attributes: attributes,
mimeType: symbol?.httpMediaType,
required: required,
deprecated: deprecated,
readOnly: isReadOnly,
introducedVersion: introducedVersion
)
}
init(
context: DocumentationContext,
bundle: DocumentationBundle,
identifier: ResolvedTopicReference,
source: URL?,
renderContext: RenderContext? = nil,
emitSymbolSourceFileURIs: Bool = false,
emitSymbolAccessLevels: Bool = false,
sourceRepository: SourceRepository? = nil,
symbolIdentifiersWithExpandedDocumentation: [String]? = nil
) {
self.context = context
self.bundle = bundle
self.identifier = identifier
self.source = source
self.renderContext = renderContext
self.contentRenderer = DocumentationContentRenderer(documentationContext: context, bundle: bundle)
self.shouldEmitSymbolSourceFileURIs = emitSymbolSourceFileURIs
self.shouldEmitSymbolAccessLevels = emitSymbolAccessLevels
self.sourceRepository = sourceRepository
self.symbolIdentifiersWithExpandedDocumentation = symbolIdentifiersWithExpandedDocumentation
}
}
fileprivate typealias BundleModuleIdentifier = String
extension BundleModuleIdentifier {
fileprivate init(bundle: DocumentationBundle, moduleName: String) {
self = "\(bundle.identifier):\(moduleName)"
}
}
public protocol RenderTree {}
extension Array: RenderTree where Element: RenderTree {}
extension RenderBlockContent: RenderTree {}
extension RenderReferenceIdentifier: RenderTree {}
extension RenderNode: RenderTree {}
extension IntroRenderSection: RenderTree {}
extension VolumeRenderSection: RenderTree {}
extension VolumeRenderSection.Chapter: RenderTree {}
extension ContentAndMediaSection: RenderTree {}
extension ContentAndMediaGroupSection: RenderTree {}
extension CallToActionSection: RenderTree {}
extension TutorialSectionsRenderSection: RenderTree {}
extension TutorialSectionsRenderSection.Section: RenderTree {}
extension TutorialAssessmentsRenderSection: RenderTree {}
extension TutorialAssessmentsRenderSection.Assessment: RenderTree {}
extension TutorialAssessmentsRenderSection.Assessment.Choice: RenderTree {}
extension RenderInlineContent: RenderTree {}
extension RenderTile: RenderTree {}
extension ResourcesRenderSection: RenderTree {}
extension TutorialArticleSection: RenderTree {}
extension ContentLayout: RenderTree {}
extension ContentRenderSection: RenderTree {}
private extension Sequence<SourceLanguage> {
func matchesOneOf(traits: Set<DocumentationDataVariantsTrait>) -> Bool {
traits.contains(where: {
guard let languageID = $0.interfaceLanguage,
let traitLanguage = SourceLanguage(knownLanguageIdentifier: languageID)
else {
return false
}
return self.contains(traitLanguage)
})
}
}
|