@aiquants/period-slider 0.10.2 → 0.11.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,27 +1,47 @@
1
1
  /**
2
2
  * @fileoverview Date (yyyy-MM-dd) selector component with stepper buttons.
3
3
  *
4
- * Provides a day-resolution selector rendered either as a native `input[type="date"]`,
5
- * a single `<select>` of yyyy-MM-dd options, or three year / month / day selects,
6
- * always flanked by previous/next stepper buttons.
4
+ * Provides a day-resolution selector rendered either as a native `input[type="date"]`, a
5
+ * virtualized combobox over the whole day range, or three year / month / day selects, always
6
+ * flanked by previous/next stepper buttons.
7
+ *
8
+ * The combobox never materializes its option list: the option set is an index space derived from
9
+ * the bounds (`dateOptionDomain`) and only the visible rows exist as DOM, so a host that moves
10
+ * `minDate` / `maxDate` per pointer move pays O(1) rather than O(option count).
7
11
  *
8
12
  * Human-facing option text is locale-independent ISO 8601 until a `locale` tag opts into Intl
9
13
  * formatting or a per-part formatter overrides it, while every machine-read value stays yyyy-MM-dd.
10
14
  * The previous / next buttons are drawn by `StepperButton`.
11
15
  *
12
16
  * 年月日セレクタコンポーネントの提供モジュール。
13
- * ネイティブ `input[type="date"]`、yyyy-MM-dd の単一セレクトボックス、
17
+ * ネイティブ `input[type="date"]`、日付範囲全体を仮想化したコンボボックス、
14
18
  * 年・月・日の 3 分割セレクトのいずれかを、前日/翌日ステッパーで挟んで描画。
19
+ * コンボボックスは選択肢配列を実体化せず、選択肢集合は境界から導いた添字空間
20
+ * (`dateOptionDomain`)、DOM に存在するのは可視行のみ。
21
+ * このためポインタ移動ごとに `minDate` / `maxDate` を動かすホストの費用は選択肢数に比例しない。
15
22
  * 表示テキストは既定でロケール非依存の ISO 8601 表記 (`locale` 指定時は Intl 書式、
16
23
  * 部位別フォーマッタ指定時はそれが最優先)、機械可読値は常に yyyy-MM-dd。
17
24
  * 前日/翌日ボタンは `StepperButton` が描く。
18
25
  */
19
26
 
20
- import { addDays, format, getDaysInMonth, parseISO } from "date-fns"
27
+ import { addDays, getDaysInMonth, parseISO } from "date-fns"
21
28
  import type React from "react"
22
29
  import { memo, useEffect, useMemo, useState } from "react"
30
+ import {
31
+ createContinuousDateOptionDomain,
32
+ createDiscreteDateOptionDomain,
33
+ type DateOptionDomain,
34
+ type DiscreteIndexWindow,
35
+ EMPTY_DATE_OPTION_DOMAIN,
36
+ findDiscreteNeighbour,
37
+ formatIsoDay,
38
+ NO_OPTION_INDEX,
39
+ normalizeAllowedDates,
40
+ resolveDiscreteIndexWindow,
41
+ } from "./dateOptionDomain"
23
42
  import { formatLabel } from "./PeriodSlider"
24
43
  import { STEPPER_ROW_GAP_CLASS, StepperButton } from "./StepperButton"
44
+ import { VirtualDateDropdown } from "./VirtualDateDropdown"
25
45
 
26
46
  /**
27
47
  * Props of the day-resolution selector.
@@ -56,7 +76,7 @@ export interface DateSelectorProps {
56
76
  /**
57
77
  * UI Variant:
58
78
  * - "date": Native input[type="date"] (default / 既定)
59
- * - "dropdown": Single select element with yyyy-MM-dd options; requires a bounded range or allowedDates
79
+ * - "dropdown": Virtualized combobox over yyyy-MM-dd options; requires a bounded range or allowedDates
60
80
  * - "split-dropdown": Three separate selects for year, month, and day; requires a bounded range and rejects allowedDates
61
81
  */
62
82
  variant?: "date" | "dropdown" | "split-dropdown"
@@ -241,80 +261,13 @@ const formatDatePart = (part: DatePart, anchor: Date, locale: string | undefined
241
261
  return getPartFormat(part, locale).format(anchor)
242
262
  }
243
263
 
