Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add authoring support for @TitleHeading directive #611

Merged
merged 18 commits into from
Jun 12, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ public class OutOfProcessReferenceResolver: ExternalReferenceResolver, FallbackR
// with a render node.

if let topicImages = resolvedInformation.topicImages, !topicImages.isEmpty {
let metadata = node.metadata ?? Metadata(originalMarkup: BlockDirective(name: "Metadata", children: []), documentationExtension: nil, technologyRoot: nil, displayName: nil)
let metadata = node.metadata ?? Metadata(originalMarkup: BlockDirective(name: "Metadata", children: []), documentationExtension: nil, technologyRoot: nil, displayName: nil, titleHeading: nil)

metadata.pageImages = topicImages.map { topicImage in
let purpose: PageImage.Purpose
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public struct RenderMetadata: VariantContainer {

/// The variants of the title.
public var titleVariants: VariantCollection<String?> = .init(defaultValue: nil)
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved

/// An identifier for a symbol generated externally.
public var externalID: String? {
get { getVariantDefaultValue(keyPath: \.externalIDVariants) }
Expand Down
10 changes: 9 additions & 1 deletion Sources/SwiftDocC/Model/Rendering/RenderNodeTranslator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -841,12 +841,16 @@ public struct RenderNodeTranslator: SemanticVisitor {
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.headingText
}

collectedTopicReferences.append(contentsOf: contentCompiler.collectedTopicReferences)
node.references = createTopicRenderReferences()

Expand Down Expand Up @@ -1247,6 +1251,10 @@ public struct RenderNodeTranslator: SemanticVisitor {
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.headingText)
}

node.metadata.symbolKindVariants = VariantCollection<String?>(from: symbol.kindVariants) { _, kindVariants in
kindVariants.identifier.renderingIdentifier
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftDocC/Semantics/Article/Article.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ public final class Article: Semantic, MarkupConvertible, Abstracted, Redirected,
problems.append(Problem(diagnostic: diagnostic, possibleSolutions: solutions))

// Remove the display name customization from the article's metadata.
optionalMetadata = Metadata(originalMarkup: metadata.originalMarkup, documentationExtension: metadata.documentationOptions, technologyRoot: metadata.technologyRoot, displayName: nil)
optionalMetadata = Metadata(originalMarkup: metadata.originalMarkup, documentationExtension: metadata.documentationOptions, technologyRoot: metadata.technologyRoot, displayName: nil, titleHeading: metadata.titleHeading)
}

self.init(
Expand Down
15 changes: 11 additions & 4 deletions Sources/SwiftDocC/Semantics/Metadata/Metadata.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import Markdown
/// - ``Availability``
/// - ``PageKind``
/// - ``SupportedLanguage``
/// - ``TitleHeading``
public final class Metadata: Semantic, AutomaticDirectiveConvertible {
public let originalMarkup: BlockDirective

Expand Down Expand Up @@ -68,6 +69,9 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
var pageColor: PageColor.Color? {
_pageColor?.color
}

@ChildDirective
var titleHeading: TitleHeading? = nil

static var keyPaths: [String : AnyKeyPath] = [
"documentationOptions" : \Metadata._documentationOptions,
Expand All @@ -79,20 +83,23 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
"availability" : \Metadata._availability,
"pageKind" : \Metadata._pageKind,
"supportedLanguages" : \Metadata._supportedLanguages,
"_pageColor" : \Metadata.__pageColor,
"_pageColor" : \Metadata.__pageColor,
"titleHeading" : \Metadata._titleHeading,
]

/// Creates a metadata object with a given markup, documentation extension, and technology root.
/// - Parameters:
/// - originalMarkup: The original markup for this metadata directive.
/// - documentationExtension: Optional configuration that describes how this documentation extension file merges or overrides the in-source documentation.
/// - technologyRoot: Optional configuration to make this page root-level documentation.
/// - displayName:Optional configuration to customize this page's symbol's display name.
init(originalMarkup: BlockDirective, documentationExtension: DocumentationExtension?, technologyRoot: TechnologyRoot?, displayName: DisplayName?) {
/// - displayName: Optional configuration to customize this page's symbol's display name.
/// - titleHeading: Optional configuration to customize the text of this page's title heading.
init(originalMarkup: BlockDirective, documentationExtension: DocumentationExtension?, technologyRoot: TechnologyRoot?, displayName: DisplayName?, titleHeading: TitleHeading?) {
self.originalMarkup = originalMarkup
self.documentationOptions = documentationExtension
self.technologyRoot = technologyRoot
self.displayName = displayName
self.titleHeading = titleHeading
}

@available(*, deprecated, message: "Do not call directly. Required for 'AutomaticDirectiveConvertible'.")
Expand All @@ -102,7 +109,7 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {

func validate(source: URL?, for bundle: DocumentationBundle, in context: DocumentationContext, problems: inout [Problem]) -> Bool {
// Check that something is configured in the metadata block
if documentationOptions == nil && technologyRoot == nil && displayName == nil && pageImages.isEmpty && customMetadata.isEmpty && callToAction == nil && availability.isEmpty && pageKind == nil && pageColor == nil {
if documentationOptions == nil && technologyRoot == nil && displayName == nil && pageImages.isEmpty && customMetadata.isEmpty && callToAction == nil && availability.isEmpty && pageKind == nil && pageColor == nil && titleHeading == nil {
let diagnostic = Diagnostic(
source: source,
severity: .information,
Expand Down
39 changes: 39 additions & 0 deletions Sources/SwiftDocC/Semantics/Metadata/TitleHeading.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
This source file is part of the Swift.org open source project

Copyright (c) 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

/// A directive for customizing the text of a page-title heading (aka an eyebrow or kick).
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
///
/// @TitleHeading accepts an unnamed parameter containing containing the page-title’s heading text.
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
///
/// This directive is only valid within a top-level ``Metadata`` directive:
/// ```markdown
/// @Metadata {
/// @TitleHeading("Release Notes")
/// }
/// ```
public final class TitleHeading: Semantic, AutomaticDirectiveConvertible {
public let originalMarkup: BlockDirective

/// An unnamed parameter containing containing the page-title’s heading text.
@DirectiveArgumentWrapped(name: .unnamed)
public var headingText: String
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved

static var keyPaths: [String : AnyKeyPath] = [
"headingText" : \TitleHeading._headingText,
]

@available(*, deprecated, message: "Do not call directly. Required for 'AutomaticDirectiveConvertible'.")
init(originalMarkup: BlockDirective) {
self.originalMarkup = originalMarkup
}
}
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ Use the `Metadata` directive with the ``DisplayName`` directive to configure a s
}
```

Use the `Metadata` directive with the ``TitleHeading`` directive to configure the text of a page-title heading (also known as an eyebrow or kick).
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved

```
# ``SlothCreator``

@Metadata {
@TitleHeading("Release Notes")
}
```

## Topics

### Extending or Overriding Source Documentation
Expand All @@ -47,6 +57,7 @@ Use the `Metadata` directive with the ``DisplayName`` directive to configure a s
- ``PageKind``
- ``PageColor``
- ``CallToAction``
- ``TitleHeading``

### Customizing the Languages of an Article

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ class TestMultiResultExternalReferenceResolver: ExternalReferenceResolver, Fallb
// This is a workaround for how external content is processed. See details in OutOfProcessReferenceResolver.addImagesAndCacheMediaReferences(to:from:)

if let topicImages = entityInfo.topicImages {
let metadata = node.metadata ?? Metadata(originalMarkup: BlockDirective(name: "Metadata", children: []), documentationExtension: nil, technologyRoot: nil, displayName: nil)
let metadata = node.metadata ?? Metadata(originalMarkup: BlockDirective(name: "Metadata", children: []), documentationExtension: nil, technologyRoot: nil, displayName: nil, titleHeading: nil)

metadata.pageImages = topicImages.map { topicImage, alt in
let purpose: PageImage.Purpose
Expand Down
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ class RenderNodeTranslatorTests: XCTestCase {
let source = """
# My Article
My introduction.
My exposè.
My exposé.
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
My conclusion.
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
Expand All @@ -247,7 +247,7 @@ class RenderNodeTranslatorTests: XCTestCase {
let source = """
# My Article
My introduction.
My exposè.
My exposé.
My conclusion.
## Topics
### Basics
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class DirectiveIndexTests: XCTestCase {
"Tab",
"TabNavigator",
"TechnologyRoot",
"TitleHeading",
"TopicsVisualStyle",
"Tutorial",
"TutorialReference",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ class DirectiveMirrorTests: XCTestCase {
XCTAssertEqual(reflectedDirective.arguments["style"]?.propertyLabel, "style")
XCTAssertEqual(reflectedDirective.arguments["style"]?.allowedValues, ["conceptual", "symbol"])
}

func testReflectTitleHeadingDirective() {
let reflectedDirective = DirectiveMirror(reflecting: TitleHeading.self).reflectedDirective

XCTAssertEqual(reflectedDirective.name, "TitleHeading")
XCTAssertFalse(reflectedDirective.allowsMarkup)
XCTAssertEqual(reflectedDirective.arguments.count, 1)

XCTAssertEqual(reflectedDirective.arguments["headingText"]?.unnamed, true)
XCTAssertEqual(reflectedDirective.arguments["headingText"]?.required, true)
XCTAssertEqual(reflectedDirective.arguments["headingText"]?.labelDisplayName, "_ headingText")
XCTAssertEqual(reflectedDirective.arguments["headingText"]?.propertyLabel, "headingText")
}

func testReflectMetadataDirective() {
let reflectedDirective = DirectiveMirror(reflecting: Metadata.self).reflectedDirective
Expand All @@ -39,7 +52,7 @@ class DirectiveMirrorTests: XCTestCase {
XCTAssertFalse(reflectedDirective.allowsMarkup)
XCTAssert(reflectedDirective.arguments.isEmpty)

XCTAssertEqual(reflectedDirective.childDirectives.count, 10)
XCTAssertEqual(reflectedDirective.childDirectives.count, 11)

XCTAssertEqual(
reflectedDirective.childDirectives["DocumentationExtension"]?.propertyLabel,
Expand Down
66 changes: 66 additions & 0 deletions Tests/SwiftDocCTests/Semantics/MetadataTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ class MetadataTests: XCTestCase {

XCTAssertEqual(metadata?.displayName?.name, "Custom Name")
}

func testTitleHeadingSupport() throws {
let source = """
@Metadata {
@TitleHeading("Custom Heading")
}
"""
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let metadata = Metadata(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(metadata)
XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.summary })")

XCTAssertEqual(metadata?.titleHeading?.headingText, "Custom Heading")
}

func testCustomMetadataSupport() throws {
let source = """
Expand Down Expand Up @@ -231,6 +248,55 @@ class MetadataTests: XCTestCase {
XCTAssertEqual(solution.replacements.last?.range, SourceLocation(line: 1, column: 1, source: nil) ..< SourceLocation(line: 1, column: 16, source: nil))
XCTAssertEqual(solution.replacements.last?.replacement, "# Custom Name")
}

func testSymbolArticleSupportsMetadataTitleHeading() throws {
let source = """
# ``SomeSymbol``

@Metadata {
@TitleHeading("Custom Heading")
}

The abstract of this documentation extension
"""
let document = Document(parsing: source, options: [.parseBlockDirectives, .parseSymbolLinks])
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let article = Article(from: document, source: nil, for: bundle, in: context, problems: &problems)
emilyychenn marked this conversation as resolved.
Show resolved Hide resolved
XCTAssertNotNil(article, "An Article value can be created with a Metadata child with a TitleHeading child.")
XCTAssertNotNil(article?.metadata?.titleHeading, "The Article has the parsed TitleHeading metadata.")

XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.summary })")

var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got:\n \(DiagnosticConsoleWriter.formattedDescription(for: analyzer.problems))")
}

func testArticleSupportsMetadataTitleHeading() throws {
let source = """
# Article title

@Metadata {
@TitleHeading("Custom Heading")
}

The abstract of this documentation extension
"""
let document = Document(parsing: source, options: [.parseBlockDirectives, .parseSymbolLinks])
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let article = Article(from: document, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNotNil(article, "An Article value can be created with a Metadata child with a TitleHeading child.")
XCTAssertNotNil(article?.metadata?.titleHeading, "The Article has the parsed TitleHeading metadata.")
XCTAssertEqual(article?.metadata?.titleHeading?.headingText, "Custom Heading")

XCTAssert(problems.isEmpty, "There shouldn't be any problems. Got:\n\(problems.map { $0.diagnostic.summary })")

var analyzer = SemanticAnalyzer(source: nil, context: context, bundle: bundle)
_ = analyzer.visit(document)
XCTAssert(analyzer.problems.isEmpty, "Expected no problems. Got:\n \(DiagnosticConsoleWriter.formattedDescription(for: analyzer.problems))")
}

func testDuplicateMetadata() throws {
let source = """
Expand Down