Files
Khaemhat/src/Khaemhat.Web/Help/WikiMarkdown.cs
T
Alby96andClaude Opus 5.5 f415dc37a8 feat: in-app help, notifications panel and global search (#32)
F1 and "?" now open the wiki page of the screen inside the application
(/aiuto, mockup 011) from a copy of the wiki shipped next to the program,
so help works offline and always matches the installed version. Markdown
is converted in-house and fully encoded; images of the repository are
served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind
"Apri nel wiki"; "Segnala un problema" opens a new issue of that repo.
A test checks that every page and menu entry has an existing wiki page.

The bell opens a notifications panel (mockup 010) with all/unread
filters and mark read. Broadcast notifications are now read per user
through sys_notification_reads / notification_reads instead of one
shared read_at.

The global search asks ISearchProvider implementations through
GlobalSearchService after a short pause; the first provider finds help
pages and sections, # and @ say which modules will fill them.

Escape also closes a side panel when the focus fell out of it.
Decisions in ADR 0023.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:39:17 +01:00

466 lines
17 KiB
C#

using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace Khaemhat.Web.Help;
/// <summary>Where the links and images of a wiki page point inside the application.</summary>
/// <param name="Page">The address of another wiki page (<c>Anagrafiche</c>, <c>Anagrafiche#clienti</c>).</param>
/// <param name="Media">The local address of an image, or <see langword="null"/> to keep the original one.</param>
public sealed record WikiLinks(Func<string, string> Page, Func<string, string?> Media);
/// <summary>
/// Turns the Markdown of <c>docs/wiki/</c> into HTML for the help (SPEC §17, mockup 011), written in house (no external
/// libraries, ADR 0002). It covers what the wiki uses: headings with anchors, paragraphs, bold, italic, code, links,
/// images, nested lists, tables, quotes, code blocks and rules. Every piece of text is encoded and only http, https,
/// anchors and wiki pages become links, so a page cannot inject markup or scripts.
/// </summary>
public static partial class WikiMarkdown
{
/// <summary>Converts a page.</summary>
/// <param name="markdown">The Markdown.</param>
/// <param name="links">Where links and images go.</param>
/// <returns>The HTML.</returns>
public static string ToHtml(string markdown, WikiLinks links)
{
ArgumentNullException.ThrowIfNull(markdown);
ArgumentNullException.ThrowIfNull(links);
var lines = markdown.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n');
var html = new StringBuilder();
new Parser(lines, links, html).Blocks(0, lines.Length);
return html.ToString();
}
/// <summary>The anchor of a heading, as the wiki makes it: lower case, words joined by dashes.</summary>
/// <param name="text">The heading text (Markdown).</param>
/// <returns>The anchor.</returns>
public static string Slug(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = PlainText(text).ToLower(CultureInfo.InvariantCulture);
var slug = new StringBuilder();
foreach (var c in plain)
{
if (char.IsLetterOrDigit(c) || c is '-' or '_')
{
slug.Append(c);
}
else if (c == ' ')
{
slug.Append('-');
}
}
return slug.ToString();
}
/// <summary>The text of a line of Markdown without its marks.</summary>
/// <param name="text">The Markdown.</param>
/// <returns>The text.</returns>
public static string PlainText(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = LinkPattern().Replace(text, "$1");
return plain.Replace("**", string.Empty, StringComparison.Ordinal).Replace("`", string.Empty, StringComparison.Ordinal)
.Replace("*", string.Empty, StringComparison.Ordinal).Trim();
}
[GeneratedRegex(@"!?\[([^\]]*)\]\([^)]*\)")]
private static partial Regex LinkPattern();
[GeneratedRegex(@"^(\s*)([-*+]|\d+[.)])\s+(.*)$")]
private static partial Regex ListItemPattern();
[GeneratedRegex(@"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")]
private static partial Regex TableRulePattern();
[GeneratedRegex(@"^(#{1,6})\s+(.*?)\s*#*\s*$")]
private static partial Regex HeadingPattern();
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9-]*(#[A-Za-z0-9_\-\p{L}]*)?$")]
private static partial Regex PagePattern();
private sealed class Parser(string[] lines, WikiLinks links, StringBuilder html)
{
public void Blocks(int start, int end)
{
var i = start;
while (i < end)
{
var line = lines[i];
var trimmed = line.Trim();
if (trimmed.Length == 0)
{
i++;
}
else if (trimmed.StartsWith("```", StringComparison.Ordinal))
{
i = Fence(i, end);
}
else if (HeadingPattern().Match(trimmed) is { Success: true } heading)
{
var level = heading.Groups[1].Length;
var text = heading.Groups[2].Value;
html.Append(CultureInfo.InvariantCulture, $"<h{level} id=\"{Attr(Slug(text))}\">").Append(Inline(text)).Append(CultureInfo.InvariantCulture, $"</h{level}>\n");
i++;
}
else if (trimmed is "---" or "***" or "___")
{
html.Append("<hr />\n");
i++;
}
else if (trimmed.StartsWith('>'))
{
i = Quote(i, end);
}
else if (trimmed.StartsWith('|') && i + 1 < end && TableRulePattern().IsMatch(lines[i + 1]))
{
i = Table(i, end);
}
else if (ListItemPattern().Match(line) is { Success: true } item)
{
i = List(i, end, item.Groups[1].Value.Length);
}
else
{
i = Paragraph(i, end);
}
}
}
private int Fence(int i, int end)
{
var body = new List<string>();
var j = i + 1;
while (j < end && !lines[j].Trim().StartsWith("```", StringComparison.Ordinal))
{
body.Add(lines[j]);
j++;
}
html.Append("<pre><code>").Append(Encode(string.Join('\n', body))).Append("</code></pre>\n");
return Math.Min(j + 1, end);
}
private int Quote(int i, int end)
{
var inner = new List<string>();
var j = i;
while (j < end && lines[j].TrimStart().StartsWith('>'))
{
var text = lines[j].TrimStart()[1..];
inner.Add(text.StartsWith(' ') ? text[1..] : text);
j++;
}
// "> **Stato:** bozza · ..." at the top of every page is the page state, not a note.
var meta = inner.Count > 0 && inner[0].StartsWith("**Stato:**", StringComparison.Ordinal);
html.Append(meta ? "<div class=\"kh-help-meta\">" : "<div class=\"callout info\"><div>");
// Each line of the page state is a fact of its own: keep them on separate lines.
var nested = new Parser(meta ? [.. inner.Select((l, n) => n < inner.Count - 1 ? l.TrimEnd() + " " : l)] : [.. inner], links, html);
nested.Blocks(0, inner.Count);
html.Append(meta ? "</div>\n" : "</div></div>\n");
return j;
}
private int Table(int i, int end)
{
var header = Cells(lines[i]);
html.Append("<div class=\"kh-help-table\"><table class=\"grid\"><thead><tr>");
foreach (var cell in header)
{
html.Append("<th>").Append(Inline(cell)).Append("</th>");
}
html.Append("</tr></thead><tbody>");
var j = i + 2;
while (j < end && lines[j].Trim().StartsWith('|'))
{
html.Append("<tr>");
var cells = Cells(lines[j]);
for (var c = 0; c < header.Count; c++)
{
html.Append("<td>").Append(c < cells.Count ? Inline(cells[c]) : string.Empty).Append("</td>");
}
html.Append("</tr>");
j++;
}
html.Append("</tbody></table></div>\n");
return j;
}
private static List<string> Cells(string line)
{
var text = line.Trim();
if (text.StartsWith('|'))
{
text = text[1..];
}
if (text.EndsWith('|') && !text.EndsWith("\\|", StringComparison.Ordinal))
{
text = text[..^1];
}
var cells = new List<string>();
var current = new StringBuilder();
var inCode = false;
for (var k = 0; k < text.Length; k++)
{
var c = text[k];
if (c == '\\' && k + 1 < text.Length && text[k + 1] == '|')
{
current.Append('|');
k++;
}
else if (c == '`')
{
inCode = !inCode;
current.Append(c);
}
else if (c == '|' && !inCode)
{
cells.Add(current.ToString().Trim());
current.Clear();
}
else
{
current.Append(c);
}
}
cells.Add(current.ToString().Trim());
return cells;
}
private int List(int i, int end, int indent)
{
var ordered = char.IsDigit(ListItemPattern().Match(lines[i]).Groups[2].Value[0]);
html.Append(ordered ? "<ol>" : "<ul>");
var j = i;
while (j < end)
{
var match = ListItemPattern().Match(lines[j]);
if (!match.Success || match.Groups[1].Value.Length != indent)
{
break;
}
var text = new StringBuilder(match.Groups[3].Value);
j++;
var nested = new StringBuilder();
while (j < end)
{
var line = lines[j];
var lead = line.Length - line.TrimStart().Length;
if (line.Trim().Length == 0)
{
// A blank line ends the item unless the list goes on after it.
var next = j + 1;
if (next < end && lines[next].Trim().Length > 0 && (lines[next].Length - lines[next].TrimStart().Length) > indent)
{
j++;
continue;
}
break;
}
if (ListItemPattern().Match(line) is { Success: true } sub)
{
if (sub.Groups[1].Value.Length > indent)
{
var inner = new StringBuilder();
j = new Parser(lines, links, inner).List(j, end, sub.Groups[1].Value.Length);
nested.Append(inner);
continue;
}
break;
}
if (lead <= indent || IsBlockStart(line))
{
break;
}
text.Append(' ').Append(line.Trim());
j++;
}
html.Append("<li>").Append(Inline(text.ToString())).Append(nested).Append("</li>");
if (j < end && lines[j].Trim().Length == 0 && j + 1 < end && ListItemPattern().Match(lines[j + 1]) is { Success: true } after
&& after.Groups[1].Value.Length == indent)
{
j++;
}
}
html.Append(ordered ? "</ol>\n" : "</ul>\n");
return j;
}
private int Paragraph(int i, int end)
{
var text = new StringBuilder();
var j = i;
while (j < end && lines[j].Trim().Length > 0 && (j == i || !IsBlockStart(lines[j])))
{
// Two spaces at the end of a line are a line break, as in the wiki.
var line = lines[j];
text.Append(Inline(line.Trim())).Append(line.EndsWith(" ", StringComparison.Ordinal) ? "<br />" : " ");
j++;
}
html.Append("<p>").Append(text.ToString().TrimEnd()).Append("</p>\n");
return j;
}
private static bool IsBlockStart(string line)
{
var trimmed = line.Trim();
return trimmed.StartsWith("```", StringComparison.Ordinal) || trimmed.StartsWith('>') || trimmed.StartsWith('|')
|| HeadingPattern().IsMatch(trimmed) || ListItemPattern().IsMatch(line) || trimmed is "---" or "***" or "___";
}
private string Inline(string text)
{
var output = new StringBuilder();
var i = 0;
while (i < text.Length)
{
var c = text[i];
if (c == '\\' && i + 1 < text.Length && char.IsPunctuation(text[i + 1]) || c == '\\' && i + 1 < text.Length && char.IsSymbol(text[i + 1]))
{
output.Append(Encode(text[i + 1].ToString()));
i += 2;
}
else if (c == '`' && text.IndexOf('`', i + 1) is var close && close > i)
{
output.Append("<code>").Append(Encode(text[(i + 1)..close])).Append("</code>");
i = close + 1;
}
else if (c == '!' && i + 1 < text.Length && text[i + 1] == '[' && TryLink(text, i + 1, out var alt, out var src, out var after))
{
var local = links.Media(src);
var url = local ?? (IsWeb(src) ? src : null);
output.Append(url is null
? Encode(alt)
: $"<img src=\"{Attr(url)}\" alt=\"{Attr(PlainText(alt))}\" loading=\"lazy\" />");
i = after;
}
else if (c == '[' && TryLink(text, i, out var label, out var href, out var next))
{
output.Append(Anchor(label, href));
i = next;
}
else if (c == '*' && i + 1 < text.Length && text[i + 1] == '*' && text.IndexOf("**", i + 2, StringComparison.Ordinal) is var bold && bold > i + 2)
{
output.Append("<strong>").Append(Inline(text[(i + 2)..bold])).Append("</strong>");
i = bold + 2;
}
else if (c is '*' or '_' && i + 1 < text.Length && !char.IsWhiteSpace(text[i + 1]) && (c == '*' || i == 0 || !char.IsLetterOrDigit(text[i - 1]))
&& Closing(text, i + 1, c) is var em && em > i + 1)
{
output.Append("<em>").Append(Inline(text[(i + 1)..em])).Append("</em>");
i = em + 1;
}
else if (c == '<' && text.AsSpan(i).StartsWith("<br", StringComparison.OrdinalIgnoreCase) && text.IndexOf('>', i) is var gt && gt > i)
{
output.Append("<br />");
i = gt + 1;
}
else
{
output.Append(Encode(c.ToString()));
i++;
}
}
return output.ToString();
}
private static int Closing(string text, int from, char mark)
{
for (var k = from; k < text.Length; k++)
{
if (text[k] == mark && !char.IsWhiteSpace(text[k - 1]) && (k + 1 >= text.Length || text[k + 1] != mark)
&& (mark == '*' || k + 1 >= text.Length || !char.IsLetterOrDigit(text[k + 1])))
{
return k;
}
}
return -1;
}
private static bool TryLink(string text, int open, out string label, out string href, out int after)
{
label = href = string.Empty;
after = open;
var depth = 0;
var k = open;
for (; k < text.Length; k++)
{
if (text[k] == '[')
{
depth++;
}
else if (text[k] == ']' && --depth == 0)
{
break;
}
}
if (k + 1 >= text.Length || text[k + 1] != '(')
{
return false;
}
var closeParen = text.IndexOf(')', k + 2);
if (closeParen < 0)
{
return false;
}
label = text[(open + 1)..k];
href = text[(k + 2)..closeParen].Trim();
var space = href.IndexOf(' ', StringComparison.Ordinal);
if (space > 0)
{
href = href[..space];
}
after = closeParen + 1;
return true;
}
private string Anchor(string label, string href)
{
var inner = Inline(label);
if (IsWeb(href))
{
return $"<a href=\"{Attr(href)}\" target=\"_blank\" rel=\"noopener\">{inner}</a>";
}
if (href.StartsWith('#'))
{
return $"<a href=\"{Attr("#" + Slug(href[1..].Replace('-', ' ')))}\">{inner}</a>";
}
return PagePattern().IsMatch(href) ? $"<a href=\"{Attr(links.Page(href))}\">{inner}</a>" : inner;
}
private static bool IsWeb(string url) =>
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("http://", StringComparison.OrdinalIgnoreCase);
private static string Encode(string text) => WebUtility.HtmlEncode(text);
private static string Attr(string text) => WebUtility.HtmlEncode(text);
}
}