-
-
Notifications
You must be signed in to change notification settings - Fork 588
Expand file tree
/
Copy pathDocumentationMarkdownViewer.cs
More file actions
259 lines (227 loc) · 8.75 KB
/
Copy pathDocumentationMarkdownViewer.cs
File metadata and controls
259 lines (227 loc) · 8.75 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using ColorTextBlock.Avalonia;
using Markdown.Avalonia;
using StabilityMatrix.Core.Models.Documentation;
namespace StabilityMatrix.Avalonia.Controls;
/// <summary>
/// A <see cref="BetterMarkdownScrollViewer"/> that routes hyperlink clicks through a
/// bindable <see cref="LinkCommand"/> (so relative <c>.md</c> links can navigate in-app
/// and external links can open in the browser) and resolves relative image paths against
/// <see cref="ImageBaseUrl"/> via the engine's asset path root.
/// </summary>
public class DocumentationMarkdownViewer : BetterMarkdownScrollViewer
{
/// <summary>
/// Command invoked when a hyperlink is clicked. The command parameter is the raw href string.
/// </summary>
public static readonly StyledProperty<ICommand?> LinkCommandProperty = AvaloniaProperty.Register<
DocumentationMarkdownViewer,
ICommand?
>(nameof(LinkCommand));
/// <summary>
/// Base URL used to resolve relative image paths in the rendered markdown
/// (e.g. the raw URL of the current page's folder).
/// </summary>
public static readonly StyledProperty<string?> ImageBaseUrlProperty = AvaloniaProperty.Register<
DocumentationMarkdownViewer,
string?
>(nameof(ImageBaseUrl));
public ICommand? LinkCommand
{
get => GetValue(LinkCommandProperty);
set => SetValue(LinkCommandProperty, value);
}
/// <summary>
/// Zoom factor applied to the rendered document content (1.0 = 100%).
/// Scales the content inside the internal scroll viewer, so the scrollbar is unaffected.
/// </summary>
public static readonly StyledProperty<double> ContentZoomProperty = AvaloniaProperty.Register<
DocumentationMarkdownViewer,
double
>(nameof(ContentZoom), 1.0);
public string? ImageBaseUrl
{
get => GetValue(ImageBaseUrlProperty);
set => SetValue(ImageBaseUrlProperty, value);
}
public double ContentZoom
{
get => GetValue(ContentZoomProperty);
set => SetValue(ContentZoomProperty, value);
}
/// <summary>
/// Hosts the document content inside the internal scroll viewer so zoom can scale the
/// content without scaling the scrollbar. Null if the base control's composition changes.
/// </summary>
private readonly LayoutTransformControl? zoomHost;
public DocumentationMarkdownViewer()
{
ApplyLinkCommand();
ApplyImageBaseUrl();
// The base ctor composes a non-templated inner ScrollViewer (a direct visual child)
// whose Content is the document wrapper, and never reassigns Content afterwards
// (page changes only swap the wrapper's Document). Re-parent the wrapper into a
// LayoutTransformControl so zoom scales the document but not the scrollbar, and add
// right margin so the overlay scrollbar doesn't cover the rightmost text.
if (this.GetVisualChildren().OfType<ScrollViewer>().FirstOrDefault() is { } innerViewer)
{
if (innerViewer.Content is Control content)
{
innerViewer.Content = null;
zoomHost = new LayoutTransformControl
{
Child = content,
Margin = new Thickness(0, 0, 18, 0),
};
innerViewer.Content = zoomHost;
}
else
{
// Fallback: at least keep the scrollbar off the content.
innerViewer.Padding = new Thickness(0, 0, 18, 0);
}
}
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == LinkCommandProperty)
{
ApplyLinkCommand();
}
else if (change.Property == ImageBaseUrlProperty)
{
ApplyImageBaseUrl();
}
else if (change.Property == ContentZoomProperty)
{
ApplyContentZoom();
}
else if (change.Property == MarkdownProperty)
{
// Page changes swap the document inside the same scroll viewer, which otherwise
// keeps the previous page's offset and drops the reader mid-way down a page they
// have never seen. Anchor navigation re-scrolls on a later layout pass, so a
// deep link to a heading still wins over this.
ScrollValue = new Vector(ScrollValue.X, 0);
}
}
private void ApplyContentZoom()
{
if (zoomHost is null)
return;
// Guard against zero/negative values from bad bindings.
var zoom = Math.Clamp(ContentZoom, 0.25, 4.0);
zoomHost.LayoutTransform = new ScaleTransform(zoom, zoom);
}
private void ApplyLinkCommand()
{
// The engine owns the HyperlinkCommand used for all rendered links. The Engine getter
// always returns an IMarkdownEngine2 (custom IMarkdownEngine values are upgraded to a
// wrapper that only implements IMarkdownEngine2), so match on that interface.
if (Engine is IMarkdownEngine2 engine)
{
engine.HyperlinkCommand = LinkCommand;
}
}
private void ApplyImageBaseUrl()
{
// AssetPathRoot flows through to the engine's bitmap loader so relative image
// paths resolve against the raw docs URL.
AssetPathRoot = ImageBaseUrl ?? string.Empty;
}
private static readonly string[] HeadingClasses =
[
"Heading1",
"Heading2",
"Heading3",
"Heading4",
"Heading5",
"Heading6",
];
/// <summary>
/// Scrolls the rendered content so the heading matching the given GitHub-style anchor slug
/// is brought to the top of the viewport.
/// </summary>
/// <param name="anchor">The bare heading slug (no leading <c>#</c>).</param>
/// <returns><c>true</c> if a matching heading was found at call time; otherwise <c>false</c>.</returns>
public bool ScrollToAnchor(string anchor)
{
if (string.IsNullOrWhiteSpace(anchor))
return false;
var slug = DocumentationPathResolver.Slugify(anchor);
if (slug.Length == 0)
return false;
// Content is built synchronously when Markdown changes, but layout/measure (needed for
// TranslatePoint) only runs on the next layout pass — defer the actual scroll.
var found = FindHeadingBySlug(slug) is not null;
Dispatcher.UIThread.Post(
() =>
{
var target = FindHeadingBySlug(slug);
if (target is not null)
ScrollHeadingIntoView(target);
},
DispatcherPriority.Background
);
return found;
}
/// <summary>
/// Locates the heading control whose slug matches, applying GitHub-style duplicate suffixes
/// (<c>-1</c>, <c>-2</c>, ...) in document order.
/// </summary>
private CTextBlock? FindHeadingBySlug(string slug)
{
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var descendant in this.GetVisualDescendants())
{
if (descendant is not CTextBlock textBlock || !IsHeading(textBlock))
continue;
var baseSlug = DocumentationPathResolver.Slugify(textBlock.Text ?? string.Empty);
if (baseSlug.Length == 0)
continue;
string effectiveSlug;
if (seen.TryGetValue(baseSlug, out var count))
{
effectiveSlug = $"{baseSlug}-{count}";
seen[baseSlug] = count + 1;
}
else
{
effectiveSlug = baseSlug;
seen[baseSlug] = 1;
}
if (string.Equals(effectiveSlug, slug, StringComparison.Ordinal))
return textBlock;
}
return null;
}
private static bool IsHeading(StyledElement control)
{
foreach (var cls in HeadingClasses)
{
if (control.Classes.Contains(cls))
return true;
}
return false;
}
private void ScrollHeadingIntoView(Visual heading)
{
// Position of the heading relative to this control's viewport, plus the current scroll
// offset, gives the heading's Y within the scrollable content.
var current = ScrollValue;
var point = heading.TranslatePoint(new Point(0, 0), this);
if (point is null)
return;
var targetY = Math.Max(0, point.Value.Y + current.Y);
ScrollValue = new Vector(current.X, targetY);
}
}