-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathToolkitSampleRenderer.xaml.cs
More file actions
378 lines (325 loc) · 13.9 KB
/
ToolkitSampleRenderer.xaml.cs
File metadata and controls
378 lines (325 loc) · 13.9 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if !HAS_UNO
using ColorCode;
#endif
using CommunityToolkit.Tooling.SampleGen.Metadata;
using Windows.Storage;
#if WINAPPSDK
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
#endif
namespace CommunityToolkit.App.Shared.Renderers;
/// <summary>
/// Handles the display of a single toolkit sample, its source code, and the options that control it.
/// </summary>
public sealed partial class ToolkitSampleRenderer : Page
{
/// <summary>
/// Creates a new instance of <see cref="ToolkitSampleRenderer"/>.
/// </summary>
public ToolkitSampleRenderer()
{
this.InitializeComponent();
}
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="Metadata"/> property.
/// </summary>
public static readonly DependencyProperty MetadataProperty =
DependencyProperty.Register(nameof(Metadata), typeof(ToolkitSampleMetadata), typeof(ToolkitSampleRenderer), new PropertyMetadata(null, OnMetadataPropertyChanged));
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="SampleControlInstance"/> property.
/// </summary>
public static readonly DependencyProperty SampleControlInstanceProperty =
DependencyProperty.Register(nameof(SampleControlInstance), typeof(UIElement), typeof(ToolkitSampleRenderer), new PropertyMetadata(null));
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="SampleOptionsPaneInstance"/> property.
/// </summary>
public static readonly DependencyProperty SampleOptionsPaneInstanceProperty =
DependencyProperty.Register(nameof(SampleOptionsPaneInstance), typeof(UIElement), typeof(ToolkitSampleRenderer), new PropertyMetadata(null));
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="XamlCode"/> property.
/// </summary>
public static readonly DependencyProperty XamlCodeProperty =
DependencyProperty.Register(nameof(XamlCode), typeof(string), typeof(ToolkitSampleRenderer), new PropertyMetadata(null));
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="CSharpCode"/> property.
/// </summary>
public static readonly DependencyProperty CSharpCodeProperty =
DependencyProperty.Register(nameof(CSharpCode), typeof(string), typeof(ToolkitSampleRenderer), new PropertyMetadata(null));
/// <summary>
/// The backing <see cref="DependencyProperty"/> for the <see cref="IsTabbedMode"/> property.
/// </summary>
public static readonly DependencyProperty IsTabbedModeProperty =
DependencyProperty.Register(nameof(IsTabbedMode), typeof(bool), typeof(ToolkitSampleRenderer), new PropertyMetadata(false));
public ToolkitSampleMetadata? Metadata
{
get { return (ToolkitSampleMetadata?)GetValue(MetadataProperty); }
set { SetValue(MetadataProperty, value); }
}
/// <summary>
/// The sample control instance being displayed.
/// </summary>
public UIElement? SampleControlInstance
{
get => (UIElement?)GetValue(SampleControlInstanceProperty);
set => SetValue(SampleControlInstanceProperty, value);
}
/// <summary>
/// The options pane for the sample being displayed.
/// </summary>
public UIElement? SampleOptionsPaneInstance
{
get => (UIElement?)GetValue(SampleOptionsPaneInstanceProperty);
set => SetValue(SampleOptionsPaneInstanceProperty, value);
}
/// <summary>
/// The XAML code being rendered.
/// </summary>
public string? XamlCode
{
get => (string?)GetValue(XamlCodeProperty);
set => SetValue(XamlCodeProperty, value);
}
/// <summary>
/// The backing C# for the <see cref="XamlCode"/> being rendered.
/// </summary>
public string? CSharpCode
{
get => (string?)GetValue(CSharpCodeProperty);
set => SetValue(CSharpCodeProperty, value);
}
/// <summary>
/// The mode of which the control renders.
/// </summary>
public bool IsTabbedMode
{
get => (bool)GetValue(IsTabbedModeProperty);
set => SetValue(IsTabbedModeProperty, value);
}
private static async void OnMetadataPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
if (dependencyObject is ToolkitSampleRenderer renderer &&
renderer.Metadata != null &&
args.OldValue != args.NewValue)
{
await renderer.LoadData();
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Metadata = (ToolkitSampleMetadata)e.Parameter;
}
private async Task LoadData()
{
if (Metadata is null)
{
return;
}
XamlCode = (await GetMetadataFileContents(Metadata, "xaml"))?.Trim();
CSharpCode = (await GetMetadataFileContents(Metadata, "xaml.cs"))?.Trim();
// Remove Header License Comments from code samples for space
if (XamlCode?.StartsWith("<!-- Licensed") == true ||
XamlCode?.StartsWith("<!-- Licensed") == true)
{
// Note: We just use \n directly here as we don't know if the content will match the expected environment setup, we do know there'll be at least a \n though separating newlines, so we want to split on that, otherwise we'll skip the entire set of contents...
var lines = XamlCode.Split('\n').Skip(1);
XamlCode = string.Join('\n', lines).Trim();
}
if (CSharpCode?.StartsWith("// Licensed") == true)
{
var lines = CSharpCode.Split('\n').Skip(3);
CSharpCode = string.Join('\n', lines).Trim();
}
// Remove namespace line as not relevant to sample
if (CSharpCode?.StartsWith("namespace") == true)
{
var lines = CSharpCode.Split('\n').Skip(1);
CSharpCode = string.Join('\n', lines).Trim();
}
RenderCode();
var sampleControlInstance = (UIElement)Metadata.SampleControlFactory();
// Bind button commands to the sample instance so they can invoke methods via reflection.
if (Metadata.SampleButtons is not null)
{
foreach (var button in Metadata.SampleButtons)
{
button.BindToInstance(sampleControlInstance);
}
}
// Custom control-based sample options.
if (Metadata.SampleOptionsPaneType is not null && Metadata.SampleOptionsPaneFactory is not null)
{
SampleOptionsPaneInstance = (UIElement)Metadata.SampleOptionsPaneFactory(sampleControlInstance);
}
// Source generater-based sample options
else if (sampleControlInstance is IToolkitSampleGeneratedOptionPropertyContainer propertyContainer)
{
// Pass the generated sample options to the displayed Control instance.
// Generated properties reference these in getters and setters.
propertyContainer.GeneratedPropertyMetadata = Metadata.GeneratedSampleOptions;
if (propertyContainer.GeneratedPropertyMetadata is not null)
{
SampleOptionsPaneInstance = new GeneratedSampleOptionsRenderer
{
SampleOptions = propertyContainer.GeneratedPropertyMetadata
};
}
}
else
{
OptionsScrollViewer.Visibility = Visibility.Collapsed;
}
// Generated options must be assigned before attempting to render the control,
// else some platforms will nullref from XAML but not properly ignore the exception when binding to generated properties.
SampleControlInstance = sampleControlInstance;
}
public static async Task<string?> GetMetadataFileContents(ToolkitSampleMetadata metadata, string fileExtension)
{
var filePath = GetRelativePathToFileWithoutExtension(metadata.SampleControlType);
try
{
// Workaround for https://github.com/unoplatform/uno/issues/8649
if (fileExtension.Contains(".cs"))
{
fileExtension = fileExtension.Replace(".cs", ".cs.dat");
}
var finalPath = $"ms-appx:///{filePath}.{fileExtension.Trim('.')}";
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///{filePath}.{fileExtension.Trim('.')}"));
var textContents = await FileIO.ReadTextAsync(file);
return textContents;
}
catch (Exception e)
{
return $"Exception Encountered Loading file '{filePath}':\n{e.Message}\n{e.StackTrace}";
}
}
/// <summary>
/// Compute path to a code file bundled in the app using type information.
/// Assumes path to file within the included assembly folder matches the namespace.
/// </summary>
private static string GetRelativePathToFileWithoutExtension(Type type)
{
// TODO: https://github.com/CommunityToolkit/Labs-Windows/issues/142
// MSBuild uses wildcard to find the files, and the wildcards decide where they end up
// Single experiments use relative paths, the allExperiment head uses absolute paths that grab from all experiments
// The wildcard captures decide the paths. This discrepency is accounted for manually.
// Logic here is the exact same that MSBuild uses to find and include the files we need.
var assemblyName = typeof(ToolkitSampleRenderer).Assembly.GetName().Name;
if (string.IsNullOrWhiteSpace(assemblyName))
throw new InvalidOperationException();
var isAllExperimentHead = assemblyName.StartsWith("CommunityToolkit.", StringComparison.OrdinalIgnoreCase);
var isProjectTemplateHead = assemblyName.StartsWith("ProjectTemplate");
var isSingleExperimentHead = !isAllExperimentHead && !isProjectTemplateHead;
var simpleAssemblyName = type.Assembly.GetName().Name;
var typeNamespace = type.Namespace;
if (string.IsNullOrWhiteSpace(simpleAssemblyName))
{
throw new ArgumentException($"Unable to find assembly name for provided type {type}.", nameof(simpleAssemblyName));
}
if (string.IsNullOrWhiteSpace(typeNamespace))
{
throw new ArgumentException($"Unable to find namespace for provided type {type}.", nameof(typeNamespace));
}
var folderPath = typeNamespace.Replace(simpleAssemblyName, "").Trim('.').Replace('.', '/');
if (folderPath.Length != 0)
folderPath += "/";
// Component assembly names are formatted as 'ProjectTemplateExperiment.Samples'
// but the content folder is formatted as 'ProjectTemplate.Samples'
simpleAssemblyName = simpleAssemblyName.Replace("Experiment", "");
if (isSingleExperimentHead || isProjectTemplateHead)
{
return $"SourceAssets/{folderPath}{type.Name}";
}
if (isAllExperimentHead)
{
var sampleName = simpleAssemblyName.Replace(".Samples", "");
return $"SourceAssets/{sampleName}/samples/{folderPath}{type.Name}";
}
throw new InvalidOperationException("Unable to determine if running in a single or all experiment solution.");
}
private void ToolkitSampleRenderer_Loaded(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(this, IsTabbedMode ? "Tabbed" : "Normal", true);
}
private void ThemeBtn_OnClick(object sender, RoutedEventArgs e)
{
if (ContentPageHolder.ActualTheme == ElementTheme.Dark)
{
ContentPageHolder.RequestedTheme = ElementTheme.Light;
}
else
{
ContentPageHolder.RequestedTheme = ElementTheme.Dark;
}
if (this.ActualTheme != ContentPageHolder.RequestedTheme)
{
ThemeBG.Visibility = Visibility.Visible;
}
else
{
ThemeBG.Visibility = Visibility.Collapsed;
}
}
private void FlowDirectionBtn_OnClick(object sender, RoutedEventArgs e)
{
#if !HAS_UNO
if (PageControl.FlowDirection == FlowDirection.LeftToRight)
{
PageControl.FlowDirection = FlowDirection.RightToLeft;
}
else
{
PageControl.FlowDirection = FlowDirection.LeftToRight;
}
#endif
}
private void CodeBtn_OnClick(object sender, RoutedEventArgs e)
{
SourcecodeExpander.IsExpanded = !SourcecodeExpander.IsExpanded;
}
private void RenderCode()
{
// Uno doesn't support RichTextBlock, so we are using a normal TextBlock instead on WASM
#if !HAS_UNO
RichTextBlockFormatter codeFormatter = new RichTextBlockFormatter(ActualTheme);
#endif
if (XamlCode is not null)
{
#if HAS_UNO
XAMLCodeRenderer.Text = XamlCode;
#else
XAMLCodeRenderer.Blocks?.Clear();
codeFormatter.FormatRichTextBlock(XamlCode, Languages.FindById("xaml"), XAMLCodeRenderer);
#endif
}
if (CSharpCode is not null)
{
#if HAS_UNO
CSharpCodeRenderer.Text = CSharpCode;
#else
CSharpCodeRenderer.Blocks?.Clear();
codeFormatter.FormatRichTextBlock(CSharpCode, Languages.CSharp, CSharpCodeRenderer);
#endif
}
}
private void ToolkitSampleRenderer_ActualThemeChanged(FrameworkElement sender, object args)
{
RenderCode();
}
}