Files
tbd-station-14/Content.Client/UserInterface/Controls/DatePicker.xaml.cs
0x6273 fdbcd3fdc5 Add date picker (#40660)
* Add DatePicker

* DatePicker fixes

- Now uses `DateOnly` (currently fails sandbox, but PJB has promised to add
it in engine)
- Add MinDate and MaxDate fields
- Use constructor instead of parsing date string
2025-10-14 17:26:07 +00:00

85 lines
2.1 KiB
C#

using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.XAML;
namespace Content.Client.UserInterface.Controls;
/// <summary>
/// An input control for dates.
/// </summary>
[GenerateTypedNameReferences]
public sealed partial class DatePicker : Control
{
/// <summary>
/// Raised when <see cref="SelectedDate"> is changed.
/// </summary>
public event Action? OnChanged;
/// <summary>
/// The date currently selected by the input, or null if it's not a valid date.
/// </summary>
public DateOnly? SelectedDate;
/// <summary>
/// The oldest possible date that the user can select.
/// </summary>
public DateOnly MinDate = DateOnly.MinValue;
/// <summary>
/// The most recent date that the user can select.
/// </summary>
public DateOnly MaxDate = DateOnly.MaxValue;
/// <summary>
/// True if a valid date is selected.
/// </summary>
public bool IsValid => SelectedDate is not null;
public DatePicker()
{
RobustXamlLoader.Load(this);
MonthOptionButton.AddItem(Loc.GetString("datepicker-month"), 0);
for (var i = 1; i <= 12; i++)
{
MonthOptionButton.AddItem(Loc.GetString($"month-{i}"), i);
}
DayLineEdit.OnTextChanged += _ => Update();
YearLineEdit.OnTextChanged += _ => Update();
MonthOptionButton.OnItemSelected += args => {
if (args.Id != 0)
{
MonthOptionButton.SelectId(args.Id);
}
Update();
};
}
private void Update()
{
var monthNum = MonthOptionButton.SelectedId;
DateOnly? newDate = null;
if (int.TryParse(YearLineEdit.Text, out var year)
&& int.TryParse(DayLineEdit.Text, out var day)
&& monthNum != 0
)
{
newDate = new DateOnly(year, monthNum, day);
}
if (newDate < MinDate || newDate > MaxDate)
{
newDate = null;
}
if (SelectedDate != newDate)
{
SelectedDate = newDate;
OnChanged?.Invoke();
}
}
}