Skip to content

Commit

Permalink
Merge pull request #993 from unoplatform/dev/xygu/20230912/xmlns-on-a…
Browse files Browse the repository at this point in the history
…ttached-property
  • Loading branch information
Xiaoy312 authored Sep 15, 2023
2 parents e3a0303 + 2180b4e commit c1a5b9d
Showing 1 changed file with 35 additions and 12 deletions.
47 changes: 35 additions & 12 deletions Uno.Gallery/Uno.Gallery.Shared/Extensions/XamlDisplayExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -375,26 +375,49 @@ protected override XmlWriter CreateRewriter(StringBuilder buffer)
}
protected override string PostprocessXaml(string xaml)
{
xaml = RemoveXmlns(xaml);

xaml = ExtractXmlns(xaml);
xaml = RemoveOptions(xaml);

return xaml;
}

private static string RemoveXmlns(string xaml)
private static string ExtractXmlns(string xaml)
{
var namespaces = new[]
{
"http://schemas.microsoft.com/winfx/2006/xaml/presentation",
"http://schemas.microsoft.com/winfx/2006/xaml",
};
return Regex.Replace(xaml, @"\s+xmlns(:(?<prefix>\w+))?=""(?<uri>[^""]+)""", m =>
// extract/remove all xmlns declarations from the xaml,
// and add them at the start, like so:
// xmlns:this="example.com"
// ...
//
// <!-- rest of xaml... -->

// some well known xmlns are also skipped:
bool SkipWellKnownXmlns(KeyValuePair<string, string> x) =>
// skip well known xmlnses that are just assumed
// check prefix too, since default name(url) can also be used for platform conditionals, and we should not ignore those
x is not { Key: "", Value: "http://schemas.microsoft.com/winfx/2006/xaml/presentation" } &&
x is not { Key: "x", Value: "http://schemas.microsoft.com/winfx/2006/xaml" };

var xmlns = new Dictionary<string, string>();

xaml = Regex.Replace(xaml, @"\s+xmlns(?<prefix>:\w+)?=\""(?<name>[^""]+)""", m =>
{
return namespaces?.Contains(m.Groups["uri"].Value) == true
? null
: m.Value;
if (xmlns.TryAdd(m.Groups["prefix"].Value.TrimStart(':'), m.Groups["name"].Value))
{
// ignoring xmlns re-definitions in nested node for now
}

return string.Empty;
});

if (xmlns.Where(SkipWellKnownXmlns).ToArray() is { Length: >0 } injectables)
{
xaml = string.Join("\n", injectables
.OrderBy(x => x.Key)
.Select(x => $"xmlns{(string.IsNullOrEmpty(x.Key) ? null : $":{x.Key}")}=\"{x.Value}\"")
) + "\n...\n\n" + xaml;
}

return xaml;
}

private static string RemoveOptions(string xaml)
Expand Down

0 comments on commit c1a5b9d

Please sign in to comment.