-
Notifications
You must be signed in to change notification settings - Fork 0
/
MarkdownConverter.cs
61 lines (51 loc) · 2.16 KB
/
MarkdownConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using BlazorSite.BlogService;
using CommonMark;
using CommonMark.Syntax;
using System.Text;
namespace BlazorSite.Markdown
{
public interface IMarkdownConverter
{
string ConvertMarkdownToHTML(string postId, string markdown);
}
public class MarkdownConverter : IMarkdownConverter
{
private readonly ICodeHeighlighter codeHighlighter;
public MarkdownConverter(ICodeHeighlighter codeHighlighter)
{
this.codeHighlighter = codeHighlighter;
}
public string ConvertMarkdownToHTML(string postId, string markdown)
{
var formatterSettingsw = CreateSettings(postId);
return CommonMarkConverter.Convert(markdown, formatterSettingsw);
}
private CommonMarkSettings CreateSettings(string postId)
{
var formatterSettings = CommonMarkSettings.Default.Clone();
formatterSettings.OutputDelegate = (doc, output, settings) =>
new ExtensibleHtmlFormatter(output, settings)
.WithFormatter(BlockTag.FencedCode, block =>
{
var language = block.FencedCodeData.Info;
var code = block.StringContent.ToString();
var sb = new StringBuilder();
sb.AppendLine($"<pre><code class=\"language-{language} hljs\">");
var formattedCode = codeHighlighter.HighlightSyntax(code, language);
sb.AppendLine(formattedCode);
sb.AppendLine("</code></pre>");
return sb.ToString();
})
.WithFormatter(InlineTag.Image,
inline => !(inline.TargetUrl.StartsWith("http://") || inline.TargetUrl.StartsWith("https://")),
inline =>
{
var imgUrl = BlogPostUriHelper.GetContentFileUri(postId, inline.TargetUrl);
var imgAlt = inline.LiteralContent;
return $"<img src=\"{imgUrl}\" alt=\"imgAlt\" title=\"{imgAlt}\">";
})
.WriteDocument(doc);
return formatterSettings;
}
}
}