Files
MdToHtmlDashboard/MdToHtmlDashboard/Converter/MarkdownConverter.cs
T

310 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Markdig;
using MdToHtmlDashboard.Templates;
namespace MdToHtmlDashboard.Converter;
/// <summary>
/// Markdown文字列を解析し、インタラクティブ機能付きの完全自己完結HTMLへ変換するコンバーター
/// </summary>
public class MarkdownConverter
{
private readonly MarkdownPipeline _pipeline;
public MarkdownConverter()
{
// Markdig 高度拡張パイプライン(パイプテーブル、タスクリスト、コードブロック等)
_pipeline = new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.UseEmojiAndSmiley()
.Build();
}
/// <summary>
/// Markdownファイルを読み込み、インタラクティブHTMLを生成して保存します
/// </summary>
public string ConvertFile(string markdownFilePath, string? outputHtmlPath = null)
{
if (!File.Exists(markdownFilePath))
{
throw new FileNotFoundException($"Markdownファイルが見つかりません: {markdownFilePath}");
}
outputHtmlPath ??= Path.ChangeExtension(markdownFilePath, ".html");
var markdownContent = File.ReadAllText(markdownFilePath, Encoding.UTF8);
var html = ConvertText(markdownContent, Path.GetFileNameWithoutExtension(markdownFilePath));
File.WriteAllText(outputHtmlPath, html, new UTF8Encoding(true));
return outputHtmlPath;
}
/// <summary>
/// MarkdownテキストをインタラクティブHTMLに変換します
/// </summary>
public string ConvertText(string markdownContent, string defaultTitle = "ドキュメント")
{
// 1. Markdig による基本HTML変換
var rawHtml = Markdown.ToHtml(markdownContent, _pipeline);
// 2. HtmlAgilityPack によるDOM解析・エンリッチメント
var doc = new HtmlDocument();
doc.LoadHtml(rawHtml);
var title = defaultTitle;
var subtitle = "";
// タイトル抽出(最初のH1)
var firstH1 = doc.DocumentNode.SelectSingleNode("//h1");
if (firstH1 != null)
{
title = firstH1.InnerText.Trim();
}
// 目次(TOC)抽出と見出しへのID付与
var tocHtml = BuildTableOfContents(doc);
// テーブルの拡張(レスポンシブラッパーの追加)
EnrichTables(doc);
// コードブロックの拡張(コピーボタン、言語ヘッダー、diffハイライト)
EnrichCodeBlocks(doc);
// ファイルパス・リンクの拡張(コピーボタン付与)
EnrichLinksAndPaths(doc);
// H2セクションの安全なアコーディオン構造化(線形再構築)
EnrichSections(doc);
var bodyHtml = doc.DocumentNode.OuterHtml;
// 3. テンプレートへ統合
return HtmlTemplate.Render(title, subtitle, bodyHtml, tocHtml);
}
/// <summary>
/// 見出しから目次(TOC)ツリーを生成し、見出し要素にアンカーIDを付与します
/// </summary>
private string BuildTableOfContents(HtmlDocument doc)
{
var headings = doc.DocumentNode.SelectNodes("//h1 | //h2 | //h3 | //h4");
if (headings == null || headings.Count == 0)
{
return "<p style=\"color: #94a3b8; font-size: 13px;\">目次項目はありません</p>";
}
var sb = new StringBuilder();
sb.AppendLine("<ul>");
int index = 1;
foreach (var h in headings)
{
var level = int.Parse(h.Name.Substring(1));
var text = h.InnerText.Trim();
if (string.IsNullOrWhiteSpace(text)) continue;
var anchorId = $"heading-{index++}";
h.SetAttributeValue("id", anchorId);
var indent = (level - 1) * 12;
sb.AppendLine($" <li style=\"padding-left: {indent}px;\"><a href=\"#{anchorId}\" onclick=\"if(window.innerWidth<=992)toggleSidebar(false);\">{System.Net.WebUtility.HtmlEncode(text)}</a></li>");
}
sb.AppendLine("</ul>");
return sb.ToString();
}
/// <summary>
/// テーブル要素を横スクロールラッパーで囲みます
/// </summary>
private void EnrichTables(HtmlDocument doc)
{
var tables = doc.DocumentNode.SelectNodes("//table");
if (tables == null) return;
foreach (var table in tables)
{
var parent = table.ParentNode;
if (parent == null) continue;
var wrapper = doc.CreateElement("div");
wrapper.SetAttributeValue("class", "table-container");
parent.ReplaceChild(wrapper, table);
wrapper.AppendChild(table);
}
}
/// <summary>
/// コードブロックにコピーボタンと言語表示ヘッダーを付与し、diffブロックをハイライトします
/// </summary>
private void EnrichCodeBlocks(HtmlDocument doc)
{
var preNodes = doc.DocumentNode.SelectNodes("//pre");
if (preNodes == null) return;
foreach (var pre in preNodes)
{
var parent = pre.ParentNode;
if (parent == null) continue;
var codeNode = pre.SelectSingleNode("code");
var lang = "code";
if (codeNode != null)
{
var classAttr = codeNode.GetAttributeValue("class", "");
var match = Regex.Match(classAttr, @"language-([\w-]+)");
if (match.Success)
{
lang = match.Groups[1].Value;
}
// diff コードブロックの行ハイライト
if (lang.Equals("diff", StringComparison.OrdinalIgnoreCase))
{
HighlightDiff(codeNode);
}
}
var container = doc.CreateElement("div");
container.SetAttributeValue("class", "code-container");
var header = doc.CreateElement("div");
header.SetAttributeValue("class", "code-header");
header.InnerHtml = $"<span>{System.Net.WebUtility.HtmlEncode(lang)}</span><button class=\"code-copy-btn\" onclick=\"copyPreCode(this)\">📋 コピー</button>";
container.AppendChild(header);
parent.ReplaceChild(container, pre);
container.AppendChild(pre);
}
}
/// <summary>
/// diff 内の行頭 + / - をクラス付けしてハイライトします
/// </summary>
private void HighlightDiff(HtmlNode codeNode)
{
var rawText = codeNode.InnerText;
var lines = rawText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var sb = new StringBuilder();
foreach (var line in lines)
{
var trimmed = line.TrimStart();
if (trimmed.StartsWith("+") && !trimmed.StartsWith("+++"))
{
sb.AppendLine($"<span class=\"diff-add\">{System.Net.WebUtility.HtmlEncode(line)}</span>");
}
else if (trimmed.StartsWith("-") && !trimmed.StartsWith("---"))
{
sb.AppendLine($"<span class=\"diff-del\">{System.Net.WebUtility.HtmlEncode(line)}</span>");
}
else
{
sb.AppendLine(System.Net.WebUtility.HtmlEncode(line));
}
}
codeNode.InnerHtml = sb.ToString();
}
/// <summary>
/// ファイルリンクや file:/// 形式のリンクを拡張し、パスコピー機能を提供します
/// </summary>
private void EnrichLinksAndPaths(HtmlDocument doc)
{
var links = doc.DocumentNode.SelectNodes("//a[@href]");
if (links == null) return;
foreach (var a in links)
{
var href = a.GetAttributeValue("href", "");
if (href.StartsWith("file:///") || href.EndsWith(".aspx") || href.EndsWith(".vb") || href.EndsWith(".cs") || href.EndsWith(".md"))
{
var parent = a.ParentNode;
if (parent == null) continue;
var cleanPath = href.Replace("file:///", "").TrimStart('/');
var badge = doc.CreateElement("span");
badge.SetAttributeValue("class", "file-path-badge");
badge.InnerHtml = $"<button class=\"badge-copy-btn\" onclick=\"copyText('{cleanPath.Replace("\\", "\\\\")}')\" title=\"パスをコピー\">📋</button>";
parent.InsertAfter(badge, a);
}
}
}
/// <summary>
/// H2見出し単位で安全に details/summary セクションを線形再構築します(重複バグの完全解消)
/// </summary>
private void EnrichSections(HtmlDocument doc)
{
var nodes = doc.DocumentNode.ChildNodes.ToList();
if (nodes.Count == 0) return;
var newContainer = doc.CreateElement("div");
newContainer.SetAttributeValue("class", "doc-flow");
HtmlNode? currentSectionContent = null;
HtmlNode? introContainer = null;
foreach (var node in nodes)
{
// 空白テキストノードの無視
if (node.NodeType == HtmlNodeType.Text && string.IsNullOrWhiteSpace(node.InnerText))
{
continue;
}
if (node.Name.Equals("h2", StringComparison.OrdinalIgnoreCase))
{
// 新しい H2 セクション開始
var details = doc.CreateElement("details");
details.SetAttributeValue("class", "doc-section");
details.SetAttributeValue("open", "open"); // デフォルト展開
var summary = doc.CreateElement("summary");
summary.SetAttributeValue("class", "doc-section-header");
summary.AppendChild(node.CloneNode(true));
currentSectionContent = doc.CreateElement("div");
currentSectionContent.SetAttributeValue("class", "doc-section-content");
details.AppendChild(summary);
details.AppendChild(currentSectionContent);
newContainer.AppendChild(details);
}
else
{
if (currentSectionContent != null)
{
// 既存セクションの中に追加
currentSectionContent.AppendChild(node.CloneNode(true));
}
else
{
// 最初の H2 が来る前のイントロ要素群
if (introContainer == null)
{
introContainer = doc.CreateElement("div");
introContainer.SetAttributeValue("class", "doc-intro");
newContainer.AppendChild(introContainer);
}
introContainer.AppendChild(node.CloneNode(true));
}
}
}
doc.DocumentNode.RemoveAllChildren();
foreach (var child in newContainer.ChildNodes)
{
doc.DocumentNode.AppendChild(child);
}
}
}