add tag helpers +icon configuration

This commit is contained in:
2022-12-12 16:11:49 +01:00
parent 430de2ae54
commit 05585ed886
13 changed files with 440 additions and 3 deletions
+26
View File
@@ -41,4 +41,30 @@ public static class HttpContextExtensions
//string ipAddress = context.GetServerVariable("HTTP_X_FORWARDED_FOR");
//return !ipAddress.IsNullOrEmpty() ? ipAddress.Split(',')[0] : context.GetServerVariable("REMOTE_ADDR");
}
public static bool IsPartOfUrl(this HttpContext model, string url)
{
if (url.IsNullOrEmpty())
{
return false;
}
string destination = url.EnsureStartsWith('/').TrimEnd('/');
string current = model.Request.Path.ToUriComponent().TrimEnd('/');
return current.StartsWith(destination, StringComparison.InvariantCultureIgnoreCase);
}
public static bool IsUrl(this HttpContext model, string url)
{
if (url.IsNullOrEmpty())
{
return false;
}
string destination = url.EnsureStartsWith('/').TrimEnd('/');
string current = model.Request.Path.ToUriComponent().TrimEnd('/');
return current.Equals(destination, StringComparison.InvariantCultureIgnoreCase);
}
}
+19
View File
@@ -1,4 +1,6 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace zero.Extensions;
@@ -193,4 +195,21 @@ public static class StringExtensions
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
public static string NewLinesToBr(this string source)
{
StringBuilder builder = new();
string[] lines = source.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
{
builder.Append("<br/>");
}
builder.Append(WebUtility.HtmlEncode(lines[i]));
}
return builder.ToString();
}
}
+12
View File
@@ -0,0 +1,12 @@
namespace zero.Rendering;
public class IconOptions
{
public string CssClass { get; set; } = "app-icon";
public int DefaultSize { get; set; } = 18;
public decimal DefaultStrokeWidth { get; set; } = 2;
public string Path { get; set; }
}
+2
View File
@@ -8,5 +8,7 @@ public class ZeroRenderingModule : ZeroModule
public override void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IRazorRenderer, RazorRenderer>();
services.AddOptions<IconOptions>().Bind(configuration.GetSection("Zero:Icons"));
}
}
+42
View File
@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement(Attributes = "app-active")]
public class ActiveTagHelper : TagHelper
{
private readonly IHttpContextAccessor _httpContextAccessor;
[HtmlAttributeName("class")]
public string Classes { get; set; }
[HtmlAttributeName("href")]
public string Href { get; set; }
public ActiveTagHelper(IHttpContextAccessor contextAccessor)
{
_httpContextAccessor = contextAccessor;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.RemoveAll("app-active");
HashSet<string> classes = Classes?.Split(" ").ToHashSet() ?? new HashSet<string>();
if (_httpContextAccessor.HttpContext.IsPartOfUrl(Href))
{
classes.Add("is-active");
}
if (_httpContextAccessor.HttpContext.IsUrl(Href))
{
classes.Add("is-active-exact");
}
output.Attributes.SetAttribute("href", Href);
output.Attributes.SetAttribute("class", string.Join(" ", classes));
}
}
+134
View File
@@ -0,0 +1,134 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Collections;
namespace zero.TagHelpers;
public abstract class BaseSelectTagHelper : TagHelper
{
protected const string FOR_ATTRIBUTE_NAME = "asp-for";
protected bool AllowMultiple;
protected ICollection<string> CurrentValues;
protected BaseSelectTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
/// <summary>
/// Gets the <see cref="IHtmlGenerator"/> used to generate the <see cref="SelectTagHelper"/>'s output.
/// </summary>
protected IHtmlGenerator Generator { get; }
/// <summary>
/// Gets the <see cref="Rendering.ViewContext"/> of the executing view.
/// </summary>
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName(FOR_ATTRIBUTE_NAME)]
public ModelExpression For { get; set; }
/// <summary>
/// A collection of <see cref="SelectListItem"/> objects used to populate the &lt;select&gt; element with
/// &lt;optgroup&gt; and &lt;option&gt; elements.
/// </summary>
public List<SelectListItem> Items { get; set; } = new List<SelectListItem>();
/// <summary>
/// The name of the &lt;input&gt; element.
/// </summary>
/// <remarks>
/// Passed through to the generated HTML in all cases. Also used to determine whether <see cref="For"/> is
/// valid with an empty <see cref="ModelExpression.Name"/>.
/// </remarks>
public string Name { get; set; }
/// <inheritdoc />
public override void Init(TagHelperContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (For == null)
{
// Informs contained elements that they're running within a targeted <select/> element.
context.Items[typeof(SelectTagHelper)] = null;
return;
}
// Base allowMultiple on the instance or declared type of the expression to avoid a
// "SelectExpressionNotEnumerable" InvalidOperationException during generation.
// Metadata.IsEnumerableType is similar but does not take runtime type into account.
var realModelType = For.ModelExplorer.ModelType;
AllowMultiple = typeof(string) != realModelType && typeof(IEnumerable).IsAssignableFrom(realModelType);
CurrentValues = Generator.GetCurrentValues(ViewContext, For.ModelExplorer, For.Name, AllowMultiple);
// Whether or not (not being highly unlikely) we generate anything, could update contained <option/>
// elements. Provide selected values for <option/> tag helpers.
//var currentValues = _currentValues == null ? null : new CurrentValues(_currentValues);
//context.Items[typeof(SelectTagHelper)] = currentValues;
}
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "select";
// Pass through attribute that is also a well-known HTML attribute. Must be done prior to any copying
// from a TagBuilder.
if (Name != null)
{
output.CopyHtmlAttribute(nameof(Name), context);
}
// Ensure GenerateSelect() _never_ looks anything up in ViewData.
var items = Items ?? Enumerable.Empty<SelectListItem>();
// Ensure Generator does not throw due to empty "fullName" if user provided a name attribute.
IDictionary<string, object> htmlAttributes = null;
if (string.IsNullOrEmpty(For.Name) && string.IsNullOrEmpty(ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix) && !string.IsNullOrEmpty(Name))
{
htmlAttributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)
{
{ "name", Name },
};
}
var tagBuilder = Generator.GenerateSelect(
ViewContext,
For.ModelExplorer,
optionLabel: null,
expression: For.Name,
selectList: items,
currentValues: CurrentValues,
allowMultiple: AllowMultiple,
htmlAttributes: htmlAttributes);
if (tagBuilder != null)
{
output.MergeAttributes(tagBuilder);
if (tagBuilder.HasInnerHtml)
{
output.PostContent.AppendHtml(tagBuilder.InnerHtml);
}
}
output.PreElement.AppendHtml("<div class=\"form-select\">");
// TODO use iconoptions + taghelper
output.PostElement.AppendHtml("<span class=\"-icon\"><svg class=\"app-icon\" width=\"18\" height=\"18\" xmlns=\"http://www.w3.org/2000/svg\" stroke-width=\"2\" data-symbol=\"chevron-down\"><use xlink:href=\"/assets/icons/feather.svg#chevron-down\"></use></svg></span>");
output.PostElement.AppendHtml("</div>");
return Task.CompletedTask;
}
}
+38
View File
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement(Attributes = PREFIX + "*")]
public class ClassTagHelper : TagHelper
{
private const string PREFIX = "app-class:";
[HtmlAttributeName("class")]
public string Classes { get; set; }
private IDictionary<string, bool> _classValues;
[HtmlAttributeName("", DictionaryAttributePrefix = PREFIX)]
public IDictionary<string, bool> ClassValues
{
get => _classValues ?? (_classValues = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase));
set => _classValues = value;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var items = _classValues.Where(e => e.Value).Select(e => e.Key).ToList();
if (!String.IsNullOrEmpty(Classes))
{
items.Insert(0, Classes);
}
if (items.Any())
{
var classes = String.Join(" ", items.ToArray());
output.Attributes.Add("class", classes);
}
}
}
+68
View File
@@ -0,0 +1,68 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace zero.TagHelpers;
[HtmlTargetElement("app-icon", TagStructure = TagStructure.NormalOrSelfClosing)]
public class IconTagHelper : TagHelper
{
public string Symbol { get; set; }
public int Size { get; set; } = -1;
public decimal Stroke { get; set; } = -1;
public string Class { get; set; }
private IconOptions _options;
private readonly ILogger<IconTagHelper> _logger;
public IconTagHelper(IOptionsMonitor<IconOptions> options, ILogger<IconTagHelper> logger)
{
_options = options.CurrentValue;
_logger = logger;
options.OnChange(val => _options = val);
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (_options.Path.IsNullOrWhiteSpace())
{
_logger.LogWarning("Could not render <app-icon />. Please configure the path with IconOptions before.");
output.SuppressOutput();
return;
}
int size = Size < 0 ? _options.DefaultSize : Size;
string stroke = (Stroke < 0 ? _options.DefaultStrokeWidth : Stroke).ToString().Replace(',', '.');
output.TagName = "svg";
output.Attributes.SetAttribute("class", Class.HasValue() ? $"{_options.CssClass} {Class}" : _options.CssClass);
output.Attributes.SetAttribute("width", size);
output.Attributes.SetAttribute("height", size);
output.Attributes.SetAttribute("xmlns", "http://www.w3.org/2000/svg");
output.Attributes.SetAttribute("stroke-width", stroke);
output.Attributes.SetAttribute("data-symbol", Symbol);
output.Content.SetHtmlContent(BuildIcon(Symbol, size, stroke));
}
public string BuildIcon(string symbol, int size = 18, string stroke = "2", string classes = null, bool withSvg = false)
{
string inner = $"<use xlink:href='{_options.Path}#{symbol}\'></use>";
if (!withSvg)
{
return inner;
}
return $"<svg class='{_options.CssClass}{(classes.HasValue() ? " " + classes : string.Empty)}' width='{size}' height='{size}'" +
$"xmlns='http://www.w3.org/2000/svg' stroke-width='{stroke}' data-symbol='{symbol}'>{inner}</svg>";
}
}
+17
View File
@@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement(Attributes = "app-if")]
public class IfTagHelper : TagHelper
{
public bool AppIf { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!AppIf)
{
output.SuppressOutput();
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement("app-multiline", Attributes = "text")]
public class MultilineTagHelper : TagHelper
{
[HtmlAttributeName("text")]
public string Text { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = string.Empty;
output.Content.SetHtmlContent(Text.NewLinesToBr());
}
}
@@ -4,13 +4,13 @@ using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement(Attributes = "zero-resize")]
[HtmlTargetElement(Attributes = "app-resize")]
public class ResizeTagHelper : TagHelper
{
[HtmlAttributeName("src")]
public string Src { get; set; }
[HtmlAttributeName("zero-resize")]
[HtmlAttributeName("app-resize")]
public string Preset { get; set; }
[ViewContext]
@@ -28,7 +28,7 @@ public class ResizeTagHelper : TagHelper
public override void Process(TagHelperContext context, TagHelperOutput output)
{
string src = FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, Src).Resize(Preset);
output.Attributes.RemoveAll("zero-resize");
output.Attributes.RemoveAll("app-resize");
output.Attributes.SetAttribute("src", src);
}
}
+30
View File
@@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace zero.TagHelpers;
[HtmlTargetElement("app-gender-select", Attributes = FOR_ATTRIBUTE_NAME)]
public class SelectGenderTagHelper : BaseSelectTagHelper
{
ILocalizer _localizer;
public SelectGenderTagHelper(IHtmlGenerator generator, ILocalizer localizer) : base(generator)
{
_localizer = localizer;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
Items.Add(new SelectListItem(string.Empty, null));
foreach (Gender gender in Enum.GetValues<Gender>())
{
string key = "forms.gender." + gender.ToString().ToLowerInvariant();
Items.Add(new SelectListItem(_localizer.Text(key), gender.ToString()));
}
await base.ProcessAsync(context, output);
}
}
+33
View File
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Net;
using System.Text.RegularExpressions;
namespace zero.TagHelpers;
[HtmlTargetElement("app-striphtml", Attributes = "text")]
public class StripHtmlTagHelper : TagHelper
{
[HtmlAttributeName("text")]
public string Text { get; set; }
[HtmlAttributeName("maxLength")]
public int MaxLength { get; set; } = -1;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = string.Empty;
string text = string.Empty;
if (!String.IsNullOrWhiteSpace(Text))
{
text = WebUtility.HtmlDecode(Regex.Replace(Text, "<[^>]*(>|$)", string.Empty).Trim());
if (MaxLength > 0 && text.Length > MaxLength)
{
text = text.Substring(0, MaxLength) + "...";
}
}
output.Content.SetHtmlContent(text);
}
}