-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathTouchDateField.tsx
More file actions
1257 lines (1214 loc) · 46.1 KB
/
Copy pathTouchDateField.tsx
File metadata and controls
1257 lines (1214 loc) · 46.1 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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
/**
* @file TouchDateField.tsx
* @input Uses React, Field, BottomSheet, Button, Icon, Calendar hooks, MonthScroller, MonthYearWheels
* @output Exports TouchDateField — the touch surface behind DateInput
* @position Internal component; consumed by DateInput.tsx
*
* The touch half of `DateInput`, holding `DateInput`'s whole prop
* contract so the two are interchangeable. Everything field-shaped —
* `Field` wrapper, status treatment, optimistic `changeAction`, the
* disabled-reason tooltip, `InputGroup` membership — behaves exactly as it
* does on the desktop control; only the picker differs.
*
* ## The closed field is deliberately the same control
*
* It is a real `<input>`, not a button: same element, same `role="combobox"`,
* same border, same clear button, so `ref` (typed `Ref<HTMLInputElement>` by
* `DateInputProps`) is honestly a reference to an input, the label's `for`
* names it natively, and the switch between surfaces moves nothing on screen.
*
* It just cannot be typed into: `readOnly` blocks entry, and `inputMode="none"`
* stops the virtual keyboard from opening over the sheet. Text entry is the
* one part of the desktop control that has no place here — the keyboard it
* summons would cover the picker it is meant to fill in.
*
* ## Three ideas in the picker
*
* 1. One month per screen. Every pane is exactly the height of the scrollport
* and snaps to its start, so the picker is a fixed height and there is no
* resting position showing half of two months. See MonthScroller.
* 2. Swiping is the month control, and the arrows are the backup. A flick
* reaches a neighbouring month in the direction you already think of it;
* the pair of arrows in the header's trailing corner is there for a
* deliberate single step, and for anyone not swiping at all.
* 3. The title is the escape hatch. Tap it and the same box becomes a month
* wheel and a year wheel — a flick each to reach 2019 instead of forty.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/DateInput/DateInput.tsx
* - /packages/core/src/DateInput/DateInput.doc.mjs
* - /packages/core/src/DateInput/DateInputTouch.test.tsx
*/
import {
useCallback,
useEffect,
useId,
useMemo,
useOptimistic,
useRef,
useState,
useTransition,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {BottomSheet} from '../BottomSheet';
import {Button} from '../Button';
import {useCalendarConstraints} from '../Calendar';
import type {DateInputProps} from './DateInput';
import {
Field,
InputClearButton,
inputWrapperStyles,
inputStatusBorderStyles,
inputStatusHoverShadowStyles,
inputStatusFocusWithinStyles,
} from '../Field';
import {useInputStatusIcon} from '../hooks';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {Icon} from '../Icon';
import {IconButton} from '../IconButton';
import {useTranslator} from '../i18n';
import {useInputGroup} from '../InputGroup';
import {groupStyles} from '../InputGroup/groupStyles';
import {stableClassName} from '../naming';
import {useSize} from '../SizeContext';
import {Spinner} from '../Spinner';
import {
colorVars,
spacingVars,
radiusVars,
sizeVars,
borderVars,
fontWeightVars,
typeScaleVars,
typographyVars,
durationVars,
easeVars,
} from '../theme/tokens.stylex';
import {useTooltip} from '../Tooltip';
import {VisuallyHidden} from '../VisuallyHidden';
import {
focusOutlineStyles,
getInputARIA,
isImeKeyEvent,
mergeProps,
mergeRefs,
rtlStyles,
themeProps,
formatSharedDate,
plainDateFromISO,
plainDateToday,
plainDateFormat,
DATE_FORMAT_MONTH_YEAR,
DATE_FORMAT_WEEKDAY_ONLY,
type ISODateString,
} from '../utils';
import {normalizeDayOfWeek} from '../utils/dateTypes';
import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
import {MonthYearWheels} from './MonthYearWheels';
import {
DEFAULT_MONTH_REACH,
clampIndex,
fromMonthIndex,
monthIndexOf,
} from './monthGeometry';
import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
/**
* The comfortable minimum tap target on both iOS and Android. Applied as a
* FLOOR under the size prop rather than replacing it: `size` still means what
* it means, it just cannot produce a control a thumb misses.
*/
const TOUCH_TARGET = dateInputTouchSizes.daySize;
/**
* The whole surface swap, in one leg.
*
* It used to be two: the outgoing surface faded out, then the incoming one
* faded in, 110ms each. The sequencing existed for one reason — the wheels'
* panel was transparent, so overlapping the two put the wheels' translucent
* selection band over the calendar grid and tinted a band-shaped strip of it,
* which read as "the grey area animates differently from the content".
*
* Giving the wheels an opaque background removes the reason. Nothing shows
* through them, so they can simply fade in ON TOP of a calendar that does not
* move at all — no empty middle, no outgoing animation, and one duration
* instead of a wait plus a fade.
*
* `--duration-fast` rather than a literal now that this is a whole duration
* and not half of one.
*/
const SWAP_DURATION = durationVars['--duration-fast'];
const sizeStyles = stylex.create({
sm: {
height: sizeVars['--size-element-sm'],
minWidth: 180,
minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
},
md: {
height: sizeVars['--size-element-md'],
minWidth: 180,
minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
},
lg: {
height: sizeVars['--size-element-lg'],
minWidth: 180,
minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
},
});
const styles = stylex.create({
// ---- the closed field ----
wrapper: {
gap: spacingVars['--spacing-2'],
},
iconButton: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
margin: 0,
borderWidth: 0,
borderStyle: 'none',
backgroundColor: 'transparent',
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
borderRadius: radiusVars['--radius-element'],
},
iconButtonDisabled: {
cursor: 'default',
},
input: {
display: 'block',
flex: 1,
minWidth: 0,
borderWidth: 0,
borderStyle: 'none',
padding: 0,
fontFamily: typographyVars['--font-family-body'],
// Below 16px iOS zooms the page on focus. The field is focusable even
// though it is not typable, so it needs the same floor DateInput has.
fontSize: {
default: typeScaleVars['--text-body-size'],
'@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
},
lineHeight: typeScaleVars['--text-body-leading'],
color: colorVars['--color-text-primary'],
backgroundColor: 'transparent',
outline: 'none',
// It opens a picker; it does not take text. The caret would say otherwise.
caretColor: 'transparent',
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
userSelect: 'none',
'::placeholder': {
color: colorVars['--color-text-secondary'],
},
},
inputDisabled: {
cursor: 'default',
},
// ---- the picker surface ----
surface: {
display: 'flex',
flexDirection: 'column',
inlineSize: '100%',
},
header: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: spacingVars['--spacing-2'],
blockSize: sizeVars['--size-element-lg'],
// No inline padding of its own: the content box owns the inset, and any
// extra here would push the arrows off the line the day grid sits on.
},
/**
* Both arrows together, at the trailing corner. `IconButton` draws each
* one — a hand-rolled button had the glyph off-centre, and matching
* Button's optical centring by hand is exactly the sort of thing a shared
* component is for.
*/
monthArrows: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-0-5'],
// The pair is the trailing item; the title takes the space before it.
marginInlineStart: 'auto',
// The plate starts below the header, so these two are the one part of the
// calendar the layer above cannot cover. They fade on its timing instead,
// both directions, so the change reads as one motion rather than chrome
// blinking out a beat before the grid is covered.
transitionProperty: 'opacity, visibility',
transitionDuration: SWAP_DURATION,
transitionTimingFunction: 'linear',
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
/**
* Hidden while the wheels are up: they step the calendar, and the calendar
* is not on screen. Hidden rather than unmounted because they are the
* tallest thing in the header — dropping them would shorten it by 8px and
* shift the whole sheet just as the panels cross-fade.
*
* `visibility: hidden` also takes them out of the tab order and the
* accessibility tree, so there is nothing to reach that cannot be seen.
*/
/**
* An arrow with nowhere to go. Hidden, not unmounted, and not merely
* disabled — it keeps its 44px so the remaining arrow does not slide
* sideways as the range's edge is reached, and `visibility: hidden` takes
* it out of the tab order and the accessibility tree so nothing invisible
* is reachable.
*/
monthArrowUnavailable: {
visibility: 'hidden',
},
monthArrowsHidden: {
visibility: 'hidden',
opacity: 0,
pointerEvents: 'none',
},
/**
* `Button`'s own sizes top out at 36px, which is fine for a mouse and short
* of the 44px every other target in this sheet honours. Floor it on a
* coarse pointer, the same way the field and the day cells do.
*/
monthArrow: {
minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
minInlineSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
},
/**
* The wrapper the RTL mirror rides on has to be a flex box. A bare inline
* span puts the glyph on the text baseline, which lifts it a few px off the
* button's optical centre — the whole reason these are `IconButton`s now.
* Core's Calendar carries the identical `navIcon` rule.
*/
monthArrowIcon: {
display: 'inline-flex',
},
/**
* The month and year, and the toggle into the wheels. Leading, so it reads
* first and sits on the same line as the day grid below it.
*/
title: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-1'],
blockSize: '100%',
paddingInline: spacingVars['--spacing-2'],
// Pulls the text back onto the grid's line: the button's own padding
// would otherwise inset the label past it.
marginInlineStart: `calc(-1 * ${spacingVars['--spacing-2']})`,
borderWidth: 0,
borderStyle: 'none',
borderRadius: radiusVars['--radius-element'],
backgroundColor: {
default: 'transparent',
'@media (hover: hover)': {
default: 'transparent',
':hover:where(:not(:disabled,[aria-disabled="true"]))':
colorVars['--color-overlay-hover'],
},
':active': colorVars['--color-overlay-pressed'],
},
color: colorVars['--color-text-primary'],
fontSize: typeScaleVars['--text-large-size'],
fontWeight: fontWeightVars['--font-weight-semibold'],
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
whiteSpace: 'nowrap',
},
titleChevron: {
display: 'inline-flex',
// The one part of the swap that keeps `--ease-standard`, because it is
// the one part that travels: a rotation has a distance to cover, and
// fast-out-slow-in is what that curve is for. Same duration as the
// surface it announces, so the two land together.
transitionProperty: 'transform',
transitionDuration: SWAP_DURATION,
transitionTimingFunction: easeVars['--ease-standard'],
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
titleChevronOpen: {
transform: 'rotate(180deg)',
},
weekdays: {
display: 'grid',
gridTemplateColumns: 'repeat(7, 1fr)',
blockSize: sizeVars['--size-element-sm'],
alignItems: 'center',
// Same as the arrows: above the plate's reach, so it fades on the layer's
// timing rather than clearing on its own.
transitionProperty: 'opacity, visibility',
transitionDuration: SWAP_DURATION,
transitionTimingFunction: 'linear',
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
weekdaysHidden: {
// Hidden, not unmounted: the row still owes the surface its height, or
// opening the wheels would make the picker shorter.
visibility: 'hidden',
opacity: 0,
},
weekday: {
textAlign: 'center',
fontSize: typeScaleVars['--text-supporting-size'],
fontWeight: fontWeightVars['--font-weight-normal'],
color: colorVars['--color-text-secondary'],
},
body: {
display: 'grid',
blockSize: dateInputTouchGeometry.paneBlockSize,
position: 'relative',
},
/**
* The two panels share one grid cell, and the wheels are the one on top.
*/
panel: {
gridArea: '1 / 1',
minWidth: 0,
},
/**
* The layer underneath — the calendar, and the calendar's footer actions.
*
* It has no opacity and never fades. `visibility` is the only thing that
* moves, and giving it the layer's own duration is what times it: CSS
* interpolates `visibility` discretely, holding `visible` for the whole
* transition whenever either end is `visible` and taking the final value
* only at the finish. So it disappears exactly when the cover completes,
* and on the way back it is there from the first frame, revealed as the
* layer above fades off it. Nothing about it is ever seen changing.
*
* It is not merely decorative to hide it: `inert` keeps it off the tab
* order, but a layer that is only COVERED is still `visible` to a screen
* reader, so the two footer actions would both be announced.
*
* `visibility` (not `display`) also keeps the month scroller laid out while
* the wheels are up, so its scroll offset survives the round trip and the
* wheels can steer it before it is shown again.
*/
panelBeneath: {
transitionProperty: 'visibility',
transitionDuration: SWAP_DURATION,
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
panelBeneathHidden: {
visibility: 'hidden',
pointerEvents: 'none',
},
/**
* The month and year, as one layer that fades in and out on top.
*
* The calendar underneath does not fade with it — this layer is opaque, so
* covering it is enough, and animating it too would be animating the date
* picker rather than the thing arriving over it.
*
* Three properties carry the whole design:
*
* `backgroundColor` is what makes the fade uniform. Without it the wheels
* are a translucent selection band and some text, each compositing against
* a live calendar grid on its own terms — so the band area faded unlike the
* rest and read as "the grey area animates differently from the content".
* With the plate inside the fading group, the group renders opaque first
* and the fade applies to the finished image, so every pixel of it crosses
* at the same rate.
*
* `isolation` is what makes the plate actually cover. Backgrounds and text
* paint in separate phases, so without a stacking context a later sibling's
* background lands UNDER an earlier sibling's text — the plate went in
* opaque and the calendar's day numbers showed straight through it. Easy to
* lose, because any opacity below 1 makes a stacking context anyway: the
* cover only breaks at the two ends of the fade, where opacity is exactly
* 1, which is to say whenever anyone is actually looking.
*
* `visibility` rides along with `opacity`, on the same rule as the layer
* beneath: it stays `visible` for the whole transition, so fading out is
* seen rather than cut on the first frame, and the layer still leaves the
* a11y tree and the hit testing at the end of it.
*
* Easing is `linear`, not `--ease-standard`. That token is
* `cubic-bezier(0.24, 1, 0.4, 1)`, which is right for something travelling
* a distance and wrong for a fade: measured, it put the opacity at 50% in
* 91ms and 95% in 241ms of a 410ms transition, so the fade was over long
* before the duration was, and lengthening the duration bought an
* imperceptible tail rather than a slower fade. A fade has no distance to
* cover, so its progress should be its progress.
*/
panelOverlay: {
backgroundColor: colorVars['--color-background-surface'],
isolation: 'isolate',
transitionProperty: 'opacity, visibility',
transitionDuration: SWAP_DURATION,
transitionTimingFunction: 'linear',
'@media (prefers-reduced-motion: reduce)': {
transitionDuration: '0.01s',
},
},
panelOverlayHidden: {
visibility: 'hidden',
opacity: 0,
pointerEvents: 'none',
},
footer: {
paddingBlockStart: spacingVars['--spacing-2'],
// Same reason as the header: the content box owns the inline inset, so
// Done's edge lines up with the grid's rather than sitting 4px inside it.
// One grid cell, so the two actions stack and the row is as tall as one
// button whichever is showing.
display: 'grid',
gridTemplateColumns: '1fr',
},
/**
* One footer action. Both occupy the same cell, and the wheels' one is a
* layer over the calendar's pair exactly as the panels above are. The row
* never changes height either way.
*/
footerAction: {
gridArea: '1 / 1',
// Side by side and equal: the calendar's cell holds Reset and Save, the
// wheels' holds one button. `1fr` each rather than content width, so
// neither label's length decides how the row is divided.
display: 'flex',
gap: spacingVars['--spacing-2'],
},
sheetBody: {
// One inset on every edge. The block-start is the exception and has to
// be: the sheet's grab handle floats out of flow, costing no layout
// height of its own, so the content wrapper owes it the 24px it occupies
// — which reads as the same inset, because the handle sits in it.
paddingInline: spacingVars['--spacing-4'],
paddingBlockStart: spacingVars['--spacing-6'],
paddingBlockEnd: spacingVars['--spacing-4'],
},
divider: {
blockSize: borderVars['--border-width'],
backgroundColor: colorVars['--color-border'],
marginBlockStart: spacingVars['--spacing-1'],
},
});
/**
* The touch surface. Takes `DateInput`'s props verbatim; see
* {@link DateInput} for when it is chosen over the desktop control.
*/
export function TouchDateField({
label,
isLabelHidden = false,
description,
isOptional = false,
isRequired = false,
isDisabled = false,
disabledMessage,
value,
onChange,
changeAction,
isLoading = false,
min,
max,
dateConstraints,
placeholder: placeholderFromProps,
size: sizeProp,
status,
statusVariant = 'attached',
labelTooltip,
hasClear = false,
// Desktop-only: the scroller is a single continuously paged column, so a
// second month would be the month already one flick away. Accepted (the
// prop types are shared) and ignored.
numberOfMonths: _numberOfMonths,
weekStartsOn: weekStartsOnProp = 0,
format = 'date_long',
width,
xstyle,
className,
style,
ref,
...rest
}: DateInputProps) {
const t = useTranslator();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder =
placeholderFromProps ?? t('@astryx.dateInput.placeholder');
const size = useSize(sizeProp, 'md');
const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);
const id = useId();
const inputLabelID = useId();
const descriptionID = useId();
const statusMessageID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
const inputGroup = useInputGroup();
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
const isEffectivelyDisabled = isDisabled || isBusy;
// Disabled-reason tooltip, same contract as DateInput: a disabled control
// swallows pointer events, so the listeners attach to the wrapper and the
// input stays focusable via aria-disabled rather than the disabled
// attribute. Only the persistent disabled state surfaces a reason, never
// the transient busy one.
const showsDisabledMessage = isDisabled && !!disabledMessage;
const disabledMessageTooltip = useTooltip({
placement: 'above',
focusTrigger: 'always',
isEnabled: showsDisabledMessage,
});
const {isDateDisabled} = useCalendarConstraints({min, max, dateConstraints});
const {statusIcon, describedBy: statusTooltipDescribedBy} =
useInputStatusIcon({
status,
statusVariant,
isInGroup: !!inputGroup,
});
const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
inputLabelID,
[
description ? descriptionID : null,
statusVariant !== 'tooltip' && status?.message ? statusMessageID : null,
statusTooltipDescribedBy,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
],
inputGroup,
);
const [isSheetOpen, setIsSheetOpen] = useState(false);
const [isWheelOpen, setIsWheelOpen] = useState(false);
const scrollerHandleRef = useRef<MonthScrollerHandle | null>(null);
// Pending focus handoff from the clear button; see handleClear.
const clearFocusTimerRef = useRef<number | null>(null);
useEffect(
() => () => {
if (clearFocusTimerRef.current != null) {
clearTimeout(clearFocusTimerRef.current);
}
},
[],
);
const today = useMemo(() => plainDateToday(), []);
const selectedDate = useMemo(
() =>
optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
? plainDateFromISO(optimisticValue)
: null,
[optimisticValue],
);
// The reachable range. Explicit bounds win; otherwise the scroller reaches a
// century in each direction from wherever it opened. Anchored once, in a
// state initializer: recomputing it as the selection moves would shift every
// pane's scroll offset under the user mid-gesture.
const [anchorMonthIndex] = useState(() =>
monthIndexOf(
value != null && /^\d{4}-\d{2}-\d{2}$/.test(value)
? plainDateFromISO(value)
: plainDateToday(),
),
);
const minMonthIndex =
min != null
? monthIndexOf(plainDateFromISO(min))
: anchorMonthIndex - DEFAULT_MONTH_REACH;
const maxMonthIndex =
max != null
? monthIndexOf(plainDateFromISO(max))
: anchorMonthIndex + DEFAULT_MONTH_REACH;
const [monthIndex, setMonthIndex] = useState(() =>
clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),
);
const {year, month} = fromMonthIndex(monthIndex);
/**
* Three-letter weekday names — "Sun", not Calendar's "Su".
*
* The sheet is full width and the columns are ~51px, so there is room for
* the form people actually read, and a picker operated by thumb should not
* make anyone decode "Tu" against "Th".
*
* This is CLDR's `abbreviated` width, which `Intl` produces natively — no
* truncation, so the 28 non-English locales stay correct rather than being
* sliced to three characters. (Verified against the CLDR tables for all 30
* locales in the catalog.) Calendar's 2-letter row is CLDR's *short* width,
* which `Intl` cannot express, which is exactly why that surface needs a
* generated table and this one does not.
*
* Built here rather than taken from `useCalendarDays`, which supplies the
* short form for Calendar's own header. The rotation matches: day 4 of
* January 1970 was a Sunday, so offsetting from it by `weekStartsOn` walks
* the week in the same order the panes lay out their columns.
*/
const dayNames = useMemo(
() =>
Array.from({length: 7}, (_, offset) =>
plainDateFormat(
{year: 1970, month: 1, day: 4 + ((weekStartsOn + offset) % 7)},
DATE_FORMAT_WEEKDAY_ONLY,
),
),
[weekStartsOn],
);
const monthYearLabel = plainDateFormat(
{year, month, day: 1},
DATE_FORMAT_MONTH_YEAR,
);
// Formats the committed value only. A function format is called with the ISO
// value; a named one reuses Timestamp's shared date mapping, so the same
// literal renders the same shape here and on the desktop control.
const displayValue =
optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
? typeof format === 'function'
? format(optimisticValue)
: formatSharedDate(plainDateFromISO(optimisticValue), format)
: '';
const fireChange = useCallback(
(newValue: ISODateString | undefined) => {
if (isBusy) {
return;
}
onChange?.(newValue);
if (changeAction) {
startTransition(async () => {
setOptimisticValue(newValue);
await changeAction(newValue);
});
}
},
[isBusy, onChange, changeAction, startTransition, setOptimisticValue],
);
const openSheet = useCallback(() => {
if (!isEffectivelyDisabled) {
// Always onto the calendar, whatever was showing last time. The wheels
// are a detour taken to reach a far month, not a mode to be left in:
// reopening into them would answer a question the user has not asked
// yet, and hide the dates they came back for behind another tap.
setIsWheelOpen(false);
setIsSheetOpen(true);
}
}, [isEffectivelyDisabled]);
const handleClear = useCallback(() => {
fireChange(undefined);
// Focus goes back to the field on the NEXT task, not synchronously.
//
// Clearing unmounts this button (it only renders while there is a value),
// and focusing another element in the same task as that unmount makes iOS
// Safari scroll the whole document to the top — the user is thrown from
// wherever the field sat to the start of the page. Measured on the iOS 26
// simulator against the live docsite, field at scrollY 2055: synchronous
// focus lands at 0, deferred focus stays at 2055.
//
// `preventScroll` alone does NOT fix it (verified: still 0) — this is not
// the browser's ordinary scroll-the-focused-element-into-view step, so the
// deferral is the load-bearing half. It is kept because the reveal scroll
// is real too, and unwanted for the same reason: the field the user just
// tapped is already on screen (+12px on a plain page without it).
//
// Skipping the focus entirely would also stop the scroll, but then focus
// dies with the unmounting button and lands on <body>.
const field = inputRef.current;
if (field == null) {
return;
}
clearFocusTimerRef.current = window.setTimeout(() => {
clearFocusTimerRef.current = null;
field.focus({preventScroll: true});
}, 0);
}, [fireChange]);
/**
* Put the picker back to how it opens: no date, current month.
*
* Two things, because clearing a date and then being left staring at the
* month of the date you just cleared is a half-finished action — the
* calendar should look the way it does before anything is chosen.
*
* "If possible" is load-bearing: a range can exclude the current month
* entirely (a booking window starting next quarter), and there is no
* honest place to go in that case. `clampIndex` would silently land on the
* nearest edge, which is a different month presented as if it were today's,
* so the move is skipped instead and the calendar stays where it is. The
* value is still cleared either way — that half never depends on the range.
*/
const handleResetInSheet = useCallback(() => {
fireChange(undefined);
const currentMonth = monthIndexOf(today);
if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {
return;
}
if (currentMonth === monthIndex) {
return;
}
setMonthIndex(currentMonth);
scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');
}, [fireChange, today, monthIndex, minMonthIndex, maxMonthIndex]);
// Selection commits on the tap and leaves the sheet up, so a mistake can be
// corrected in place and a nearby date reconsidered without reopening.
// Dismissal is the footer's Done (and the handle, the scrim, Escape) — none
// of which commit anything, because this already has.
const handleSelect = useCallback(
(next: ISODateString) => {
fireChange(next);
},
[fireChange],
);
// Whether there is anywhere to step. An arrow with nowhere to go is hidden
// rather than disabled: a disabled control still says "this is a thing you
// could do", and at the end of a range it is not — the range is the whole
// truth, and there is no state the user can reach where it becomes
// available. A greyed chevron sitting there permanently reads as broken.
const canStepBack = monthIndex > minMonthIndex;
const canStepForward = monthIndex < maxMonthIndex;
// One month either way, clamped to the reachable range. Goes through the
// same scrollToMonth the swipe settles on, so the arrows and the gesture
// cannot disagree about where a month rests.
const stepMonth = useCallback(
(delta: number) => {
const target = clampIndex(
monthIndex + delta,
minMonthIndex,
maxMonthIndex,
);
if (target === monthIndex) {
return;
}
setMonthIndex(target);
scrollerHandleRef.current?.scrollToMonth(target, 'smooth');
},
[monthIndex, minMonthIndex, maxMonthIndex],
);
// A wheel commit steers the scroller immediately, even though it is behind
// the wheels: it keeps its layout box while hidden, so by the time the
// wheels close it is already resting on the new month.
const handleWheelChange = useCallback((next: number) => {
setMonthIndex(next);
scrollerHandleRef.current?.scrollToMonth(next, 'auto');
}, []);
/**
* The calendar reports the month it has scrolled to — but only while it is
* the surface being scrolled.
*
* While the wheels are up the wheels are the source of truth, and the
* calendar is being STEERED by them: a wheel commit calls `scrollToMonth`
* above, the calendar scrolls, and it would report that month straight back
* here. That closes a cycle — wheel commits, calendar echoes, the echo moves
* the wheel's selected row, the wheel is repositioned onto it, and the
* resulting scroll reads as another commit.
*
* Whether that cycle converges depends on how precisely a browser reports
* "scrolling stopped", which is not something to rely on. With `scrollend`
* (Chrome) it settles at once; on iOS below Safari 26 there is no
* `scrollend` and momentum runs on for a second or more after the finger
* lifts, so each lap committed the next month along and the value climbed
* on its own. Ignoring the echo removes the cycle instead of damping it.
*/
const handleVisibleMonthChange = useCallback(
(next: number) => {
if (isWheelOpen) {
return;
}
setMonthIndex(next);
},
[isWheelOpen],
);
/**
* Put the calendar back where it belongs when the wheels close.
*
* The wheels steer it while it is hidden, and a hidden scroller is not a
* reliable place to leave a scroll position: `visibility: hidden` keeps the
* layout box, but iOS re-snaps the scroller when it becomes visible again,
* and it does not necessarily re-snap to the pane we put it on. That fires
* a scroll at the exact moment reports start being trusted again — which is
* why the month drifted on the way back to the dates.
*
* Re-asserting is cheap when nothing moved (the scroller is already there,
* so nothing scrolls) and exactly right when something did. `scrollToMonth`
* marks the target as steered, so this correction does not report itself
* back either.
*/
// Read through a ref so this effect depends on the surface change alone.
// Listing `monthIndex` would re-run it on every month the user swipes to,
// yanking the scroller back mid-gesture.
const monthIndexRef = useRef(monthIndex);
monthIndexRef.current = monthIndex;
useEffect(() => {
if (isWheelOpen) {
return;
}
scrollerHandleRef.current?.scrollToMonth(monthIndexRef.current, 'auto');
}, [isWheelOpen]);
// APG combobox keys. The field takes no text, so every printable key is
// free — but only the documented openers are wired, so a stray keystroke
// does not pop a sheet.
const handleInputKeyDown = useCallback(
(event: React.KeyboardEvent) => {
// Same guard core's pointer surface carries. This field is readOnly and
// takes no composition of its own, but an IME sitting over it still
// sends its committing Enter here first — and opening a date sheet on
// the keystroke that finishes a Korean syllable is the same wrong
// answer. See utils/ime.ts.
if (isImeKeyEvent(event.nativeEvent)) {
return;
}
if (
event.key === 'ArrowDown' ||
event.key === 'Enter' ||
event.key === ' ' ||
event.key === 'Spacebar'
) {
event.preventDefault();
openSheet();
}
},
[openSheet],
);
const surface = (
<div {...stylex.props(styles.surface)}>
<div {...stylex.props(styles.header)}>
<button
type="button"
onClick={() => setIsWheelOpen(open => !open)}
aria-expanded={isWheelOpen}
// One string, not a template: the comma and the word order are
// the translator's to choose, not English's.
aria-label={t('@astryx.dateInput.chooseMonthYear', {
monthYear: monthYearLabel,
})}
// A `data-` hook rather than a theme target. `themeProps` would
// publish `astryx-date-input-touch-title` as a themeable selector,
// and this is internal structure of the sheet — the field and its
// toggle icon are the documented targets, and nothing has asked to
// restyle the header button. Adding a target later is additive;
// withdrawing one is not.
data-title="month-year"
{...stylex.props(styles.title, focusOutlineStyles.focusVisible)}>
<span>{monthYearLabel}</span>
<Icon
icon="chevronDown"
size="sm"
color="secondary"
// The transform rides on the Icon itself, not a wrapper span, so
// the element a theme can target is the element that moves.
xstyle={[
styles.titleChevron,
isWheelOpen && styles.titleChevronOpen,
]}
/>
</button>
{/* Both arrows at the trailing corner, as a pair — and only while the
calendar is the surface they step. `IconButton` gives them
Button's optical centring, focus ring, disabled treatment and hit
area; the hand-rolled version had the glyph off-centre.
Mirrored under RTL by the shared helper: "previous" is the earlier
month, which sits on the right when the inline axis runs that way,
and the panes mirror with it. */}
<span
data-arrows="months"
// `inert` as well as the hidden styling: the fade keeps them
// `visible` until it finishes, and a control that is on its way out
// should not answer a click or a Tab in the meantime.
inert={isWheelOpen ? true : undefined}
{...stylex.props(
styles.monthArrows,
isWheelOpen && styles.monthArrowsHidden,
)}>
<IconButton
variant="ghost"
size="sm"
xstyle={[
styles.monthArrow,
!canStepBack && styles.monthArrowUnavailable,
]}
isDisabled={!canStepBack}
onClick={() => stepMonth(-1)}
label={t('@astryx.calendar.previousMonth')}
icon={
<span {...stylex.props(styles.monthArrowIcon, rtlStyles.mirror)}>
<Icon icon="chevronLeft" size="sm" color="inherit" />
</span>
}
/>
<IconButton
variant="ghost"
size="sm"
xstyle={[
styles.monthArrow,
!canStepForward && styles.monthArrowUnavailable,
]}
isDisabled={!canStepForward}
onClick={() => stepMonth(1)}
label={t('@astryx.calendar.nextMonth')}
icon={
<span {...stylex.props(styles.monthArrowIcon, rtlStyles.mirror)}>
<Icon icon="chevronRight" size="sm" color="inherit" />
</span>
}
/>
</span>
</div>
{/* Decorative: each day carries its weekday in its accessible name, so
this row is not a header row for assistive technology — and it must
live outside the scroller, or it would scroll away with the month. */}
<div
aria-hidden="true"
{...stylex.props(
styles.weekdays,
isWheelOpen && styles.weekdaysHidden,
)}>
{dayNames.map(name => (
<div key={name} {...stylex.props(styles.weekday)}>
{name}
</div>