@aiquants/period-slider 0.2.0

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.
@@ -0,0 +1,414 @@
1
+ import { addDays, format, getDaysInMonth, parseISO } from "date-fns"
2
+ import type React from "react"
3
+ import { memo, useEffect, useMemo, useState } from "react"
4
+ import type { PeriodSliderUnit } from "./PeriodSlider"
5
+
6
+ export interface DateSelectorProps {
7
+ /** Controlled selected date / 選択日付(外部制御用) */
8
+ value?: Date
9
+ /** Initial selected date (defaults to current date) / 選択日付(未指定時は現在日) */
10
+ initialDate?: Date
11
+ /** Time resolution unit (ignored by selector, accepted for hook interoperability) / 時間解像度単位 (フック相互運用用) */
12
+ unit?: PeriodSliderUnit
13
+ /** Callback triggered when date changes / 日付変更時コールバック */
14
+ onChange?(date: Date): void
15
+ /** Child elements / 子要素 */
16
+ children?: React.ReactNode
17
+ /** Minimum selectable year / ドロップダウン・可能範囲の最小年 */
18
+ minYear?: number
19
+ /** Maximum selectable year / ドロップダウン・可能範囲の最大年 */
20
+ maxYear?: number
21
+ /** Minimum selectable date / 選択可能範囲の最小日付 */
22
+ minDate?: Date
23
+ /** Maximum selectable date / 選択可能範囲の最大日付 */
24
+ maxDate?: Date
25
+ /** Discrete allowed dates list / 選択可能な離散日付配列 */
26
+ allowedDates?: Date[]
27
+ /**
28
+ * UI Variant:
29
+ * - "dropdown": Single select element with yyyy-MM-dd options (既定の単一セレクトボックス)
30
+ * - "date": Native input[type="date"]
31
+ * - "split-dropdown": Three separate selects for year, month, and day
32
+ */
33
+ variant?: "date" | "dropdown" | "split-dropdown"
34
+ /** Additional CSS class name / 追加の CSS クラス名 */
35
+ className?: string
36
+ /** Custom styles / スタイル */
37
+ style?: React.CSSProperties
38
+ /** Disabled flag / 無効化フラグ */
39
+ disabled?: boolean
40
+ /** Accessible label for previous date button / 前日ボタンのアクセシブル名 */
41
+ prevDateAriaLabel?: string
42
+ /** Accessible label for next date button / 翌日ボタンのアクセシブル名 */
43
+ nextDateAriaLabel?: string
44
+ /** Accessible label for date select combobox / 年月日セレクトのアクセシブル名 */
45
+ selectAriaLabel?: string
46
+ }
47
+
48
+ /**
49
+ * Generates yyyy-MM-dd option list for the single select-box mode.
50
+ * 単一セレクトボックス表示用の yyyy-MM-dd 選択肢リストを降順で生成する。
51
+ */
52
+ function generateDateDropdownOptions(currentDate: Date, minDateBound: Date | null, maxDateBound: Date | null, allowedDates?: Date[]): { label: string; value: string }[] {
53
+ if (allowedDates && allowedDates.length > 0) {
54
+ const valid = allowedDates
55
+ .filter((d) => d && !Number.isNaN(d.getTime()))
56
+ .map((d) => {
57
+ const copy = new Date(d)
58
+ copy.setHours(0, 0, 0, 0)
59
+ return copy
60
+ })
61
+ .sort((a, b) => b.getTime() - a.getTime())
62
+
63
+ return valid.map((d) => {
64
+ const str = format(d, "yyyy-MM-dd")
65
+ return { label: str, value: str }
66
+ })
67
+ }
68
+
69
+ const currentY = currentDate.getFullYear()
70
+ const startDate = minDateBound ?? new Date(currentY - 1, 0, 1)
71
+ const endDate = maxDateBound ?? new Date(currentY + 1, 11, 31)
72
+
73
+ const actualStart = new Date(Math.min(startDate.getTime(), currentDate.getTime()))
74
+ actualStart.setHours(0, 0, 0, 0)
75
+ const actualEnd = new Date(Math.max(endDate.getTime(), currentDate.getTime()))
76
+ actualEnd.setHours(0, 0, 0, 0)
77
+
78
+ const list: { label: string; value: string }[] = []
79
+ let curr = actualEnd
80
+ while (curr >= actualStart) {
81
+ const str = format(curr, "yyyy-MM-dd")
82
+ list.push({ label: str, value: str })
83
+ curr = addDays(curr, -1)
84
+ }
85
+
86
+ return list
87
+ }
88
+
89
+ /**
90
+ * Date (yyyy-MM-dd) selector component supporting min/max boundaries, stepper buttons (◀▶), and single select-box dropdown.
91
+ * 日付け(年月日)セレクタ共通コンポーネント。
92
+ * 単一セレクトボックス (`<select>` yyyy-MM-dd) または `<input type="date">` と両脇のステッパーボタン (◀▶) で ±1 日を変更可能。
93
+ */
94
+ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
95
+ const { value, initialDate, onChange, children, minYear, maxYear, minDate, maxDate, allowedDates, variant = "dropdown", className = "", style, disabled = false, prevDateAriaLabel = "前日", nextDateAriaLabel = "翌日", selectAriaLabel = "年月日" } = props
96
+ const effectiveDate = value ?? initialDate
97
+
98
+ const [currentDate, setCurrentDate] = useState<Date>(() => {
99
+ const d = new Date(effectiveDate ?? new Date())
100
+ d.setHours(0, 0, 0, 0)
101
+ return d
102
+ })
103
+
104
+ const isControlled = value !== undefined
105
+ const activeDate = useMemo(() => {
106
+ if (isControlled) {
107
+ if (value && !Number.isNaN(value.getTime())) {
108
+ const d = new Date(value)
109
+ d.setHours(0, 0, 0, 0)
110
+ return d
111
+ }
112
+ const d = new Date()
113
+ d.setHours(0, 0, 0, 0)
114
+ return d
115
+ }
116
+ return currentDate
117
+ }, [isControlled, value?.getTime(), currentDate])
118
+
119
+ const minTime = minDate?.getTime()
120
+ const maxTime = maxDate?.getTime()
121
+
122
+ const minDateBound = useMemo(() => {
123
+ if (minDate) {
124
+ const d = new Date(minDate)
125
+ d.setHours(0, 0, 0, 0)
126
+ return d
127
+ }
128
+ if (minYear !== undefined) {
129
+ const d = new Date(minYear, 0, 1)
130
+ d.setFullYear(minYear)
131
+ d.setHours(0, 0, 0, 0)
132
+ return d
133
+ }
134
+ return null
135
+ }, [minTime, minYear])
136
+
137
+ const maxDateBound = useMemo(() => {
138
+ if (maxDate) {
139
+ const d = new Date(maxDate)
140
+ d.setHours(0, 0, 0, 0)
141
+ return d
142
+ }
143
+ if (maxYear !== undefined) {
144
+ const d = new Date(maxYear, 11, 31)
145
+ d.setFullYear(maxYear)
146
+ d.setHours(0, 0, 0, 0)
147
+ return d
148
+ }
149
+ return null
150
+ }, [maxTime, maxYear])
151
+
152
+ // 外部からの value または initialDate 変更に追従
153
+ const effectiveTime = effectiveDate?.getTime()
154
+ useEffect(() => {
155
+ if (!isControlled && effectiveDate && !Number.isNaN(effectiveDate.getTime())) {
156
+ const d = new Date(effectiveDate)
157
+ d.setHours(0, 0, 0, 0)
158
+ setCurrentDate(d)
159
+ }
160
+ }, [isControlled, effectiveTime])
161
+
162
+ const emit = (nextDate: Date) => {
163
+ if (disabled) return
164
+ let clamped = new Date(nextDate)
165
+ clamped.setHours(0, 0, 0, 0)
166
+
167
+ if (minDateBound && clamped < minDateBound) {
168
+ clamped = new Date(minDateBound)
169
+ }
170
+ if (maxDateBound && clamped > maxDateBound) {
171
+ clamped = new Date(maxDateBound)
172
+ }
173
+
174
+ if (!isControlled) {
175
+ setCurrentDate(clamped)
176
+ }
177
+ onChange?.(clamped)
178
+ }
179
+
180
+ const prevDate = useMemo(() => addDays(activeDate, -1), [activeDate])
181
+ const nextDate = useMemo(() => addDays(activeDate, 1), [activeDate])
182
+
183
+ const isPrevDisabled = disabled || (minDateBound !== null && prevDate < minDateBound)
184
+ const isNextDisabled = disabled || (maxDateBound !== null && nextDate > maxDateBound)
185
+
186
+ const handlePrevious = () => emit(prevDate)
187
+ const handleNext = () => emit(nextDate)
188
+
189
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
190
+ if (e.target.value) {
191
+ const parsed = parseISO(e.target.value)
192
+ if (!Number.isNaN(parsed.getTime())) {
193
+ emit(parsed)
194
+ }
195
+ }
196
+ }
197
+
198
+ const handleDropdownChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
199
+ if (e.target.value) {
200
+ const parsed = parseISO(e.target.value)
201
+ if (!Number.isNaN(parsed.getTime())) {
202
+ emit(parsed)
203
+ }
204
+ }
205
+ }
206
+
207
+ const currentYear = activeDate.getFullYear()
208
+ const currentMonth = activeDate.getMonth() + 1
209
+ const currentDay = activeDate.getDate()
210
+
211
+ const minBoundTime = minDateBound?.getTime() ?? null
212
+ const maxBoundTime = maxDateBound?.getTime() ?? null
213
+ const currTime = activeDate.getTime()
214
+
215
+ const optionsRangeKey = useMemo(() => {
216
+ if (allowedDates && allowedDates.length > 0) {
217
+ return allowedDates.map((d) => d.getTime()).join(",")
218
+ }
219
+ const startMs = minBoundTime ?? new Date(currentYear - 1, 0, 1).getTime()
220
+ const endMs = maxBoundTime ?? new Date(currentYear + 1, 11, 31).getTime()
221
+ const actualStartMs = Math.min(startMs, currTime)
222
+ const actualEndMs = Math.max(endMs, currTime)
223
+ return `${actualStartMs}_${actualEndMs}`
224
+ }, [allowedDates, minBoundTime, maxBoundTime, currTime, currentYear])
225
+
226
+ // --- Single Select-Box Options ---
227
+ const dateDropdownOptions = useMemo(() => {
228
+ if (variant !== "dropdown") return []
229
+ return generateDateDropdownOptions(activeDate, minDateBound, maxDateBound, allowedDates)
230
+ }, [variant, optionsRangeKey, activeDate])
231
+
232
+ // --- Split Dropdown Options (Optional Backward Compatibility) ---
233
+ const yearOptions = useMemo(() => {
234
+ if (variant !== "split-dropdown") return []
235
+ const minY = minDateBound ? minDateBound.getFullYear() : currentYear - 10
236
+ const maxY = maxDateBound ? maxDateBound.getFullYear() : currentYear + 1
237
+ const start = Math.min(minY, currentYear)
238
+ const end = Math.max(maxY, currentYear)
239
+ const list: number[] = []
240
+ for (let y = end; y >= start; y--) {
241
+ list.push(y)
242
+ }
243
+ return list
244
+ }, [variant, minDateBound, maxDateBound, currentYear])
245
+
246
+ const monthOptions = useMemo(() => {
247
+ if (variant !== "split-dropdown") return []
248
+ let minM = 1
249
+ let maxM = 12
250
+
251
+ if (minDateBound && currentYear === minDateBound.getFullYear()) {
252
+ minM = minDateBound.getMonth() + 1
253
+ }
254
+ if (maxDateBound && currentYear === maxDateBound.getFullYear()) {
255
+ maxM = maxDateBound.getMonth() + 1
256
+ }
257
+
258
+ const list: number[] = []
259
+ for (let m = minM; m <= maxM; m++) {
260
+ list.push(m)
261
+ }
262
+ return list
263
+ }, [variant, minDateBound, maxDateBound, currentYear])
264
+
265
+ const dayOptions = useMemo(() => {
266
+ if (variant !== "split-dropdown") return []
267
+ const totalDays = getDaysInMonth(activeDate)
268
+ let minD = 1
269
+ let maxD = totalDays
270
+
271
+ if (minDateBound && currentYear === minDateBound.getFullYear() && currentMonth === minDateBound.getMonth() + 1) {
272
+ minD = minDateBound.getDate()
273
+ }
274
+
275
+ if (maxDateBound && currentYear === maxDateBound.getFullYear() && currentMonth === maxDateBound.getMonth() + 1) {
276
+ maxD = maxDateBound.getDate()
277
+ }
278
+
279
+ const list: number[] = []
280
+ for (let d = minD; d <= maxD; d++) {
281
+ list.push(d)
282
+ }
283
+ return list
284
+ }, [variant, minDateBound, maxDateBound, activeDate, currentYear, currentMonth])
285
+
286
+ const handleSplitSelectChange = (newYear: number, newMonth: number, newDay: number) => {
287
+ const maxDaysInNewMonth = getDaysInMonth(new Date(newYear, newMonth - 1, 1))
288
+ const validDay = Math.min(newDay, maxDaysInNewMonth)
289
+
290
+ const target = new Date(newYear, newMonth - 1, validDay)
291
+ target.setFullYear(newYear)
292
+ emit(target)
293
+ }
294
+
295
+ const formattedDate = format(activeDate, "yyyy-MM-dd")
296
+ const minFormatted = minDateBound ? format(minDateBound, "yyyy-MM-dd") : undefined
297
+ const maxFormatted = maxDateBound ? format(maxDateBound, "yyyy-MM-dd") : undefined
298
+
299
+ const containerWidthClass = variant === "split-dropdown" ? "w-auto" : "w-38"
300
+
301
+ const singleSelectClassName =
302
+ "mx-1 my-auto w-28 appearance-none rounded-md border border-gray-300 bg-gray-100 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums [text-align-last:center] [text-align:center] focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100 dark:focus:border-blue-500 dark:focus:ring-blue-500"
303
+
304
+ return (
305
+ <div className={`inline-flex items-center ${containerWidthClass} ${className}`} style={style}>
306
+ <button
307
+ type="button"
308
+ aria-label={prevDateAriaLabel}
309
+ disabled={isPrevDisabled}
310
+ className="relative my-auto inline-flex h-5 w-4 cursor-pointer items-center justify-center rounded p-0 after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 disabled:opacity-40"
311
+ onClick={handlePrevious}>
312
+ <span className="h-0 w-0 border-y-[6px] border-y-transparent border-r-[6px] border-r-slate-500 border-solid hover:border-r-slate-700 dark:border-r-slate-400 dark:hover:border-r-slate-200" />
313
+ </button>
314
+
315
+ {variant === "dropdown" ? (
316
+ <select aria-label={selectAriaLabel} disabled={disabled} className={singleSelectClassName} value={formattedDate} onChange={handleDropdownChange}>
317
+ {dateDropdownOptions.map((opt) => (
318
+ <option key={opt.value} value={opt.value} className="text-center font-mono text-gray-900 tabular-nums [text-align-last:center] [text-align:center] dark:bg-slate-700 dark:text-slate-100">
319
+ {opt.label}
320
+ </option>
321
+ ))}
322
+ </select>
323
+ ) : variant === "split-dropdown" ? (
324
+ <div className="mx-1 my-auto inline-flex items-center gap-1">
325
+ <select
326
+ aria-label="年"
327
+ disabled={disabled}
328
+ className="rounded-md border border-gray-300 bg-gray-50 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100"
329
+ value={currentYear}
330
+ onChange={(e) => handleSplitSelectChange(Number(e.target.value), currentMonth, currentDay)}>
331
+ {yearOptions.map((y) => (
332
+ <option key={y} value={y} className="dark:bg-slate-700 dark:text-slate-100">
333
+ {y}年
334
+ </option>
335
+ ))}
336
+ </select>
337
+ <select
338
+ aria-label="月"
339
+ disabled={disabled}
340
+ className="rounded-md border border-gray-300 bg-gray-50 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100"
341
+ value={currentMonth}
342
+ onChange={(e) => handleSplitSelectChange(currentYear, Number(e.target.value), currentDay)}>
343
+ {monthOptions.map((m) => (
344
+ <option key={m} value={m} className="dark:bg-slate-700 dark:text-slate-100">
345
+ {String(m).padStart(2, "0")}月
346
+ </option>
347
+ ))}
348
+ </select>
349
+ <select
350
+ aria-label="日"
351
+ disabled={disabled}
352
+ className="rounded-md border border-gray-300 bg-gray-50 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100"
353
+ value={currentDay}
354
+ onChange={(e) => handleSplitSelectChange(currentYear, currentMonth, Number(e.target.value))}>
355
+ {dayOptions.map((d) => (
356
+ <option key={d} value={d} className="dark:bg-slate-700 dark:text-slate-100">
357
+ {String(d).padStart(2, "0")}日
358
+ </option>
359
+ ))}
360
+ </select>
361
+ </div>
362
+ ) : (
363
+ <input
364
+ aria-label={selectAriaLabel}
365
+ disabled={disabled}
366
+ className="mx-1 my-auto w-28 rounded-md border border-gray-300 bg-gray-50 px-1 py-0.5 text-gray-900 text-xs focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100 dark:focus:border-blue-500 dark:focus:ring-blue-500 dark:placeholder:text-gray-400"
367
+ value={formattedDate}
368
+ min={minFormatted}
369
+ max={maxFormatted}
370
+ onChange={handleInputChange}
371
+ type="date"
372
+ />
373
+ )}
374
+
375
+ <button
376
+ type="button"
377
+ aria-label={nextDateAriaLabel}
378
+ disabled={isNextDisabled}
379
+ className="relative my-auto inline-flex h-5 w-4 cursor-pointer items-center justify-center rounded p-0 after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 disabled:opacity-40"
380
+ onClick={handleNext}>
381
+ <span className="h-0 w-0 border-y-[6px] border-y-transparent border-l-[6px] border-l-slate-500 border-solid hover:border-l-slate-700 dark:border-l-slate-400 dark:hover:border-l-slate-200" />
382
+ </button>
383
+ {children}
384
+ </div>
385
+ )
386
+ }
387
+
388
+ export const DateSelector = memo(DateSelectorComponent, (prev, next) => {
389
+ const prevDate = prev.value ?? prev.initialDate
390
+ const nextDate = next.value ?? next.initialDate
391
+ const prevYmd = prevDate && !Number.isNaN(prevDate.getTime()) ? prevDate.getFullYear() * 10000 + (prevDate.getMonth() + 1) * 100 + prevDate.getDate() : null
392
+ const nextYmd = nextDate && !Number.isNaN(nextDate.getTime()) ? nextDate.getFullYear() * 10000 + (nextDate.getMonth() + 1) * 100 + nextDate.getDate() : null
393
+ if (prevYmd !== nextYmd) return false
394
+ if (prev.variant !== next.variant) return false
395
+ if (prev.disabled !== next.disabled) return false
396
+ if (prev.className !== next.className) return false
397
+ if (prev.style !== next.style) return false
398
+ if (prev.minYear !== next.minYear) return false
399
+ if (prev.maxYear !== next.maxYear) return false
400
+ const prevMinYmd = prev.minDate && !Number.isNaN(prev.minDate.getTime()) ? prev.minDate.getFullYear() * 10000 + (prev.minDate.getMonth() + 1) * 100 + prev.minDate.getDate() : null
401
+ const nextMinYmd = next.minDate && !Number.isNaN(next.minDate.getTime()) ? next.minDate.getFullYear() * 10000 + (next.minDate.getMonth() + 1) * 100 + next.minDate.getDate() : null
402
+ if (prevMinYmd !== nextMinYmd) return false
403
+ const prevMaxYmd = prev.maxDate && !Number.isNaN(prev.maxDate.getTime()) ? prev.maxDate.getFullYear() * 10000 + (prev.maxDate.getMonth() + 1) * 100 + prev.maxDate.getDate() : null
404
+ const nextMaxYmd = next.maxDate && !Number.isNaN(next.maxDate.getTime()) ? next.maxDate.getFullYear() * 10000 + (next.maxDate.getMonth() + 1) * 100 + next.maxDate.getDate() : null
405
+ if (prevMaxYmd !== nextMaxYmd) return false
406
+ if (prev.onChange !== next.onChange) return false
407
+ if (prev.allowedDates !== next.allowedDates) return false
408
+ if (prev.children !== next.children) return false
409
+ if (prev.prevDateAriaLabel !== next.prevDateAriaLabel) return false
410
+ if (prev.nextDateAriaLabel !== next.nextDateAriaLabel) return false
411
+ if (prev.selectAriaLabel !== next.selectAriaLabel) return false
412
+ return true
413
+ })
414
+ DateSelector.displayName = "DateSelector"