DatePicker.tsx
11.7 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
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import type { ButtonHTMLAttributes, CSSProperties, RefObject } from 'react';
import styles from './Shared.module.css';
import { Icon } from './Icon';
import { cx } from './utils';
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
const datePopupOpenEvent = 'gl-date-popup-open';
function pad(value: number) {
return String(value).padStart(2, '0');
}
function toDateId(date: Date) {
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
function parseDate(value?: string) {
if (!value) return new Date(2026, 4, 16);
const [year, month, day] = value.split('-').map(Number);
return new Date(year, month - 1, day);
}
function buildMonthDays(displayMonth: Date) {
const year = displayMonth.getFullYear();
const month = displayMonth.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const dayCount = new Date(year, month + 1, 0).getDate();
return [
...Array.from({ length: firstDay }, () => undefined),
...Array.from({ length: dayCount }, (_, index) => new Date(year, month, index + 1)),
];
}
function isBetween(day: string, range?: [string, string]) {
if (!range) return false;
return day > range[0] && day < range[1];
}
function isRangeStart(day: string, range?: [string, string]) {
return range?.[0] === day;
}
function isRangeEnd(day: string, range?: [string, string]) {
return range?.[1] === day;
}
function notifyDatePopupOpen(id: string) {
window.dispatchEvent(new CustomEvent(datePopupOpenEvent, { detail: id }));
}
function useExclusiveDatePopup(setOpen: (open: boolean) => void) {
const id = useId();
useEffect(() => {
const closeOtherPopup = (event: Event) => {
if ((event as CustomEvent<string>).detail !== id) setOpen(false);
};
window.addEventListener(datePopupOpenEvent, closeOtherPopup);
return () => window.removeEventListener(datePopupOpenEvent, closeOtherPopup);
}, [id, setOpen]);
return id;
}
function useFloatingDatePopupPosition(open: boolean, rootRef: RefObject<HTMLSpanElement | null>) {
const [popupStyle, setPopupStyle] = useState<CSSProperties>();
useLayoutEffect(() => {
if (!open) return undefined;
const updatePopupPosition = () => {
const root = rootRef.current;
if (!root) return;
const rect = root.getBoundingClientRect();
setPopupStyle({
position: 'fixed',
top: rect.bottom + 4,
left: rect.left,
minWidth: rect.width,
});
};
updatePopupPosition();
window.addEventListener('resize', updatePopupPosition);
window.addEventListener('scroll', updatePopupPosition, true);
return () => {
window.removeEventListener('resize', updatePopupPosition);
window.removeEventListener('scroll', updatePopupPosition, true);
};
}, [open, rootRef]);
return popupStyle;
}
function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean) => void) {
const rootRef = useRef<HTMLSpanElement>(null);
const popupRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return undefined;
const closeOnOutsideClick = (event: MouseEvent | PointerEvent) => {
const target = event.target as Node;
const isInsideTrigger = rootRef.current?.contains(target);
const isInsidePopup = popupRef.current?.contains(target);
if (!isInsideTrigger && !isInsidePopup) {
// 延迟关闭,确保 click 事件先触发完成(mousedown 在 click 之前)
setTimeout(() => setOpen(false), 0);
}
};
// 使用 mousedown 而不是 pointerdown,避免与 click 事件的竞态
document.addEventListener('mousedown', closeOnOutsideClick);
return () => document.removeEventListener('mousedown', closeOnOutsideClick);
}, [open, setOpen]);
return { rootRef, popupRef };
}
export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> {
/** ISO 日期字符串,当前基础实现以 yyyy-MM-dd 作为组件契约。 */
value?: string;
placeholder?: string;
disabledDate?: (date: string) => boolean;
onChange?: (value: string) => void;
}
export function DatePicker({ value, placeholder = '请选择日期', disabledDate, onChange, ...props }: DatePickerProps) {
const [open, setOpen] = useState(false);
const popupId = useExclusiveDatePopup(setOpen);
const { rootRef, popupRef } = useCloseDatePopupOnOutsideClick(open, setOpen);
const popupStyle = useFloatingDatePopupPosition(open, rootRef);
const [innerValue, setInnerValue] = useState(value);
const currentValue = value ?? innerValue;
const [displayMonth, setDisplayMonth] = useState(() => parseDate(currentValue));
const monthDays = useMemo(() => buildMonthDays(displayMonth), [displayMonth]);
const today = toDateId(new Date());
const commit = (day: string) => {
if (value === undefined) setInnerValue(day);
onChange?.(day);
setOpen(false);
};
const toggleOpen = () => {
setOpen((nextOpen) => {
if (!nextOpen) notifyDatePopupOpen(popupId);
return !nextOpen;
});
};
return (
<span ref={rootRef} className={styles.dateWrapper}>
<button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}>
{props['aria-label'] ? `${props['aria-label']} ${currentValue ?? placeholder}` : currentValue ?? placeholder}
</button>
{open ? createPortal(
<div ref={popupRef} className={cx(styles.popup, styles.datePopup)} style={popupStyle}>
<div className={styles.dateHeader}>
<button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}>
<Icon name="chevron-left" />
</button>
<h3 className={styles.dateTitle}>{displayMonth.getFullYear()}年 {displayMonth.getMonth() + 1}月</h3>
<button className={styles.plainButton} type="button" aria-label="下个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() + 1, 1))}>
<Icon name="chevron-right" />
</button>
</div>
<div className={styles.grid} role="grid">
{weekDays.map((day) => <div key={day} className={styles.weekDay}>{day}</div>)}
{monthDays.map((date, index) => {
if (!date) return <span key={`empty-${index}`} />;
const day = toDateId(date);
const disabled = disabledDate?.(day);
const selected = day === currentValue;
const isToday = day === today;
return (
<button
key={day}
className={cx(styles.day, isToday && styles.dateToday, selected && styles.dateSelected)}
disabled={disabled}
role="gridcell"
type="button"
aria-label={day}
onClick={() => {
if (disabled) return;
commit(day);
}}
>
{Number(day.slice(-2))}
</button>
);
})}
</div>
<div className={cx(styles.row, styles.dateFooter)}>
<button className={styles.dateTodayButton} type="button" onClick={() => commit(today)}>今天</button>
</div>
</div>,
document.body,
) : null}
</span>
);
}
export interface DateRangePickerProps extends Omit<DatePickerProps, 'onChange' | 'value'> {
value?: [string, string];
onChange?: (value: [string, string]) => void;
}
export function DateRangePicker({ value, placeholder = '请选择日期范围', disabledDate, onChange, ...props }: DateRangePickerProps) {
const [open, setOpen] = useState(false);
const popupId = useExclusiveDatePopup(setOpen);
const { rootRef, popupRef } = useCloseDatePopupOnOutsideClick(open, setOpen);
const popupStyle = useFloatingDatePopupPosition(open, rootRef);
const [draftStart, setDraftStart] = useState<string | undefined>();
const [innerValue, setInnerValue] = useState<[string, string] | undefined>(value);
const currentValue = value ?? innerValue;
const [displayMonth, setDisplayMonth] = useState(() => parseDate(currentValue?.[0]));
const monthDays = useMemo(() => buildMonthDays(displayMonth), [displayMonth]);
const today = toDateId(new Date());
const visibleRange = draftStart ? undefined : currentValue;
const toggleOpen = () => {
setOpen((nextOpen) => {
if (!nextOpen) notifyDatePopupOpen(popupId);
return !nextOpen;
});
};
return (
<span ref={rootRef} className={styles.dateWrapper}>
<button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}>
{props['aria-label'] ? `${props['aria-label']} ${currentValue?.join(' ~ ') ?? placeholder}` : currentValue?.join(' ~ ') ?? placeholder}
</button>
{open ? createPortal(
<div ref={popupRef} className={cx(styles.popup, styles.datePopup)} style={popupStyle}>
<div className={styles.dateHeader}>
<button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}>
<Icon name="chevron-left" />
</button>
<h3 className={styles.dateTitle}>{displayMonth.getFullYear()}年 {displayMonth.getMonth() + 1}月</h3>
<button className={styles.plainButton} type="button" aria-label="下个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() + 1, 1))}>
<Icon name="chevron-right" />
</button>
</div>
<div className={cx(styles.grid, styles.dateRangeGrid)} role="grid">
{weekDays.map((day) => <div key={day} className={styles.weekDay}>{day}</div>)}
{monthDays.map((date, index) => {
if (!date) return <span key={`empty-${index}`} />;
const day = toDateId(date);
const disabled = disabledDate?.(day);
const selected = visibleRange?.includes(day) || draftStart === day;
const inRange = isBetween(day, visibleRange);
const rangeStart = isRangeStart(day, visibleRange);
const rangeEnd = isRangeEnd(day, visibleRange);
const isToday = day === today;
return (
<button
key={day}
className={cx(
styles.day,
isToday && styles.dateToday,
inRange && styles.dateInRange,
rangeStart && styles.dateRangeStart,
rangeEnd && styles.dateRangeEnd,
selected && styles.dateSelected,
)}
disabled={disabled}
role="gridcell"
type="button"
aria-label={day}
onClick={() => {
if (disabled) return;
if (!draftStart) {
setDraftStart(day);
return;
}
const next: [string, string] = draftStart <= day ? [draftStart, day] : [day, draftStart];
if (value === undefined) setInnerValue(next);
onChange?.(next);
setDraftStart(undefined);
setOpen(false);
}}
>
{Number(day.slice(-2))}
</button>
);
})}
</div>
</div>,
document.body,
) : null}
</span>
);
}