Skip to content

Instantly share code, notes, and snippets.

@cambiata
Last active May 29, 2019 09:29
Show Gist options
  • Save cambiata/481c5bcc2906ff5d96497c549ae6f53f to your computer and use it in GitHub Desktop.
Save cambiata/481c5bcc2906ff5d96497c549ae6f53f to your computer and use it in GitHub Desktop.
Basic Haxe solution for creating MVCoconut RenderResult from markdown using https://github.com/dpeek/haxe-markdown
package tools;
import Markdown;
import markdown.AST;
import markdown.InlineParser;
class MarkdownTools {
/*
Example usage in a MVCoconut View:
function testMarkdown(md:String):RenderResult return MarkdownTools.markdown2RenderResults(md);
function render() '
<p>Markdown in MVCoconut</p>
{testMarkdown("#Hello world!")}
';
*/
static public function markdown2RenderResults(markdown:String, addInlSyntax:Array<InlineSyntax> = null):RenderResult {
var nodes:Array<Node> = getNodes(markdown, addInlSyntax);
var results:Array<RenderResult> = nodes.map(block -> nodeToResult(block));
return @:privateAccess coconut.vdom.Html.h('div.markdown', null, null, null, results);
}
// private functions -------------------------------------------
static function nodeToResult(node:Node):RenderResult {
return switch Type.getClass(node) {
case ElementNode:
var elementNode:ElementNode = cast node;
var attributes = {};
for (key => value in elementNode.attributes) {
Reflect.setField(attributes, key, value);
}
return @:privateAccess coconut.vdom.Html.h(elementNode.tag, null, null, attributes, elementNode.children.map(child -> nodeToResult(child)));
case TextNode:
var textNode:TextNode = cast node;
return textNode.text;
case CustomNode: // For use with custom inline syntax, returning a MVCoconut View instance
var customNode:CustomNode = cast node;
return coconut.Ui.hxx('<CustomView code=${CustomNode.customCode} />');
case _:
trace('ERROR');
return 'error';
}
}
static public function getNodes(markdown:String, additionalInlineSyntaxes:Array<InlineSyntax> = null):Array<Node> {
var document = new Document();
if (additionalInlineSyntaxes != null)
for (s in additionalInlineSyntaxes)
document.inlineSyntaxes.push(s);
var blocks = null;
try {
// replace windows line endings with unix, and split
var lines = ~/(\r\n|\r)/g.replace(markdown, '\n').split("\n");
// parse ref links
document.parseRefLinks(lines);
// parse ast
blocks = document.parseLines(lines);
return blocks;
} catch (e:Dynamic) {
trace(e);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment