Skip to content

Commit 949508f

Browse files
committed
Add support for custom scripts
1 parent 1c05ea6 commit 949508f

File tree

10 files changed

+192
-54
lines changed

10 files changed

+192
-54
lines changed

Sources/SwiftDocC/Infrastructure/DocumentationBundle.swift

+7-17
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,9 @@ public struct DocumentationBundle {
9090
/// A custom JSON settings file used to theme renderer output.
9191
public let themeSettings: URL?
9292

93+
/// A custom JSON settings file used to add custom scripts to the renderer output.
94+
public let customScripts: URL?
95+
9396
/**
9497
A URL prefix to be appended to the relative presentation URL.
9598

@@ -108,6 +111,7 @@ public struct DocumentationBundle {
108111
/// - customHeader: A custom HTML file to use as the header for rendered output.
109112
/// - customFooter: A custom HTML file to use as the footer for rendered output.
110113
/// - 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.
111115
public init(
112116
info: Info,
113117
baseURL: URL = URL(string: "/")!,
@@ -116,7 +120,8 @@ public struct DocumentationBundle {
116120
miscResourceURLs: [URL],
117121
customHeader: URL? = nil,
118122
customFooter: URL? = nil,
119-
themeSettings: URL? = nil
123+
themeSettings: URL? = nil,
124+
customScripts: URL? = nil
120125
) {
121126
self.info = info
122127
self.baseURL = baseURL
@@ -126,29 +131,14 @@ public struct DocumentationBundle {
126131
self.customHeader = customHeader
127132
self.customFooter = customFooter
128133
self.themeSettings = themeSettings
134+
self.customScripts = customScripts
129135
self.rootReference = ResolvedTopicReference(bundleIdentifier: info.identifier, path: "/", sourceLanguage: .swift)
130136
self.documentationRootReference = ResolvedTopicReference(bundleIdentifier: info.identifier, path: NodeURLGenerator.Path.documentationFolder, sourceLanguage: .swift)
131137
self.tutorialsRootReference = ResolvedTopicReference(bundleIdentifier: info.identifier, path: NodeURLGenerator.Path.tutorialsFolder, sourceLanguage: .swift)
132138
self.technologyTutorialsRootReference = tutorialsRootReference.appendingPath(urlReadablePath(info.displayName))
133139
self.articlesDocumentationRootReference = documentationRootReference.appendingPath(urlReadablePath(info.displayName))
134140
}
135141

136-
@available(*, deprecated, renamed: "init(info:baseURL:symbolGraphURLs:markupURLs:miscResourceURLs:customHeader:customFooter:themeSettings:)", message: "Use 'init(info:baseURL:symbolGraphURLs:markupURLs:miscResourceURLs:customHeader:customFooter:themeSettings:)' instead. This deprecated API will be removed after 6.1 is released")
137-
public init(
138-
info: Info,
139-
baseURL: URL = URL(string: "/")!,
140-
attributedCodeListings: [String: AttributedCodeListing] = [:],
141-
symbolGraphURLs: [URL],
142-
markupURLs: [URL],
143-
miscResourceURLs: [URL],
144-
customHeader: URL? = nil,
145-
customFooter: URL? = nil,
146-
themeSettings: URL? = nil
147-
) {
148-
self.init(info: info, baseURL: baseURL, symbolGraphURLs: symbolGraphURLs, markupURLs: markupURLs, miscResourceURLs: miscResourceURLs, customHeader: customHeader, customFooter: customFooter, themeSettings: themeSettings)
149-
self.attributedCodeListings = attributedCodeListings
150-
}
151-
152142
public private(set) var rootReference: ResolvedTopicReference
153143

154144
/// Default path to resolve symbol links.

Sources/SwiftDocC/Infrastructure/DocumentationBundleFileTypes.swift

+8
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

+9
Original file line numberDiff line numberDiff line change
@@ -1649,6 +1649,7 @@ public class DocumentationContext: DocumentationContextDataProviderDelegate {
16491649

16501650
private static let supportedImageExtensions: Set<String> = ["png", "jpg", "jpeg", "svg", "gif"]
16511651
private static let supportedVideoExtensions: Set<String> = ["mov", "mp4"]
1652+
private static let supportedScriptExtensions: Set<String> = ["js"]
16521653

16531654
// TODO: Move this functionality to ``DocumentationBundleFileTypes`` (rdar://68156425).
16541655

@@ -1729,6 +1730,14 @@ public class DocumentationContext: DocumentationContextDataProviderDelegate {
17291730
public func registeredDownloadsAssets(forBundleID bundleIdentifier: BundleIdentifier) -> [DataAsset] {
17301731
return registeredAssets(inContexts: [DataAsset.Context.download], forBundleID: bundleIdentifier)
17311732
}
1733+
1734+
/// Returns a list of all the custom scripts that registered for a given `bundleIdentifier`.
1735+
///
1736+
/// - Parameter bundleIdentifier: The identifier of the bundle to return download assets for.
1737+
/// - Returns: A list of all the custom scripts for the given bundle.
1738+
public func registeredCustomScripts(forBundleID bundleIdentifier: BundleIdentifier) -> [DataAsset] {
1739+
return registeredAssets(withExtensions: DocumentationContext.supportedScriptExtensions, forBundleID: bundleIdentifier)
1740+
}
17321741

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

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

+7-1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ extension LocalFileSystemDataProvider {
8282
let customHeader = findCustomHeader(bundleChildren)?.url
8383
let customFooter = findCustomFooter(bundleChildren)?.url
8484
let themeSettings = findThemeSettings(bundleChildren)?.url
85+
let customScripts = findCustomScripts(bundleChildren)?.url
8586

8687
return DocumentationBundle(
8788
info: info,
@@ -90,7 +91,8 @@ extension LocalFileSystemDataProvider {
9091
miscResourceURLs: miscResources,
9192
customHeader: customHeader,
9293
customFooter: customFooter,
93-
themeSettings: themeSettings
94+
themeSettings: themeSettings,
95+
customScripts: customScripts
9496
)
9597
}
9698

@@ -139,6 +141,10 @@ extension LocalFileSystemDataProvider {
139141
private func findThemeSettings(_ bundleChildren: [FSNode]) -> FSNode.File? {
140142
return bundleChildren.firstFile { DocumentationBundleFileTypes.isThemeSettingsFile($0.url) }
141143
}
144+
145+
private func findCustomScripts(_ bundleChildren: [FSNode]) -> FSNode.File? {
146+
return bundleChildren.firstFile { DocumentationBundleFileTypes.isCustomScriptsFile($0.url) }
147+
}
142148
}
143149

144150
fileprivate extension [FSNode] {
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

+22
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,18 @@ struct ConvertFileWritingConsumer: ConvertOutputConsumer {
120120
for downloadAsset in context.registeredDownloadsAssets(forBundleID: bundleIdentifier) {
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

+1
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

+38-35
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

+1-1
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

+1
Original file line numberDiff line numberDiff line change
@@ -3251,6 +3251,7 @@ class ConvertActionTests: XCTestCase {
32513251

32523252
XCTAssertEqual(fileSystem.dump(subHierarchyFrom: targetURL.path), """
32533253
Output.doccarchive/
3254+
├─ custom-scripts/
32543255
├─ data/
32553256
│ ╰─ documentation/
32563257
│ ╰─ something.json

0 commit comments

Comments
 (0)