|
| 1 | +package org.commonmark.ext.gfm.alerts.internal; |
| 2 | + |
| 3 | +import org.commonmark.ext.gfm.alerts.Alert; |
| 4 | +import org.commonmark.ext.gfm.alerts.AlertTitle; |
| 5 | +import org.commonmark.node.Node; |
| 6 | +import org.commonmark.renderer.text.LineBreakRendering; |
| 7 | +import org.commonmark.renderer.text.TextContentNodeRendererContext; |
| 8 | +import org.commonmark.renderer.text.TextContentWriter; |
| 9 | + |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +public class AlertTextContentNodeRenderer extends AlertNodeRenderer { |
| 13 | + |
| 14 | + private final TextContentNodeRendererContext context; |
| 15 | + private final TextContentWriter textContent; |
| 16 | + private final Map<String, String> allowedTypes; |
| 17 | + |
| 18 | + public AlertTextContentNodeRenderer(TextContentNodeRendererContext context, Map<String, String> allowedTypes) { |
| 19 | + this.context = context; |
| 20 | + this.textContent = context.getWriter(); |
| 21 | + this.allowedTypes = allowedTypes; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + protected void renderAlert(Alert alert) { |
| 26 | + var type = alert.getType(); |
| 27 | + var defaultTitle = allowedTypes.get(type); |
| 28 | + if (defaultTitle == null) { |
| 29 | + throw new IllegalStateException("Unknown alert type: " + type); |
| 30 | + } |
| 31 | + |
| 32 | + var first = alert.getFirstChild(); |
| 33 | + if (first instanceof AlertTitle) { |
| 34 | + renderChildren(first); |
| 35 | + } else { |
| 36 | + textContent.write(defaultTitle); |
| 37 | + } |
| 38 | + |
| 39 | + if (alert.hasBody()) { |
| 40 | + if (context.lineBreakRendering() == LineBreakRendering.STRIP) { |
| 41 | + textContent.write(": "); |
| 42 | + } else { |
| 43 | + textContent.block(); |
| 44 | + } |
| 45 | + renderChildren(alert); |
| 46 | + } |
| 47 | + |
| 48 | + textContent.block(); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + protected void renderNode(Node node) { |
| 53 | + context.render(node); |
| 54 | + } |
| 55 | +} |
0 commit comments