not-pretty xhtml gets line breaks before block tags to keep line length down (work around a jekyll issue)

This commit is contained in:
Grahame Grieve 2024-04-03 20:14:05 +11:00
parent 0d57115ede
commit 364a2aeec4
1 changed files with 33 additions and 3 deletions

View File

@ -38,7 +38,7 @@ import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Set;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xml.IXMLWriter;
@ -46,6 +46,7 @@ import org.w3c.dom.Element;
public class XhtmlComposer {
protected static Set<String> BLOCK_NAMES = Set.of("li", "ul", "ol", "tr", "td", "th", "div", "table");
public static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
private boolean pretty;
private boolean xml;
@ -69,13 +70,38 @@ public class XhtmlComposer {
private Writer dst;
public String compose(XhtmlDocument doc) throws IOException {
if (!xml && !pretty) {
breakBlocksWithLines(doc);
}
StringWriter sdst = new StringWriter();
dst = sdst;
composeDoc(doc);
return sdst.toString();
}
private void breakBlocksWithLines(XhtmlNode node) {
if (node.hasChildren()) {
breakBlocksWithLines(node.getChildNodes());
}
}
private void breakBlocksWithLines(List<XhtmlNode> list) {
for (int i = list.size() -1; i > 0; i--) {
XhtmlNode node = list.get(i);
if (node.getNodeType() == NodeType.Element && BLOCK_NAMES.contains(node.getName())) {
XhtmlNode prev = list.get(i-1);
if (prev.getNodeType() != NodeType.Text || prev.getContent() == null || !(prev.getContent().endsWith("\r") || prev.getValue().endsWith("\n"))) {
list.add(i, new XhtmlNode(NodeType.Text).setContent("\r\n"));
}
}
breakBlocksWithLines(node);
}
}
public String compose(XhtmlNode node) throws IOException {
if (!xml && !pretty) {
breakBlocksWithLines(node);
}
StringWriter sdst = new StringWriter();
dst = sdst;
writeNode("", node, false);
@ -83,6 +109,9 @@ public class XhtmlComposer {
}
public String compose(List<XhtmlNode> nodes) throws IOException {
if (!xml && !pretty) {
breakBlocksWithLines(nodes);
}
StringWriter sdst = new StringWriter();
dst = sdst;
for (XhtmlNode node : nodes) {
@ -100,6 +129,9 @@ public class XhtmlComposer {
}
private void composeDoc(XhtmlDocument doc) throws IOException {
if (!xml) {
breakBlocksWithLines(doc);
}
// headers....
// dst.append("<html>" + (pretty ? "\r\n" : ""));
for (XhtmlNode c : doc.getChildNodes()) {
@ -128,8 +160,6 @@ public class XhtmlComposer {
}
}
private boolean isValidUrlChar(char c) {
return Character.isAlphabetic(c) || Character.isDigit(c) || Utilities.existsInList(c, ';', ',', '/', '?', ':', '@', '&', '=', '+', '$', '-', '_', '.', '!', '~', '*', '\'', '(', ')');
}