|
| 1 | +using System.Text; |
| 2 | +using System.Text.RegularExpressions; |
| 3 | +using System.Web; |
1 | 4 | using Microsoft.AspNetCore.Razor.TagHelpers; |
2 | 5 |
|
3 | 6 | namespace XtremeIdiots.Portal.Web.Helpers; |
4 | 7 |
|
5 | 8 | [HtmlTargetElement("player-name")] |
6 | | -public class PlayerNameTagHelper : TagHelper |
| 9 | +public partial class PlayerNameTagHelper : TagHelper |
7 | 10 | { |
8 | 11 | [HtmlAttributeName("value")] public string? Value { get; set; } |
9 | 12 |
|
10 | 13 | public override void Process(TagHelperContext context, TagHelperOutput output) |
11 | 14 | { |
12 | 15 | output.TagName = "span"; |
13 | 16 | output.TagMode = TagMode.StartTagAndEndTag; |
| 17 | + output.Attributes.SetAttribute("class", "cod-colored"); |
| 18 | + |
14 | 19 | if (string.IsNullOrWhiteSpace(Value)) |
15 | 20 | { |
16 | 21 | output.Content.SetContent(string.Empty); |
17 | 22 | return; |
18 | 23 | } |
19 | 24 |
|
20 | | - var cleaned = Value; |
21 | | - string[] toRemove = ["^1", "^2", "^3", "^4", "^5", "^6", "^7", "^8", "^9"]; |
22 | | - foreach (var code in toRemove) |
| 25 | + output.Content.SetHtmlContent(CodColorHelper.RenderColorCodes(Value)); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +internal static partial class CodColorHelper |
| 30 | +{ |
| 31 | + [GeneratedRegex(@"\^([0-9])")] |
| 32 | + private static partial Regex colorCodeRegex(); |
| 33 | + |
| 34 | + public static string RenderColorCodes(string input) |
| 35 | + { |
| 36 | + var matches = colorCodeRegex().Matches(input); |
| 37 | + if (matches.Count == 0) |
| 38 | + return HttpUtility.HtmlEncode(input); |
| 39 | + |
| 40 | + var result = new StringBuilder(); |
| 41 | + var lastIndex = 0; |
| 42 | + int? currentColor = null; |
| 43 | + |
| 44 | + foreach (var match in matches.Cast<Match>()) |
| 45 | + { |
| 46 | + var textBefore = input[lastIndex..match.Index]; |
| 47 | + if (textBefore.Length > 0) |
| 48 | + { |
| 49 | + var encoded = HttpUtility.HtmlEncode(textBefore); |
| 50 | + if (currentColor.HasValue) |
| 51 | + result.Append($"<span class=\"cod-color-{currentColor.Value}\">{encoded}</span>"); |
| 52 | + else |
| 53 | + result.Append(encoded); |
| 54 | + } |
| 55 | + |
| 56 | + currentColor = int.Parse(match.Groups[1].Value); |
| 57 | + lastIndex = match.Index + match.Length; |
| 58 | + } |
| 59 | + |
| 60 | + var remaining = input[lastIndex..]; |
| 61 | + if (remaining.Length > 0) |
23 | 62 | { |
24 | | - cleaned = cleaned.Replace(code, string.Empty); |
| 63 | + var encoded = HttpUtility.HtmlEncode(remaining); |
| 64 | + if (currentColor.HasValue) |
| 65 | + result.Append($"<span class=\"cod-color-{currentColor.Value}\">{encoded}</span>"); |
| 66 | + else |
| 67 | + result.Append(encoded); |
25 | 68 | } |
26 | 69 |
|
27 | | - output.Content.SetContent(cleaned); |
| 70 | + return result.ToString(); |
28 | 71 | } |
29 | 72 | } |
0 commit comments