Skip to content

Commit c9542e4

Browse files
committed
Add support for custom scripts
1 parent ae6a083 commit c9542e4

File tree

12 files changed

+197
-39
lines changed

12 files changed

+197
-39
lines changed

Sources/SwiftDocC/Infrastructure/DocumentationBundle.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ public struct DocumentationBundle {
9191

9292
/// A custom JSON settings file used to theme renderer output.
9393
public let themeSettings: URL?
94+
95+
/// A custom JSON settings file used to add custom scripts to the renderer output.
96+
public let customScripts: URL?
97+
9498
/// A URL prefix to be appended to the relative presentation URL.
9599
///
96100
/// This is used when a built documentation is hosted in a known location.
@@ -107,6 +111,7 @@ public struct DocumentationBundle {
107111
/// - customHeader: A custom HTML file to use as the header for rendered output.
108112
/// - customFooter: A custom HTML file to use as the footer for rendered output.
109113
/// - themeSettings: A custom JSON settings file used to theme renderer output.
114+
/// - customScripts: A custom JSON settings file used to add custom scripts to the renderer output.
110115
public init(
111116
info: Info,
112117
baseURL: URL = URL(string: "/")!,
@@ -115,7 +120,8 @@ public struct DocumentationBundle {
115120
miscResourceURLs: [URL],
116121
customHeader: URL? = nil,
117122
customFooter: URL? = nil,
118-
themeSettings: URL? = nil
123+
themeSettings: URL? = nil,
124+
customScripts: URL? = nil
119125
) {
120126
self.info = info
121127
self.baseURL = baseURL
@@ -125,6 +131,7 @@ public struct DocumentationBundle {
125131
self.customHeader = customHeader
126132
self.customFooter = customFooter
127133
self.themeSettings = themeSettings
134+
self.customScripts = customScripts
128135
self.rootReference = ResolvedTopicReference(bundleID: info.id, path: "/", sourceLanguage: .swift)
129136
self.documentationRootReference = ResolvedTopicReference(bundleID: info.id, path: NodeURLGenerator.Path.documentationFolder, sourceLanguage: .swift)
130137
self.tutorialTableOfContentsContainer = ResolvedTopicReference(bundleID: info.id, path: NodeURLGenerator.Path.tutorialsFolder, sourceLanguage: .swift)

Sources/SwiftDocC/Infrastructure/DocumentationBundleFileTypes.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,12 @@ public enum DocumentationBundleFileTypes {
8484
public static func isThemeSettingsFile(_ url: URL) -> Bool {
8585
return url.lastPathComponent == themeSettingsFileName
8686
}
87+
88+
private static let customScriptsFileName = "custom-scripts.json"
89+
/// Checks if a file is `custom-scripts.json`.
90+
/// - Parameter url: The file to check.
91+
/// - Returns: Whether or not the file at `url` is `custom-scripts.json`.
92+
public static func isCustomScriptsFile(_ url: URL) -> Bool {
93+
return url.lastPathComponent == customScriptsFileName
94+
}
8795
}

Sources/SwiftDocC/Infrastructure/DocumentationContext.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,7 @@ public class DocumentationContext {
15841584

15851585
private static let supportedImageExtensions: Set<String> = ["png", "jpg", "jpeg", "svg", "gif"]
15861586
private static let supportedVideoExtensions: Set<String> = ["mov", "mp4"]
1587+
private static let supportedScriptExtensions: Set<String> = ["js"]
15871588

15881589
// TODO: Move this functionality to ``DocumentationBundleFileTypes`` (rdar://68156425).
15891590

@@ -1663,6 +1664,14 @@ public class DocumentationContext {
16631664
public func registeredDownloadsAssets(for bundleID: DocumentationBundle.Identifier) -> [DataAsset] {
16641665
registeredAssets(inContexts: [DataAsset.Context.download], forBundleID: bundleID)
16651666
}
1667+
1668+
/// Returns a list of all the custom scripts that registered for a given `bundleID`.
1669+
///
1670+
/// - Parameter bundleID: The identifier of the bundle to return custom scripts for.
1671+
/// - Returns: A list of all the custom scripts for the given bundle.
1672+
public func registeredCustomScripts(for bundleID: DocumentationBundle.Identifier) -> [DataAsset] {
1673+
return registeredAssets(withExtensions: DocumentationContext.supportedScriptExtensions, forBundleID: bundleID)
1674+
}
16661675

16671676
typealias Articles = [DocumentationContext.SemanticResult<Article>]
16681677
private typealias ArticlesTuple = (articles: Articles, rootPageArticles: Articles)

Sources/SwiftDocC/Infrastructure/Input Discovery/DocumentationInputsProvider.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ extension DocumentationContext {
2525
/// ``DocumentationBundle/symbolGraphURLs`` | ``DocumentationBundleFileTypes/isSymbolGraphFile(_:)``
2626
/// ``DocumentationBundle/info`` | ``DocumentationBundleFileTypes/isInfoPlistFile(_:)``
2727
/// ``DocumentationBundle/themeSettings`` | ``DocumentationBundleFileTypes/isThemeSettingsFile(_:)``
28+
/// ``DocumentationBundle/customScripts`` | ``DocumentationBundleFileTypes/isCustomScriptsFile(_:)``
2829
/// ``DocumentationBundle/customHeader`` | ``DocumentationBundleFileTypes/isCustomHeader(_:)``
2930
/// ``DocumentationBundle/customFooter`` | ``DocumentationBundleFileTypes/isCustomFooter(_:)``
3031
/// ``DocumentationBundle/miscResourceURLs`` | Any file not already matched above.
@@ -165,7 +166,8 @@ extension DocumentationContext.InputsProvider {
165166
miscResourceURLs: foundContents.resources,
166167
customHeader: shallowContent.first(where: FileTypes.isCustomHeader),
167168
customFooter: shallowContent.first(where: FileTypes.isCustomFooter),
168-
themeSettings: shallowContent.first(where: FileTypes.isThemeSettingsFile)
169+
themeSettings: shallowContent.first(where: FileTypes.isThemeSettingsFile),
170+
customScripts: shallowContent.first(where: FileTypes.isCustomScriptsFile)
169171
)
170172
}
171173

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
{
2+
"openapi": "3.0.0",
3+
"info": {
4+
"title": "Custom Scripts",
5+
"description": "This spec describes the permissible contents of a custom-scripts.json file in a documentation catalog, which is used to add custom scripts to a DocC-generated website.",
6+
"version": "0.0.1"
7+
},
8+
"paths": {},
9+
"components": {
10+
"schemas": {
11+
"Scripts": {
12+
"type": "array",
13+
"description": "An array of custom scripts, which is the top-level container in a custom-scripts.json file.",
14+
"items": {
15+
"oneOf": [
16+
{ "$ref": "#/components/schemas/ExternalScript" },
17+
{ "$ref": "#/components/schemas/LocalScript" },
18+
{ "$ref": "#/components/schemas/InlineScript" }
19+
]
20+
}
21+
},
22+
"Script": {
23+
"type": "object",
24+
"description": "An abstract schema representing any script, from which all three script types inherit.",
25+
"properties": {
26+
"type": {
27+
"type": "string",
28+
"description": "The `type` attribute of the HTML script element."
29+
},
30+
"run": {
31+
"type": "string",
32+
"enum": ["on-load", "on-navigate", "on-load-and-navigate"],
33+
"description": "Whether the custom script should be run only on the initial page load, each time the reader navigates after the initial page load, or both."
34+
}
35+
}
36+
},
37+
"ScriptFromFile": {
38+
"description": "An abstract schema representing a script from an external or local file; that is, not an inline script.",
39+
"allOf": [
40+
{ "$ref": "#/components/schemas/Script" },
41+
{
42+
"properties": {
43+
"async": { "type": "boolean" },
44+
"defer": { "type": "boolean" }
45+
}
46+
}
47+
]
48+
},
49+
"ExternalScript": {
50+
"description": "A script at an external URL.",
51+
"allOf": [
52+
{ "$ref": "#/components/schemas/ScriptFromFile" },
53+
{
54+
"required": ["url"],
55+
"properties": {
56+
"url": { "type": "string" },
57+
"integrity": { "type": "string" }
58+
}
59+
}
60+
]
61+
},
62+
"LocalScript": {
63+
"description": "A script from a local file.",
64+
"allOf": [
65+
{ "$ref": "#/components/schemas/ScriptFromFile" },
66+
{
67+
"required": ["name"],
68+
"properties": {
69+
"name": {
70+
"type": "string",
71+
"description": "The name of the local script file, optionally including the '.js' extension."
72+
},
73+
}
74+
}
75+
]
76+
},
77+
"InlineScript": {
78+
"description": "A script whose source code is in the custom-scripts.json file itself.",
79+
"allOf": [
80+
{ "$ref": "#/components/schemas/Script" },
81+
{
82+
"required": ["code"],
83+
"properties": {
84+
"code": {
85+
"type": "string",
86+
"description": "The source code of the inline script."
87+
}
88+
}
89+
}
90+
]
91+
}
92+
},
93+
"requestBodies": {},
94+
"securitySchemes": {},
95+
"links": {},
96+
"callbacks": {}
97+
}
98+
}

Sources/SwiftDocCUtilities/Action/Actions/Convert/ConvertFileWritingConsumer.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,18 @@ struct ConvertFileWritingConsumer: ConvertOutputConsumer, ExternalNodeConsumer {
125125
for downloadAsset in context.registeredDownloadsAssets(for: bundleID) {
126126
try copyAsset(downloadAsset, to: downloadsDirectory)
127127
}
128+
129+
// Create custom scripts directory if needed. Do not append the bundle identifier.
130+
let scriptsDirectory = targetFolder
131+
.appendingPathComponent("custom-scripts", isDirectory: true)
132+
if !fileManager.directoryExists(atPath: scriptsDirectory.path) {
133+
try fileManager.createDirectory(at: scriptsDirectory, withIntermediateDirectories: true, attributes: nil)
134+
}
135+
136+
// Copy all registered custom scripts to the output directory.
137+
for customScript in context.registeredCustomScripts(for: bundleID) {
138+
try copyAsset(customScript, to: scriptsDirectory)
139+
}
128140

129141
// If the bundle contains a `header.html` file, inject a <template> into
130142
// the `index.html` file using its contents. This will only be done if
@@ -150,6 +162,16 @@ struct ConvertFileWritingConsumer: ConvertOutputConsumer, ExternalNodeConsumer {
150162
}
151163
try fileManager._copyItem(at: themeSettings, to: targetFile)
152164
}
165+
166+
// Copy the `custom-scripts.json` file into the output directory if one
167+
// is provided.
168+
if let customScripts = bundle.customScripts {
169+
let targetFile = targetFolder.appendingPathComponent(customScripts.lastPathComponent, isDirectory: false)
170+
if fileManager.fileExists(atPath: targetFile.path) {
171+
try fileManager.removeItem(at: targetFile)
172+
}
173+
try fileManager._copyItem(at: customScripts, to: targetFile)
174+
}
153175
}
154176

155177
func consume(linkableElementSummaries summaries: [LinkDestinationSummary]) throws {

Sources/SwiftDocCUtilities/PreviewServer/RequestHandler/FileRequestHandler.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ struct FileRequestHandler: RequestHandlerFactory {
107107
TopLevelAssetFileMetadata(filePath: "/favicon.ico", mimetype: "image/x-icon"),
108108
TopLevelAssetFileMetadata(filePath: "/theme-settings.js", mimetype: "text/javascript"),
109109
TopLevelAssetFileMetadata(filePath: "/theme-settings.json", mimetype: "application/json"),
110+
TopLevelAssetFileMetadata(filePath: "/custom-scripts.json", mimetype: "application/json"),
110111
]
111112

112113
/// Returns a Boolean value that indicates whether the given path is located inside an asset folder.

Tests/SwiftDocCTests/Infrastructure/DocumentationBundleFileTypesTests.swift

Lines changed: 40 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -13,46 +13,51 @@ import XCTest
1313

1414
class DocumentationBundleFileTypesTests: XCTestCase {
1515
func testIsCustomHeader() {
16-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomHeader(
17-
URL(fileURLWithPath: "header.html")))
18-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomHeader(
19-
URL(fileURLWithPath: "/header.html")))
20-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomHeader(
21-
URL(fileURLWithPath: "header")))
22-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomHeader(
23-
URL(fileURLWithPath: "/header.html/foo")))
24-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomHeader(
25-
URL(fileURLWithPath: "footer.html")))
26-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomHeader(
27-
URL(fileURLWithPath: "DocC.docc/header.html")))
16+
assertThat(DocumentationBundleFileTypes.isCustomHeader, matchesFilesNamed: "header", withExtension: "html")
2817
}
2918

3019
func testIsCustomFooter() {
31-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomFooter(
32-
URL(fileURLWithPath: "footer.html")))
33-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomFooter(
34-
URL(fileURLWithPath: "/footer.html")))
35-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomFooter(
36-
URL(fileURLWithPath: "footer")))
37-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomFooter(
38-
URL(fileURLWithPath: "/footer.html/foo")))
39-
XCTAssertFalse(DocumentationBundleFileTypes.isCustomFooter(
40-
URL(fileURLWithPath: "header.html")))
41-
XCTAssertTrue(DocumentationBundleFileTypes.isCustomFooter(
42-
URL(fileURLWithPath: "DocC.docc/footer.html")))
20+
assertThat(DocumentationBundleFileTypes.isCustomFooter, matchesFilesNamed: "footer", withExtension: "html")
4321
}
4422

