Skip to content

Commit 013ceb4

Browse files
committed
Add support for custom scripts
1 parent bda4ac9 commit 013ceb4

File tree

10 files changed

+193
-38
lines changed

10 files changed

+193
-38
lines changed

Sources/SwiftDocC/Infrastructure/DocumentationBundle.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,15 @@ public struct DocumentationBundle {
110110

111111
/// A custom JSON settings file used to theme renderer output.
112112
public let themeSettings: URL?
113+
113114
/// A URL prefix to be appended to the relative presentation URL.
114115
///
115116
/// This is used when a built documentation is hosted in a known location.
116117
public let baseURL: URL
117118

119+
/// A custom JSON settings file used to add custom scripts to the renderer output.
120+
public let customScripts: URL?
121+
118122
/// Creates a new collection of build inputs for a unit of documentation.
119123
///
120124
/// - Parameters:
@@ -126,6 +130,7 @@ public struct DocumentationBundle {
126130
/// - customHeader: A custom HTML file to use as the header for rendered output.
127131
/// - customFooter: A custom HTML file to use as the footer for rendered output.
128132
/// - themeSettings: A custom JSON settings file used to theme renderer output.
133+
/// - customScripts: A custom JSON settings file used to add custom scripts to the renderer output.
129134
public init(
130135
info: Info,
131136
baseURL: URL = URL(string: "/")!,
@@ -134,7 +139,8 @@ public struct DocumentationBundle {
134139
miscResourceURLs: [URL],
135140
customHeader: URL? = nil,
136141
customFooter: URL? = nil,
137-
themeSettings: URL? = nil
142+
themeSettings: URL? = nil,
143+
customScripts: URL? = nil
138144
) {
139145
self.info = info
140146
self.baseURL = baseURL
@@ -144,6 +150,7 @@ public struct DocumentationBundle {
144150
self.customHeader = customHeader
145151
self.customFooter = customFooter
146152
self.themeSettings = themeSettings
153+
self.customScripts = customScripts
147154
self.rootReference = ResolvedTopicReference(bundleID: info.id, path: "/", sourceLanguage: .swift)
148155
self.documentationRootReference = ResolvedTopicReference(bundleID: info.id, path: NodeURLGenerator.Path.documentationFolder, sourceLanguage: .swift)
149156
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,6 +84,14 @@ 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
}
8896

8997
extension DocumentationBundleFileTypes {

Sources/SwiftDocC/Infrastructure/DocumentationContext.swift

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

17851785
private static let supportedImageExtensions: Set<String> = ["png", "jpg", "jpeg", "svg", "gif"]
17861786
private static let supportedVideoExtensions: Set<String> = ["mov", "mp4"]
1787+
private static let supportedScriptExtensions: Set<String> = ["js"]
17871788

17881789
// TODO: Move this functionality to ``DocumentationBundleFileTypes`` (rdar://68156425).
17891790

@@ -1878,6 +1879,14 @@ public class DocumentationContext {
18781879
public func registeredDownloadsAssets(forBundleID bundleIdentifier: BundleIdentifier) -> [DataAsset] {
18791880
registeredDownloadsAssets(for: DocumentationBundle.Identifier(rawValue: bundleIdentifier))
18801881
}
1882+
1883+
/// Returns a list of all the custom scripts that registered for a given `bundleIdentifier`.
1884+
///
1885+
/// - Parameter bundleIdentifier: The identifier of the bundle to return download assets for.
1886+
/// - Returns: A list of all the custom scripts for the given bundle.
1887+
public func registeredCustomScripts(forBundleID bundleIdentifier: BundleIdentifier) -> [DataAsset] {
1888+
return registeredAssets(withExtensions: DocumentationContext.supportedScriptExtensions, forBundleID: bundleIdentifier)
1889+
}
18811890

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

Sources/SwiftDocC/Infrastructure/Workspace/LocalFileSystemDataProvider+BundleDiscovery.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ extension LocalFileSystemDataProvider: DocumentationWorkspaceDataProvider {
8383
let customHeader = findCustomHeader(bundleChildren)?.url
8484
let customFooter = findCustomFooter(bundleChildren)?.url
8585
let themeSettings = findThemeSettings(bundleChildren)?.url
86+
let customScripts = findCustomScripts(bundleChildren)?.url
8687

8788
return DocumentationBundle(
8889
info: info,
@@ -91,7 +92,8 @@ extension LocalFileSystemDataProvider: DocumentationWorkspaceDataProvider {
9192
miscResourceURLs: miscResources,
9293
customHeader: customHeader,
9394
customFooter: customFooter,
94-
themeSettings: themeSettings
95+
themeSettings: themeSettings,
96+
customScripts: customScripts
9597
)
9698
}
9799

@@ -140,6 +142,10 @@ extension LocalFileSystemDataProvider: DocumentationWorkspaceDataProvider {
140142
private func findThemeSettings(_ bundleChildren: [FSNode]) -> FSNode.File? {
141143
return bundleChildren.firstFile { DocumentationBundleFileTypes.isThemeSettingsFile($0.url) }
142144
}
145+
146+
private func findCustomScripts(_ bundleChildren: [FSNode]) -> FSNode.File? {
147+
return bundleChildren.firstFile { DocumentationBundleFileTypes.isCustomScriptsFile($0.url) }
148+
}
143149
}
144150

145151
@available(*, deprecated, message: "This deprecated API will be removed after 6.2 is released.")
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+
"integrity": { "type": "string" },
46+
}
47+
}
48+
]
49+
},
50+
"ExternalScript": {
51+
"description": "A script at an external URL.",
52+
"allOf": [
53+
{ "$ref": "#/components/schemas/ScriptFromFile" },
54+
{
55+
"required": ["url"],
56+
"properties": {
57+
"url": { "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
@@ -120,6 +120,18 @@ struct ConvertFileWritingConsumer: ConvertOutputConsumer {
120120
for downloadAsset in context.registeredDownloadsAssets(for: bundleID) {
121121
try copyAsset(downloadAsset, to: downloadsDirectory)
122122
}
123+
124+
// Create custom scripts directory if needed. Do not append the bundle identifier.
125+
let scriptsDirectory = targetFolder
126+
.appendingPathComponent("custom-scripts", isDirectory: true)
127+
if !fileManager.directoryExists(atPath: scriptsDirectory.path) {
128+
try fileManager.createDirectory(at: scriptsDirectory, withIntermediateDirectories: true, attributes: nil)
129+
}
130+
131+
// Copy all registered custom scripts to the output directory.
132+
for customScript in context.registeredCustomScripts(forBundleID: bundleIdentifier) {
133+
try copyAsset(customScript, to: scriptsDirectory)
134+
}
123135

124136
// If the bundle contains a `header.html` file, inject a <template> into
125137
// the `index.html` file using its contents. This will only be done if
@@ -145,6 +157,16 @@ struct ConvertFileWritingConsumer: ConvertOutputConsumer {
145157
}
146158
try fileManager.copyItem(at: themeSettings, to: targetFile)
147159
}
160+
161+
// Copy the `custom-scripts.json` file into the output directory if one
162+
// is provided.
163+
if let customScripts = bundle.customScripts {
164+
let targetFile = targetFolder.appendingPathComponent(customScripts.lastPathComponent, isDirectory: false)
165+
if fileManager.fileExists(atPath: targetFile.path) {
166+
try fileManager.removeItem(at: targetFile)
167+
}
168+
try fileManager.copyItem(at: customScripts, to: targetFile)
169+
}
148170
}
149171

150172
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: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -13,46 +13,49 @@ 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+
test(whether: 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+
test(whether: 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+
test(whether: DocumentationBundleFileTypes.isThemeSettingsFile, matchesFilesNamed: "theme-settings", withExtension: "json")
25+
}
26+
27+
func testIsCustomScriptsFile() {
28+
test(whether: DocumentationBundleFileTypes.isCustomScriptsFile, matchesFilesNamed: "custom-scripts", withExtension: "json")
29+
}
30+
31+
private func test(
32+
whether predicate: (URL) -> Bool,
33+
matchesFilesNamed fileName: String,
34+
withExtension extension: String
35+
) {
36+
let fileNameWithExtension = "\(fileName).\(`extension`)"
37+
38+
let pathsThatShouldMatch = [
39+
fileNameWithExtension,
40+
"/\(fileNameWithExtension)",
41+
"DocC/docc/\(fileNameWithExtension)",
42+
"/a/b/\(fileNameWithExtension)"
43+
].map { URL(fileURLWithPath: $0) }
44+
45+
let pathsThatShouldNotMatch = [
46+
fileName,
47+
"/\(fileNameWithExtension)/foo",
48+
"/a/\(fileNameWithExtension)/bar",
49+
"\(fileName).wrongextension",
50+
"wrongname.\(`extension`)"
51+
].map { URL(fileURLWithPath: $0) }
52+
53+
for url in pathsThatShouldMatch {
54+
XCTAssertTrue(predicate(url))
55+
}
56+
57+
for url in pathsThatShouldNotMatch {
58+
XCTAssertFalse(predicate(url))
59+
}
5760
}
5861
}

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)

Tests/SwiftDocCUtilitiesTests/ConvertActionTests.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3108,6 +3108,7 @@ class ConvertActionTests: XCTestCase {
31083108

31093109
XCTAssertEqual(fileSystem.dump(subHierarchyFrom: targetURL.path), """
31103110
Output.doccarchive/
3111+
├─ custom-scripts/
31113112
├─ data/
31123113
│ ╰─ documentation/
31133114
│ ╰─ something.json

0 commit comments

Comments
 (0)