A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Enabled Hover capability on Monaco Editor and fixed JSON serialization issue. (#1015)
Etienne BAUDOUX80a226c596dc
diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/Monaco/TextModel.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/Monaco/TextModel.csindex 613d5a787..56cccc2d3 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/Monaco/TextModel.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/Monaco/TextModel.cs@@ -291,7 +291,7 @@ public class TextModel/// @return An array containing the new decorations identifiers./// </summary>public ValueTask<string[]> DeltaDecorationsAsync(IJSRuntime runtime, string[] oldDecorations, ModelDeltaDecoration[] newDecorations, int? ownerId)- => runtime.InvokeAsync<string[]>("devtoys.MonacoEditor.TextModel.deltaDecorations", Uri, oldDecorations, newDecorations, ownerId);+ => runtime.InvokeAsync<string[]>("devtoys.MonacoEditor.TextModel.deltaDecorations", Uri, oldDecorations, newDecorations.PrepareJsInterop(), ownerId);/// <summary>/// Get the options associated with a decoration.diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.csindex fb1abd42a..a4654806e 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs@@ -77,13 +77,13 @@ public partial class MonacoEditor : RicherMonacoEditorBaseoptions.MouseWheelZoom = false;options.OverviewRulerBorder = false;options.ScrollBeyondLastLine = false;- options.FontLigatures = false;+ options.FontLigatures = true;options.SnippetSuggestions = "none";options.CodeLens = false;options.QuickSuggestions = new QuickSuggestionsOptions { Comments = false, Other = false, Strings = false };options.WordBasedSuggestions = false;options.Minimap = new EditorMinimapOptions { Enabled = false };- options.Hover = new EditorHoverOptions { Enabled = false };+ options.Hover = new EditorHoverOptions { Enabled = true, Above = false };options.MatchBrackets = "always";options.BracketPairColorization = new BracketPairColorizationOptions { Enabled = true };options.RenderLineHighlightOnlyWhenFocus = true;diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorDiff.razor.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorDiff.razor.csindex 4f8849d41..2e175e1db 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorDiff.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorDiff.razor.cs@@ -51,12 +51,12 @@ public partial class MonacoEditorDiff : RicherMonacoEditorDiffBaseoptions.MouseWheelZoom = false;options.OverviewRulerBorder = false;options.ScrollBeyondLastLine = false;- options.FontLigatures = false;+ options.FontLigatures = true;options.SnippetSuggestions = "none";options.CodeLens = false;options.QuickSuggestions = new QuickSuggestionsOptions { Comments = false, Other = false, Strings = false };options.Minimap = new EditorMinimapOptions { Enabled = false };- options.Hover = new EditorHoverOptions { Enabled = false };+ options.Hover = new EditorHoverOptions { Enabled = true, Above = false };options.MatchBrackets = "always";options.BracketPairColorization = new BracketPairColorizationOptions { Enabled = true };options.RenderLineHighlightOnlyWhenFocus = true;diff --git a/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverter.cs b/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverter.csnew file mode 100644index 000000000..9000bcaea--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverter.cs@@ -0,0 +1,18 @@+using System.Text.Json;+using System.Text.Json.Serialization;++namespace DevToys.Blazor.Core.Converters;++internal sealed class PolymorphicConverter<T> : JsonConverter<T>+{+ public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)+ {+ throw new NotImplementedException();+ }++ public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)+ {+ Guard.IsNotNull(value);+ JsonSerializer.Serialize(writer, value, value.GetType(), options);+ }+}diff --git a/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverterFactory.cs b/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverterFactory.csnew file mode 100644index 000000000..50ad531bd--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Core/Converters/PolymorphicConverterFactory.cs@@ -0,0 +1,25 @@+using System.Reflection;+using System.Text.Json;+using System.Text.Json.Serialization;++namespace DevToys.Blazor.Core.Converters;++internal sealed class PolymorphicConverterFactory : JsonConverterFactory+{+ /// <inheritdoc />+ public override bool CanConvert(Type typeToConvert)+ {+ return typeToConvert.IsInterface || typeToConvert.IsAbstract;+ }++ /// <inheritdoc />+ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)+ {+ return (JsonConverter)Activator.CreateInstance(+ typeof(PolymorphicConverter<>).MakeGenericType(typeToConvert),+ BindingFlags.Instance | BindingFlags.Public,+ null,+ new object[] { },+ null)!;+ }+}diff --git a/src/app/dev/DevToys.Blazor/Core/Extensions/JsonExtensions.cs b/src/app/dev/DevToys.Blazor/Core/Extensions/JsonExtensions.csnew file mode 100644index 000000000..f968c5c92--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Core/Extensions/JsonExtensions.cs@@ -0,0 +1,113 @@+using System.Dynamic;+using System.Text.Json;+using DevToys.Blazor.Core.Converters;++namespace DevToys.Blazor.Core.Extensions;++internal static class JsonExtensions+{+ /// <summary>+ /// Converts the given object to a dynamic object resulting from the serialization of the object using the given <paramref name="serializerOptions"/>.+ /// By default, this method will not include null values. This can be beneficial for interop scenarios where a JavaScript code handles `undefined` and `null` differently.+ /// </summary>+ /// <remarks>+ /// <para>+ /// In Blazor, passing an object to a JavaScript using <see cref="IJSRuntime.InvokeAsync{TValue}(string, CancellationToken, object?[]?)"/> will serialize the object+ /// into a JSON using a <see cref="JsonSerializerOptions"/> defined in the .NET framework.+ /// <see href="https://github.com/dotnet/aspnetcore/blob/e6be3e95fec33ca3a3b576df4b265ead680a91a0/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs#L31-L44">See code on GitHub</see>.+ /// Unfortunately, we are not allowed to customize this JSON serialization and can have a negative impact on us occasionally. For instance, it does not allow to exclude null values.+ /// <see href="https://github.com/dotnet/aspnetcore/issues/12685">See issue #12685 on GitHub</see>+ /// </para>+ /// <para>+ /// Monaco Editor, for instance, has many properties that are optional. Most of the time, it is fine. But occasionally, Monaco Editor behavior varies based on whether+ /// a property is `null` or `undefined`.+ /// </para>+ /// <para>+ /// This <see cref="PrepareJsInterop{T}(T, JsonSerializerOptions?)"/> method is workaround to this limitation as it will (by default) exclude null values from the JSON serialization,+ /// making any .NET `null` value being interpreted as `undefined` in JavaScript.+ /// </para>+ /// <para>+ /// Due to the nature of this method, it is recommended to avoid using this method as much as possible as it can cause some significant performance issues.+ /// </para>+ /// </remarks>+ internal static object? PrepareJsInterop<T>(this T obj, JsonSerializerOptions? serializerOptions = null)+ {+ // Handle simple types+ if (obj == null)+ {+ return obj;+ }++ Type type = obj.GetType();+ if (obj.GetType().IsPrimitive || type == typeof(string))+ {+ return obj;+ }++ // Handle jsonElements+ if (obj is JsonElement jsonElement)+ {+ return jsonElement.PrepareJsonElement();+ }++ // Set default serializer options if necessary+ serializerOptions ??= new JsonSerializerOptions+ {+ MaxDepth = 32,+ DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,+ Converters =+ {+ new PolymorphicConverterFactory()+ }+ };++ // Handle all kind of complex objects+ object? result+ = JsonSerializer+ .Deserialize<JsonElement>(+ JsonSerializer.Serialize<object>(obj, serializerOptions))+ .PrepareJsonElement();++ return result;+ }++ private static object? PrepareJsonElement(this JsonElement obj)+ {+ switch (obj.ValueKind)+ {+ case JsonValueKind.Object:+ IDictionary<string, object?> expando = new ExpandoObject();+ foreach (JsonProperty property in obj.EnumerateObject())+ {+ expando.Add(property.Name, property.Value.PrepareJsonElement());+ }++ return expando;++ case JsonValueKind.Array:+ return obj.EnumerateArray().Select(jsonElement => jsonElement.PrepareJsonElement());++ case JsonValueKind.String:+ return obj.GetString();++ case JsonValueKind.Number:+ return obj.GetDecimal();++ case JsonValueKind.True:+ return true;++ case JsonValueKind.False:+ return false;++ case JsonValueKind.Null:+ return null;++ case JsonValueKind.Undefined:+ return null;++ default:+ throw new NotSupportedException();+ }+ }+}