Skip to content

Commit

Permalink
Fix: Process even deeply nested versions
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Jul 4, 2024
1 parent 4a9de25 commit 90b8cf4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 13 deletions.
51 changes: 38 additions & 13 deletions src/LinkDotNet.Blog.Web/Features/MarkdownConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Markdig;
using Markdig.Extensions.AutoIdentifiers;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
Expand Down Expand Up @@ -42,30 +43,54 @@ public static IReadOnlyCollection<TocItem> GenerateToc(string markdownContent)
return document
.Descendants<HeadingBlock>()
.Where(h => h.Inline?.FirstChild is not null)
.Select(heading => new TocItem { Level = heading.Level, Text = InlineToString(heading.Inline), Id = heading.GetAttributes().Id })
.Select(heading => new TocItem
{
Level = heading.Level, Text = InlineToString(heading.Inline), Id = heading.GetAttributes().Id
})
.ToArray();
}

private static string InlineToString(ContainerInline inline)
{
var sb = new StringBuilder();
var current = inline.FirstChild;
while (current is not null)
ProcessInlineDelegate(inline, sb);
return sb.ToString();

static void ProcessInlineDelegate(Inline inline, StringBuilder stringBuilder)
{
var text = current switch
if (inline is null)
{
CodeInline cd => cd.Content,
LinkInline link => link.FirstChild?.ToString(),
EmphasisInline em => em.FirstChild?.ToString(),
_ => current.ToString()
};
return;
}

sb.Append(text);
var current = inline;
while (current is not null)
{
switch (current)
{
case CodeInline cd:
stringBuilder.Append(cd.Content);
break;
case LinkInline link:
ProcessInlineDelegate(link.FirstChild, stringBuilder);
break;
case EmphasisInline em:
ProcessInlineDelegate(em.FirstChild, stringBuilder);
break;
case LiteralInline literal:
stringBuilder.Append(literal.Content);
break;
case ContainerInline container:
ProcessInlineDelegate(container.FirstChild, stringBuilder);
break;
default:
stringBuilder.Append(current);
break;
}

current = current.NextSibling;
current = current.NextSibling;
}
}

return sb.ToString();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public void ShouldSetAnchorLinkCorrectWhenAlreadyAnchorInUrl()
[InlineData("# This is `Header` 1", "This is Header 1")]
[InlineData("# [This is a link](https://link.com)", "This is a link")]
[InlineData("# **What** *if*", "What if")]
[InlineData("# *[Link](link)*", "Link")]
public void ShouldCreateCorrectToc(string markdown, string expectedToc)
{
var cut = Render<TableOfContents>(p => p
Expand Down

0 comments on commit 90b8cf4

Please sign in to comment.