[PreviewPane][Monaco]Format json/xml before rendering (#19980)

This commit is contained in:
Davide Giacometti
2022-08-24 13:08:10 +02:00
committed by GitHub
parent e7d3aadec3
commit 16c7a22410
10 changed files with 198 additions and 11 deletions

View File

@@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.PowerToys.PreviewHandler.Monaco.Formatters
{
public interface IFormatter
{
/// <summary>
/// Gets the language to which the formatter is applied
/// </summary>
string LangSet { get; }
/// <summary>
/// Format the value
/// </summary>
/// <param name="value">The value to format</param>
/// <returns>The value formatted</returns>
string Format(string value);
}
}

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.PowerToys.PreviewHandler.Monaco.Formatters
{
using System.Text.Json;
public class JsonFormatter : IFormatter
{
/// <inheritdoc/>
public string LangSet => "json";
/// <inheritdoc/>
public string Format(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
using (var jDocument = JsonDocument.Parse(value, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }))
{
return JsonSerializer.Serialize(jDocument, new JsonSerializerOptions { WriteIndented = true });
}
}
}
}

View File

@@ -0,0 +1,41 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.PowerToys.PreviewHandler.Monaco.Formatters
{
using System.Text;
using System.Xml;
public class XmlFormatter : IFormatter
{
/// <inheritdoc/>
public string LangSet => "xml";
/// <inheritdoc/>
public string Format(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(value);
var stringBuilder = new StringBuilder();
var xmlWriterSettings = new XmlWriterSettings()
{
OmitXmlDeclaration = xmlDocument.FirstChild.NodeType != XmlNodeType.XmlDeclaration,
Indent = true,
};
using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
{
xmlDocument.Save(xmlWriter);
}
return stringBuilder.ToString();
}
}
}