-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathRenderNodeTranslator.swift
1952 lines (1647 loc) · 94.6 KB
/
RenderNodeTranslator.swift
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
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2023 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
fileReferences[result.file.path]?.deleteHighlights = result.deleteHighlights
}
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 = contentRenderer.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 assesments = tutorial.assessments {
node.sections.append(visitAssessments(assesments) 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.pathsTo(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)]()
context.traverseBreadthFirst(from: volume) { node in
if node.kind == .tutorial || node.kind == .tutorialArticle {
surroundingTopics.append((node.reference, node.kind))
}
return .continue
}
// 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, 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
context.traverseBreadthFirst(from: identifier) { node in
if let entity = try? context.entity(with: node.reference),
let durationMinutes = (entity.semantic as? Timed)?.durationMinutes
{
if totalDurationMinutes == nil {
totalDurationMinutes = 0
}
totalDurationMinutes! += durationMinutes
}
return .continue
}
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 = contentRenderer.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 = 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 = 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<Reference>(_ references: [String: Reference], to node: inout RenderNode) where Reference: RenderReference {
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)
}
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)
var contentCompiler = RenderContentCompiler(context: context, bundle: bundle, identifier: identifier)
node.metadata.title = article.title!.plainText
// Detect the article modules from its breadcrumbs.
let modules = context.pathsTo(identifier).compactMap({ path -> ResolvedTopicReference? in
return path.mapFirst(where: { ancestor in
guard let ancestorNode = try? context.entity(with: ancestor) else { return nil }
return (ancestorNode.semantic as? Symbol)?.moduleReference
})
})
let moduleNames = Set(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: &contentCompiler
)
)
}
// 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: &contentCompiler
)
)
}
// 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.
contentCompiler.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: &contentCompiler
)
)
}
return sections
} ?? .init(defaultValue: [])
node.topicSectionsStyle = topicsSectionStyle(for: documentationNode)
if shouldCreateAutomaticRoleHeading(for: documentationNode) {
if node.topicSections.isEmpty {
// Set an eyebrow for articles
node.metadata.roleHeading = "Article"
}
node.metadata.role = contentRenderer.roleForArticle(article, nodeKind: documentationNode.kind).rawValue
}
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: &contentCompiler
)
)
}
// Automatic See Also section
if let seeAlso = try! AutomaticCuration.seeAlso(
for: documentationNode,
withTraits: allowedTraits,
context: context,
bundle: bundle,
renderContext: renderContext,
renderer: contentRenderer
) {
contentCompiler.collectedTopicReferences.append(contentsOf: seeAlso.references)
seeAlsoSections.append(TaskGroupRenderSection(
title: seeAlso.title,
abstract: nil,
discussion: nil,
identifiers: seeAlso.references.map { $0.absoluteString },
generated: true
))
}
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))
externalLocationReferences[url.description] = ExternalLocationReference(identifier: downloadIdentifier)
} 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
}
collectedTopicReferences.append(contentsOf: contentCompiler.collectedTopicReferences)
node.references = createTopicRenderReferences()
addReferences(imageReferences, to: &node)
addReferences(videoReferences, to: &node)
addReferences(linkReferences, to: &node)
addReferences(downloadReferences, to: &node)
addReferences(externalLocationReferences, to: &node)
// See Also can contain external links, we need to separately transfer
// link references from the content compiler
addReferences(contentCompiler.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 = contentRenderer.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.pathsTo(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: Sequence>(_ markupLayouts: MarkupLayouts) -> [ContentLayout] where MarkupLayouts.Element == MarkupLayout {
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
)
}
}
/// 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.