Skip to content

Commit 8b4e6ba

Browse files
committed
8289332: Auto-generate ids for user-defined headings
Reviewed-by: jjg
1 parent 0fc9263 commit 8b4e6ba

File tree

5 files changed

+195
-11
lines changed

5 files changed

+195
-11
lines changed

src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlConfiguration.java

-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727

2828
import java.time.ZonedDateTime;
2929
import java.util.ArrayList;
30-
import java.util.Date;
3130
import java.util.EnumSet;
3231
import java.util.HashMap;
3332
import java.util.List;
@@ -44,7 +43,6 @@
4443
import javax.tools.JavaFileObject;
4544
import javax.tools.StandardJavaFileManager;
4645

47-
import com.sun.source.util.DocTreePath;
4846
import jdk.javadoc.doclet.Doclet;
4947
import jdk.javadoc.doclet.DocletEnvironment;
5048
import jdk.javadoc.doclet.Reporter;

src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java

+38-4
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ public class HtmlDocletWriter {
172172

173173
protected final HtmlIds htmlIds;
174174

175+
private final Set<String> headingIds = new HashSet<>();
176+
175177
/**
176178
* To check whether the repeated annotations is documented or not.
177179
*/
@@ -1203,10 +1205,6 @@ private boolean inAnAtag() {
12031205
return (tag instanceof StartElementTree st) && equalsIgnoreCase(st.getName(), "a");
12041206
}
12051207

1206-
private boolean equalsIgnoreCase(Name name, String s) {
1207-
return name != null && name.toString().equalsIgnoreCase(s);
1208-
}
1209-
12101208
@Override
12111209
public Boolean visitAttribute(AttributeTree node, Content content) {
12121210
if (!content.isEmpty()) {
@@ -1367,6 +1365,9 @@ public Boolean visitLiteral(LiteralTree node, Content content) {
13671365
@Override
13681366
public Boolean visitStartElement(StartElementTree node, Content content) {
13691367
Content attrs = new ContentBuilder();
1368+
if (node.getName().toString().matches("(?i)h[1-6]") && !hasIdAttribute(node)) {
1369+
generateHeadingId(node, trees, attrs);
1370+
}
13701371
for (DocTree dt : node.getAttributes()) {
13711372
dt.accept(this, attrs);
13721373
}
@@ -1436,6 +1437,39 @@ protected Boolean defaultAction(DocTree node, Content content) {
14361437
return result;
14371438
}
14381439

1440+
private boolean equalsIgnoreCase(Name name, String s) {
1441+
return name != null && name.toString().equalsIgnoreCase(s);
1442+
}
1443+
1444+
private boolean hasIdAttribute(StartElementTree node) {
1445+
return node.getAttributes().stream().anyMatch(
1446+
dt -> dt instanceof AttributeTree at && equalsIgnoreCase(at.getName(), "id"));
1447+
}
1448+
1449+
private void generateHeadingId(StartElementTree node, List<? extends DocTree> trees, Content content) {
1450+
StringBuilder sb = new StringBuilder();
1451+
String tagName = node.getName().toString().toLowerCase(Locale.ROOT);
1452+
for (DocTree docTree : trees.subList(trees.indexOf(node) + 1, trees.size())) {
1453+
if (docTree instanceof TextTree text) {
1454+
sb.append(text.getBody());
1455+
} else if (docTree instanceof LiteralTree literal) {
1456+
sb.append(literal.getBody().getBody());
1457+
} else if (docTree instanceof LinkTree link) {
1458+
var label = link.getLabel();
1459+
sb.append(label.isEmpty() ? link.getReference().getSignature() : label.toString());
1460+
} else if (docTree instanceof EndElementTree endElement
1461+
&& equalsIgnoreCase(endElement.getName(), tagName)) {
1462+
break;
1463+
} else if (docTree instanceof StartElementTree nested
1464+
&& equalsIgnoreCase(nested.getName(), "a")
1465+
&& hasIdAttribute(nested)) {
1466+
return; // Avoid generating id if embedded <a id=...> is present
1467+
}
1468+
}
1469+
HtmlId htmlId = htmlIds.forHeading(sb, headingIds);
1470+
content.add("id=\"").add(htmlId.name()).add("\"");
1471+
}
1472+
14391473
/**
14401474
* Returns true if relative links should be redirected.
14411475
*

src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlIds.java

+26
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import java.util.List;
2929
import java.util.Locale;
3030
import java.util.Map;
31+
import java.util.Set;
3132
import javax.lang.model.element.Element;
3233
import javax.lang.model.element.ExecutableElement;
3334
import javax.lang.model.element.PackageElement;
@@ -511,4 +512,29 @@ public HtmlId forPreviewSection(Element el) {
511512
public HtmlId forPage(Navigation.PageMode page) {
512513
return HtmlId.of(page.name().toLowerCase(Locale.ROOT).replace("_", "-"));
513514
}
515+
516+
/**
517+
* Returns an id for a heading in a doc comment. The id value is derived from the contents
518+
* of the heading with additional checks to make it unique within its containing page.
519+
*
520+
* @param headingText the text contained by the heading
521+
* @param headingIds the set of heading ids already generated for the current page
522+
* @return a unique id value for the heading
523+
*/
524+
public HtmlId forHeading(CharSequence headingText, Set<String> headingIds) {
525+
String idValue = headingText.toString()
526+
.toLowerCase(Locale.ROOT)
527+
.trim()
528+
.replaceAll("[^\\w_-]+", "-");
529+
// Make id value unique
530+
idValue = idValue + "-heading";
531+
if (!headingIds.add(idValue)) {
532+
int counter = 1;
533+
while (!headingIds.add(idValue + counter)) {
534+
counter++;
535+
}
536+
idValue = idValue + counter;
537+
}
538+
return HtmlId.of(idValue);
539+
}
514540
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/*
2+
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation.
8+
*
9+
* This code is distributed in the hope that it will be useful, but WITHOUT
10+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12+
* version 2 for more details (a copy is included in the LICENSE file that
13+
* accompanied this code).
14+
*
15+
* You should have received a copy of the GNU General Public License version
16+
* 2 along with this work; if not, write to the Free Software Foundation,
17+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18+
*
19+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20+
* or visit www.oracle.com if you need additional information or have any
21+
* questions.
22+
*/
23+
24+
/*
25+
* @test
26+
* @bug 8289332
27+
* @summary Auto-generate ids for user-defined headings
28+
* @library /tools/lib ../../lib
29+
* @modules jdk.javadoc/jdk.javadoc.internal.tool
30+
* @build javadoc.tester.* toolbox.ToolBox
31+
* @run main TestAutoHeaderId
32+
*/
33+
34+
import java.nio.file.Path;
35+
36+
import toolbox.ToolBox;
37+
38+
import javadoc.tester.JavadocTester;
39+
40+
public class TestAutoHeaderId extends JavadocTester {
41+
42+
public static void main(String... args) throws Exception {
43+
TestAutoHeaderId tester = new TestAutoHeaderId();
44+
tester.runTests();
45+
}
46+
47+
private final ToolBox tb;
48+
49+
TestAutoHeaderId() {
50+
tb = new ToolBox();
51+
}
52+
53+
@Test
54+
public void testAutoHeaderId(Path base) throws Exception {
55+
Path src = base.resolve("src");
56+
tb.writeJavaFiles(src,
57+
"""
58+
package p;
59+
/**
60+
* First sentence.
61+
*
62+
* <h2>First Header</h2>
63+
*
64+
* <h3 id="fixed-id-1">Header with ID</h3>
65+
*
66+
* <h4><a id="fixed-id-2">Embedded A-Tag with ID</a></h4>
67+
*
68+
* <h5>{@code Embedded Code Tag}</h5>
69+
*
70+
* <h6>{@linkplain C Embedded Link Tag}</h6>
71+
*
72+
* <h3>Duplicate Text</h3>
73+
*
74+
* <h4>Duplicate Text</h4>
75+
*
76+
* <h2>Extra (#*!. chars</h2>
77+
*
78+
* <h3 style="color: red;" class="some-class">Other attributes</h3>
79+
*
80+
* <h4></h4>
81+
*
82+
* Last sentence.
83+
*/
84+
public class C {
85+
/** Comment. */
86+
C() { }
87+
}
88+
""");
89+
90+
javadoc("-d", base.resolve("api").toString(),
91+
"-sourcepath", src.toString(),
92+
"--no-platform-links", "p");
93+
94+
checkOutput("p/C.html", true,
95+
"""
96+
<h2 id="first-header-heading">First Header</h2>
97+
""",
98+
"""
99+
<h3 id="fixed-id-1">Header with ID</h3>
100+
""",
101+
"""
102+
<h4><a id="fixed-id-2">Embedded A-Tag with ID</a></h4>
103+
""",
104+
"""
105+
<h5 id="embedded-code-tag-heading"><code>Embedded Code Tag</code></h5>
106+
""",
107+
"""
108+
<h6 id="embedded-link-tag-heading"><a href="C.html" title="class in p">Embedded Link Tag</a></h6>
109+
""",
110+
"""
111+
<h3 id="duplicate-text-heading">Duplicate Text</h3>
112+
""",
113+
"""
114+
<h4 id="duplicate-text-heading1">Duplicate Text</h4>
115+
""",
116+
"""
117+
<h2 id="extra-chars-heading">Extra (#*!. chars</h2>
118+
""",
119+
"""
120+
<h3 id="other-attributes-heading" style="color: red;" class="some-class">Other attributes</h3>
121+
""",
122+
"""
123+
<h4 id="-heading"></h4>
124+
""");
125+
}
126+
}

test/langtools/jdk/javadoc/doclet/testIndexInDocFiles/TestIndexInDocFiles.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -100,13 +100,13 @@ public void testPackageDocFiles(Path base) throws IOException {
100100

101101
checkOutput("doc-files/top-level-file.html", true,
102102
"""
103-
<h1>Package HTML file</h1>
103+
<h1 id="package-html-file-heading">Package HTML file</h1>
104104
<span id="top-level-index" class="search-tag-result">top-level-index</span>
105105
<code><span id="top.level.property" class="search-tag-result">top.level.property</span></code>
106106
""");
107107
checkOutput("p/q/doc-files/package-file.html", true,
108108
"""
109-
<h1>Package HTML file</h1>
109+
<h1 id="package-html-file-heading">Package HTML file</h1>
110110
<span id="package-index" class="search-tag-result">package-index</span>
111111
<code><span id="package.property" class="search-tag-result">package.property</span></code>
112112
""");
@@ -170,13 +170,13 @@ public void testModuleDocFiles(Path base) throws IOException {
170170

171171
checkOutput("m.n/doc-files/module-file.html", true,
172172
"""
173-
<h1>Module HTML file</h1>
173+
<h1 id="module-html-file-heading">Module HTML file</h1>
174174
<span id="module-index" class="search-tag-result">module-index</span>
175175
<code><span id="module.property" class="search-tag-result">module.property</span></code>
176176
""");
177177
checkOutput("m.n/p/q/doc-files/package-file.html", true,
178178
"""
179-
<h1>Package HTML file</h1>
179+
<h1 id="package-html-file-heading">Package HTML file</h1>
180180
<span id="package-index" class="search-tag-result">package-index</span>
181181
<code><span id="package.property" class="search-tag-result">package.property</span></code>
182182
""");

0 commit comments

Comments
 (0)