forked from CodeBeamOrg/CodeBeam.MudBlazor.Extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMudDateTimePicker.razor.cs
More file actions
966 lines (798 loc) · 27.6 KB
/
Copy pathMudDateTimePicker.razor.cs
File metadata and controls
966 lines (798 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
using MudBlazor.Extensions;
using MudBlazor.Utilities;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace MudExtensions;
/// <summary>
/// Provides date and time selection in a single component. The date and time can be submitted together or separately. The time selection is done through an interactive clock interface where the user can select hours and minutes by clicking or dragging a pointer.
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class MudDateTimePicker<T> : MudBaseDatePickerX<T>
{
[Inject] private IJSRuntime JsRuntime { get; set; } = null!;
[DynamicDependency(nameof(OnStickClick))]
[DynamicDependency(nameof(SelectTimeFromStick))]
public MudDateTimePicker()
{
_dotNetReferenceLazy = new Lazy<DotNetObjectReference<MudDateTimePicker<T>>>(CreateDotNetObjectReference);
}
private string? _clockElementReferenceId;
private readonly Lazy<DotNetObjectReference<MudDateTimePicker<T>>> _dotNetReferenceLazy;
private DotNetObjectReference<MudDateTimePicker<T>> CreateDotNetObjectReference() => DotNetObjectReference.Create(this);
private DateTime? _workingValue;
private readonly SetTime _timeSet = new();
private string _timeHourFormat;
private record SetTime
{
public int Hour { get; set; }
public int Minute { get; set; }
}
public bool PointerMoving { get; set; }
protected ElementReference ClockElementReference { get; private set; }
private bool _amPm = false;
/// <inheritdoc />
protected override void OnInitialized()
{
base.OnInitialized();
_workingValue = ToDateTime(Value);
}
/// <inheritdoc />
protected override void OnParametersSet()
{
base.OnParametersSet();
_workingValue = ToDateTime(Value);
SyncTimeFromValue();
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
// Initialize the pointer events for the clock every time it's created (ex: popover opening and closing).
if (ClockElementReference.Id != _clockElementReferenceId)
{
_clockElementReferenceId = ClockElementReference.Id;
await JsRuntime.InvokeVoidAsyncWithErrorHandling("mudTimePicker.initPointerEvents", ClockElementReference, _dotNetReferenceLazy.Value);
}
}
private void SyncTimeFromValue()
{
if (_workingValue == null)
{
_timeSet.Hour = 0;
_timeSet.Minute = 0;
return;
}
_timeSet.Hour = _workingValue.Value.Hour;
_timeSet.Minute = _workingValue.Value.Minute;
}
protected PickerMode _mode = PickerMode.Date;
/// <summary>
/// The currently selected value.
/// </summary>
/// <remarks>
/// When this value changes, <see cref="ValueChanged"/> occurs.
/// </remarks>
[Parameter]
public T? Value
{
get => _value;
set => SetDateAsync(ToDateTime(value), true).CatchAndLog();
}
/// <summary>
/// Occurs when <see cref="Value"/> has changed.
/// </summary>
[Parameter]
public EventCallback<T?> ValueChanged { get; set; }
/// <summary>
/// Shows a 12-hour selection clock.
/// </summary>
/// <remarks>
/// Defaults to <c>false</c>.<br />
/// When <c>true</c>, hours 1-12 are displayed with an AM or PM marker.<br />
/// When <c>false</c>, hours 0-23 are displayed.<br />
/// </remarks>
[Parameter]
public bool AmPm
{
get => _amPm;
set
{
if (_amPm == value)
return;
_amPm = value;
Touched = true;
_ = SetTextAsync(ConvertSet(_value), false);
}
}
/// <summary>
/// The step interval when selecting minutes.
/// </summary>
/// <remarks>
/// Defaults to <c>1</c>. For example: a value of <c>15</c> would allow minutes <c>0</c>, <c>15</c>,
/// <c>30</c>, and <c>45</c> be selected.
/// </remarks>
[Parameter]
public int MinuteSelectionStep { get; set; } = 1;
/// <summary>
/// Controls which values can be edited.
/// </summary>
/// <remarks>
/// Defaults to <see cref="TimeEditMode.Normal"/>.
/// </remarks>
[Parameter]
[Category(CategoryTypes.FormComponent.PickerBehavior)]
public TimeEditMode TimeEditMode { get; set; } = TimeEditMode.Normal;
private int RoundToStepInterval(int value)
{
if (MinuteSelectionStep > 1)
{
var interval = MinuteSelectionStep % 60;
value = (value + (interval / 2)) / interval * interval;
if (value == 60)
value = 0;
}
return value;
}
/// <summary>
/// Gets or sets the text displayed for the AM period in a time picker or similar control.
/// </summary>
[Parameter]
public string AmText { get; set; } = "AM";
/// <summary>
/// Gets or sets the text displayed for the post-meridiem (PM) indicator.
/// </summary>
[Parameter]
public string PmText { get; set; } = "PM";
protected override async Task WriteTextAsync(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
_workingValue = null;
_value = default;
await ValueChanged.InvokeAsync(_value);
return;
}
var culture = GetCulture();
if (DateTime.TryParseExact(text, GetFormat(), culture, DateTimeStyles.None, out var parsed))
{
_workingValue = parsed;
_value = FromDateTime(parsed);
SyncTimeFromValue();
PickerMonth = new DateTime(parsed.Year, parsed.Month, 1);
await ValueChanged.InvokeAsync(_value);
await BeginValidateAsync();
FieldChanged(_value);
}
else
{
await SetTextAsync(ConvertSet(_value), false);
}
}
private async Task OnAmClickedAsync()
{
_timeSet.Hour %= 12;
await UpdateTimeAsync();
await FocusAsync();
}
private async Task OnPmClickedAsync()
{
if (_timeSet.Hour <= 12)
{
_timeSet.Hour += 12;
}
_timeSet.Hour %= 24;
await UpdateTimeAsync();
await FocusAsync();
}
private DateTimeOffset _lastSetTime = DateTimeOffset.MinValue;
private const int DebounceTimeoutMs = 100;
protected internal async Task SetDateAsync(DateTime? date, bool updateValue)
{
var current = ToDateTime(_value);
if (current != null && date != null && date.Value.Kind == DateTimeKind.Unspecified)
{
date = DateTime.SpecifyKind(date.Value, current.Value.Kind);
}
var now = TimeProvider.GetUtcNow();
if (current == date && (now - _lastSetTime).TotalMilliseconds < DebounceTimeoutMs)
return;
_lastSetTime = now;
if (current != date || (date is null && Text != null))
{
Touched = true;
HighlightedDate = date;
if (date is not null && IsDateDisabledFunc(date.Value.Date))
{
await SetTextAsync(null, false);
return;
}
if (date is not null)
{
var culture = GetCulture();
PickerMonth = new DateTime(
culture.Calendar.GetYear(date.Value),
culture.Calendar.GetMonth(date.Value),
1,
culture.Calendar);
}
var converted = FromDateTime(date);
_value = converted;
if (updateValue)
{
ResetConverterErrors();
await SetTextAsync(ConvertSet(_value), false);
}
await ValueChanged.InvokeAsync(_value);
await BeginValidateAsync();
FieldChanged(_value);
}
}
private async Task UpdateTimeAsync()
{
if (_workingValue == null)
_workingValue = TimeProvider.GetLocalNow().Date;
_workingValue = new DateTime(
_workingValue.Value.Year,
_workingValue.Value.Month,
_workingValue.Value.Day,
_timeSet.Hour,
_timeSet.Minute,
0
);
}
private void SetDatePart(DateTime date)
{
var current = _workingValue ?? TimeProvider.GetLocalNow().Date;
_workingValue = new DateTime(
date.Year,
date.Month,
date.Day,
current.Hour,
current.Minute,
current.Second
);
}
private void SetTimePart(int hour, int minute)
{
var current = _workingValue ?? TimeProvider.GetLocalNow().Date;
_workingValue = new DateTime(
current.Year,
current.Month,
current.Day,
hour,
minute,
0
);
}
protected override string GetDayClasses(int month, DateTime day)
{
var b = new CssBuilder("mud-day");
b.AddClass(AdditionalDateClassesFunc?.Invoke(day) ?? string.Empty);
if (day < GetMonthStart(month) || day > GetMonthEnd(month))
return b.AddClass("mud-hidden").Build();
var current = _workingValue ?? ToDateTime(Value);
if (current?.Date == day.Date)
return b.AddClass("mud-selected")
.AddClass($"mud-theme-{Color.ToString().ToLowerInvariant()}")
.Build();
if (day.Date == TimeProvider.GetLocalNow().Date)
return b.AddClass("mud-current mud-button-outlined")
.AddClass($"mud-button-outlined-{Color.ToString().ToLowerInvariant()} mud-{Color.ToString().ToLowerInvariant()}-text")
.Build();
return b.Build();
}
/// <summary>
/// Handles the event when a day is clicked in the calendar view. This method updates the working value with the selected date, and if appropriate based on the component's configuration, submits the new value and closes the picker.
/// </summary>
/// <param name="dateTime">The date that was clicked.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
protected override async Task OnDayClickedAsync(DateTime dateTime)
{
await FocusAsync();
SetDatePart(dateTime);
if (PickerActions == null || AutoClose || PickerVariant == PickerVariant.Static)
{
await Task.Run(() => InvokeAsync(SubmitAsync));
if (PickerVariant != PickerVariant.Static)
{
await Task.Delay(TimeSpan.FromMilliseconds(ClosingDelay), TimeProvider);
await CloseAsync(false);
}
}
}
/// <summary>
/// Submits the current value asynchronously, triggering value change notifications and validation as appropriate.
/// </summary>
/// <remarks>The method does not perform any action if the control is in a read-only state or if the
/// working value is null. Upon successful submission, the method updates the value, invokes change notifications,
/// updates the displayed text, and initiates validation.</remarks>
/// <returns>A task that represents the asynchronous submit operation.</returns>
protected override async Task SubmitAsync()
{
if (GetReadOnlyState())
return;
if (_workingValue == null)
return;
var converted = FromDateTime(_workingValue);
_value = converted;
await ValueChanged.InvokeAsync(_value);
await SetTextAsync(ConvertSet(_value), false);
await BeginValidateAsync();
FieldChanged(_value);
}
/// <summary>
/// Clears the selected date and time, resetting the component to its initial state. If <see cref="AutoClose"/> is <c>true</c>, the picker will also close after clearing the value.
/// </summary>
/// <param name="close">Indicates whether the picker should close after clearing the value.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async Task ClearAsync(bool close = true)
{
await SetDateAsync(null, true);
if (AutoClose)
await CloseAsync(false);
}
/// <summary>
/// Gets the formatted date string for the title of the picker, based on the current working value, the component's value, or the current local date if neither is set. The date is formatted according to the culture settings and the specified format for the title.
/// </summary>
/// <returns>The formatted date string for the title of the picker.</returns>
protected string GetTitleDateString()
{
var date = _workingValue
?? ToDateTime(Value)
?? TimeProvider.GetLocalNow().Date;
return FormatTitleDate(date);
}
/// <summary>
/// Calculates the first day of the month for the current calendar context.
/// </summary>
/// <remarks>The returned date is determined using the culture-specific calendar, which may affect the
/// calculation of the month's start depending on the culture in use.</remarks>
/// <returns>A <see cref="DateTime"/> representing the first day of the month, based on the current value, highlighted date,
/// or the current local date if neither is set.</returns>
protected override DateTime GetCalendarStartOfMonth()
{
var date = ToDateTime(Value) ?? HighlightedDate ?? TimeProvider.GetLocalNow().Date;
return date.StartOfMonth(GetCulture());
}
/// <summary>
/// Calculates the calendar year corresponding to the specified date, adjusted according to the current value and
/// culture settings.
/// </summary>
/// <remarks>The result is determined using the calendar of the current culture. If the current value is
/// not set, the calculation uses the current local date.</remarks>
/// <param name="yearDate">The date for which to determine the calendar year. The calculation is based on the calendar associated with the
/// current culture.</param>
/// <returns>The calendar year as an integer, adjusted based on the current value and the specified date.</returns>
protected override int GetCalendarYear(DateTime yearDate)
{
var date = ToDateTime(Value) ?? TimeProvider.GetLocalNow().Date;
var diff = GetCulture().Calendar.GetYear(date) - GetCulture().Calendar.GetYear(yearDate);
return GetCulture().Calendar.GetYear(date) - diff;
}
protected string GetMonthName(int month)
{
var date = GetMonthStart(month);
return date.ToString("MMMM yyyy", GetCulture());
}
protected Task OnPreviousMonthClick()
{
PickerMonth = GetMonthStart(0).AddMonths(-1);
return Task.CompletedTask;
}
protected Task OnNextMonthClick()
{
PickerMonth = GetMonthStart(0).AddMonths(1);
return Task.CompletedTask;
}
private void GoToSelectedYear()
{
PickerMonth = HighlightedDate;
OnYearClick();
}
private void OnYearClick()
{
if (!FixYear.HasValue)
{
_mode = PickerMode.Date;
CurrentView = OpenTo.Year;
StateHasChanged();
_scrollToYearAfterRender = true;
}
}
protected int GetMinYear()
{
return MinDate?.Year ?? 1900;
}
protected int GetMaxYear()
{
return MaxDate?.Year ?? 2100;
}
protected Task OnYearClickedAsync(int year)
{
var current = ToDateTime(Value) ?? TimeProvider.GetLocalNow().Date;
PickerMonth = new DateTime(year, current.Month, 1);
_workingValue = new DateTime(
year,
current.Month,
current.Day,
current.Hour,
current.Minute,
current.Second
);
CurrentView = OpenTo.Month;
return Task.CompletedTask;
}
protected Typo GetYearTypo(int year)
{
var current = ToDateTime(Value);
return current?.Year == year ? Typo.h5 : Typo.body1;
}
protected string GetYearClasses(int year)
{
var current = ToDateTime(Value);
return new CssBuilder("mud-picker-year-text")
.AddClass("mud-selected", current?.Year == year)
.Build();
}
protected Task OnPreviousYearClick()
{
PickerMonth = (PickerMonth ?? DateTime.Today).AddYears(-1);
return Task.CompletedTask;
}
protected Task OnNextYearClick()
{
PickerMonth = (PickerMonth ?? DateTime.Today).AddYears(1);
return Task.CompletedTask;
}
protected IEnumerable<int> GetAllMonths()
{
return Enumerable.Range(1, 12);
}
protected Task OnMonthSelectedAsync(int month)
{
var current = _workingValue ?? ToDateTime(Value) ?? TimeProvider.GetLocalNow().Date;
PickerMonth = new DateTime(current.Year, month, 1);
_workingValue = new DateTime(
current.Year,
month,
current.Day,
current.Hour,
current.Minute,
current.Second
);
CurrentView = OpenTo.Date;
return Task.CompletedTask;
}
protected bool IsMonthDisabled(int month)
{
if (!MinDate.HasValue && !MaxDate.HasValue)
return false;
var year = (PickerMonth ?? DateTime.Today).Year;
var start = new DateTime(year, month, 1);
var end = start.AddMonths(1).AddDays(-1);
return (MinDate.HasValue && end < MinDate.Value)
|| (MaxDate.HasValue && start > MaxDate.Value);
}
protected Typo GetMonthTypo(int month)
{
var current = ToDateTime(Value);
return current?.Month == month ? Typo.h6 : Typo.body2;
}
protected string GetMonthClasses(int month)
{
var current = ToDateTime(Value);
return new CssBuilder()
.AddClass("mud-selected", current?.Month == month)
.Build();
}
protected string GetAbbreviatedMonthName(int month)
{
return GetCulture().DateTimeFormat.AbbreviatedMonthNames[month - 1];
}
protected int GetWeekNumber(int month, int week)
{
var firstDay = GetWeek(month, week).First();
return GetCulture().Calendar.GetWeekOfYear(
firstDay,
CalendarWeekRule.FirstFourDayWeek,
GetFirstDayOfWeek());
}
protected string GetCalendarDayOfMonth(DateTime date)
{
return date.Day.ToString(GetCulture());
}
protected void OnFormattedDateClick()
{
CurrentView = OpenTo.Month;
}
protected void OnMonthClicked(int month)
{
CurrentView = OpenTo.Month;
}
private string GetCalendarHeaderClasses(int month)
{
return new CssBuilder("mud-picker-calendar-header")
.AddClass($"mud-picker-calendar-header-{month + 1}")
.AddClass($"mud-picker-calendar-header-last", month == DisplayMonths - 1)
.Build();
}
private string HourDialClassname =>
new CssBuilder("mud-time-picker-dial")
.AddClass("mud-time-picker-hour")
.AddClass("mud-time-picker-dial-out", CurrentView != OpenTo.Hours)
.AddClass("mud-time-picker-dial-hidden", CurrentView != OpenTo.Hours)
.Build();
private string MinuteDialClassname =>
new CssBuilder("mud-time-picker-dial")
.AddClass("mud-time-picker-minute")
.AddClass("mud-time-picker-dial-out", CurrentView != OpenTo.Minutes)
.AddClass("mud-time-picker-dial-hidden", CurrentView != OpenTo.Minutes)
.Build();
private string GetPointerRotation()
{
return $"rotateZ({GetDeg()}deg);";
}
private double GetDeg()
{
double deg = 0;
if (CurrentView == OpenTo.Hours)
{
deg = _timeSet.Hour * 30 % 360;
}
if (CurrentView == OpenTo.Minutes)
{
deg = _timeSet.Minute * 6 % 360;
}
return deg;
}
private string GetPointerHeight()
{
var height = 40;
if (CurrentView == OpenTo.Minutes)
{
height = 40;
}
if (CurrentView == OpenTo.Hours)
{
if (!AmPm && _timeSet.Hour > 0 && _timeSet.Hour < 13)
{
height = 26;
}
else
{
height = 40;
}
}
return $"{height}%;";
}
private string GetNumberColor(int value)
{
if (CurrentView == OpenTo.Hours)
{
var h = _timeSet.Hour;
if (AmPm)
{
h = _timeSet.Hour % 12;
if (_timeSet.Hour % 12 == 0)
{
h = 12;
}
}
if (h == value)
{
return $"mud-clock-number mud-theme-{Color.ToString().ToLowerInvariant()}";
}
}
else if (CurrentView == OpenTo.Minutes && _timeSet.Minute == value)
{
return $"mud-clock-number mud-theme-{Color.ToString().ToLowerInvariant()}";
}
return "mud-clock-number";
}
private string GetClockPointerColor()
{
return PointerMoving
? $"mud-picker-time-clock-pointer mud-{Color.ToString().ToLowerInvariant()}"
: $"mud-picker-time-clock-pointer mud-picker-time-clock-pointer-animation mud-{Color.ToString().ToLowerInvariant()}";
}
private string GetClockPinColor()
{
return $"mud-picker-time-clock-pin mud-{Color.ToString().ToLowerInvariant()}";
}
private string GetClockPointerThumbColor()
{
var deg = GetDeg();
return deg % 30 == 0
? $"mud-picker-time-clock-pointer-thumb mud-onclock-text mud-onclock-primary mud-{Color.ToString().ToLowerInvariant()}"
: $"mud-picker-time-clock-pointer-thumb mud-onclock-minute mud-{Color.ToString().ToLowerInvariant()}-text";
}
private static string GetTransform(double angle, double radius, double offsetX, double offsetY)
{
angle = angle / 180 * Math.PI;
var x = ((Math.Sin(angle) * radius) + offsetX).ToString("F3", CultureInfo.InvariantCulture);
var y = (((Math.Cos(angle) + 1) * radius) + offsetY).ToString("F3", CultureInfo.InvariantCulture);
return $"transform: translate({x}px, {y}px);";
}
[JSInvokable]
public async Task SelectTimeFromStick(int value, bool pointerMoving)
{
PointerMoving = pointerMoving;
if (CurrentView == OpenTo.Minutes)
_timeSet.Minute = RoundToStepInterval(value);
else
_timeSet.Hour = value;
await UpdateTimeAsync();
StateHasChanged();
}
[JSInvokable]
public async Task OnStickClick(int value)
{
// The pointer is up and not moving so animations can be enabled again.
PointerMoving = false;
// Clicking a stick will submit the time.
if (CurrentView == OpenTo.Minutes)
{
await SubmitAndCloseAsync();
}
else if (CurrentView == OpenTo.Hours)
{
if (TimeEditMode == TimeEditMode.Normal)
{
CurrentView = OpenTo.Minutes;
}
else if (TimeEditMode == TimeEditMode.OnlyHours)
{
await SubmitAndCloseAsync();
}
}
// Manually update because the event won't do it from JavaScript.
StateHasChanged();
}
protected async Task SubmitAndCloseAsync()
{
if (PickerActions == null || AutoClose)
{
await SubmitAsync();
if (PickerVariant != PickerVariant.Static)
{
await Task.Delay(TimeSpan.FromMilliseconds(ClosingDelay), TimeProvider);
await CloseAsync(false);
}
}
}
/// <summary>
/// Gets the hour portion of the selected time.
/// </summary>
/// <returns>A two-character string depending on whether <see cref="AmPm"/> is set, or <c>--</c> if no value is set.</returns>
private string GetHourString()
{
if (_workingValue?.Hour == null)
{
return "--";
}
return _workingValue.Value.Hour.ToString("D2");
}
/// <summary>
/// Gets the minute portion of the selected time.
/// </summary>
/// <returns>A two-digit string for minutes, or <c>--</c> if no value is set.</returns>
private string GetMinuteString()
{
if (_workingValue?.Minute == null)
{
return "--";
}
return _workingValue.Value.Minute.ToString("D2");
}
private async Task OnHourClickAsync()
{
CurrentView = OpenTo.Hours;
await FocusAsync();
}
private async Task OnMinutesClick()
{
CurrentView = OpenTo.Minutes;
await FocusAsync();
}
private async Task HourFormatChanged(string value)
{
if (value == "am")
{
await OnAmClickedAsync();
}
else if (value == "pm")
{
await OnPmClickedAsync();
}
StateHasChanged();
}
private void HandleModeChange(PickerMode mode)
{
if (mode == PickerMode.Date)
{
CurrentView = OpenTo.Date;
}
else if (mode == PickerMode.Time)
{
CurrentView = OpenTo.Hours;
}
}
protected string GetFormattedYearString()
{
var date = _workingValue
?? ToDateTime(Value)
?? TimeProvider.GetLocalNow().Date;
return date.Year.ToString();
}
/// <summary>
/// Scrolls to the current year.
/// </summary>
public override async Task ScrollToYearAsync(DateTime? date = null)
{
var culture = GetCulture();
var calendar = culture.Calendar;
_scrollToYearAfterRender = false;
var dateTime =
date
?? _workingValue
?? ToDateTime(Value)
?? TimeProvider.GetLocalNow().Date;
var id = $"{_componentId}{calendar.GetYear(dateTime)}";
await ScrollManager.ScrollToYearAsync(id);
StateHasChanged();
}
protected override async Task OnOpenedAsync()
{
_mode = PickerMode.Date;
CurrentView = OpenTo.Hours;
await base.OnOpenedAsync();
}
/// <summary>
/// Sets the current view of the picker to the specified value.
/// </summary>
public void SetView(OpenTo view)
{
switch (view)
{
case OpenTo.Date:
_mode = PickerMode.Date;
CurrentView = OpenTo.Date;
break;
case OpenTo.Month:
_mode = PickerMode.Date;
CurrentView = OpenTo.Month;
break;
case OpenTo.Year:
_mode = PickerMode.Date;
CurrentView = OpenTo.Year;
break;
case OpenTo.Hours:
_mode = PickerMode.Time;
CurrentView = OpenTo.Hours;
break;
case OpenTo.Minutes:
_mode = PickerMode.Time;
CurrentView = OpenTo.Minutes;
break;
}
StateHasChanged();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
/// </summary>
protected override async ValueTask DisposeAsyncCore()
{
await base.DisposeAsyncCore();
if (IsJSRuntimeAvailable)
{
await JsRuntime.InvokeVoidAsyncWithErrorHandling("mudTimePicker.destroyPointerEvents", ClockElementReference);
}
if (_dotNetReferenceLazy.IsValueCreated)
{
_dotNetReferenceLazy.Value.Dispose();
}
}
}