|
2 | 2 |
|
3 | 3 | import org.commonmark.ext.gfm.alerts.Alert; |
4 | 4 | import org.commonmark.ext.gfm.alerts.AlertTitle; |
| 5 | +import org.commonmark.node.HtmlInline; |
5 | 6 | import org.commonmark.node.Node; |
| 7 | +import org.commonmark.node.Text; |
6 | 8 | import org.commonmark.renderer.html.HtmlNodeRendererContext; |
7 | 9 | import org.commonmark.renderer.html.HtmlWriter; |
8 | 10 |
|
@@ -38,6 +40,21 @@ protected void renderAlert(Alert alert) { |
38 | 40 | htmlWriter.tag("p", context.extendAttributes(alert, "p", Map.of("class", "markdown-alert-title"))); |
39 | 41 | var first = alert.getFirstChild(); |
40 | 42 | if (first instanceof AlertTitle) { |
| 43 | + /* |
| 44 | + * If the alert title only contains HTML comments like this: |
| 45 | + * |
| 46 | + * > [!TIP] <!-- This won't appear --> <!---> <!-- Neither will this --> |
| 47 | + * > Body text |
| 48 | + * |
| 49 | + * Then the reader will see a blank title. In this case, it's better |
| 50 | + * to render the default title (but keep the comments for accuracy). |
| 51 | + * |
| 52 | + * These comments will be visible when rendered to other formats like |
| 53 | + * Markdown, so this is only relevant for the HTML renderer. |
| 54 | + */ |
| 55 | + if (isCommentOnlyTitle(first)) { |
| 56 | + htmlWriter.text(getAlertTitle(type)); |
| 57 | + } |
41 | 58 | renderChildren(first); |
42 | 59 | } else { |
43 | 60 | htmlWriter.text(getAlertTitle(type)); |
@@ -73,6 +90,38 @@ private String getAlertTitle(String type) { |
73 | 90 | } |
74 | 91 | } |
75 | 92 |
|
| 93 | + private boolean isCommentOnlyTitle(Node title) { |
| 94 | + var node = title.getFirstChild(); |
| 95 | + if (node == null) { |
| 96 | + return false; |
| 97 | + } |
| 98 | + while (node != null) { |
| 99 | + if (node instanceof HtmlInline) { |
| 100 | + if (!isHtmlComment((HtmlInline) node)) { |
| 101 | + return false; |
| 102 | + } |
| 103 | + } else if (node instanceof Text) { |
| 104 | + if (!((Text) node).getLiteral().trim().isEmpty()) { |
| 105 | + return false; |
| 106 | + } |
| 107 | + } else { |
| 108 | + return false; |
| 109 | + } |
| 110 | + node = node.getNext(); |
| 111 | + } |
| 112 | + return true; |
| 113 | + } |
| 114 | + |
| 115 | + private boolean isHtmlComment(HtmlInline htmlInline) { |
| 116 | + String literal = htmlInline.getLiteral(); |
| 117 | + if (literal == null || !literal.startsWith("<!--")) { |
| 118 | + return false; |
| 119 | + } |
| 120 | + return literal.equals("<!-->") |
| 121 | + || literal.equals("<!--->") |
| 122 | + || literal.endsWith("-->"); |
| 123 | + } |
| 124 | + |
76 | 125 | private void renderChildren(Node parent) { |
77 | 126 | var node = parent.getFirstChild(); |
78 | 127 | while (node != null) { |
|
0 commit comments