1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-11-24 13:42:53 +01:00
Minecraft-Phantom-Panel/Server/Phantom.Server.Web.Components/Forms/Fields/InputFieldNumeric.cs

75 lines
2.8 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Web;
using Phantom.Server.Web.Components.Forms.Base;
namespace Phantom.Server.Web.Components.Forms.Fields;
public sealed class InputFieldNumeric<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase<TValue>, ICustomFormField {
[Parameter]
public FormNumberInputType Type { get; set; }
[Parameter]
public EventCallback<ChangeEventArgs> OnChange { get; set; }
[Parameter]
public EventCallback<FocusEventArgs> OnBlur { get; set; }
[Parameter]
public string ParsingErrorMessage { get; set; } = "The {0} field must be a number.";
public bool TwoWayValueBinding { get; set; } = true;
public void SetStringValue(string? value) {
CurrentValueAsString = value;
}
protected override void BuildRenderTree(RenderTreeBuilder builder) {
builder.OpenElement(0, "input");
builder.AddMultipleAttributes(1, AdditionalAttributes);
builder.AddAttribute(2, "type", Type.GetHtmlInputType());
if (!string.IsNullOrEmpty(CssClass)) {
builder.AddAttribute(3, "class", CssClass);
}
if (TwoWayValueBinding) {
builder.AddAttribute(4, "value", BindConverter.FormatValue(CurrentValueAsString));
}
builder.AddAttribute(5, "onchange", OnChange);
builder.AddAttribute(6, "oninput", OnChange);
builder.AddAttribute(7, "onblur", OnBlur);
builder.CloseElement();
}
protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage) {
if (BindConverter.TryConvertTo(value, CultureInfo.InvariantCulture, out result)) {
validationErrorMessage = null;
return true;
}
else {
validationErrorMessage = string.Format(CultureInfo.InvariantCulture, ParsingErrorMessage, DisplayName ?? FieldIdentifier.FieldName);
return false;
}
}
protected override string? FormatValueAsString(TValue? value) {
return value switch {
null => null,
int v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
long v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
short v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
float v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
double v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
decimal v => BindConverter.FormatValue(v, CultureInfo.InvariantCulture),
ushort v => BindConverter.FormatValue((int) v, CultureInfo.InvariantCulture),
uint v => BindConverter.FormatValue((long) v, CultureInfo.InvariantCulture),
_ => throw new InvalidOperationException($"Unsupported value type {value.GetType()}")
};
}
}