Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bootstrap alert renderer #782

Merged
merged 2 commits into from
Mar 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/Markdig/Extensions/Bootstrap/BootstrapExtension.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

using System.Linq;
using Markdig.Extensions.Alerts;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
Expand All @@ -24,6 +26,17 @@ public void Setup(MarkdownPipelineBuilder pipeline)

public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
if (renderer is HtmlRenderer htmlRenderer)
{
var alertRenderer = htmlRenderer.ObjectRenderers.OfType<AlertBlockRenderer>().FirstOrDefault();
if (alertRenderer == null)
{
alertRenderer = new AlertBlockRenderer();
renderer.ObjectRenderers.InsertBefore<QuoteBlockRenderer>(new AlertBlockRenderer());
}

alertRenderer.RenderKind = (_, _) => { };
}
}

private static void PipelineOnDocumentProcessed(MarkdownDocument document)
Expand All @@ -43,6 +56,29 @@ private static void PipelineOnDocumentProcessed(MarkdownDocument document)
{
node.GetAttributes().AddClass("table");
}
else if (node is AlertBlock alertBlock) // Needs to be before QuoteBlock
{
var attributes = node.GetAttributes();
attributes.AddClass("alert");
attributes.AddProperty("role", "alert");
string? @class = alertBlock.Kind.AsSpan() switch
{
"NOTE" => "alert-primary",
"TIP" => "alert-success",
"IMPORTANT" => "alert-info",
"WARNING" => "alert-warning",
"CAUTION" => "alert-danger",
_ => null,
};

if (@class is not null)
{
attributes.AddClass(@class);
}

var lastParagraph = alertBlock.Descendants().OfType<ParagraphBlock>().LastOrDefault();
lastParagraph?.GetAttributes().AddClass("mb-0");
}
else if (node is QuoteBlock)
{
node.GetAttributes().AddClass("blockquote");
Expand Down