@aiquants/period-slider 0.2.0 → 0.3.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.
@@ -1,11 +1,37 @@
1
+ /**
2
+ * @fileoverview Month (yyyy-MM) selector component
3
+ * @package @aiquants/period-slider
4
+ *
5
+ * Provides a month selector rendered either as a native `input[type="month"]` or as a dropdown of
6
+ * yyyy-MM options, always flanked by stepper buttons that move the selection by one month. Bounds
7
+ * are the stricter of the year and date declarations; missing, invalid and out-of-bounds inputs
8
+ * fail fast rather than being substituted or clamped. Option text is locale-independent ISO 8601
9
+ * until a `locale` tag opts into Intl formatting, while every machine-read value stays yyyy-MM.
10
+ *
11
+ * ネイティブ `input[type="month"]` または yyyy-MM ドロップダウンと ±1 ヶ月ステッパーによる年月セレクタ。
12
+ * 境界は年指定と日付指定の厳しい方を採用し、欠落値・不正値・境界外値は代替もクランプもせず即時エラー。
13
+ * 選択肢テキストは既定でロケール非依存の ISO 8601 表記 (`locale` 指定時のみ Intl 書式)、機械可読値は常に yyyy-MM。
14
+ */
15
+
1
16
  import type React from "react"
2
17
  import { memo, useEffect, useMemo, useState } from "react"
3
- import type { PeriodSliderUnit } from "./PeriodSlider"
18
+ import { formatLabel, type PeriodSliderUnit } from "./PeriodSlider"
4
19
 
