cx 26.2.4 → 26.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,862 +1,772 @@
1
- /** @jsxImportSource react */
2
-
3
- import { StringTemplate } from "../../data/StringTemplate";
4
- import { Culture } from "../../ui/Culture";
5
- import { FocusManager, offFocusOut, oneFocusOut } from "../../ui/FocusManager";
6
- import "../../ui/Format";
7
- import { Localization } from "../../ui/Localization";
8
- import { VDOM, Widget } from "../../ui/Widget";
9
- import { parseDateInvariant } from "../../util";
10
- import { KeyCode } from "../../util/KeyCode";
11
- import { dateDiff } from "../../util/date/dateDiff";
12
- import { lowerBoundCheck } from "../../util/date/lowerBoundCheck";
13
- import { monthStart } from "../../util/date/monthStart";
14
- import { sameDate } from "../../util/date/sameDate";
15
- import { upperBoundCheck } from "../../util/date/upperBoundCheck";
16
- import { zeroTime } from "../../util/date/zeroTime";
17
- import DropdownIcon from "../icons/drop-down";
18
- import ForwardIcon from "../icons/forward";
19
- import {
20
- tooltipMouseLeave,
21
- tooltipMouseMove,
22
- tooltipParentDidMount,
23
- tooltipParentWillReceiveProps,
24
- tooltipParentWillUnmount,
25
- } from "../overlay/tooltip-ops";
26
- import { Field, FieldConfig, getFieldTooltip, FieldInstance } from "./Field";
27
- import type { Instance } from "../../ui/Instance";
28
- import type { RenderingContext } from "../../ui/RenderingContext";
29
- import { BooleanProp, DataRecord, Prop } from "../../ui/Prop";
30
-
31
- interface DayInfo {
32
- mod?: string;
33
- className?: string;
34
- style?: DataRecord | string;
35
- unselectable?: boolean;
36
- disabled?: boolean;
37
- }
38
-
39
- interface DayData {
40
- [day: string]: DayInfo;
41
- }
42
-
43
- export interface CalendarConfig extends FieldConfig {
44
- /** Selected date. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
45
- value?: Prop<string | Date>;
46
-
47
- /** View reference date. If no date is selected, this date is used to determine which month to show in the calendar. */
48
- refDate?: Prop<string | Date>;
49
-
50
- /** Minimum date value. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
51
- minValue?: Prop<string | Date>;
52
-
53
- /** Set to `true` to disallow the `minValue`. Default value is `false`. */
54
- minExclusive?: BooleanProp;
55
-
56
- /** Maximum date value. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
57
- maxValue?: Prop<string | Date>;
58
-
59
- /** Set to `true` to disallow the `maxValue`. Default value is `false`. */
60
- maxExclusive?: BooleanProp;
61
-
62
- /** Base CSS class to be applied to the calendar. Defaults to `calendar`. */
63
- baseClass?: string;
64
-
65
- /** Highlight today's date. Default is true. */
66
- highlightToday?: boolean;
67
-
68
- /** Maximum value error text. */
69
- maxValueErrorText?: string;
70
-
71
- /** Maximum exclusive value error text. */
72
- maxExclusiveErrorText?: string;
73
-
74
- /** Minimum value error text. */
75
- minValueErrorText?: string;
76
-
77
- /** Minimum exclusive value error text. */
78
- minExclusiveErrorText?: string;
79
-
80
- /** The function that will be used to convert Date objects before writing data to the store.
81
- * Default implementation is Date.toISOString.
82
- * See also Culture.setDefaultDateEncoding.
83
- */
84
- encoding?: (date: Date) => any;
85
-
86
- /** Set to true to show the button for quickly selecting today's date. */
87
- showTodayButton?: boolean;
88
-
89
- /** Localizable text for the todayButton. Defaults to `"Today"`. */
90
- todayButtonText?: string;
91
-
92
- /** Defines which days of week should be displayed as disabled, i.e. `[0, 6]` will make Sunday and Saturday unselectable. */
93
- disabledDaysOfWeek?: number[];
94
-
95
- /** Set to true to show weeks starting from Monday. */
96
- startWithMonday?: boolean;
97
-
98
- /** Map of days to additional day information such as style, className, mod, unselectable and disabled. */
99
- dayData?: Prop<DayData>;
100
- }
101
-
102
- export class Calendar extends Field<CalendarConfig> {
103
- declare public baseClass: string;
104
- declare public unfocusable?: boolean;
105
- declare public focusable?: boolean;
106
- declare public highlightToday?: boolean;
107
- declare public maxValueErrorText?: string;
108
- declare public maxExclusiveErrorText?: string;
109
- declare public minValueErrorText?: string;
110
- declare public minExclusiveErrorText?: string;
111
- declare public disabledDaysOfWeekErrorText?: string;
112
- declare public showTodayButton?: boolean;
113
- declare public todayButtonText?: string;
114
- declare public startWithMonday?: boolean;
115
- declare public onBeforeSelect?:
116
- | string
117
- | ((e: React.MouseEvent, instance: Instance, date: Date) => boolean | void);
118
- declare public onSelect?:
119
- | string
120
- | ((e: React.MouseEvent, instance: Instance, date: Date) => void);
121
- declare public onBlur?:
122
- | string
123
- | ((e: React.FocusEvent, instance: Instance) => void);
124
- declare public onFocusOut?: string | ((instance: Instance) => void);
125
- declare public disabledDaysOfWeek?: number[];
126
- declare public partial?: boolean;
127
- declare public encoding?: (date: Date) => string;
128
-
129
- constructor(config?: CalendarConfig) {
130
- super(config);
131
- }
132
-
133
- declareData(...args: Record<string, unknown>[]) {
134
- super.declareData(
135
- {
136
- value: undefined,
137
- refDate: undefined,
138
- disabled: undefined,
139
- enabled: undefined,
140
- minValue: undefined,
141
- minExclusive: undefined,
142
- maxValue: undefined,
143
- maxExclusive: undefined,
144
- focusable: undefined,
145
- dayData: undefined,
146
- },
147
- ...args,
148
- );
149
- }
150
-
151
- init() {
152
- if (this.unfocusable) this.focusable = false;
153
-
154
- super.init();
155
- }
156
-
157
- prepareData(
158
- context: RenderingContext,
159
- instance: FieldInstance<Calendar>,
160
- ...args: any[]
161
- ) {
162
- const { data } = instance;
163
- data.stateMods = {
164
- disabled: data.disabled,
165
- };
166
-
167
- if (data.value) {
168
- let d = parseDateInvariant(data.value);
169
- if (!isNaN(d.getTime())) {
170
- data.date = zeroTime(d);
171
- }
172
- }
173
-
174
- if (data.refDate) data.refDate = zeroTime(parseDateInvariant(data.refDate));
175
-
176
- if (data.maxValue)
177
- data.maxValue = zeroTime(parseDateInvariant(data.maxValue));
178
-
179
- if (data.minValue)
180
- data.minValue = zeroTime(parseDateInvariant(data.minValue));
181
-
182
- super.prepareData(context, instance, ...args);
183
- }
184
-
185
- validate(context: RenderingContext, instance: FieldInstance<Calendar>) {
186
- super.validate(context, instance);
187
- let { data, widget } = instance;
188
- let calendarWidget = widget as Calendar;
189
-
190
- if (!data.error && data.date) {
191
- let d;
192
- if (data.maxValue) {
193
- d = dateDiff(data.date, data.maxValue);
194
- if (d > 0)
195
- data.error = StringTemplate.format(
196
- this.maxValueErrorText!,
197
- data.maxValue,
198
- );
199
- else if (d == 0 && data.maxExclusive)
200
- data.error = StringTemplate.format(
201
- this.maxExclusiveErrorText!,
202
- data.maxValue,
203
- );
204
- }
205
-
206
- if (data.minValue) {
207
- d = dateDiff(data.date, data.minValue);
208
- if (d < 0)
209
- data.error = StringTemplate.format(
210
- this.minValueErrorText!,
211
- data.minValue,
212
- );
213
- else if (d == 0 && data.minExclusive)
214
- data.error = StringTemplate.format(
215
- this.minExclusiveErrorText!,
216
- data.minValue,
217
- );
218
- }
219
-
220
- if (calendarWidget.disabledDaysOfWeek) {
221
- if (calendarWidget.disabledDaysOfWeek.includes(data.date.getDay()))
222
- data.error = this.disabledDaysOfWeekErrorText;
223
- }
224
-
225
- if (data.dayData) {
226
- let date = parseDateInvariant(data.value);
227
- let info = data.dayData[date.toDateString()];
228
- if (info && info.disabled)
229
- data.error = this.disabledDaysOfWeekErrorText;
230
- }
231
- }
232
- }
233
-
234
- renderInput(
235
- context: RenderingContext,
236
- instance: any,
237
- key: string,
238
- ): React.ReactElement {
239
- return (
240
- <CalendarCmp
241
- key={key}
242
- instance={instance}
243
- handleSelect={(e: React.MouseEvent, date: Date) =>
244
- this.handleSelect(e, instance, date)
245
- }
246
- />
247
- );
248
- }
249
-
250
- handleSelect(e: React.MouseEvent, instance: any, date: Date): void {
251
- let { store, data, widget } = instance;
252
- let calendarWidget = widget as Calendar;
253
-
254
- e.stopPropagation();
255
-
256
- if (data.disabled) return;
257
-
258
- if (!validationCheck(date, data, calendarWidget.disabledDaysOfWeek)) return;
259
-
260
- if (
261
- this.onBeforeSelect &&
262
- instance.invoke("onBeforeSelect", e, instance, date) === false
263
- )
264
- return;
265
-
266
- if (calendarWidget.partial) {
267
- let mixed = parseDateInvariant(data.value);
268
- if (data.value && !isNaN(mixed.getTime())) {
269
- mixed.setFullYear(date.getFullYear());
270
- mixed.setMonth(date.getMonth());
271
- mixed.setDate(date.getDate());
272
- date = mixed;
273
- }
274
- }
275
-
276
- let encode = calendarWidget.encoding || Culture.getDefaultDateEncoding()!;
277
- instance.set("value", encode(date));
278
-
279
- if (this.onSelect) instance.invoke("onSelect", e, instance, date);
280
- }
281
- }
282
-
283
- Calendar.prototype.baseClass = "calendar";
284
- Calendar.prototype.highlightToday = true;
285
- Calendar.prototype.maxValueErrorText = "Select a date not after {0:d}.";
286
- Calendar.prototype.maxExclusiveErrorText = "Select a date before {0:d}.";
287
- Calendar.prototype.minValueErrorText = "Select a date not before {0:d}.";
288
- Calendar.prototype.minExclusiveErrorText = "Select a date after {0:d}.";
289
- Calendar.prototype.disabledDaysOfWeekErrorText =
290
- "Selected day of week is not allowed.";
291
- Calendar.prototype.suppressErrorsUntilVisited = false;
292
- Calendar.prototype.showTodayButton = false;
293
- Calendar.prototype.todayButtonText = "Today";
294
- Calendar.prototype.startWithMonday = false;
295
- Calendar.prototype.focusable = true;
296
-
297
- Localization.registerPrototype("cx/widgets/Calendar", Calendar);
298
-
299
- interface CalendarData {
300
- maxValue?: Date;
301
- maxExclusive?: boolean;
302
- minValue?: Date;
303
- minExclusive?: boolean;
304
- dayData?: Record<string, DayInfo>;
305
- }
306
-
307
- const validationCheck = (
308
- date: Date,
309
- data: CalendarData,
310
- disabledDaysOfWeek?: number[],
311
- ): boolean => {
312
- if (data.maxValue && !upperBoundCheck(date, data.maxValue, data.maxExclusive))
313
- return false;
314
-
315
- if (data.minValue && !lowerBoundCheck(date, data.minValue, data.minExclusive))
316
- return false;
317
-
318
- if (disabledDaysOfWeek && disabledDaysOfWeek.includes(date.getDay()))
319
- return false;
320
-
321
- if (data.dayData) {
322
- let day = data.dayData[date.toDateString()];
323
- if (day && (day.disabled || day.unselectable)) return false;
324
- }
325
-
326
- return true;
327
- };
328
-
329
- interface CalendarCmpProps {
330
- instance: FieldInstance<Calendar>;
331
- handleSelect: (e: React.MouseEvent, date: Date) => void;
332
- }
333
-
334
- interface CalendarState {
335
- hover: boolean;
336
- focus: boolean;
337
- cursor: Date;
338
- activeView: string;
339
- refDate: Date;
340
- startDate: Date;
341
- endDate: Date;
342
- yearPickerHeight?: number;
343
- }
344
-
345
- export class CalendarCmp extends VDOM.Component<
346
- CalendarCmpProps,
347
- CalendarState
348
- > {
349
- el: HTMLElement | null = null;
350
-
351
- constructor(props: CalendarCmpProps) {
352
- super(props);
353
- let { data } = props.instance;
354
-
355
- let refDate = data.refDate
356
- ? data.refDate
357
- : data.date || zeroTime(new Date());
358
-
359
- this.state = {
360
- hover: false,
361
- focus: false,
362
- cursor: zeroTime(data.date || refDate),
363
- activeView: "calendar",
364
- ...this.getPage(refDate),
365
- };
366
-
367
- this.handleMouseMove = this.handleMouseMove.bind(this);
368
- this.handleMouseDown = this.handleMouseDown.bind(this);
369
- }
370
-
371
- getPage(refDate: Date): { refDate: Date; startDate: Date; endDate: Date } {
372
- refDate = monthStart(refDate); //make a copy
373
-
374
- let calendarWidget = this.props.instance.widget as Calendar;
375
- let startWithMonday = calendarWidget.startWithMonday;
376
-
377
- let startDay = startWithMonday ? 1 : 0;
378
- let startDate = new Date(refDate);
379
- while (startDate.getDay() != startDay)
380
- startDate.setDate(startDate.getDate() - 1);
381
-
382
- let endDate = new Date(refDate);
383
- endDate.setMonth(refDate.getMonth() + 1);
384
- endDate.setDate(endDate.getDate() - 1);
385
-
386
- let endDay = startWithMonday ? 0 : 6;
387
- while (endDate.getDay() != endDay) endDate.setDate(endDate.getDate() + 1);
388
-
389
- return {
390
- refDate,
391
- startDate,
392
- endDate,
393
- };
394
- }
395
-
396
- moveCursor(
397
- e: React.SyntheticEvent | React.KeyboardEvent,
398
- date: Date,
399
- options: { movePage?: boolean } = {},
400
- ): void {
401
- e.preventDefault();
402
- e.stopPropagation();
403
-
404
- date = zeroTime(date);
405
- if (date.getTime() == this.state.cursor.getTime()) return;
406
-
407
- let refDate = this.state.refDate;
408
-
409
- if (
410
- options.movePage ||
411
- date < this.state.startDate ||
412
- date > this.state.endDate
413
- )
414
- refDate = date;
415
-
416
- this.setState({
417
- ...this.getPage(refDate),
418
- cursor: date,
419
- });
420
- }
421
-
422
- move(e: React.MouseEvent, period: string, delta: number): void {
423
- e.preventDefault();
424
- e.stopPropagation();
425
-
426
- let refDate = new Date(this.state.refDate);
427
-
428
- switch (period) {
429
- case "y":
430
- refDate.setFullYear(refDate.getFullYear() + delta);
431
- break;
432
-
433
- case "m":
434
- refDate.setMonth(refDate.getMonth() + delta);
435
- break;
436
- }
437
-
438
- let page = this.getPage(refDate);
439
- let cursor = this.state.cursor;
440
- if (cursor < page.startDate) cursor = page.startDate;
441
- else if (cursor > page.endDate) cursor = page.endDate;
442
-
443
- this.setState({ ...page, cursor });
444
- }
445
-
446
- handleKeyPress(e: React.KeyboardEvent): void {
447
- let cursor = new Date(this.state.cursor);
448
-
449
- switch (e.keyCode) {
450
- case KeyCode.enter:
451
- this.props.handleSelect(
452
- e as unknown as React.MouseEvent,
453
- this.state.cursor,
454
- );
455
- break;
456
-
457
- case KeyCode.left:
458
- cursor.setDate(cursor.getDate() - 1);
459
- this.moveCursor(e, cursor);
460
- break;
461
-
462
- case KeyCode.right:
463
- cursor.setDate(cursor.getDate() + 1);
464
- this.moveCursor(e, cursor);
465
- break;
466
-
467
- case KeyCode.up:
468
- cursor.setDate(cursor.getDate() - 7);
469
- this.moveCursor(e, cursor);
470
- break;
471
-
472
- case KeyCode.down:
473
- cursor.setDate(cursor.getDate() + 7);
474
- this.moveCursor(e, cursor);
475
- break;
476
-
477
- case KeyCode.pageUp:
478
- cursor.setMonth(cursor.getMonth() - 1);
479
- this.moveCursor(e, cursor, { movePage: true });
480
- break;
481
-
482
- case KeyCode.pageDown:
483
- cursor.setMonth(cursor.getMonth() + 1);
484
- this.moveCursor(e, cursor, { movePage: true });
485
- break;
486
-
487
- case KeyCode.home:
488
- cursor.setDate(1);
489
- this.moveCursor(e, cursor, { movePage: true });
490
- break;
491
-
492
- case KeyCode.end:
493
- cursor.setMonth(cursor.getMonth() + 1);
494
- cursor.setDate(0);
495
- this.moveCursor(e, cursor, { movePage: true });
496
- break;
497
-
498
- default:
499
- let { instance } = this.props;
500
- let calendarWidget = instance.widget as Calendar;
501
- if (calendarWidget.onKeyDown) instance.invoke("onKeyDown", e, instance);
502
- break;
503
- }
504
- }
505
-
506
- handleWheel(e: WheelEvent): void {
507
- e.preventDefault();
508
- e.stopPropagation();
509
-
510
- let cursor = new Date(this.state.cursor);
511
-
512
- if (e.deltaY < 0) {
513
- cursor.setMonth(cursor.getMonth() - 1);
514
- this.moveCursor(e as unknown as React.SyntheticEvent, cursor, {
515
- movePage: true,
516
- });
517
- } else if (e.deltaY > 0) {
518
- cursor.setMonth(cursor.getMonth() + 1);
519
- this.moveCursor(e as unknown as React.SyntheticEvent, cursor, {
520
- movePage: true,
521
- });
522
- }
523
- }
524
-
525
- handleBlur(e: React.FocusEvent): void {
526
- FocusManager.nudge();
527
- let { instance } = this.props;
528
- let calendarWidget = instance.widget as Calendar;
529
- if (calendarWidget.onBlur) instance.invoke("onBlur", e, instance);
530
- this.setState({
531
- focus: false,
532
- });
533
- }
534
-
535
- handleFocus(e: React.FocusEvent): void {
536
- oneFocusOut(this, this.el!, this.handleFocusOut.bind(this));
537
- this.setState({
538
- focus: true,
539
- });
540
- }
541
-
542
- handleFocusOut(): void {
543
- let { instance } = this.props;
544
- let calendarWidget = instance.widget as Calendar;
545
- if (calendarWidget.onFocusOut)
546
- instance.invoke("onFocusOut", null, instance);
547
- }
548
-
549
- handleMouseLeave(e: React.MouseEvent): void {
550
- tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance));
551
- this.setState({
552
- hover: false,
553
- });
554
- }
555
-
556
- handleMouseEnter(e: React.MouseEvent): void {
557
- this.setState({
558
- hover: true,
559
- });
560
- }
561
-
562
- handleMouseMove(e: React.MouseEvent): void {
563
- this.moveCursor(e, readDate((e.target as HTMLElement).dataset));
564
- }
565
-
566
- handleMouseDown(e: React.MouseEvent): void {
567
- this.props.handleSelect(e, readDate((e.target as HTMLElement).dataset));
568
- }
569
-
570
- componentDidMount(): void {
571
- //calendar doesn't bring up keyboard so it's ok to focus it even on mobile
572
- let calendarWidget = this.props.instance.widget as Calendar;
573
- if (calendarWidget.autoFocus && this.el) this.el.focus();
574
-
575
- if (this.el) {
576
- tooltipParentDidMount(this.el, ...getFieldTooltip(this.props.instance));
577
- this.el.addEventListener("wheel", (e) => this.handleWheel(e));
578
- }
579
- }
580
-
581
- UNSAFE_componentWillReceiveProps(props: CalendarCmpProps): void {
582
- let { data } = props.instance;
583
- if (data.date)
584
- this.setState({
585
- ...this.getPage(data.date),
586
- });
587
-
588
- if (this.el) {
589
- tooltipParentWillReceiveProps(
590
- this.el,
591
- ...getFieldTooltip(props.instance),
592
- );
593
- }
594
- }
595
-
596
- componentWillUnmount(): void {
597
- offFocusOut(this);
598
- tooltipParentWillUnmount(this.props.instance);
599
- }
600
-
601
- showYearDropdown(): void {
602
- if (this.el && this.el.firstChild) {
603
- this.setState({
604
- activeView: "year-picker",
605
- yearPickerHeight: (this.el.firstChild as HTMLElement).offsetHeight,
606
- });
607
- }
608
- }
609
-
610
- handleYearSelect(e: React.MouseEvent, year: number): void {
611
- e.preventDefault();
612
- e.stopPropagation();
613
- let refDate = new Date(this.state.refDate);
614
- refDate.setFullYear(year);
615
- this.setState({
616
- ...this.getPage(refDate),
617
- activeView: "calendar",
618
- });
619
- }
620
-
621
- renderYearPicker(): React.ReactElement {
622
- let { data, widget } = this.props.instance;
623
- let calendarWidget = widget as Calendar;
624
- let minYear: number | undefined = data.minValue?.getFullYear();
625
- let maxYear: number | undefined = data.maxValue?.getFullYear();
626
- let { CSS } = widget;
627
-
628
- let years: number[] = [];
629
- let currentYear = new Date().getFullYear();
630
- let midYear = currentYear - (currentYear % 5);
631
- let refYear = new Date(this.state.refDate).getFullYear();
632
- for (let i = midYear - 100; i <= midYear + 100; i++) {
633
- years.push(i);
634
- }
635
-
636
- let rows: number[][] = [];
637
- for (let i = 0; i < years.length; i += 5) {
638
- rows.push(years.slice(i, i + 5));
639
- }
640
- return (
641
- <div
642
- className={CSS.element(calendarWidget.baseClass, "year-picker")}
643
- style={{
644
- height: this.state.yearPickerHeight,
645
- }}
646
- ref={(el) => {
647
- if (el) {
648
- el.addEventListener("wheel", (e) => {
649
- e.stopPropagation();
650
- });
651
-
652
- let activeYear = el.querySelector("." + CSS.state("selected"));
653
- if (activeYear)
654
- activeYear.scrollIntoView({
655
- block: "center",
656
- behavior: "instant",
657
- });
658
- }
659
- }}
660
- >
661
- <table>
662
- <tbody>
663
- {rows.map((row: number[], rowIndex: number) => (
664
- <tr key={rowIndex}>
665
- {row.map((year: number) => (
666
- <td
667
- key={year}
668
- className={CSS.element(
669
- calendarWidget.baseClass,
670
- "year-option",
671
- {
672
- unselectable:
673
- (minYear && year < minYear) ||
674
- (maxYear && year > maxYear),
675
- selected: year === refYear,
676
- active: year === currentYear,
677
- },
678
- )}
679
- onClick={(e) => this.handleYearSelect(e, year)}
680
- >
681
- {year}
682
- </td>
683
- ))}
684
- </tr>
685
- ))}
686
- </tbody>
687
- </table>
688
- </div>
689
- );
690
- }
691
-
692
- render(): React.ReactElement {
693
- let { data, widget } = this.props.instance;
694
- let calendarWidget = widget as Calendar;
695
- let { CSS, baseClass, disabledDaysOfWeek, startWithMonday } =
696
- calendarWidget;
697
-
698
- let { refDate, startDate, endDate } = this.getPage(this.state.refDate);
699
-
700
- let month = refDate.getMonth();
701
- let year = refDate.getFullYear();
702
- let weeks: React.ReactNode[] = [];
703
- let date = startDate;
704
-
705
- let empty: Record<string, any> = {};
706
-
707
- let today = zeroTime(new Date());
708
- while (date >= startDate && date <= endDate) {
709
- let days: React.ReactNode[] = [];
710
- for (let i = 0; i < 7; i++) {
711
- let dayInfo =
712
- (data.dayData && data.dayData[date.toDateString()]) || empty;
713
- let unselectable = !validationCheck(date, data, disabledDaysOfWeek);
714
- let classNames = CSS.expand(
715
- CSS.element(baseClass, "day", {
716
- outside: month != date.getMonth(),
717
- unselectable: unselectable,
718
- selected: data.date && sameDate(data.date, date),
719
- cursor:
720
- (this.state.hover || this.state.focus) &&
721
- this.state.cursor &&
722
- sameDate(this.state.cursor, date),
723
- today: calendarWidget.highlightToday && sameDate(date, today),
724
- }),
725
- dayInfo.className,
726
- CSS.mod(dayInfo.mod),
727
- );
728
- let dateInst = new Date(date);
729
- days.push(
730
- <td
731
- key={i}
732
- className={classNames}
733
- style={CSS.parseStyle(dayInfo.style)}
734
- data-year={dateInst.getFullYear()}
735
- data-month={dateInst.getMonth() + 1}
736
- data-date={dateInst.getDate()}
737
- onMouseMove={unselectable ? undefined : this.handleMouseMove}
738
- onMouseDown={unselectable ? undefined : this.handleMouseDown}
739
- >
740
- {date.getDate()}
741
- </td>,
742
- );
743
- date.setDate(date.getDate() + 1);
744
- }
745
- weeks.push(
746
- <tr key={weeks.length} className={CSS.element(baseClass, "week")}>
747
- <td />
748
- {days}
749
- <td />
750
- </tr>,
751
- );
752
- }
753
-
754
- let culture = Culture.getDateTimeCulture();
755
- let monthNames = culture.getMonthNames("long");
756
- let dayNames = culture
757
- .getWeekdayNames("short")
758
- .map((x: string) => x.substr(0, 2));
759
- if (startWithMonday) dayNames = [...dayNames.slice(1), dayNames[0]];
760
-
761
- return (
762
- <div
763
- className={data.classNames}
764
- tabIndex={data.disabled || !data.focusable ? null : data.tabIndex || 0}
765
- onKeyDown={(e) => this.handleKeyPress(e)}
766
- onMouseDown={(e) => {
767
- // prevent losing focus from the input field
768
- if (!data.focusable) {
769
- e.preventDefault();
770
- }
771
- e.stopPropagation();
772
- }}
773
- ref={(el) => {
774
- this.el = el;
775
- }}
776
- onMouseMove={(e) =>
777
- tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))
778
- }
779
- onMouseLeave={(e) => this.handleMouseLeave(e)}
780
- onMouseEnter={(e) => this.handleMouseEnter(e)}
781
- // onWheel={(e) => this.handleWheel(e)}
782
- onFocus={(e) => this.handleFocus(e)}
783
- onBlur={(e) => this.handleBlur(e)}
784
- >
785
- {this.state.activeView == "calendar" && (
786
- <table>
787
- <thead>
788
- <tr key="h" className={CSS.element(baseClass, "header")}>
789
- <td />
790
- <td onClick={(e) => this.move(e, "y", -1)}>
791
- <ForwardIcon
792
- className={CSS.element(baseClass, "icon-prev-year")}
793
- />
794
- </td>
795
- <td onClick={(e) => this.move(e, "m", -1)}>
796
- <DropdownIcon
797
- className={CSS.element(baseClass, "icon-prev-month")}
798
- />
799
- </td>
800
- <th className={CSS.element(baseClass, "display")} colSpan={3}>
801
- {monthNames[month]}
802
- <br />
803
- <span
804
- onClick={() => this.showYearDropdown()}
805
- className={CSS.element(baseClass, "year-name")}
806
- >
807
- {year}
808
- </span>
809
- </th>
810
- <td onClick={(e) => this.move(e, "m", +1)}>
811
- <DropdownIcon
812
- className={CSS.element(baseClass, "icon-next-month")}
813
- />
814
- </td>
815
- <td onClick={(e) => this.move(e, "y", +1)}>
816
- <ForwardIcon
817
- className={CSS.element(baseClass, "icon-next-year")}
818
- />
819
- </td>
820
- <td />
821
- </tr>
822
- <tr key="d" className={CSS.element(baseClass, "day-names")}>
823
- <td />
824
- {dayNames.map((name: string, i: number) => (
825
- <th key={i}>{name}</th>
826
- ))}
827
- <td />
828
- </tr>
829
- </thead>
830
- <tbody>{weeks}</tbody>
831
- </table>
832
- )}
833
- {this.state.activeView == "calendar" &&
834
- calendarWidget.showTodayButton && (
835
- <div className={CSS.element(baseClass, "toolbar")}>
836
- <button
837
- className={CSS.expand(
838
- CSS.element(baseClass, "today-button"),
839
- CSS.block("button", "hollow"),
840
- )}
841
- data-year={today.getFullYear()}
842
- data-month={today.getMonth() + 1}
843
- data-date={today.getDate()}
844
- onClick={(e) => {
845
- this.handleMouseDown(e);
846
- }}
847
- >
848
- {calendarWidget.todayButtonText}
849
- </button>
850
- </div>
851
- )}
852
-
853
- {this.state.activeView == "year-picker" && this.renderYearPicker()}
854
- </div>
855
- );
856
- }
857
- }
858
-
859
- const readDate = (ds: DOMStringMap): Date =>
860
- new Date(Number(ds.year), Number(ds.month) - 1, Number(ds.date));
861
-
862
- Widget.alias("calendar", Calendar);
1
+ /** @jsxImportSource react */
2
+
3
+ import { StringTemplate } from "../../data/StringTemplate";
4
+ import { Culture } from "../../ui/Culture";
5
+ import { FocusManager, offFocusOut, oneFocusOut } from "../../ui/FocusManager";
6
+ import "../../ui/Format";
7
+ import { Localization } from "../../ui/Localization";
8
+ import { VDOM, Widget } from "../../ui/Widget";
9
+ import { addEventListenerWithOptions, parseDateInvariant } from "../../util";
10
+ import { KeyCode } from "../../util/KeyCode";
11
+ import { dateDiff } from "../../util/date/dateDiff";
12
+ import { lowerBoundCheck } from "../../util/date/lowerBoundCheck";
13
+ import { monthStart } from "../../util/date/monthStart";
14
+ import { sameDate } from "../../util/date/sameDate";
15
+ import { upperBoundCheck } from "../../util/date/upperBoundCheck";
16
+ import { zeroTime } from "../../util/date/zeroTime";
17
+ import DropdownIcon from "../icons/drop-down";
18
+ import ForwardIcon from "../icons/forward";
19
+ import {
20
+ tooltipMouseLeave,
21
+ tooltipMouseMove,
22
+ tooltipParentDidMount,
23
+ tooltipParentWillReceiveProps,
24
+ tooltipParentWillUnmount,
25
+ } from "../overlay/tooltip-ops";
26
+ import { Field, FieldConfig, getFieldTooltip, FieldInstance } from "./Field";
27
+ import type { Instance } from "../../ui/Instance";
28
+ import type { RenderingContext } from "../../ui/RenderingContext";
29
+ import { BooleanProp, DataRecord, Prop } from "../../ui/Prop";
30
+
31
+ interface DayInfo {
32
+ mod?: string;
33
+ className?: string;
34
+ style?: DataRecord | string;
35
+ unselectable?: boolean;
36
+ disabled?: boolean;
37
+ }
38
+
39
+ interface DayData {
40
+ [day: string]: DayInfo;
41
+ }
42
+
43
+ export interface CalendarConfig extends FieldConfig {
44
+ /** Selected date. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
45
+ value?: Prop<string | Date>;
46
+
47
+ /** View reference date. If no date is selected, this date is used to determine which month to show in the calendar. */
48
+ refDate?: Prop<string | Date>;
49
+
50
+ /** Minimum date value. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
51
+ minValue?: Prop<string | Date>;
52
+
53
+ /** Set to `true` to disallow the `minValue`. Default value is `false`. */
54
+ minExclusive?: BooleanProp;
55
+
56
+ /** Maximum date value. This should be a `Date` object or a valid date string consumable by `Date.parse` function. */
57
+ maxValue?: Prop<string | Date>;
58
+
59
+ /** Set to `true` to disallow the `maxValue`. Default value is `false`. */
60
+ maxExclusive?: BooleanProp;
61
+
62
+ /** Base CSS class to be applied to the calendar. Defaults to `calendar`. */
63
+ baseClass?: string;
64
+
65
+ /** Highlight today's date. Default is true. */
66
+ highlightToday?: boolean;
67
+
68
+ /** Maximum value error text. */
69
+ maxValueErrorText?: string;
70
+
71
+ /** Maximum exclusive value error text. */
72
+ maxExclusiveErrorText?: string;
73
+
74
+ /** Minimum value error text. */
75
+ minValueErrorText?: string;
76
+
77
+ /** Minimum exclusive value error text. */
78
+ minExclusiveErrorText?: string;
79
+
80
+ /** The function that will be used to convert Date objects before writing data to the store.
81
+ * Default implementation is Date.toISOString.
82
+ * See also Culture.setDefaultDateEncoding.
83
+ */
84
+ encoding?: (date: Date) => any;
85
+
86
+ /** Set to true to show the button for quickly selecting today's date. */
87
+ showTodayButton?: boolean;
88
+
89
+ /** Localizable text for the todayButton. Defaults to `"Today"`. */
90
+ todayButtonText?: string;
91
+
92
+ /** Defines which days of week should be displayed as disabled, i.e. `[0, 6]` will make Sunday and Saturday unselectable. */
93
+ disabledDaysOfWeek?: number[];
94
+
95
+ /** Set to true to show weeks starting from Monday. */
96
+ startWithMonday?: boolean;
97
+
98
+ /** Map of days to additional day information such as style, className, mod, unselectable and disabled. */
99
+ dayData?: Prop<DayData>;
100
+ }
101
+
102
+ export class Calendar extends Field<CalendarConfig> {
103
+ declare public baseClass: string;
104
+ declare public unfocusable?: boolean;
105
+ declare public focusable?: boolean;
106
+ declare public highlightToday?: boolean;
107
+ declare public maxValueErrorText?: string;
108
+ declare public maxExclusiveErrorText?: string;
109
+ declare public minValueErrorText?: string;
110
+ declare public minExclusiveErrorText?: string;
111
+ declare public disabledDaysOfWeekErrorText?: string;
112
+ declare public showTodayButton?: boolean;
113
+ declare public todayButtonText?: string;
114
+ declare public startWithMonday?: boolean;
115
+ declare public onBeforeSelect?: string | ((e: React.MouseEvent, instance: Instance, date: Date) => boolean | void);
116
+ declare public onSelect?: string | ((e: React.MouseEvent, instance: Instance, date: Date) => void);
117
+ declare public onBlur?: string | ((e: React.FocusEvent, instance: Instance) => void);
118
+ declare public onFocusOut?: string | ((instance: Instance) => void);
119
+ declare public disabledDaysOfWeek?: number[];
120
+ declare public partial?: boolean;
121
+ declare public encoding?: (date: Date) => string;
122
+
123
+ constructor(config?: CalendarConfig) {
124
+ super(config);
125
+ }
126
+
127
+ declareData(...args: Record<string, unknown>[]) {
128
+ super.declareData(
129
+ {
130
+ value: undefined,
131
+ refDate: undefined,
132
+ disabled: undefined,
133
+ enabled: undefined,
134
+ minValue: undefined,
135
+ minExclusive: undefined,
136
+ maxValue: undefined,
137
+ maxExclusive: undefined,
138
+ focusable: undefined,
139
+ dayData: undefined,
140
+ },
141
+ ...args,
142
+ );
143
+ }
144
+
145
+ init() {
146
+ if (this.unfocusable) this.focusable = false;
147
+
148
+ super.init();
149
+ }
150
+
151
+ prepareData(context: RenderingContext, instance: FieldInstance<Calendar>, ...args: any[]) {
152
+ const { data } = instance;
153
+ data.stateMods = {
154
+ disabled: data.disabled,
155
+ };
156
+
157
+ if (data.value) {
158
+ let d = parseDateInvariant(data.value);
159
+ if (!isNaN(d.getTime())) {
160
+ data.date = zeroTime(d);
161
+ }
162
+ }
163
+
164
+ if (data.refDate) data.refDate = zeroTime(parseDateInvariant(data.refDate));
165
+
166
+ if (data.maxValue) data.maxValue = zeroTime(parseDateInvariant(data.maxValue));
167
+
168
+ if (data.minValue) data.minValue = zeroTime(parseDateInvariant(data.minValue));
169
+
170
+ super.prepareData(context, instance, ...args);
171
+ }
172
+
173
+ validate(context: RenderingContext, instance: FieldInstance<Calendar>) {
174
+ super.validate(context, instance);
175
+ let { data, widget } = instance;
176
+ let calendarWidget = widget as Calendar;
177
+
178
+ if (!data.error && data.date) {
179
+ let d;
180
+ if (data.maxValue) {
181
+ d = dateDiff(data.date, data.maxValue);
182
+ if (d > 0) data.error = StringTemplate.format(this.maxValueErrorText!, data.maxValue);
183
+ else if (d == 0 && data.maxExclusive)
184
+ data.error = StringTemplate.format(this.maxExclusiveErrorText!, data.maxValue);
185
+ }
186
+
187
+ if (data.minValue) {
188
+ d = dateDiff(data.date, data.minValue);
189
+ if (d < 0) data.error = StringTemplate.format(this.minValueErrorText!, data.minValue);
190
+ else if (d == 0 && data.minExclusive)
191
+ data.error = StringTemplate.format(this.minExclusiveErrorText!, data.minValue);
192
+ }
193
+
194
+ if (calendarWidget.disabledDaysOfWeek) {
195
+ if (calendarWidget.disabledDaysOfWeek.includes(data.date.getDay()))
196
+ data.error = this.disabledDaysOfWeekErrorText;
197
+ }
198
+
199
+ if (data.dayData) {
200
+ let date = parseDateInvariant(data.value);
201
+ let info = data.dayData[date.toDateString()];
202
+ if (info && info.disabled) data.error = this.disabledDaysOfWeekErrorText;
203
+ }
204
+ }
205
+ }
206
+
207
+ renderInput(context: RenderingContext, instance: any, key: string): React.ReactElement {
208
+ return (
209
+ <CalendarCmp
210
+ key={key}
211
+ instance={instance}
212
+ handleSelect={(e: React.MouseEvent, date: Date) => this.handleSelect(e, instance, date)}
213
+ />
214
+ );
215
+ }
216
+
217
+ handleSelect(e: React.MouseEvent, instance: any, date: Date): void {
218
+ let { store, data, widget } = instance;
219
+ let calendarWidget = widget as Calendar;
220
+
221
+ e.stopPropagation();
222
+
223
+ if (data.disabled) return;
224
+
225
+ if (!validationCheck(date, data, calendarWidget.disabledDaysOfWeek)) return;
226
+
227
+ if (this.onBeforeSelect && instance.invoke("onBeforeSelect", e, instance, date) === false) return;
228
+
229
+ if (calendarWidget.partial) {
230
+ let mixed = parseDateInvariant(data.value);
231
+ if (data.value && !isNaN(mixed.getTime())) {
232
+ mixed.setFullYear(date.getFullYear());
233
+ mixed.setMonth(date.getMonth());
234
+ mixed.setDate(date.getDate());
235
+ date = mixed;
236
+ }
237
+ }
238
+
239
+ let encode = calendarWidget.encoding || Culture.getDefaultDateEncoding()!;
240
+ instance.set("value", encode(date));
241
+
242
+ if (this.onSelect) instance.invoke("onSelect", e, instance, date);
243
+ }
244
+ }
245
+
246
+ Calendar.prototype.baseClass = "calendar";
247
+ Calendar.prototype.highlightToday = true;
248
+ Calendar.prototype.maxValueErrorText = "Select a date not after {0:d}.";
249
+ Calendar.prototype.maxExclusiveErrorText = "Select a date before {0:d}.";
250
+ Calendar.prototype.minValueErrorText = "Select a date not before {0:d}.";
251
+ Calendar.prototype.minExclusiveErrorText = "Select a date after {0:d}.";
252
+ Calendar.prototype.disabledDaysOfWeekErrorText = "Selected day of week is not allowed.";
253
+ Calendar.prototype.suppressErrorsUntilVisited = false;
254
+ Calendar.prototype.showTodayButton = false;
255
+ Calendar.prototype.todayButtonText = "Today";
256
+ Calendar.prototype.startWithMonday = false;
257
+ Calendar.prototype.focusable = true;
258
+
259
+ Localization.registerPrototype("cx/widgets/Calendar", Calendar);
260
+
261
+ interface CalendarData {
262
+ maxValue?: Date;
263
+ maxExclusive?: boolean;
264
+ minValue?: Date;
265
+ minExclusive?: boolean;
266
+ dayData?: Record<string, DayInfo>;
267
+ }
268
+
269
+ const validationCheck = (date: Date, data: CalendarData, disabledDaysOfWeek?: number[]): boolean => {
270
+ if (data.maxValue && !upperBoundCheck(date, data.maxValue, data.maxExclusive)) return false;
271
+
272
+ if (data.minValue && !lowerBoundCheck(date, data.minValue, data.minExclusive)) return false;
273
+
274
+ if (disabledDaysOfWeek && disabledDaysOfWeek.includes(date.getDay())) return false;
275
+
276
+ if (data.dayData) {
277
+ let day = data.dayData[date.toDateString()];
278
+ if (day && (day.disabled || day.unselectable)) return false;
279
+ }
280
+
281
+ return true;
282
+ };
283
+
284
+ interface CalendarCmpProps {
285
+ instance: FieldInstance<Calendar>;
286
+ handleSelect: (e: React.MouseEvent, date: Date) => void;
287
+ }
288
+
289
+ interface CalendarState {
290
+ hover: boolean;
291
+ focus: boolean;
292
+ cursor: Date;
293
+ activeView: string;
294
+ refDate: Date;
295
+ startDate: Date;
296
+ endDate: Date;
297
+ yearPickerHeight?: number;
298
+ }
299
+
300
+ export class CalendarCmp extends VDOM.Component<CalendarCmpProps, CalendarState> {
301
+ el: HTMLElement | null = null;
302
+ unsubscribeWheel?: () => void;
303
+
304
+ constructor(props: CalendarCmpProps) {
305
+ super(props);
306
+ let { data } = props.instance;
307
+
308
+ let refDate = data.refDate ? data.refDate : data.date || zeroTime(new Date());
309
+
310
+ this.state = {
311
+ hover: false,
312
+ focus: false,
313
+ cursor: zeroTime(data.date || refDate),
314
+ activeView: "calendar",
315
+ ...this.getPage(refDate),
316
+ };
317
+
318
+ this.handleMouseMove = this.handleMouseMove.bind(this);
319
+ this.handleMouseDown = this.handleMouseDown.bind(this);
320
+ }
321
+
322
+ getPage(refDate: Date): { refDate: Date; startDate: Date; endDate: Date } {
323
+ refDate = monthStart(refDate); //make a copy
324
+
325
+ let calendarWidget = this.props.instance.widget as Calendar;
326
+ let startWithMonday = calendarWidget.startWithMonday;
327
+
328
+ let startDay = startWithMonday ? 1 : 0;
329
+ let startDate = new Date(refDate);
330
+ while (startDate.getDay() != startDay) startDate.setDate(startDate.getDate() - 1);
331
+
332
+ let endDate = new Date(refDate);
333
+ endDate.setMonth(refDate.getMonth() + 1);
334
+ endDate.setDate(endDate.getDate() - 1);
335
+
336
+ let endDay = startWithMonday ? 0 : 6;
337
+ while (endDate.getDay() != endDay) endDate.setDate(endDate.getDate() + 1);
338
+
339
+ return {
340
+ refDate,
341
+ startDate,
342
+ endDate,
343
+ };
344
+ }
345
+
346
+ moveCursor(e: React.SyntheticEvent | React.KeyboardEvent, date: Date, options: { movePage?: boolean } = {}): void {
347
+ e.preventDefault();
348
+ e.stopPropagation();
349
+
350
+ date = zeroTime(date);
351
+ if (date.getTime() == this.state.cursor.getTime()) return;
352
+
353
+ let refDate = this.state.refDate;
354
+
355
+ if (options.movePage || date < this.state.startDate || date > this.state.endDate) refDate = date;
356
+
357
+ this.setState({
358
+ ...this.getPage(refDate),
359
+ cursor: date,
360
+ });
361
+ }
362
+
363
+ move(e: React.MouseEvent, period: string, delta: number): void {
364
+ e.preventDefault();
365
+ e.stopPropagation();
366
+
367
+ let refDate = new Date(this.state.refDate);
368
+
369
+ switch (period) {
370
+ case "y":
371
+ refDate.setFullYear(refDate.getFullYear() + delta);
372
+ break;
373
+
374
+ case "m":
375
+ refDate.setMonth(refDate.getMonth() + delta);
376
+ break;
377
+ }
378
+
379
+ let page = this.getPage(refDate);
380
+ let cursor = this.state.cursor;
381
+ if (cursor < page.startDate) cursor = page.startDate;
382
+ else if (cursor > page.endDate) cursor = page.endDate;
383
+
384
+ this.setState({ ...page, cursor });
385
+ }
386
+
387
+ handleKeyPress(e: React.KeyboardEvent): void {
388
+ let cursor = new Date(this.state.cursor);
389
+
390
+ switch (e.keyCode) {
391
+ case KeyCode.enter:
392
+ this.props.handleSelect(e as unknown as React.MouseEvent, this.state.cursor);
393
+ break;
394
+
395
+ case KeyCode.left:
396
+ cursor.setDate(cursor.getDate() - 1);
397
+ this.moveCursor(e, cursor);
398
+ break;
399
+
400
+ case KeyCode.right:
401
+ cursor.setDate(cursor.getDate() + 1);
402
+ this.moveCursor(e, cursor);
403
+ break;
404
+
405
+ case KeyCode.up:
406
+ cursor.setDate(cursor.getDate() - 7);
407
+ this.moveCursor(e, cursor);
408
+ break;
409
+
410
+ case KeyCode.down:
411
+ cursor.setDate(cursor.getDate() + 7);
412
+ this.moveCursor(e, cursor);
413
+ break;
414
+
415
+ case KeyCode.pageUp:
416
+ cursor.setMonth(cursor.getMonth() - 1);
417
+ this.moveCursor(e, cursor, { movePage: true });
418
+ break;
419
+
420
+ case KeyCode.pageDown:
421
+ cursor.setMonth(cursor.getMonth() + 1);
422
+ this.moveCursor(e, cursor, { movePage: true });
423
+ break;
424
+
425
+ case KeyCode.home:
426
+ cursor.setDate(1);
427
+ this.moveCursor(e, cursor, { movePage: true });
428
+ break;
429
+
430
+ case KeyCode.end:
431
+ cursor.setMonth(cursor.getMonth() + 1);
432
+ cursor.setDate(0);
433
+ this.moveCursor(e, cursor, { movePage: true });
434
+ break;
435
+
436
+ default:
437
+ let { instance } = this.props;
438
+ let calendarWidget = instance.widget as Calendar;
439
+ if (calendarWidget.onKeyDown) instance.invoke("onKeyDown", e, instance);
440
+ break;
441
+ }
442
+ }
443
+
444
+ handleWheel(e: WheelEvent): void {
445
+ e.preventDefault();
446
+ e.stopPropagation();
447
+
448
+ let cursor = new Date(this.state.cursor);
449
+
450
+ if (e.deltaY < 0) {
451
+ cursor.setMonth(cursor.getMonth() - 1);
452
+ this.moveCursor(e as unknown as React.SyntheticEvent, cursor, {
453
+ movePage: true,
454
+ });
455
+ } else if (e.deltaY > 0) {
456
+ cursor.setMonth(cursor.getMonth() + 1);
457
+ this.moveCursor(e as unknown as React.SyntheticEvent, cursor, {
458
+ movePage: true,
459
+ });
460
+ }
461
+ }
462
+
463
+ handleBlur(e: React.FocusEvent): void {
464
+ FocusManager.nudge();
465
+ let { instance } = this.props;
466
+ let calendarWidget = instance.widget as Calendar;
467
+ if (calendarWidget.onBlur) instance.invoke("onBlur", e, instance);
468
+ this.setState({
469
+ focus: false,
470
+ });
471
+ }
472
+
473
+ handleFocus(e: React.FocusEvent): void {
474
+ oneFocusOut(this, this.el!, this.handleFocusOut.bind(this));
475
+ this.setState({
476
+ focus: true,
477
+ });
478
+ }
479
+
480
+ handleFocusOut(): void {
481
+ let { instance } = this.props;
482
+ let calendarWidget = instance.widget as Calendar;
483
+ if (calendarWidget.onFocusOut) instance.invoke("onFocusOut", null, instance);
484
+ }
485
+
486
+ handleMouseLeave(e: React.MouseEvent): void {
487
+ tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance));
488
+ this.setState({
489
+ hover: false,
490
+ });
491
+ }
492
+
493
+ handleMouseEnter(e: React.MouseEvent): void {
494
+ this.setState({
495
+ hover: true,
496
+ });
497
+ }
498
+
499
+ handleMouseMove(e: React.MouseEvent): void {
500
+ this.moveCursor(e, readDate((e.target as HTMLElement).dataset));
501
+ }
502
+
503
+ handleMouseDown(e: React.MouseEvent): void {
504
+ this.props.handleSelect(e, readDate((e.target as HTMLElement).dataset));
505
+ }
506
+
507
+ componentDidMount(): void {
508
+ //calendar doesn't bring up keyboard so it's ok to focus it even on mobile
509
+ let calendarWidget = this.props.instance.widget as Calendar;
510
+ if (calendarWidget.autoFocus && this.el) this.el.focus();
511
+
512
+ if (this.el) {
513
+ tooltipParentDidMount(this.el, ...getFieldTooltip(this.props.instance));
514
+ this.unsubscribeWheel = addEventListenerWithOptions(this.el, "wheel", (e) => this.handleWheel(e), {
515
+ passive: false,
516
+ });
517
+ }
518
+ }
519
+
520
+ UNSAFE_componentWillReceiveProps(props: CalendarCmpProps): void {
521
+ let { data } = props.instance;
522
+ if (data.date)
523
+ this.setState({
524
+ ...this.getPage(data.date),
525
+ });
526
+
527
+ if (this.el) {
528
+ tooltipParentWillReceiveProps(this.el, ...getFieldTooltip(props.instance));
529
+ }
530
+ }
531
+
532
+ componentWillUnmount(): void {
533
+ offFocusOut(this);
534
+ tooltipParentWillUnmount(this.props.instance);
535
+ this.unsubscribeWheel?.();
536
+ }
537
+
538
+ showYearDropdown(): void {
539
+ if (this.el && this.el.firstChild) {
540
+ this.setState({
541
+ activeView: "year-picker",
542
+ yearPickerHeight: (this.el.firstChild as HTMLElement).offsetHeight,
543
+ });
544
+ }
545
+ }
546
+
547
+ handleYearSelect(e: React.MouseEvent, year: number): void {
548
+ e.preventDefault();
549
+ e.stopPropagation();
550
+ let refDate = new Date(this.state.refDate);
551
+ refDate.setFullYear(year);
552
+ this.setState({
553
+ ...this.getPage(refDate),
554
+ activeView: "calendar",
555
+ });
556
+ }
557
+
558
+ renderYearPicker(): React.ReactElement {
559
+ let { data, widget } = this.props.instance;
560
+ let calendarWidget = widget as Calendar;
561
+ let minYear: number | undefined = data.minValue?.getFullYear();
562
+ let maxYear: number | undefined = data.maxValue?.getFullYear();
563
+ let { CSS } = widget;
564
+
565
+ let years: number[] = [];
566
+ let currentYear = new Date().getFullYear();
567
+ let midYear = currentYear - (currentYear % 5);
568
+ let refYear = new Date(this.state.refDate).getFullYear();
569
+ for (let i = midYear - 100; i <= midYear + 100; i++) {
570
+ years.push(i);
571
+ }
572
+
573
+ let rows: number[][] = [];
574
+ for (let i = 0; i < years.length; i += 5) {
575
+ rows.push(years.slice(i, i + 5));
576
+ }
577
+ return (
578
+ <div
579
+ className={CSS.element(calendarWidget.baseClass, "year-picker")}
580
+ style={{
581
+ height: this.state.yearPickerHeight,
582
+ }}
583
+ ref={(el) => {
584
+ if (el) {
585
+ el.addEventListener("wheel", (e) => {
586
+ e.stopPropagation();
587
+ });
588
+
589
+ let activeYear = el.querySelector("." + CSS.state("selected"));
590
+ if (activeYear)
591
+ activeYear.scrollIntoView({
592
+ block: "center",
593
+ behavior: "instant",
594
+ });
595
+ }
596
+ }}
597
+ >
598
+ <table>
599
+ <tbody>
600
+ {rows.map((row: number[], rowIndex: number) => (
601
+ <tr key={rowIndex}>
602
+ {row.map((year: number) => (
603
+ <td
604
+ key={year}
605
+ className={CSS.element(calendarWidget.baseClass, "year-option", {
606
+ unselectable: (minYear && year < minYear) || (maxYear && year > maxYear),
607
+ selected: year === refYear,
608
+ active: year === currentYear,
609
+ })}
610
+ onClick={(e) => this.handleYearSelect(e, year)}
611
+ >
612
+ {year}
613
+ </td>
614
+ ))}
615
+ </tr>
616
+ ))}
617
+ </tbody>
618
+ </table>
619
+ </div>
620
+ );
621
+ }
622
+
623
+ render(): React.ReactElement {
624
+ let { data, widget } = this.props.instance;
625
+ let calendarWidget = widget as Calendar;
626
+ let { CSS, baseClass, disabledDaysOfWeek, startWithMonday } = calendarWidget;
627
+
628
+ let { refDate, startDate, endDate } = this.getPage(this.state.refDate);
629
+
630
+ let month = refDate.getMonth();
631
+ let year = refDate.getFullYear();
632
+ let weeks: React.ReactNode[] = [];
633
+ let date = startDate;
634
+
635
+ let empty: Record<string, any> = {};
636
+
637
+ let today = zeroTime(new Date());
638
+ while (date >= startDate && date <= endDate) {
639
+ let days: React.ReactNode[] = [];
640
+ for (let i = 0; i < 7; i++) {
641
+ let dayInfo = (data.dayData && data.dayData[date.toDateString()]) || empty;
642
+ let unselectable = !validationCheck(date, data, disabledDaysOfWeek);
643
+ let classNames = CSS.expand(
644
+ CSS.element(baseClass, "day", {
645
+ outside: month != date.getMonth(),
646
+ unselectable: unselectable,
647
+ selected: data.date && sameDate(data.date, date),
648
+ cursor:
649
+ (this.state.hover || this.state.focus) && this.state.cursor && sameDate(this.state.cursor, date),
650
+ today: calendarWidget.highlightToday && sameDate(date, today),
651
+ }),
652
+ dayInfo.className,
653
+ CSS.mod(dayInfo.mod),
654
+ );
655
+ let dateInst = new Date(date);
656
+ days.push(
657
+ <td
658
+ key={i}
659
+ className={classNames}
660
+ style={CSS.parseStyle(dayInfo.style)}
661
+ data-year={dateInst.getFullYear()}
662
+ data-month={dateInst.getMonth() + 1}
663
+ data-date={dateInst.getDate()}
664
+ onMouseMove={unselectable ? undefined : this.handleMouseMove}
665
+ onMouseDown={unselectable ? undefined : this.handleMouseDown}
666
+ >
667
+ {date.getDate()}
668
+ </td>,
669
+ );
670
+ date.setDate(date.getDate() + 1);
671
+ }
672
+ weeks.push(
673
+ <tr key={weeks.length} className={CSS.element(baseClass, "week")}>
674
+ <td />
675
+ {days}
676
+ <td />
677
+ </tr>,
678
+ );
679
+ }
680
+
681
+ let culture = Culture.getDateTimeCulture();
682
+ let monthNames = culture.getMonthNames("long");
683
+ let dayNames = culture.getWeekdayNames("short").map((x: string) => x.substr(0, 2));
684
+ if (startWithMonday) dayNames = [...dayNames.slice(1), dayNames[0]];
685
+
686
+ return (
687
+ <div
688
+ className={data.classNames}
689
+ tabIndex={data.disabled || !data.focusable ? null : data.tabIndex || 0}
690
+ onKeyDown={(e) => this.handleKeyPress(e)}
691
+ onMouseDown={(e) => {
692
+ // prevent losing focus from the input field
693
+ if (!data.focusable) {
694
+ e.preventDefault();
695
+ }
696
+ e.stopPropagation();
697
+ }}
698
+ ref={(el) => {
699
+ this.el = el;
700
+ }}
701
+ onMouseMove={(e) => tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))}
702
+ onMouseLeave={(e) => this.handleMouseLeave(e)}
703
+ onMouseEnter={(e) => this.handleMouseEnter(e)}
704
+ // onWheel={(e) => this.handleWheel(e)}
705
+ onFocus={(e) => this.handleFocus(e)}
706
+ onBlur={(e) => this.handleBlur(e)}
707
+ >
708
+ {this.state.activeView == "calendar" && (
709
+ <table>
710
+ <thead>
711
+ <tr key="h" className={CSS.element(baseClass, "header")}>
712
+ <td />
713
+ <td onClick={(e) => this.move(e, "y", -1)}>
714
+ <ForwardIcon className={CSS.element(baseClass, "icon-prev-year")} />
715
+ </td>
716
+ <td onClick={(e) => this.move(e, "m", -1)}>
717
+ <DropdownIcon className={CSS.element(baseClass, "icon-prev-month")} />
718
+ </td>
719
+ <th className={CSS.element(baseClass, "display")} colSpan={3}>
720
+ {monthNames[month]}
721
+ <br />
722
+ <span
723
+ onClick={() => this.showYearDropdown()}
724
+ className={CSS.element(baseClass, "year-name")}
725
+ >
726
+ {year}
727
+ </span>
728
+ </th>
729
+ <td onClick={(e) => this.move(e, "m", +1)}>
730
+ <DropdownIcon className={CSS.element(baseClass, "icon-next-month")} />
731
+ </td>
732
+ <td onClick={(e) => this.move(e, "y", +1)}>
733
+ <ForwardIcon className={CSS.element(baseClass, "icon-next-year")} />
734
+ </td>
735
+ <td />
736
+ </tr>
737
+ <tr key="d" className={CSS.element(baseClass, "day-names")}>
738
+ <td />
739
+ {dayNames.map((name: string, i: number) => (
740
+ <th key={i}>{name}</th>
741
+ ))}
742
+ <td />
743
+ </tr>
744
+ </thead>
745
+ <tbody>{weeks}</tbody>
746
+ </table>
747
+ )}
748
+ {this.state.activeView == "calendar" && calendarWidget.showTodayButton && (
749
+ <div className={CSS.element(baseClass, "toolbar")}>
750
+ <button
751
+ className={CSS.expand(CSS.element(baseClass, "today-button"), CSS.block("button", "hollow"))}
752
+ data-year={today.getFullYear()}
753
+ data-month={today.getMonth() + 1}
754
+ data-date={today.getDate()}
755
+ onClick={(e) => {
756
+ this.handleMouseDown(e);
757
+ }}
758
+ >
759
+ {calendarWidget.todayButtonText}
760
+ </button>
761
+ </div>
762
+ )}
763
+
764
+ {this.state.activeView == "year-picker" && this.renderYearPicker()}
765
+ </div>
766
+ );
767
+ }
768
+ }
769
+
770
+ const readDate = (ds: DOMStringMap): Date => new Date(Number(ds.year), Number(ds.month) - 1, Number(ds.date));
771
+
772
+ Widget.alias("calendar", Calendar);