Skip to content

Commit

Permalink
fix: Transform code in headers as well
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Jun 30, 2024
1 parent de73ff2 commit b682836
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/LinkDotNet.Blog.Web/Features/MarkdownConverter.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Markdig;
using Markdig.Extensions.AutoIdentifiers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Primitives;

namespace LinkDotNet.Blog.Web.Features;

Expand Down Expand Up @@ -38,9 +41,30 @@ 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 = heading.Inline.FirstChild.ToString(), 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)
{
if (current is CodeInline cd)
{
sb.Append(cd.Content);
}
else
{
sb.Append(current);
}

current = current.NextSibling;
}

return sb.ToString();
}
}

public class TocItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,17 @@ public void ShouldSetAnchorLinkCorrectWhenAlreadyAnchorInUrl()
links[0].GetAttribute("href").Should().Be("https://localhost#header-1");
links[1].GetAttribute("href").Should().Be("https://localhost#header-2");
}

[Fact]
public void ShouldCreateCorrectTocWithCodeInHeadings()
{
const string content = "# This is `Header` 1";

var cut = Render<TableOfContents>(p => p
.Add(x => x.Content, content)
.Add(x => x.CurrentUri, "https://localhost"));

var link = cut.Find("nav a");
link.TextContent.Should().Be("This is Header 1");
}
}

0 comments on commit b682836

Please sign in to comment.