Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: MarkDown supports footnote rendering #1406

Merged
merged 9 commits into from
Jun 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ ext {
huaweiObsVersion = "3.19.7"
templateInheritanceVersion = "0.4.RELEASE"
jsoupVersion = "1.13.1"
byteBuddyAgentVersion = "1.10.22"
}

dependencies {
Expand Down Expand Up @@ -141,12 +142,15 @@ dependencies {
implementation "com.vladsch.flexmark:flexmark-ext-superscript:$flexmarkVersion"
implementation "com.vladsch.flexmark:flexmark-ext-yaml-front-matter:$flexmarkVersion"
implementation "com.vladsch.flexmark:flexmark-ext-gitlab:$flexmarkVersion"
implementation "com.vladsch.flexmark:flexmark-ext-footnotes:$flexmarkVersion"


implementation "kr.pe.kwonnam.freemarker:freemarker-template-inheritance:$templateInheritanceVersion"
implementation "net.coobird:thumbnailator:$thumbnailatorVersion"
implementation "net.sf.image4j:image4j:$image4jVersion"
implementation "org.flywaydb:flyway-core:$flywayVersion"
implementation "com.google.zxing:core:$zxingVersion"
implementation "net.bytebuddy:byte-buddy-agent:$byteBuddyAgentVersion"

implementation "org.iq80.leveldb:leveldb:$levelDbVersion"
runtimeOnly "com.h2database:h2:$h2Version"
Expand Down
219 changes: 219 additions & 0 deletions src/main/java/run/halo/app/utils/FootnoteNodeRendererInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
package run.halo.app.utils;

import com.vladsch.flexmark.ast.Link;
import com.vladsch.flexmark.ast.LinkNodeBase;
import com.vladsch.flexmark.ext.footnotes.Footnote;
import com.vladsch.flexmark.ext.footnotes.FootnoteBlock;
import com.vladsch.flexmark.ext.footnotes.internal.FootnoteNodeRenderer;
import com.vladsch.flexmark.ext.footnotes.internal.FootnoteOptions;
import com.vladsch.flexmark.ext.footnotes.internal.FootnoteRepository;
import com.vladsch.flexmark.html.HtmlWriter;
import com.vladsch.flexmark.html.renderer.NodeRendererContext;
import com.vladsch.flexmark.html.renderer.RenderingPhase;
import com.vladsch.flexmark.util.ast.Document;
import com.vladsch.flexmark.util.ast.NodeVisitor;
import com.vladsch.flexmark.util.ast.VisitHandler;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import java.lang.reflect.Field;
import java.util.Locale;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Argument;
import net.bytebuddy.implementation.bind.annotation.FieldValue;
import net.bytebuddy.matcher.ElementMatchers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.yaml.snakeyaml.nodes.SequenceNode;

/**
* <code>Flexmark</code> footnote node render interceptor.
* Delegate the render method to intercept the FootNoteNodeRender by ByteBuddy runtime.
*
* @author guqing
* @date 2021-06-26
*/
public class FootnoteNodeRendererInterceptor {
guqing marked this conversation as resolved.
Show resolved Hide resolved

/**
* Delegate the render method to intercept the FootNoteNodeRender by ByteBuddy runtime.
*/
public static void doDelegationMethod() {
ByteBuddyAgent.install();
new ByteBuddy()
.redefine(FootnoteNodeRenderer.class)

.method(ElementMatchers.named("render").and(ElementMatchers.takesArguments(
Footnote.class, NodeRendererContext.class, HtmlWriter.class)))
.intercept(MethodDelegation.to(FootnoteNodeRendererInterceptor.class))

.method(ElementMatchers.named("renderDocument"))
.intercept(MethodDelegation.to(FootnoteNodeRendererInterceptor.class))

.make()
.load(Thread.currentThread().getContextClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
}

/**
* footnote render see {@link FootnoteNodeRenderer#renderDocument}.
*
* @param node footnote node
* @param context node renderer context
* @param html html writer
*/
public static void render(Footnote node, NodeRendererContext context, HtmlWriter html) {
FootnoteBlock footnoteBlock = node.getFootnoteBlock();
if (footnoteBlock == null) {
//just text
html.raw("[^");
context.renderChildren(node);
html.raw("]");
} else {
int footnoteOrdinal = footnoteBlock.getFootnoteOrdinal();
int i = node.getReferenceOrdinal();

html.attr("class", "footnote-ref");
html.srcPos(node.getChars()).withAttr()
.tag("sup", false, false, () -> {
// if (!options.footnoteLinkRefClass.isEmpty()) html.attr("class", options
// .footnoteLinkRefClass);
String ordinal = footnoteOrdinal + (i == 0 ? "" : String.format(Locale.US,
":%d", i));
html.attr("id", "fnref"
+ ordinal);
html.attr("href", "#fn" + footnoteOrdinal);
html.withAttr().tag("a");
html.raw("[" + ordinal + "]");
html.tag("/a");
});
}
}

/**
* render document.
*
* @param footnoteRepository footnoteRepository field of FootNoteRenderer class
* @param options options field of FootNoteRenderer class
* @param recheckUndefinedReferences recheckUndefinedReferences field of FootNoteRenderer class
* @param context node render context
* @param html html writer
* @param document document
* @param phase rendering phase
*/
public static void renderDocument(@FieldValue("footnoteRepository")
FootnoteRepository footnoteRepository,
@FieldValue("options") FootnoteOptions options,
@FieldValue("recheckUndefinedReferences")
boolean recheckUndefinedReferences,
@Argument(0) NodeRendererContext context,
@Argument(1) HtmlWriter html, @Argument(2) Document document,
@Argument(3)
RenderingPhase phase) {
final String footnoteBackLinkRefClass =
(String) getFootnoteOptionsFieldValue("footnoteBackLinkRefClass", options);
final String footnoteBackRefString = ObjectUtils
.getDisplayString(getFootnoteOptionsFieldValue("footnoteBackRefString", options));

if (phase == RenderingPhase.BODY_TOP) {
if (recheckUndefinedReferences) {
// need to see if have undefined footnotes that were defined after parsing
boolean[] hadNewFootnotes = {false};
NodeVisitor visitor = new NodeVisitor(
new VisitHandler<>(Footnote.class, node -> {
if (!node.isDefined()) {
FootnoteBlock footonoteBlock =
node.getFootnoteBlock(footnoteRepository);

if (footonoteBlock != null) {
footnoteRepository.addFootnoteReference(footonoteBlock, node);
node.setFootnoteBlock(footonoteBlock);
hadNewFootnotes[0] = true;
}
}
})
);

visitor.visit(document);
if (hadNewFootnotes[0]) {
footnoteRepository.resolveFootnoteOrdinals();
}
}
}

if (phase == RenderingPhase.BODY_BOTTOM) {
// here we dump the footnote blocks that were referenced in the document body, ie.
// ones with footnoteOrdinal > 0
if (footnoteRepository.getReferencedFootnoteBlocks().size() > 0) {
html.attr("class", "footnotes-sep").withAttr().tagVoid("hr");
html.attr("class", "footnotes").withAttr().tagIndent("section", () -> {
html.attr("class", "footnotes-list").withAttr().tagIndent("ol", () -> {
for (FootnoteBlock footnoteBlock : footnoteRepository
.getReferencedFootnoteBlocks()) {
int footnoteOrdinal = footnoteBlock.getFootnoteOrdinal();
html.attr("id", "fn" + footnoteOrdinal)
.attr("class", "footnote-item");
html.withAttr().tagIndent("li", () -> {
context.renderChildren(footnoteBlock);
int lineIndex = html.getLineCount() - 1;
BasedSequence line = html.getLine(lineIndex);
if (line.lastIndexOf("</p>") > -1) {
int iMax = footnoteBlock.getFootnoteReferences();
for (int i = 0; i < iMax; i++) {
StringBuilder sb = new StringBuilder();
sb.append(" <a href=\"#fnref").append(footnoteOrdinal)
.append(i == 0 ? "" : String
.format(Locale.US, ":%d", i)).append("\"");
if (StringUtils.isNotBlank(footnoteBackLinkRefClass)) {
sb.append(" class=\"").append(footnoteBackLinkRefClass)
.append("\"");
}
sb.append(">").append(footnoteBackRefString).append("</a>");
html.setLine(html.getLineCount() - 1, "",
line.insert(line.lastIndexOf("</p"), sb.toString()));
}
} else {
int iMax = footnoteBlock.getFootnoteReferences();
for (int i = 0; i < iMax; i++) {
html.attr("href", "#fnref" + footnoteOrdinal
+ (i == 0 ? "" : String.format(Locale.US, ":%d", i)));
if (StringUtils.isNotBlank(footnoteBackLinkRefClass)) {
html.attr("class", footnoteBackLinkRefClass);
}
html.line().withAttr().tag("a");
html.raw(footnoteBackRefString);
html.tag("/a");
}
}
});
}
});
});
}
}
}

/**
* Gets field value from FootnoteOptions.
*
* @param fieldName field name of FootNoteOptions class, must not be null.
* @param options target object, must not be null.
* @return field value.
*/
private static Object getFootnoteOptionsFieldValue(String fieldName, FootnoteOptions options) {
Assert.notNull(fieldName, "FieldName must not be null");
Assert.notNull(options, "FootnoteOptions type must not be null");

Object value = null;
try {
Field field = FootnoteOptions.class.getDeclaredField(fieldName);
field.setAccessible(true);
value = field.get(options);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return value;
}
}
7 changes: 6 additions & 1 deletion src/main/java/run/halo/app/utils/MarkdownUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.vladsch.flexmark.ext.emoji.EmojiImageType;
import com.vladsch.flexmark.ext.emoji.EmojiShortcutType;
import com.vladsch.flexmark.ext.escaped.character.EscapedCharacterExtension;
import com.vladsch.flexmark.ext.footnotes.FootnoteExtension;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.gfm.tasklist.TaskListExtension;
import com.vladsch.flexmark.ext.gitlab.GitLabExtension;
Expand Down Expand Up @@ -51,6 +52,7 @@ public class MarkdownUtils {
TocExtension.create(),
SuperscriptExtension.create(),
YamlFrontMatterExtension.create(),
FootnoteExtension.create(),
GitLabExtension.create()))
.set(TocExtension.LEVELS, 255)
.set(TablesExtension.WITH_CAPTION, false)
ruibaby marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -63,7 +65,8 @@ public class MarkdownUtils {
.set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true)
.set(EmojiExtension.USE_SHORTCUT_TYPE, EmojiShortcutType.EMOJI_CHEAT_SHEET)
.set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_ONLY)
.set(HtmlRenderer.SOFT_BREAK, "<br />\n");
.set(HtmlRenderer.SOFT_BREAK, "<br />\n")
.set(FootnoteExtension.FOOTNOTE_BACK_REF_STRING, "↩︎");

private static final Parser PARSER = Parser.builder(OPTIONS).build();

Expand Down Expand Up @@ -108,6 +111,8 @@ public static String renderHtml(String markdown) {
markdown = markdown
.replaceAll(HaloConst.YOUTUBE_VIDEO_REG_PATTERN, HaloConst.YOUTUBE_VIDEO_IFRAME);
}
// footnote render method delegation.
FootnoteNodeRendererInterceptor.doDelegationMethod();

Node document = PARSER.parse(markdown);

Expand Down
Loading