-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathEnhancedCodeBlockHtmlRenderer.cs
More file actions
341 lines (290 loc) · 9.69 KB
/
EnhancedCodeBlockHtmlRenderer.cs
File metadata and controls
341 lines (290 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Diagnostics.CodeAnalysis;
using Elastic.Documentation.AppliesTo;
using Elastic.Markdown.Diagnostics;
using Elastic.Markdown.Helpers;
using Elastic.Markdown.Myst.Comments;
using Elastic.Markdown.Myst.Directives.AppliesTo;
using Elastic.Markdown.Myst.Directives.Contributors;
using Markdig;
using Markdig.Helpers;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Microsoft.AspNetCore.Html;
using RazorSlices;
namespace Elastic.Markdown.Myst.CodeBlocks;
public class EnhancedCodeBlockHtmlRenderer : HtmlObjectRenderer<EnhancedCodeBlock>
{
private const int TabWidth = 4;
[SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly")]
private static void RenderRazorSlice<T>(RazorSlice<T> slice, HtmlRenderer renderer)
{
var html = slice.RenderAsync().GetAwaiter().GetResult();
_ = renderer.Write(html.EnsureTrimmed());
}
/// <summary>
/// Renders the code block lines while also removing the common indentation level.
/// Required because EnableTrackTrivia preserves extra indentation.
/// </summary>
public static void RenderCodeBlockLines(HtmlRenderer renderer, EnhancedCodeBlock block)
{
var commonIndent = GetCommonIndent(block);
var hasCode = false;
for (var i = 0; i < block.Lines.Count; i++)
{
var line = block.Lines.Lines[i];
var slice = line.Slice;
//ensure we never emit an empty line at beginning or start
if ((i == 0 || i == block.Lines.Count - 1) && line.Slice.IsEmptyOrWhitespace())
continue;
var indent = CountIndentation(slice);
if (indent >= commonIndent)
slice.Start += commonIndent;
if (!hasCode)
{
_ = renderer.Write($"<code class=\"language-{block.Language}\">");
hasCode = true;
}
RenderCodeBlockLine(renderer, block, slice, i);
}
if (hasCode)
_ = renderer.Write($"</code>");
}
private static void RenderCodeBlockLine(HtmlRenderer renderer, EnhancedCodeBlock block, StringSlice slice, int lineNumber)
{
var originalLength = slice.Length;
_ = slice.TrimEnd();
var removedSpaces = originalLength - slice.Length;
_ = renderer.WriteEscape(slice);
RenderCallouts(renderer, block, lineNumber, removedSpaces);
_ = renderer.WriteLine();
}
private static void RenderCallouts(HtmlRenderer renderer, EnhancedCodeBlock block, int lineNumber, int indent)
{
var callOuts = FindCallouts(block.CallOuts, lineNumber + 1);
foreach (var callOut in callOuts)
{
// This adds a span with the same width as the removed spaces
// to ensure the callout number is aligned with the code
_ = renderer.Write($"<span style=\"display: inline-block; width: {indent}ch\"></span>");
_ = renderer.Write($"<span class=\"code-callout\" data-index=\"{callOut.Index}\"></span>");
}
}
private static IEnumerable<CallOut> FindCallouts(
IEnumerable<CallOut> callOuts,
int lineNumber
) => callOuts.Where(callOut => callOut.Line == lineNumber);
private static int GetCommonIndent(EnhancedCodeBlock block)
{
var commonIndent = int.MaxValue;
for (var i = 0; i < block.Lines.Count; i++)
{
var line = block.Lines.Lines[i].Slice;
if (line.IsEmptyOrWhitespace())
continue;
var indent = CountIndentation(line);
commonIndent = Math.Min(commonIndent, indent);
}
return commonIndent;
}
private static int CountIndentation(StringSlice slice)
{
var indentCount = 0;
for (var i = slice.Start; i <= slice.End; i++)
{
var c = slice.Text[i];
if (c == ' ')
indentCount++;
else if (c == '\t')
indentCount += TabWidth;
else
break;
}
return indentCount;
}
private static bool IsCommentBlock(Block block) => block is CommentBlock;
protected override void Write(HtmlRenderer renderer, EnhancedCodeBlock block)
{
if (block is AppliesToDirective appliesToDirective)
{
RenderAppliesToHtml(renderer, appliesToDirective);
return;
}
if (block is ContributorsBlock contributorsBlock)
{
RenderContributorsHtml(renderer, contributorsBlock);
return;
}
// Render Mermaid diagrams as pre.mermaid for client-side rendering
if (block.Language == "mermaid")
{
RenderMermaidBlock(renderer, block);
return;
}
var callOuts = block.UniqueCallOuts;
var slice = Code.Create(new CodeViewModel
{
CrossReferenceName = string.Empty,// block.CrossReferenceName,
Language = block.Language,
Caption = block.Caption,
ApiSegments = block.ApiSegments,
EnhancedCodeBlock = block
});
RenderRazorSlice(slice, renderer);
if (!block.InlineAnnotations && callOuts.Count > 0)
{
var index = block.Parent!.IndexOf(block);
if (index == block.Parent!.Count - 1)
{
block.EmitError("Code block with annotations is not followed by any content, needs numbered list");
return;
}
var nonCommentNonListCount = 0;
ListBlock? listBlock = null;
var currentIndex = index + 1;
// Process blocks between the code block and ordered list, removing comments and allowing only one non-comment block
while (currentIndex < block.Parent.Count)
{
var nextBlock = block.Parent[currentIndex];
if (nextBlock is ListBlock lb)
{
listBlock = lb;
break;
}
else if (IsCommentBlock(nextBlock))
{
_ = renderer.Render(nextBlock);
_ = block.Parent.Remove(nextBlock);
}
else
{
nonCommentNonListCount++;
if (nonCommentNonListCount > 1)
{
block.EmitError("More than one content block between code block with annotations and its list");
return;
}
_ = renderer.Render(nextBlock);
_ = block.Parent.Remove(nextBlock);
}
}
if (listBlock == null)
{
block.EmitError("Code block with annotations is not followed by a list");
return;
}
if (listBlock.Count < callOuts.Count)
{
block.EmitError($"Code block has {callOuts.Count} callouts but the following list only has {listBlock.Count}");
return;
}
_ = block.Parent.Remove(listBlock);
_ = renderer.WriteLine("<ol class=\"code-callouts\">");
foreach (var child in listBlock)
{
var listItem = (ListItemBlock)child;
var previousImplicit = renderer.ImplicitParagraph;
renderer.ImplicitParagraph = !listBlock.IsLoose;
_ = renderer.EnsureLine();
if (renderer.EnableHtmlForBlock)
{
_ = renderer.Write("<li");
_ = renderer.WriteAttributes(listItem);
_ = renderer.Write('>');
}
renderer.WriteChildren(listItem);
if (renderer.EnableHtmlForBlock)
_ = renderer.WriteLine("</li>");
_ = renderer.EnsureLine();
renderer.ImplicitParagraph = previousImplicit;
}
_ = renderer.WriteLine("</ol>");
}
else if (block.InlineAnnotations)
{
_ = renderer.WriteLine("<ol class=\"code-callouts\">");
foreach (var c in block.UniqueCallOuts)
{
_ = renderer.WriteLine("<li>");
_ = renderer.WriteLine(RenderCalloutMarkdown(block, c).Value ?? string.Empty);
_ = renderer.WriteLine("</li>");
}
_ = renderer.WriteLine("</ol>");
}
}
private static HtmlString RenderCalloutMarkdown(EnhancedCodeBlock block, CallOut callOut)
{
if (string.IsNullOrWhiteSpace(callOut.Text))
return HtmlString.Empty;
var document = MarkdownParser.ParseMarkdownStringAsync(
block.Build,
block.Context,
callOut.Text,
block.CurrentFile,
block.Context.YamlFrontMatter,
MarkdownParser.Pipeline);
if (document.Count == 1 && document.FirstOrDefault() is ParagraphBlock paragraph && paragraph.Inline != null)
return RenderInlineMarkdown(paragraph);
var html = document.ToHtml(MarkdownParser.Pipeline);
return new HtmlString(html.EnsureTrimmed());
}
private static HtmlString RenderInlineMarkdown(ParagraphBlock paragraph)
{
if (paragraph.Inline is null)
return HtmlString.Empty;
var subscription = DocumentationObjectPoolProvider.HtmlRendererPool.Get();
subscription.HtmlRenderer.WriteChildren(paragraph.Inline);
var result = subscription.RentedStringBuilder?.ToString();
DocumentationObjectPoolProvider.HtmlRendererPool.Return(subscription);
return result == null ? HtmlString.Empty : new HtmlString(result.EnsureTrimmed());
}
[SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly")]
private static void RenderAppliesToHtml(HtmlRenderer renderer, AppliesToDirective appliesToDirective)
{
var appliesTo = appliesToDirective.AppliesTo;
if (appliesTo is null || appliesTo == ApplicableTo.All)
return;
var viewModel = new Components.ApplicableToViewModel
{
AppliesTo = appliesTo,
Inline = false,
VersionsConfig = appliesToDirective.Build.VersionsConfiguration
};
var slice = AppliesToView.Create(viewModel);
slice.RenderAsync(renderer.Writer).GetAwaiter().GetResult();
}
private static void RenderContributorsHtml(HtmlRenderer renderer, ContributorsBlock block)
{
var slice = ContributorsView.Create(new ContributorsViewModel
{
Contributors = block.Contributors
});
RenderRazorSlice(slice, renderer);
}
/// <summary>
/// Renders a Mermaid code block as a pre.mermaid element for client-side rendering by Mermaid.js.
/// </summary>
private static void RenderMermaidBlock(HtmlRenderer renderer, EnhancedCodeBlock block)
{
_ = renderer.Write("<pre class=\"mermaid\">");
var commonIndent = GetCommonIndent(block);
for (var i = 0; i < block.Lines.Count; i++)
{
var line = block.Lines.Lines[i];
var slice = line.Slice;
// Skip empty lines at beginning and end
if ((i == 0 || i == block.Lines.Count - 1) && slice.IsEmptyOrWhitespace())
continue;
// Remove common indentation
var indent = CountIndentation(slice);
if (indent >= commonIndent)
slice.Start += commonIndent;
_ = renderer.WriteEscape(slice);
_ = renderer.WriteLine();
}
_ = renderer.Write("</pre>");
}
}