Skip to content

Commit b682836

Browse files
committed
fix: Transform code in headers as well
1 parent de73ff2 commit b682836

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/LinkDotNet.Blog.Web/Features/MarkdownConverter.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
using System.Collections.Generic;
22
using System.Linq;
3+
using System.Text;
34
using Markdig;
45
using Markdig.Extensions.AutoIdentifiers;
56
using Markdig.Renderers.Html;
67
using Markdig.Syntax;
8+
using Markdig.Syntax.Inlines;
79
using Microsoft.AspNetCore.Components;
10+
using Microsoft.Extensions.Primitives;
811

912
namespace LinkDotNet.Blog.Web.Features;
1013

@@ -38,9 +41,30 @@ public static IReadOnlyCollection<TocItem> GenerateToc(string markdownContent)
3841
return document
3942
.Descendants<HeadingBlock>()
4043
.Where(h => h.Inline?.FirstChild is not null)
41-
.Select(heading => new TocItem { Level = heading.Level, Text = heading.Inline.FirstChild.ToString(), Id = heading.GetAttributes().Id })
44+
.Select(heading => new TocItem { Level = heading.Level, Text = InlineToString(heading.Inline), Id = heading.GetAttributes().Id })
4245
.ToArray();
4346
}
47+
48+
private static string InlineToString(ContainerInline inline)
49+
{
50+
var sb = new StringBuilder();
51+
var current = inline.FirstChild;
52+
while (current is not null)
53+
{
54+
if (current is CodeInline cd)
55+
{
56+
sb.Append(cd.Content);
57+
}
58+
else
59+
{
60+
sb.Append(current);
61+
}
62+
63+
current = current.NextSibling;
64+
}
65+
66+
return sb.ToString();
67+
}
4468
}
4569

4670
public class TocItem

tests/LinkDotNet.Blog.UnitTests/Web/Features/ShowBlogPost/Components/TableOfContentsTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,17 @@ public void ShouldSetAnchorLinkCorrectWhenAlreadyAnchorInUrl()
5252
links[0].GetAttribute("href").Should().Be("https://localhost#header-1");
5353
links[1].GetAttribute("href").Should().Be("https://localhost#header-2");
5454
}
55+
56+
[Fact]
57+
public void ShouldCreateCorrectTocWithCodeInHeadings()
58+
{
59+
const string content = "# This is `Header` 1";
60+
61+
var cut = Render<TableOfContents>(p => p
62+
.Add(x => x.Content, content)
63+
.Add(x => x.CurrentUri, "https://localhost"));
64+
65+
var link = cut.Find("nav a");
66+
link.TextContent.Should().Be("This is Header 1");
67+
}
5568
}

0 commit comments

Comments
 (0)