Skip to content

Commit

Permalink
8317621: --add-script should support JavaScript modules
Browse files Browse the repository at this point in the history
Reviewed-by: jjg
  • Loading branch information
hns committed May 17, 2024
1 parent 4eb1eaf commit 9bb6169
Show file tree
Hide file tree
Showing 3 changed files with 206 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@

package jdk.javadoc.internal.doclets.formats.html;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.time.ZonedDateTime;
Expand All @@ -41,6 +44,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
Expand All @@ -64,6 +68,7 @@
import jdk.javadoc.internal.doclets.toolkit.Resources;
import jdk.javadoc.internal.doclets.toolkit.util.DeprecatedAPIListBuilder;
import jdk.javadoc.internal.doclets.toolkit.util.DocFile;
import jdk.javadoc.internal.doclets.toolkit.util.DocFileIOException;
import jdk.javadoc.internal.doclets.toolkit.util.DocPath;
import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;
import jdk.javadoc.internal.doclets.toolkit.util.NewAPIBuilder;
Expand Down Expand Up @@ -198,6 +203,18 @@ public enum ConditionalPage {
*/
private final Set<PackageElement> containingPackagesSeen;

/**
* List of additional JavaScript files
*/
private List<JavaScriptFile> additionalScripts;

/**
* Record for JavaScript file and module flag.
* @param path file path
* @param isModule module flag
*/
public record JavaScriptFile(DocPath path, boolean isModule) {}

/**
* Constructs the full configuration needed by the doclet, including
* the format-specific part, defined in this class, and the format-independent
Expand Down Expand Up @@ -316,6 +333,9 @@ public boolean finishOptionSettings() {
}
}
}
additionalScripts = options.additionalScripts().stream()
.map(this::detectJSModule)
.collect(Collectors.toList());
if (options.createIndex()) {
indexBuilder = new HtmlIndexBuilder(this);
}
Expand All @@ -326,6 +346,26 @@ public boolean finishOptionSettings() {
return true;
}

private JavaScriptFile detectJSModule(String fileName) {
DocFile file = DocFile.createFileForInput(this, fileName);
boolean isModule = fileName.toLowerCase(Locale.ROOT).endsWith(".mjs");
if (!isModule) {
// Regex to detect JavaScript modules
Pattern modulePattern = Pattern.compile("""
(?:^|[;}])\\s*(?:\
import\\s*["']|\
import[\\s{*][^()]*from\\s*["']|\
export(?:\\s+(?:let|const|function|class|var|default|async)|\\s*[{*]))""");
try (InputStream in = file.openInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
isModule = reader.lines().anyMatch(s -> modulePattern.matcher(s).find());
} catch (DocFileIOException | IOException e) {
// Errors are handled when copying resources
}
}
return new JavaScriptFile(DocPath.create(file.getName()), isModule);
}

/**
* {@return the date to be recorded in generated files}
*/
Expand Down Expand Up @@ -421,11 +461,8 @@ public List<DocPath> getAdditionalStylesheets() {
.collect(Collectors.toCollection(ArrayList::new));
}

public List<DocPath> getAdditionalScripts() {
return options.additionalScripts().stream()
.map(sf -> DocFile.createFileForInput(this, sf))
.map(file -> DocPath.create(file.getName()))
.collect(Collectors.toCollection(ArrayList::new));
public List<JavaScriptFile> getAdditionalScripts() {
return additionalScripts;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.Locale;

import jdk.javadoc.internal.doclets.formats.html.Content;
import jdk.javadoc.internal.doclets.formats.html.HtmlConfiguration;
import jdk.javadoc.internal.doclets.toolkit.util.DocPath;
import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;

Expand All @@ -60,7 +61,7 @@ public class Head extends Content {
private Script mainBodyScript;
private final List<Script> scripts;
// Scripts added via --add-script option
private List<DocPath> additionalScripts = List.of();
private List<HtmlConfiguration.JavaScriptFile> additionalScripts = List.of();
private final List<Content> extraContent;
private boolean addDefaultScript = true;
private DocPath canonicalLink;
Expand Down Expand Up @@ -176,7 +177,7 @@ public Head setStylesheets(DocPath main, List<DocPath> additional, List<DocPath>
* @param scripts the list of additional script files
* @return this object
*/
public Head setAdditionalScripts(List<DocPath> scripts) {
public Head setAdditionalScripts(List<HtmlConfiguration.JavaScriptFile> scripts) {
this.additionalScripts = scripts;
return this;
}
Expand Down Expand Up @@ -346,7 +347,7 @@ private void addStylesheet(HtmlTree head, DocPath stylesheet) {

private void addScripts(HtmlTree head) {
if (addDefaultScript) {
addScriptElement(head, DocPaths.SCRIPT_FILES.resolve(DocPaths.SCRIPT_JS));
addScriptElement(head, DocPaths.SCRIPT_JS);
}
if (index) {
if (pathToRoot != null && mainBodyScript != null) {
Expand All @@ -356,19 +357,25 @@ private void addScripts(HtmlTree head) {
.append(";\n")
.append("loadScripts(document, 'script');");
}
addScriptElement(head, DocPaths.SCRIPT_FILES.resolve(DocPaths.JQUERY_JS));
addScriptElement(head, DocPaths.SCRIPT_FILES.resolve(DocPaths.JQUERY_UI_JS));
addScriptElement(head, DocPaths.JQUERY_JS);
addScriptElement(head, DocPaths.JQUERY_UI_JS);
}
for (DocPath path : additionalScripts) {
addScriptElement(head, DocPaths.SCRIPT_FILES.resolve(path));
for (HtmlConfiguration.JavaScriptFile javaScriptFile : additionalScripts) {
addScriptElement(head, javaScriptFile);
}
for (Script script : scripts) {
head.add(script.asContent());
}
}

private void addScriptElement(HtmlTree head, DocPath filePath) {
DocPath scriptFile = pathToRoot.resolve(filePath);
DocPath scriptFile = pathToRoot.resolve(DocPaths.SCRIPT_FILES).resolve(filePath);
head.add(HtmlTree.SCRIPT(scriptFile.getPath()));
}

private void addScriptElement(HtmlTree head, HtmlConfiguration.JavaScriptFile script) {
DocPath scriptFile = pathToRoot.resolve(DocPaths.SCRIPT_FILES).resolve(script.path());
HtmlTree scriptTag = HtmlTree.SCRIPT(scriptFile.getPath());
head.add(script.isModule() ? scriptTag.put(HtmlAttr.TYPE, "module") : scriptTag);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8317621
* @summary --add-script should support JavaScript modules
* @library /tools/lib ../../lib
* @modules jdk.javadoc/jdk.javadoc.internal.tool
* @build toolbox.ToolBox javadoc.tester.*
* @run main TestJavaScriptModules
*/

import java.io.IOException;
import java.nio.file.Path;

import javadoc.tester.JavadocTester;
import toolbox.ToolBox;

public class TestJavaScriptModules extends JavadocTester {

public static void main(String... args) throws Exception {
var tester = new TestJavaScriptModules();
tester.setup().runTests();
}

private final ToolBox tb = new ToolBox();
Path src;

TestJavaScriptModules setup() throws IOException {
src = Path.of("src");
tb.writeJavaFiles(src, """
/**
* Simple dummy class.
*/
public class Test {}
""");
tb.writeFile("module.mjs", """
var x = 1;
""");
tb.writeFile("module1.js", """
const x = 1;
export class FooModule {}
""");
tb.writeFile("module2.js", """
const x = 1;
export function f() {}
""");
tb.writeFile("module3.js", """
const x = 1;
export async function a() {}
""");
tb.writeFile("module4.js", """
// Another JS module
export const c = 3;
""");
tb.writeFile("module5.js", """
export default class FooModule {}
""");
tb.writeFile("module6.js", """
const x = 1;
export class FooModule {}
""");
tb.writeFile("module7.js", """
function abc() {}
import * as foo from "module1.js";
""");
tb.writeFile("module8.js", """
var z = false;
import { _A_, $b, C0 } from "abc.js";
""");
tb.writeFile("script1.js", """
var z = false;
import(1, z);
""");
tb.writeFile("script2.js", """
export("foo");
""");
tb.writeFile("script3.js", """
var import = 1;
""");
return this;
}

@Test
public void test(Path base) {
javadoc("-d", base.resolve("out").toString(),
"--add-script", "module.mjs",
"--add-script", "module1.js",
"--add-script", "module2.js",
"--add-script", "module3.js",
"--add-script", "module4.js",
"--add-script", "module5.js",
"--add-script", "module6.js",
"--add-script", "module7.js",
"--add-script", "module8.js",
"--add-script", "script1.js",
"--add-script", "script2.js",
"--add-script", "script3.js",
src.resolve("Test.java").toString());
checkExit(Exit.OK);

checkOutput("Test.html", true,
"""
<script type="module" src="script-files/module.mjs"></script>""",
"""
<script type="module" src="script-files/module1.js"></script>""",
"""
<script type="module" src="script-files/module2.js"></script>""",
"""
<script type="module" src="script-files/module3.js"></script>""",
"""
<script type="module" src="script-files/module4.js"></script>""",
"""
<script type="module" src="script-files/module5.js"></script>""",
"""
<script type="module" src="script-files/module6.js"></script>""",
"""
<script type="module" src="script-files/module7.js"></script>""",
"""
<script type="module" src="script-files/module8.js"></script>""",
"""
<script type="text/javascript" src="script-files/script1.js"></script>""",
"""
<script type="text/javascript" src="script-files/script2.js"></script>""",
"""
<script type="text/javascript" src="script-files/script3.js"></script>""");
}
}

1 comment on commit 9bb6169

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.