20
+ /**
21
+ * Props of the month-resolution selector.
22
+ * 月単位セレクタの Props。
23
+ *
24
+ * Accessible names default to English and option text to locale-independent ISO 8601, because a
25
+ * generic package cannot know the host application's language: localisation is the consumer's
26
+ * decision, expressed through `locale` or the aria-label props.
27
+ * アクセシブル名の既定は英語、選択肢テキストの既定はロケール非依存の ISO 8601 表記。
28
+ * 汎用パッケージは利用側アプリの言語を知り得ないため、地域化は `locale`・アクセシブル名 Props を
29
+ * 通じた利用側の選択。
30
+ */
5
31
  export interface MonthSelectorProps {
6
- /** Controlled selected date / 選択日付(外部制御用) */
32
+ /** Controlled selected date; required unless `initialDate` is supplied / 選択日付(外部制御用・`initialDate` 未指定時は必須) */
7
33
  value?: Date
8
- /** Initial selected date (defaults to current month) / 選択日付(未指定時は現在月) */
34
+ /** Initial selected date; required unless `value` is supplied / 選択日付(非制御用・`value` 未指定時は必須) */
9
35
  initialDate?: Date
10
36
  /** Time resolution unit (ignored by selector, accepted for hook interoperability) / 時間解像度単位 (フック相互運用用) */
11
37
  unit?: PeriodSliderUnit
@@ -18,13 +44,13 @@ export interface MonthSelectorProps {
18
44
  * 表示バリエーション: "date" (input[type="month"]) または "dropdown" (select[yyyy-mm])。既定値 "date"
19
45
  */
20
46
  variant?: "date" | "dropdown"
21
- /** Minimum year for options / 選択肢・可能範囲の最小年 */
47
+ /** Lower bound year (January); combined with `minDate` as the stricter of the two. Required for variant="dropdown" together with `minDate` / 可能範囲の最小年 (1 月起点)。`minDate` とは厳しい方を採用。variant="dropdown" では `minDate` との少なくとも一方が必須 */
22
48
  minYear?: number
23
- /** Maximum year for options / 選択肢・可能範囲の最大年 */
49
+ /** Upper bound year (December); combined with `maxDate` as the stricter of the two. Required for variant="dropdown" together with `maxDate` / 可能範囲の最大年 (12 月起点)。`maxDate` とは厳しい方を採用。variant="dropdown" では `maxDate` との少なくとも一方が必須 */
24
50
  maxYear?: number
25
- /** Minimum date for options / 選択肢・可能範囲の最小日付 */
51
+ /** Lower bound date (truncated to its month); combined with `minYear` as the stricter of the two / 可能範囲の最小日付 (月単位に切り捨て)。`minYear` とは厳しい方を採用 */
26
52
  minDate?: Date
27
- /** Maximum date for options / 選択肢・可能範囲の最大日付 */
53
+ /** Upper bound date (truncated to its month); combined with `maxYear` as the stricter of the two / 可能範囲の最大日付 (月単位に切り捨て)。`maxYear` とは厳しい方を採用 */
28
54
  maxDate?: Date
29
55
  /** Warning style flag / 警告枠スタイル適用フラグ */
30
56
  isWarning?: boolean
@@ -34,44 +60,152 @@ export interface MonthSelectorProps {
34
60
  style?: React.CSSProperties
35
61
  /** Disabled flag / 無効化フラグ */
36
62
  disabled?: boolean
37
- /** Accessible label for previous month button / 前月ボタンのアクセシブル名 */
63
+ /** Accessible label for previous month button / 前月ボタンのアクセシブル名 (既定: "Previous month") */
38
64
  prevMonthAriaLabel?: string
39
- /** Accessible label for next month button / 翌月ボタンのアクセシブル名 */
65
+ /** Accessible label for next month button / 翌月ボタンのアクセシブル名 (既定: "Next month") */
40
66
  nextMonthAriaLabel?: string
41
- /** Accessible label for month select combobox / 年月セレクトのアクセシブル名 */
67
+ /** Accessible label for month select combobox / 年月セレクトのアクセシブル名 (既定: "Month") */
42
68
  selectAriaLabel?: string
69
+ /** BCP 47 language tag switching option text to Intl formatting; omitted keeps locale-independent ISO 8601, and the input value stays yyyy-MM either way / 選択肢テキストを Intl 書式にする BCP 47 言語タグ (未指定時はロケール非依存の ISO 8601 表記・input の value は常に yyyy-MM) */
70
+ locale?: string
43
71
  }
44
72
 
45
73
  /**
46
- * Generate yyyy-mm option list for dropdown mode.
47
- * ドロップダウン表示用の yyyy-mm 選択肢リストを生成する。
74
+ * Build the first day of the given year and (possibly out-of-range) month index as a local Date.
75
+ * 指定した年と月インデックス (範囲外も可) の 1 日を表すローカル Date の生成。
76
+ *
77
+ * @param year - Calendar year / 暦年
78
+ * @param monthIndex - Month index that may under/overflow 0-11 / 0-11 を超過しうる月インデックス
79
+ * @returns First day of the normalized year and month / 正規化された年月の 1 日
48
80
  */
49
- function generateDropdownOptions(currentDate: Date, minYear?: number, maxYear?: number, minDate?: Date, maxDate?: Date): { label: string; value: string }[] {
50
- const currentY = currentDate.getFullYear()
51
- const lowerY = minYear ?? (minDate ? minDate.getFullYear() : currentY - 5)
52
- const upperY = maxYear ?? (maxDate ? maxDate.getFullYear() : currentY + 5)
81
+ function monthStart(year: number, monthIndex: number): Date {
82
+ const normalizedYear = year + Math.floor(monthIndex / 12)
83
+ const normalizedMonth = ((monthIndex % 12) + 12) % 12
84
+ const d = new Date(normalizedYear, normalizedMonth, 1)
85
+ // 0-99 年が 1900 年代へ丸められる Date の仕様を打ち消す
86
+ d.setFullYear(normalizedYear)
87
+ return d
88
+ }
53
89
 
54
- const startY = Math.min(lowerY, currentY)
55
- const endY = Math.max(upperY, currentY)
90
+ /**
91
+ * Format a date as the yyyy-MM string used by the input, the select and the option list.
92
+ * input / select / 選択肢で共用する yyyy-MM 文字列への整形。
93
+ *
94
+ * @param date - Date to format / 整形対象の日付
95
+ * @returns yyyy-MM representation / yyyy-MM 表記
96
+ */
97
+ function formatMonth(date: Date): string {
98
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`
99
+ }
56
100
 
57
- const minTime = minDate ? new Date(minDate.getFullYear(), minDate.getMonth(), 1).getTime() : null
58
- const maxTime = maxDate ? new Date(maxDate.getFullYear(), maxDate.getMonth(), 1).getTime() : null
101
+ /**
102
+ * Throw when a Date-typed prop does not hold a real calendar date.
103
+ * Date 型 prop が実在日付でない場合の即時エラー送出。
104
+ *
105
+ * @param date - Prop value to validate / 検証対象の prop 値
106
+ * @param propName - Prop name used in the error message / エラーメッセージ用 prop 名
107
+ * @returns Nothing; throws RangeError on an invalid Date / 戻り値なし (不正日付は RangeError)
108
+ */
109
+ function assertValidDateProp(date: Date | undefined, propName: string): void {
110
+ if (date === undefined) return
111
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
112
+ throw new RangeError(`MonthSelector: \`${propName}\` must be a valid Date, received ${String(date)}.`)
113
+ }
114
+ }
59
115
 
60
- const list: { label: string; value: string }[] = []
116
+ /**
117
+ * Throw when a year-typed prop does not hold a finite integer year.
118
+ * 年 prop が有限の整数年でない場合の即時エラー送出。
119
+ *
120
+ * @param year - Prop value to validate / 検証対象の prop 値
121
+ * @param propName - Prop name used in the error message / エラーメッセージ用 prop 名
122
+ * @returns Nothing; throws RangeError on an invalid year / 戻り値なし (不正年は RangeError)
123
+ */
124
+ function assertValidYearProp(year: number | undefined, propName: string): void {
125
+ if (year === undefined) return
126
+ if (!Number.isInteger(year)) {
127
+ throw new RangeError(`MonthSelector: \`${propName}\` must be an integer year, received ${String(year)}.`)
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Throw when the locale prop does not hold a language tag Intl.DateTimeFormat accepts.
133
+ * locale prop が Intl.DateTimeFormat の受理する言語タグでない場合の即時エラー送出。
134
+ *
135
+ * @param locale - Prop value to validate / 検証対象の prop 値
136
+ * @returns Nothing; throws RangeError on a tag Intl rejects / 戻り値なし (Intl が拒否するタグは RangeError)
137
+ */
138
+ function assertLocaleProp(locale: string | undefined): void {
139
+ if (locale === undefined) return
140
+ try {
141
+ // 空文字列や構造的に不正なタグは Intl の送出する例外でしか判定できない。
142
+ // 自前の正規表現で代用すると ICU が受理するタグを取りこぼす
143
+ Intl.DateTimeFormat.supportedLocalesOf([locale])
144
+ } catch {
145
+ throw new RangeError(`MonthSelector: \`locale\` must be a valid BCP 47 language tag, received ${JSON.stringify(locale)}.`)
146
+ }
147
+ }
61
148
 
62
- for (let y = endY; y >= startY; y--) {
63
- for (let m = 12; m >= 1; m--) {
64
- const d = new Date(y, m - 1, 1)
65
- d.setFullYear(y)
66
- const t = d.getTime()
149
+ /**
150
+ * Resolve the strictest lower month bound declared by `minYear` and `minDate`.
151
+ * `minYear` と `minDate` の双方を満たす最も厳しい下限月の解決。
152
+ *
153
+ * @param minYear - Lower bound year / 下限年
154
+ * @param minDate - Lower bound date / 下限日付
155
+ * @returns First day of the strictest lower month, or null when neither is declared / 最も厳しい下限月の 1 日。いずれも未宣言なら null
156
+ */
157
+ function resolveLowerBound(minYear: number | undefined, minDate: Date | undefined): Date | null {
158
+ const fromYear = minYear === undefined ? null : monthStart(minYear, 0)
159
+ const fromDate = minDate === undefined ? null : monthStart(minDate.getFullYear(), minDate.getMonth())
160
+ if (fromYear !== null && fromDate !== null) return fromYear >= fromDate ? fromYear : fromDate
161
+ if (fromYear !== null) return fromYear
162
+ return fromDate
163
+ }
67
164
 
68
- if (minTime !== null && t < minTime) continue
69
- if (maxTime !== null && t > maxTime) continue
165
+ /**
166
+ * Resolve the strictest upper month bound declared by `maxYear` and `maxDate`.
167
+ * `maxYear` と `maxDate` の双方を満たす最も厳しい上限月の解決。
168
+ *
169
+ * @param maxYear - Upper bound year / 上限年
170
+ * @param maxDate - Upper bound date / 上限日付
171
+ * @returns First day of the strictest upper month, or null when neither is declared / 最も厳しい上限月の 1 日。いずれも未宣言なら null
172
+ */
173
+ function resolveUpperBound(maxYear: number | undefined, maxDate: Date | undefined): Date | null {
174
+ const fromYear = maxYear === undefined ? null : monthStart(maxYear, 11)
175
+ const fromDate = maxDate === undefined ? null : monthStart(maxDate.getFullYear(), maxDate.getMonth())
176
+ if (fromYear !== null && fromDate !== null) return fromYear <= fromDate ? fromYear : fromDate
177
+ if (fromYear !== null) return fromYear
178
+ return fromDate
179
+ }
70
180
 
71
- const monthStr = String(m).padStart(2, "0")
72
- const valStr = `${y}-${monthStr}`
73
- list.push({ label: valStr, value: valStr })
74
- }
181
+ /**
182
+ * Build the option pairing a human-facing label with the yyyy-MM value the change handler parses.
183
+ * 表示用ラベルと、変更ハンドラが解釈する yyyy-MM 値を対にした選択肢の生成。
184
+ *
185
+ * @param date - Month the option represents / 選択肢が表す月
186
+ * @param locale - BCP 47 language tag enabling Intl label formatting / Intl ラベル書式を有効化する BCP 47 言語タグ
187
+ * @returns Option whose value is always yyyy-MM / value が常に yyyy-MM である選択肢
188
+ */
189
+ function toMonthOption(date: Date, locale: string | undefined): { label: string; value: string } {
190
+ return { label: formatLabel("month", date, undefined, locale), value: formatMonth(date) }
191
+ }
192
+
193
+ /**
194
+ * Generate the complete month option list spanning the declared bounds, newest first.
195
+ * 宣言された下限〜上限を過不足なく網羅する月選択肢リスト (降順) の生成。
196
+ *
197
+ * @param minBound - First selectable month / 選択可能な最初の月
198
+ * @param maxBound - Last selectable month / 選択可能な最後の月
199
+ * @param locale - BCP 47 language tag enabling Intl label formatting / Intl ラベル書式を有効化する BCP 47 言語タグ
200
+ * @returns Every month between the bounds in descending order / 境界間の全月 (降順)
201
+ */
202
+ function generateDropdownOptions(minBound: Date, maxBound: Date, locale: string | undefined): { label: string; value: string }[] {
203
+ const startIndex = minBound.getFullYear() * 12 + minBound.getMonth()
204
+ const endIndex = maxBound.getFullYear() * 12 + maxBound.getMonth()
205
+
206
+ const list: { label: string; value: string }[] = []
207
+ for (let i = endIndex; i >= startIndex; i--) {
208
+ list.push(toMonthOption(monthStart(Math.floor(i / 12), i % 12), locale))
75
209
  }
76
210
 
77
211
  return list
@@ -81,100 +215,89 @@ function generateDropdownOptions(currentDate: Date, minYear?: number, maxYear?:
81
215
  * Month selector component supporting both input[type="month"] and dropdown (yyyy-mm) modes.
82
216
  * 月セレクタ共通コンポーネント。
83
217
  * `<input type="month">` または `<select>` ドロップダウンと両脇のステッパーボタン (◀▶) で ±1 ヶ月を変更可能。
218
+ * アクセシブル名の既定値は全て英語、選択肢テキストは `locale` 未指定なら ISO 8601 表記。
219
+ * `value` / `initialDate` の欠落・不正値、境界の欠落・矛盾、境界外の選択値、不正な `locale` はいずれも RangeError で即時失敗。
84
220
  */
85
221
  const MonthSelectorComponent = (props: MonthSelectorProps): React.JSX.Element => {
86
- const { value, initialDate, onChange, children, variant = "date", minYear, maxYear, minDate, maxDate, isWarning = false, className = "", style, disabled = false, prevMonthAriaLabel = "前月", nextMonthAriaLabel = "翌月", selectAriaLabel = "年月" } = props
222
+ const {
223
+ value,
224
+ initialDate,
225
+ onChange,
226
+ children,
227
+ variant = "date",
228
+ minYear,
229
+ maxYear,
230
+ minDate,
231
+ maxDate,
232
+ isWarning = false,
233
+ className = "",
234
+ style,
235
+ disabled = false,
236
+ prevMonthAriaLabel = "Previous month",
237
+ nextMonthAriaLabel = "Next month",
238
+ selectAriaLabel = "Month",
239
+ locale,
240
+ } = props
241
+
242
+ assertLocaleProp(locale)
243
+ assertValidDateProp(value, "value")
244
+ assertValidDateProp(initialDate, "initialDate")
245
+ assertValidDateProp(minDate, "minDate")
246
+ assertValidDateProp(maxDate, "maxDate")
247
+ assertValidYearProp(minYear, "minYear")
248
+ assertValidYearProp(maxYear, "maxYear")
249
+
87
250
  const effectiveDate = value ?? initialDate
251
+ if (effectiveDate === undefined) {
252
+ throw new RangeError("MonthSelector: either `value` (controlled) or `initialDate` (uncontrolled) is required; the selected month is never inferred from the wall clock.")
253
+ }
88
254
 
89
- const [currentDate, setCurrentDate] = useState<Date>(() => {
90
- const base = effectiveDate ?? new Date()
91
- const d = new Date(base.getFullYear(), base.getMonth(), 1)
92
- d.setFullYear(base.getFullYear())
93
- return d
94
- })
255
+ const [currentDate, setCurrentDate] = useState<Date>(() => monthStart(effectiveDate.getFullYear(), effectiveDate.getMonth()))
95
256
 
96
257
  const isControlled = value !== undefined
97
- const activeDate = useMemo(() => {
98
- if (isControlled) {
99
- if (value && !Number.isNaN(value.getTime())) {
100
- const d = new Date(value.getFullYear(), value.getMonth(), 1)
101
- d.setFullYear(value.getFullYear())
102
- return d
103
- }
104
- return new Date()
105
- }
106
- return currentDate
107
- }, [isControlled, value?.getTime(), currentDate])
258
+ const activeDate = useMemo(() => (value !== undefined ? monthStart(value.getFullYear(), value.getMonth()) : currentDate), [value?.getTime(), currentDate])
108
259
 
109
260
  const minTime = minDate?.getTime()
110
261
  const maxTime = maxDate?.getTime()
111
262
 
112
- const minDateBound = useMemo(() => {
113
- if (minDate) {
114
- const d = new Date(minDate.getFullYear(), minDate.getMonth(), 1)
115
- d.setFullYear(minDate.getFullYear())
116
- return d
117
- }
118
- if (minYear !== undefined) {
119
- const d = new Date(minYear, 0, 1)
120
- d.setFullYear(minYear)
121
- return d
122
- }
123
- return null
124
- }, [minTime, minYear])
125
-
126
- const maxDateBound = useMemo(() => {
127
- if (maxDate) {
128
- const d = new Date(maxDate.getFullYear(), maxDate.getMonth(), 1)
129
- d.setFullYear(maxDate.getFullYear())
130
- return d
131
- }
132
- if (maxYear !== undefined) {
133
- const d = new Date(maxYear, 11, 1)
134
- d.setFullYear(maxYear)
135
- return d
136
- }
137
- return null
138
- }, [maxTime, maxYear])
263
+ const minDateBound = useMemo(() => resolveLowerBound(minYear, minDate), [minYear, minTime])
264
+ const maxDateBound = useMemo(() => resolveUpperBound(maxYear, maxDate), [maxYear, maxTime])
265
+
266
+ if (minDateBound !== null && maxDateBound !== null && minDateBound > maxDateBound) {
267
+ throw new RangeError(`MonthSelector: the resolved lower bound ${formatMonth(minDateBound)} is after the resolved upper bound ${formatMonth(maxDateBound)}.`)
268
+ }
269
+ if (variant === "dropdown" && (minDateBound === null || maxDateBound === null)) {
270
+ throw new RangeError('MonthSelector: variant="dropdown" requires a lower bound (`minYear` or `minDate`) and an upper bound (`maxYear` or `maxDate`); the option window is never invented.')
271
+ }
272
+ const isSelectionOutsideBounds = (minDateBound !== null && activeDate < minDateBound) || (maxDateBound !== null && activeDate > maxDateBound)
139
273
 
140
- // 外部からの value または initialDate 変更に追従
141
- const effectiveTime = effectiveDate?.getTime()
274
+ // 外部からの initialDate 変更に追従 (制御時は value がそのまま真実の源)
275
+ const effectiveTime = effectiveDate.getTime()
142
276
  useEffect(() => {
143
- if (!isControlled && effectiveDate && !Number.isNaN(effectiveDate.getTime())) {
144
- const next = new Date(effectiveDate.getFullYear(), effectiveDate.getMonth(), 1)
145
- next.setFullYear(effectiveDate.getFullYear())
146
- setCurrentDate(next)
147
- }
277
+ if (isControlled) return
278
+ const next = monthStart(effectiveDate.getFullYear(), effectiveDate.getMonth())
279
+ // 同一月の再設定で描画を走らせない
280
+ setCurrentDate((prev) => (prev.getTime() === next.getTime() ? prev : next))
148
281
  }, [isControlled, effectiveTime])
149
282
 
283
+ const isWithinBounds = (candidate: Date): boolean => (minDateBound === null || candidate >= minDateBound) && (maxDateBound === null || candidate <= maxDateBound)
284
+
150
285
  const emit = (nextDate: Date) => {
151
286
  if (disabled) return
152
- let clamped = nextDate
153
- if (minDateBound && clamped < minDateBound) {
154
- clamped = new Date(minDateBound)
155
- }
156
- if (maxDateBound && clamped > maxDateBound) {
157
- clamped = new Date(maxDateBound)
287
+ if (!isWithinBounds(nextDate)) {
288
+ throw new RangeError(`MonthSelector: refusing to emit ${formatMonth(nextDate)}, which lies outside the declared bounds.`)
158
289
  }
159
290
 
160
291
  if (!isControlled) {
161
- setCurrentDate(clamped)
292
+ setCurrentDate(nextDate)
162
293
  }
163
- const yyyymm = clamped.getFullYear() * 100 + (clamped.getMonth() + 1)
164
- onChange?.(clamped, yyyymm)
294
+ const yyyymm = nextDate.getFullYear() * 100 + (nextDate.getMonth() + 1)
295
+ onChange?.(nextDate, yyyymm)
165
296
  }
166
297
 
167
- const prevMonthDate = useMemo(() => {
168
- const d = new Date(activeDate.getFullYear(), activeDate.getMonth() - 1, 1)
169
- d.setFullYear(activeDate.getMonth() === 0 ? activeDate.getFullYear() - 1 : activeDate.getFullYear())
170
- return d
171
- }, [activeDate])
298
+ const prevMonthDate = useMemo(() => monthStart(activeDate.getFullYear(), activeDate.getMonth() - 1), [activeDate])
172
299
 
173
- const nextMonthDate = useMemo(() => {
174
- const d = new Date(activeDate.getFullYear(), activeDate.getMonth() + 1, 1)
175
- d.setFullYear(activeDate.getMonth() === 11 ? activeDate.getFullYear() + 1 : activeDate.getFullYear())
176
- return d
177
- }, [activeDate])
300
+ const nextMonthDate = useMemo(() => monthStart(activeDate.getFullYear(), activeDate.getMonth() + 1), [activeDate])
178
301
 
179
302
  const isPrevDisabled = disabled || (minDateBound !== null && prevMonthDate < minDateBound)
180
303
  const isNextDisabled = disabled || (maxDateBound !== null && nextMonthDate > maxDateBound)
@@ -187,50 +310,43 @@ const MonthSelectorComponent = (props: MonthSelectorProps): React.JSX.Element =>
187
310
  emit(nextMonthDate)
188
311
  }
189
312
 
190
- const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
191
- const val = e.target.value
313
+ const handleMonthString = (val: string) => {
192
314
  if (!val) return
193
315
  const [yearStr, monthStr] = val.split("-")
194
316
  const year = Number(yearStr)
195
317
  const month = Number(monthStr) - 1
196
- if (!(Number.isNaN(year) || Number.isNaN(month))) {
197
- const next = new Date(year, month, 1)
198
- next.setFullYear(year)
199
- emit(next)
200
- }
201
- }
318
+ if (!(Number.isInteger(year) && Number.isInteger(month))) return
202
319
 
203
- const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
204
- const val = e.target.value
205
- if (!val) return
206
- const [yearStr, monthStr] = val.split("-")
207
- const year = Number(yearStr)
208
- const month = Number(monthStr) - 1
209
- if (!(Number.isNaN(year) || Number.isNaN(month))) {
210
- const next = new Date(year, month, 1)
211
- next.setFullYear(year)
212
- emit(next)
213
- }
320
+ const next = monthStart(year, month)
321
+ // 境界外の直接入力は丸めずに破棄する (丸めると利用者が選んでいない月が親へ伝播するため)
322
+ if (!isWithinBounds(next)) return
323
+ emit(next)
214
324
  }
215
325
 
216
- const formattedValue = `${activeDate.getFullYear()}-${String(activeDate.getMonth() + 1).padStart(2, "0")}`
326
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
327
+ handleMonthString(e.target.value)
328
+ }
217
329
 
218
- const minFormatted = minDateBound ? `${minDateBound.getFullYear()}-${String(minDateBound.getMonth() + 1).padStart(2, "0")}` : undefined
330
+ const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
331
+ handleMonthString(e.target.value)
332
+ }
219
333
 
220
- const maxFormatted = maxDateBound ? `${maxDateBound.getFullYear()}-${String(maxDateBound.getMonth() + 1).padStart(2, "0")}` : undefined
334
+ const formattedValue = formatMonth(activeDate)
221
335
 
222
- const currentY = activeDate.getFullYear()
223
- const lowerY = minYear ?? (minDate ? minDate.getFullYear() : currentY - 5)
224
- const upperY = maxYear ?? (maxDate ? maxDate.getFullYear() : currentY + 5)
225
- const startY = Math.min(lowerY, currentY)
226
- const endY = Math.max(upperY, currentY)
336
+ const minFormatted = minDateBound ? formatMonth(minDateBound) : undefined
227
337
 
228
- const monthOptionsKey = `${startY}_${endY}_${minTime ?? "none"}_${maxTime ?? "none"}`
338
+ const maxFormatted = maxDateBound ? formatMonth(maxDateBound) : undefined
229
339
 
230
340
  const dropdownOptions = useMemo(() => {
231
- if (variant !== "dropdown") return []
232
- return generateDropdownOptions(activeDate, minYear, maxYear, minDate, maxDate)
233
- }, [variant, monthOptionsKey, activeDate])
341
+ if (variant !== "dropdown" || minDateBound === null || maxDateBound === null) return []
342
+ const options = generateDropdownOptions(minDateBound, maxDateBound, locale)
343
+ if (!isSelectionOutsideBounds) return options
344
+ // 境界が動的に狭まると、値が追従するまでの 1 描画だけ選択値が窓の外に出る。
345
+ // その月を選択肢に加えないと select は別の月を表示し、保持値と画面が食い違う
346
+ const selected = toMonthOption(activeDate, locale)
347
+ // 並べ替えは表示ラベルではなく yyyy-MM 値で行う (ラベルはロケールで語順が変わり暦順にならないため)
348
+ return [...options, selected].sort((a, b) => b.value.localeCompare(a.value))
349
+ }, [variant, minDateBound?.getTime(), maxDateBound?.getTime(), isSelectionOutsideBounds, activeDate, locale])
234
350
 
235
351
  const warningClassName = isWarning
236
352
  ? "border-amber-300 bg-amber-50 text-amber-900 focus:border-amber-500 focus:ring-amber-500 dark:border-amber-900/50 dark:bg-amber-950/20 dark:text-amber-200"
@@ -238,7 +354,7 @@ const MonthSelectorComponent = (props: MonthSelectorProps): React.JSX.Element =>
238
354
 
239
355
  const inputClassName = `mx-1 my-auto w-28 rounded-md border py-0.5 px-1 text-xs dark:placeholder:text-gray-400 disabled:opacity-50 ${warningClassName}`
240
356
 
241
- const selectClassName = `mx-1 my-auto w-28 appearance-none rounded-md border px-1 py-0.5 text-center font-mono text-xs tabular-nums [text-align-last:center] [text-align:center] focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 ${warningClassName}`
357
+ const selectClassName = `mx-1 my-auto w-28 appearance-none rounded-md border px-1 py-0.5 text-center font-mono text-xs tabular-nums [text-align-last:center] [text-align:center] disabled:opacity-50 ${warningClassName}`
242
358
 
243
359
  return (
244
360
  <div className={`inline-flex w-38 items-center ${className}`} style={style}>
@@ -274,11 +390,15 @@ const MonthSelectorComponent = (props: MonthSelectorProps): React.JSX.Element =>
274
390
  )
275
391
  }
276
392
 
393
+ /**
394
+ * Month-resolution selector re-rendering only when a prop its output depends on changes.
395
+ * 描画結果が依存する Props の変化時のみ再描画する月単位セレクタ。
396
+ */
277
397
  export const MonthSelector = memo(MonthSelectorComponent, (prev, next) => {
278
398
  const prevD = prev.value ?? prev.initialDate
279
399
  const nextD = next.value ?? next.initialDate
280
- const prevYm = prevD && !Number.isNaN(prevD.getTime()) ? prevD.getFullYear() * 12 + prevD.getMonth() : null
281
- const nextYm = nextD && !Number.isNaN(nextD.getTime()) ? nextD.getFullYear() * 12 + nextD.getMonth() : null
400
+ const prevYm = prevD ? prevD.getFullYear() * 12 + prevD.getMonth() : null
401
+ const nextYm = nextD ? nextD.getFullYear() * 12 + nextD.getMonth() : null
282
402
  if (prevYm !== nextYm) return false
283
403
  if (prev.variant !== next.variant) return false
284
404
  if (prev.disabled !== next.disabled) return false
@@ -298,6 +418,7 @@ export const MonthSelector = memo(MonthSelectorComponent, (prev, next) => {
298
418
  if (prev.prevMonthAriaLabel !== next.prevMonthAriaLabel) return false
299
419
  if (prev.nextMonthAriaLabel !== next.nextMonthAriaLabel) return false
300
420
  if (prev.selectAriaLabel !== next.selectAriaLabel) return false
421
+ if (prev.locale !== next.locale) return false
301
422
  return true
302
423
  })
303
424
  MonthSelector.displayName = "MonthSelector"