using System.Text.RegularExpressions;
using Robust.Client.UserInterface.Controls;
namespace Content.Client.UserInterface.Controls;
///
/// A line edit which accepts only integers as text input, and can clamp input to a lower or upper bound.
///
public sealed class IntegerLineEdit : LineEdit
{
private static readonly Regex RegNumbers = new("^-?[0-9]*$");
public IntegerLineEdit()
{
IsValid += s => RegNumbers.IsMatch(s);
OnTextChanged += Clamp;
}
///
/// When not null, text entered that's smaller than this will be rewritten to this.
///
/// Becomes annoying when set above 1.
[ViewVariables(VVAccess.ReadWrite)]
public int? MinValue
{
get;
set
{
if (value == field)
return;
if (value == null)
{
field = null;
return;
}
if (value > MaxValue)
{
value = MaxValue;
Log.Warning($"Min value of {this} was set above max.");
}
field = value;
}
}
///
/// When not null, text entered that's larger than this will be rewritten to this.
///
[ViewVariables(VVAccess.ReadWrite)]
public int? MaxValue
{
get;
set
{
if (value == field)
return;
if (value == null)
{
field = null;
return;
}
if (value < MinValue)
{
value = MinValue;
Log.Warning($"Max value of {this} was set below min.");
}
field = value;
}
}
/// The integer value of the text.
[ViewVariables(VVAccess.ReadOnly)]
public int Value()
{
return int.TryParse(Text, out var i) ? i : 0;
}
///
/// Sets the minimum and maximum values for clamping.
///
public void SetBoth(int? minimum, int? maximum)
{
if (minimum is { } min && maximum is { } max && min > max)
{
Log.Warning($"Min value of { this } was set above max.");
minimum = maximum;
}
MinValue = minimum;
MaxValue = maximum;
}
///
/// Clamps the value of the text between min and max.
///
private void Clamp(LineEditEventArgs _)
{
if (Text is "" or "-")
return;
Text = Math.Clamp(
Value(),
MinValue ?? int.MinValue,
MaxValue ?? int.MaxValue
).ToString();
}
}