4523
func testIsThemeSettingsFile() {
46-
XCTAssertTrue(DocumentationBundleFileTypes.isThemeSettingsFile(
47-
URL(fileURLWithPath: "theme-settings.json")))
48-
XCTAssertTrue(DocumentationBundleFileTypes.isThemeSettingsFile(
49-
URL(fileURLWithPath: "/a/b/theme-settings.json")))
50-
51-
XCTAssertFalse(DocumentationBundleFileTypes.isThemeSettingsFile(
52-
URL(fileURLWithPath: "theme-settings.txt")))
53-
XCTAssertFalse(DocumentationBundleFileTypes.isThemeSettingsFile(
54-
URL(fileURLWithPath: "not-theme-settings.json")))
55-
XCTAssertFalse(DocumentationBundleFileTypes.isThemeSettingsFile(
56-
URL(fileURLWithPath: "/a/theme-settings.json/bar")))
24+
assertThat(DocumentationBundleFileTypes.isThemeSettingsFile, matchesFilesNamed: "theme-settings", withExtension: "json")
25+
}
26+
27+
func testIsCustomScriptsFile() {
28+
assertThat(DocumentationBundleFileTypes.isCustomScriptsFile, matchesFilesNamed: "custom-scripts", withExtension: "json")
29+
}
30+
31+
private func assertThat(
32+
_ predicate: (URL) -> Bool,
33+
matchesFilesNamed fileName: String,
34+
withExtension extension: String,
35+
file: StaticString = #filePath,
36+
line: UInt = #line
37+
) {
38+
let fileNameWithExtension = "\(fileName).\(`extension`)"
39+
40+
let pathsThatShouldMatch = [
41+
fileNameWithExtension,
42+
"/\(fileNameWithExtension)",
43+
"DocC/docc/\(fileNameWithExtension)",
44+
"/a/b/\(fileNameWithExtension)"
45+
].map { URL(fileURLWithPath: $0) }
46+
47+
let pathsThatShouldNotMatch = [
48+
fileName,
49+
"/\(fileNameWithExtension)/foo",
50+
"/a/\(fileNameWithExtension)/bar",
51+
"\(fileName).wrongextension",
52+
"wrongname.\(`extension`)"
53+
].map { URL(fileURLWithPath: $0) }
54+
55+
for url in pathsThatShouldMatch {
56+
XCTAssertTrue(predicate(url), file: file, line: line)
57+
}
58+
59+
for url in pathsThatShouldNotMatch {
60+
XCTAssertFalse(predicate(url), file: file, line: line)
61+
}
5762
}
5863
}