244
- /**
245
- * Normalizes, deduplicates, sorts ascending and range-restricts the discrete allowed dates.
246
- * 離散日付配列を正規化・重複排除・昇順ソートし、境界外要素を除外する関数。
247
- *
248
- * @param allowedDates - Caller supplied discrete dates / 呼び出し側が指定した離散日付
249
- * @param minDateBound - Resolved lower bound, or null when unbounded / 解決済み下限 (無制限時は null)
250
- * @param maxDateBound - Resolved upper bound, or null when unbounded / 解決済み上限 (無制限時は null)
251
- * @returns Ascending, deduplicated dates inside the bounds (possibly empty) / 境界内の昇順・重複排除済み日付 (空の場合あり)
252
- * @throws RangeError when any entry is an Invalid Date / 要素が Invalid Date の場合
253
- */
254
- const resolveSelectableDates = (allowedDates: Date[], minDateBound: Date | null, maxDateBound: Date | null): Date[] => {
255
- const minTime = minDateBound?.getTime() ?? null
256
- const maxTime = maxDateBound?.getTime() ?? null
257
- const byTime = new Map<number, Date>()
258
-
259
- allowedDates.forEach((entry, index) => {
260
- assertValidDateProp(`allowedDates[${index}]`, entry)
261
- const normalized = toStartOfDay(entry)
262
- const time = normalized.getTime()
263
- if (minTime !== null && time < minTime) return
264
- if (maxTime !== null && time > maxTime) return
265
- if (!byTime.has(time)) {
266
- byTime.set(time, normalized)
267
- }
268
- })
269
-
270
- return Array.from(byTime.keys())
271
- .sort((a, b) => a - b)
272
- .map((time) => byTime.get(time) as Date)
273
- }
274
-
275
- /**
276
- * Expands a bounded range into every calendar day it contains, ascending.
277
- * 境界で挟まれた範囲を、含まれる全暦日 (昇順) へ展開する関数。
278
- *
279
- * @param minDateBound - Resolved lower bound / 解決済み下限
280
- * @param maxDateBound - Resolved upper bound / 解決済み上限
281
- * @returns Ascending list of every day in [minDateBound, maxDateBound] / 範囲内全日の昇順配列
282
- */
283
- const expandBoundedDays = (minDateBound: Date, maxDateBound: Date): Date[] => {
284
- const list: Date[] = []
285
- let current = toStartOfDay(minDateBound)
286
- const endTime = toStartOfDay(maxDateBound).getTime()
287
- while (current.getTime() <= endTime) {
288
- list.push(current)
289
- current = addDays(current, 1)
290
- }
291
- return list
292
- }
293
-
294
- /**
295
- * Renders an ascending date list as the descending option list of the single select-box mode.
296
- * 昇順日付配列を、単一セレクトボックス用の降順選択肢へ変換する関数。
297
- *
298
- * @param datesAscending - Ascending selectable dates / 昇順の選択可能日付
299
- * @param locale - BCP 47 language tag enabling Intl label formatting / Intl ラベル書式を有効化する BCP 47 言語タグ
300
- * @returns Descending options whose value is always yyyy-MM-dd / value が常に yyyy-MM-dd である降順選択肢
301
- */
302
- const toDescendingOptions = (datesAscending: Date[], locale: string | undefined): { label: string; value: string }[] => {
303
- const options: { label: string; value: string }[] = []
304
- for (let i = datesAscending.length - 1; i >= 0; i--) {
305
- // 表示は locale 次第で変わるが、value は change ハンドラが parseISO で解釈するため常に yyyy-MM-dd
306
- options.push({ label: formatLabel("day", datesAscending[i], undefined, locale), value: format(datesAscending[i], "yyyy-MM-dd") })
307
- }
308
- return options
309
- }
310
-
311
264
  /**
312
265
  * Date (yyyy-MM-dd) selector component supporting bounded ranges, discrete allowed dates, and ±1 stepper buttons.
313
266
  * Every control the component presents as enabled is emittable: a stepper whose target date falls
314
267
  * outside the selectable set is disabled, and so is a `variant="split-dropdown"` year or month
315
268
  * whose combination with the other two parts would be discarded.
316
269
  * 日付 (年月日) セレクタ共通コンポーネント。
317
- * ネイティブ日付入力・単一セレクトボックス・3 分割セレクトのいずれかと、両脇のステッパーボタン (◀▶) を描画。
270
+ * ネイティブ日付入力・仮想化コンボボックス・3 分割セレクトのいずれかと、両脇のステッパーボタン (◀▶) を描画。
318
271
  * 選択可能集合は `allowedDates` (離散) または [minDate/minYear, maxDate/maxYear] (連続) が決定し、集合外の日付は emit されない。
319
272
  * 発行できない日へ進むステッパーは無効化し、`variant="split-dropdown"` では他の 2 部位との組合せが
320
273
  * emit できない年・月を選択不可の選択肢として提示。
@@ -397,7 +350,7 @@ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
397
350
  const maxBoundTime = maxDateBound?.getTime() ?? null
398
351
 
399
352
  if (minDateBound !== null && maxDateBound !== null && minDateBound.getTime() > maxDateBound.getTime()) {
400
- throw new RangeError(`DateSelector: the resolved range is empty (min ${format(minDateBound, "yyyy-MM-dd")} is after max ${format(maxDateBound, "yyyy-MM-dd")})`)
353
+ throw new RangeError(`DateSelector: the resolved range is empty (min ${formatIsoDay(minDateBound)} is after max ${formatIsoDay(maxDateBound)})`)
401
354
  }
402
355
  if (variant !== "date" && allowedDates === undefined && (minDateBound === null || maxDateBound === null)) {
403
356
  throw new RangeError(`DateSelector: variant="${variant}" needs a bounded range; supply minDate/minYear and maxDate/maxYear${variant === "dropdown" ? ' or supply "allowedDates"' : ""}`)
@@ -405,16 +358,33 @@ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
405
358
 
406
359
  const allowedKey = allowedDates === undefined ? null : allowedDates.map((d) => d.getTime()).join(",")
407
360
 
408
- const selectableDates = useMemo<Date[] | null>(() => {
361
+ // 境界を含めずに正規化するのが要点。境界込みで導出すると、境界が動くたびに配列を作り直す
362
+ // ことになり、選択肢を実体化しないという前提がホストの離散集合側で崩れる
363
+ const normalizedAllowedDates = useMemo<Date[] | null>(() => {
409
364
  if (allowedDates === undefined) return null
410
- return resolveSelectableDates(allowedDates, minDateBound, maxDateBound)
411
- }, [allowedKey, minBoundTime, maxBoundTime])
365
+ return normalizeAllowedDates(allowedDates, (index, entry) => assertValidDateProp(`allowedDates[${index}]`, entry))
366
+ }, [allowedKey])
367
+
368
+ const discreteWindow = useMemo<(DiscreteIndexWindow & { ascending: readonly Date[] }) | null>(() => {
369
+ if (normalizedAllowedDates === null) return null
370
+ return { ascending: normalizedAllowedDates, ...resolveDiscreteIndexWindow(normalizedAllowedDates, minDateBound, maxDateBound) }
371
+ }, [normalizedAllowedDates, minBoundTime, maxBoundTime])
372
+
373
+ // 選択肢集合は「配列」ではなく「添字空間」として持つ。件数は境界から算出し、添字 i の
374
+ // 日付・値・ラベルは要求時に導出するため、境界が動いても件数に比例した処理は走らない
375
+ const optionDomain = useMemo<DateOptionDomain>(() => {
376
+ if (discreteWindow !== null) {
377
+ return createDiscreteDateOptionDomain(discreteWindow.ascending, discreteWindow.loIndex, discreteWindow.hiIndex, locale)
378
+ }
379
+ if (minDateBound === null || maxDateBound === null) return EMPTY_DATE_OPTION_DOMAIN
380
+ return createContinuousDateOptionDomain(minDateBound, maxDateBound, locale)
381
+ }, [discreteWindow, minBoundTime, maxBoundTime, locale])
412
382
 
413
383
  const isSelectable = (candidate: Date): boolean => {
414
- const time = candidate.getTime()
415
- if (selectableDates !== null) {
416
- return selectableDates.some((d) => d.getTime() === time)
384
+ if (discreteWindow !== null) {
385
+ return optionDomain.indexOf(candidate) !== NO_OPTION_INDEX
417
386
  }
387
+ const time = candidate.getTime()
418
388
  if (minBoundTime !== null && time < minBoundTime) return false
419
389
  if (maxBoundTime !== null && time > maxBoundTime) return false
420
390
  return true
@@ -446,26 +416,20 @@ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
446
416
  // emit が破棄する日でボタンが有効になり、押しても何も起きない死にボタンになる。
447
417
  // 押せる日と発行できる日は、どちらも選択可能集合への所属で決める
448
418
  const prevDate = useMemo<Date | null>(() => {
449
- if (selectableDates !== null) {
450
- for (let i = selectableDates.length - 1; i >= 0; i--) {
451
- if (selectableDates[i].getTime() < activeTime) return selectableDates[i]
452
- }
453
- return null
419
+ if (discreteWindow !== null) {
420
+ return findDiscreteNeighbour(discreteWindow.ascending, discreteWindow.loIndex, discreteWindow.hiIndex, activeTime, -1)
454
421
  }
455
422
  const candidate = addDays(new Date(activeTime), -1)
456
423
  return isSelectable(candidate) ? candidate : null
457
- }, [selectableDates, activeTime, minBoundTime, maxBoundTime])
424
+ }, [discreteWindow, activeTime, minBoundTime, maxBoundTime])
458
425
 
459
426
  const nextDate = useMemo<Date | null>(() => {
460
- if (selectableDates !== null) {
461
- for (const candidate of selectableDates) {
462
- if (candidate.getTime() > activeTime) return candidate
463
- }
464
- return null
427
+ if (discreteWindow !== null) {
428
+ return findDiscreteNeighbour(discreteWindow.ascending, discreteWindow.loIndex, discreteWindow.hiIndex, activeTime, 1)
465
429
  }
466
430
  const candidate = addDays(new Date(activeTime), 1)
467
431
  return isSelectable(candidate) ? candidate : null
468
- }, [selectableDates, activeTime, minBoundTime, maxBoundTime])
432
+ }, [discreteWindow, activeTime, minBoundTime, maxBoundTime])
469
433
 
470
434
  const handlePrevious = () => {
471
435
  if (prevDate !== null) emit(prevDate)
@@ -483,26 +447,10 @@ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
483
447
  }
484
448
  }
485
449
 
486
- const handleDropdownChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
487
- if (e.target.value) {
488
- const parsed = parseISO(e.target.value)
489
- if (!Number.isNaN(parsed.getTime())) {
490
- emit(parsed)
491
- }
492
- }
493
- }
494
-
495
450
  const currentYear = activeDate.getFullYear()
496
451
  const currentMonth = activeDate.getMonth() + 1
497
452
  const currentDay = activeDate.getDate()
498
453
 
499
- const dateDropdownOptions = useMemo(() => {
500
- if (variant !== "dropdown") return []
501
- if (selectableDates !== null) return toDescendingOptions(selectableDates, locale)
502
- if (minDateBound === null || maxDateBound === null) return []
503
- return toDescendingOptions(expandBoundedDays(minDateBound, maxDateBound), locale)
504
- }, [variant, selectableDates, minBoundTime, maxBoundTime, locale])
505
-
506
454
  const yearOptions = useMemo(() => {
507
455
  if (variant !== "split-dropdown" || minDateBound === null || maxDateBound === null) return []
508
456
  const list: number[] = []
@@ -570,34 +518,30 @@ const DateSelectorComponent = (props: DateSelectorProps): React.JSX.Element => {
570
518
  return formatDatePart("day", localDate(currentYear, currentMonth, day), locale)
571
519
  }
572
520
 
573
- const formattedDate = format(activeDate, "yyyy-MM-dd")
521
+ const formattedDate = formatIsoDay(activeDate)
574
522
  const activeLabel = formatLabel("day", activeDate, undefined, locale)
575
- const minFormatted = minDateBound ? format(minDateBound, "yyyy-MM-dd") : undefined
576
- const maxFormatted = maxDateBound ? format(maxDateBound, "yyyy-MM-dd") : undefined
577
- // 単一行 <select> は一致する選択肢が無いと先頭項目を表示してしまうため、集合外の現在値は選択不可の実値プレースホルダとして明示する
578
- const selectValue = isActiveSelectable ? formattedDate : ""
523
+ const minFormatted = minDateBound ? formatIsoDay(minDateBound) : undefined
524
+ const maxFormatted = maxDateBound ? formatIsoDay(maxDateBound) : undefined
579
525
  const outOfRangeOptionClassName = "text-center font-mono text-gray-500 tabular-nums [text-align-last:center] [text-align:center] dark:bg-slate-700 dark:text-slate-400"
580
526
 
581
- const singleSelectClassName =
582
- "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"
527
+ const dateComboboxClassName =
528
+ "period-slider-date-combobox-field 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"
583
529
 
584
530
  return (
585
531
  <div className={`inline-flex items-center ${STEPPER_ROW_GAP_CLASS} ${className}`} style={style} data-variant={variant} data-out-of-range={isActiveSelectable ? undefined : "true"}>
586
532
  <StepperButton neighbour="control" direction="left" disabled={disabled} canStep={prevDate !== null} onStep={handlePrevious} ariaLabel={prevDateAriaLabel} />
587
533
 
588
534
  {variant === "dropdown" ? (
589
- <select aria-label={selectAriaLabel} disabled={disabled} className={singleSelectClassName} value={selectValue} onChange={handleDropdownChange}>
590
- {isActiveSelectable ? null : (
591
- <option value="" disabled className={outOfRangeOptionClassName}>
592
- {activeLabel}
593
- </option>
594
- )}
595
- {dateDropdownOptions.map((opt) => (
596
- <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">
597
- {opt.label}
598
- </option>
599
- ))}
600
- </select>
535
+ <VirtualDateDropdown
536
+ domain={optionDomain}
537
+ selectedIndex={isActiveSelectable ? optionDomain.indexOf(activeDate) : NO_OPTION_INDEX}
538
+ displayLabel={activeLabel}
539
+ machineValue={formattedDate}
540
+ disabled={disabled}
541
+ ariaLabel={selectAriaLabel}
542
+ onCommitIndex={(index) => emit(optionDomain.dateAt(index))}
543
+ controlClassName={dateComboboxClassName}
544
+ />
601
545
  ) : variant === "split-dropdown" ? (
602
546
  <div className="inline-flex items-center gap-1">
603
547
  <select