Tests/SwiftDocCTests/Infrastructure/Input Discovery/DocumentationInputsProviderTests.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@ class DocumentationInputsProviderTests: XCTestCase {
2828
// This top-level Info.plist will be read for bundle information
2929
InfoPlist(displayName: "CustomDisplayName"),
3030

31-
// These top-level files will be treated as a custom footer and a custom theme
31+
// Top-level files with customization
3232
TextFile(name: "footer.html", utf8Content: ""),
3333
TextFile(name: "theme-settings.json", utf8Content: ""),
34+
TextFile(name: "custom-scripts.json", utf8Content: ""),
3435

3536
// Top-level content will be found
3637
TextFile(name: "CCC.md", utf8Content: ""),
@@ -95,6 +96,7 @@ class DocumentationInputsProviderTests: XCTestCase {
9596
"Found.docc/Inner/Info.plist",
9697
"Found.docc/Inner/header.html",
9798
"Found.docc/Inner/second.png",
99+
"Found.docc/custom-scripts.json",
98100
"Found.docc/first.png",
99101
"Found.docc/footer.html",
100102
"Found.docc/theme-settings.json",
@@ -107,6 +109,7 @@ class DocumentationInputsProviderTests: XCTestCase {
107109
XCTAssertEqual(bundle.customFooter.map(relativePathString), "Found.docc/footer.html")
108110
XCTAssertEqual(bundle.customHeader.map(relativePathString), nil)
109111
XCTAssertEqual(bundle.themeSettings.map(relativePathString), "Found.docc/theme-settings.json")
112+
XCTAssertEqual(bundle.customScripts.map(relativePathString), "Found.docc/custom-scripts.json")
110113
}
111114
}
112115

Tests/SwiftDocCUtilitiesTests/ConvertActionStaticHostableTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class ConvertActionStaticHostableTests: StaticHostingBaseTests {
4747
_ = try await action.perform(logHandle: .none)
4848

4949
// Test the content of the output folder.
50-
var expectedContent = ["data", "documentation", "tutorials", "downloads", "images", "metadata.json" ,"videos", "index.html", "index"]
50+
var expectedContent = ["data", "documentation", "tutorials", "downloads", "images", "custom-scripts", "metadata.json", "videos", "index.html", "index"]
5151
expectedContent += templateFolder.content.filter { $0 is Folder }.map{ $0.name }
5252

5353
let output = try fileManager.contentsOfDirectory(atPath: targetBundleURL.path)

0 commit comments

Comments
 (0)