@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,2557 @@
1
+ import type React from "react"
2
+ import { type CSSProperties, memo, useCallback, useEffect, useId, useMemo, useRef, useState } from "react"
3
+ import "./styles/period-slider.css"
4
+
5
+ // ======================================================================
6
+ // 1. Core Domain Types & Public Interfaces
7
+ // ======================================================================
8
+
9
+ export type PeriodSliderUnit = "year" | "month" | "day"
10
+ export type PeriodSliderLabelPosition = "top" | "bottom"
11
+
12
+ /**
13
+ * Color theme preset for PeriodSlider.
14
+ * スライダーの配色テーマプリセット。
15
+ */
16
+ export type PeriodSliderColorScheme = "blue-rose" | "indigo-amber" | "teal-emerald" | "violet-fuchsia" | "slate-sky" | "monochrome"
17
+
18
+ export interface ColorSchemePalette {
19
+ macro: string
20
+ macroLight: string
21
+ micro: string
22
+ microLight: string
23
+ accent: string
24
+ }
25
+
26
+ /**
27
+ * Color palette definitions for each colorScheme preset.
28
+ * 各カラーテーマプリセットのカラーパレット定義。
29
+ */
30
+ export const COLOR_SCHEME_PALETTES: Record<PeriodSliderColorScheme, ColorSchemePalette> = {
31
+ "blue-rose": {
32
+ macro: "#0284c7",
33
+ macroLight: "#38bdf8",
34
+ micro: "#e11d48",
35
+ microLight: "#fb7185",
36
+ accent: "#0284c7",
37
+ },
38
+ "indigo-amber": {
39
+ macro: "#4f46e5",
40
+ macroLight: "#818cf8",
41
+ micro: "#d97706",
42
+ microLight: "#fbbf24",
43
+ accent: "#4f46e5",
44
+ },
45
+ "teal-emerald": {
46
+ macro: "#0d9488",
47
+ macroLight: "#2dd4bf",
48
+ micro: "#059669",
49
+ microLight: "#34d399",
50
+ accent: "#0d9488",
51
+ },
52
+ "violet-fuchsia": {
53
+ macro: "#7c3aed",
54
+ macroLight: "#a78bfa",
55
+ micro: "#c026d3",
56
+ microLight: "#e879f9",
57
+ accent: "#7c3aed",
58
+ },
59
+ "slate-sky": {
60
+ macro: "#475569",
61
+ macroLight: "#94a3b8",
62
+ micro: "#0284c7",
63
+ microLight: "#38bdf8",
64
+ accent: "#475569",
65
+ },
66
+ monochrome: {
67
+ macro: "#52525b",
68
+ macroLight: "#a1a1aa",
69
+ micro: "#18181b",
70
+ microLight: "#71717a",
71
+ accent: "#27272a",
72
+ },
73
+ }
74
+
75
+ export interface LabelSlantConfig {
76
+ /** Estimated width of the label in pixels / ラベルの推定横幅(ピクセル) */
77
+ estimatedWidthPx?: number
78
+ /** Estimated height (thickness) of the label in pixels / ラベルの推定高さ・厚み(ピクセル) */
79
+ estimatedHeightPx?: number
80
+ /** Extra clearance gap in pixels / 衝突検知時の余白マージン(ピクセル) */
81
+ paddingPx?: number
82
+ /** Maximum slant angle in degrees (default: 90) / 最大傾斜角度(度、既定: 90) */
83
+ maxAngleDeg?: number
84
+ /** Clearance from handle center in Y axis (pixels, default: 18) / つまみ中心とのY軸クリアランス(ピクセル、既定: 18) */
85
+ anchorGapY?: number
86
+ }
87
+
88
+ export interface LabelSlantResult {
89
+ /** Low handle label angle in degrees (e.g., -90 to 0 for top) */
90
+ lowAngleDeg: number
91
+ /** High handle label angle in degrees (e.g., -90 to 0 for top) */
92
+ highAngleDeg: number
93
+ /** Low handle horizontal shift in pixels */
94
+ lowOffsetX: number
95
+ /** High handle horizontal shift in pixels */
96
+ highOffsetX: number
97
+ /** Low handle vertical shift in pixels (maintains boundary clearance) */
98
+ lowOffsetY: number
99
+ /** High handle vertical shift in pixels (maintains boundary clearance) */
100
+ highOffsetY: number
101
+ /** True if labels are currently slanted to avoid collision */
102
+ isSlanted: boolean
103
+ /** Normalized collision proximity factor between 0 and 1 */
104
+ proximity: number
105
+ }
106
+
107
+ export interface AccessibleSliderLabels {
108
+ /** Accessible name for lower handle / 下限つまみのアクセシブル名 (既定: "開始時期") */
109
+ lowerAriaLabel?: string
110
+ /** Accessible name for upper handle / 上限つまみのアクセシブル名 (既定: "終了時期") */
111
+ upperAriaLabel?: string
112
+ /** Accessible name for single point handle / 単一選択つまみのアクセシブル名 (既定: "選択時期") */
113
+ pointAriaLabel?: string
114
+ /** Accessible name for macro lower handle / マクロ下限つまみ (既定: "マクロ開始時期") */
115
+ macroLowerAriaLabel?: string
116
+ /** Accessible name for macro upper handle / マクロ上限つまみ (既定: "マクロ終了時期") */
117
+ macroUpperAriaLabel?: string
118
+ /** Human-readable text formatter for screen readers / スクリーンリーダー専用読み上げフォーマッタ */
119
+ formatAriaValueText?: (date: Date, unit: PeriodSliderUnit) => string
120
+ }
121
+
122
+ export interface BasePeriodSliderProps extends AccessibleSliderLabels {
123
+ unit: PeriodSliderUnit
124
+ minDate?: Date
125
+ maxDate?: Date
126
+ allowedDates?: Date[]
127
+ snapMode?: "index" | "time"
128
+ debounceMs?: number
129
+ disabled?: boolean
130
+ className?: string
131
+ /** Custom inline styles / カスタムインラインスタイル (CSS変数の直接注入等) */
132
+ style?: React.CSSProperties
133
+ showStepper?: boolean
134
+ tooltipStyle?: "always" | "hover" | "balloon"
135
+ /** Label position: "top" (default) or "bottom" / ラベル表示位置("top": 上側 [既定], "bottom": 下側) */
136
+ labelPosition?: PeriodSliderLabelPosition
137
+ /** Whether to automatically slant labels when close in range mode (default: true) / Rangeモードで接近時に自動斜め表示するか(既定: true) */
138
+ autoSlantLabels?: boolean
139
+ /** Alias for autoSlantLabels / autoSlantLabels のエイリアス */
140
+ preventCollisionSlant?: boolean
141
+ isVertical?: boolean
142
+ hideConnectBar?: boolean
143
+ showTicks?: boolean
144
+ formatLabel?: (date: Date) => string
145
+ /** Color scheme theme preset for slider rails and handles (default: "blue-rose") / スライダーのカラーテーマプリセット(既定: "blue-rose") */
146
+ colorScheme?: PeriodSliderColorScheme
147
+ }
148
+
149
+ export interface PeriodSliderRangeProps extends BasePeriodSliderProps {
150
+ mode: "range"
151
+ /** Selected date range tuple [lower, upper] / 選択期間タプル (優先指定) */
152
+ range?: [Date, Date]
153
+ /** Lower boundary date of selected range / 選択期間の開始日付 */
154
+ lowerDate?: Date
155
+ /** Upper boundary date of selected range / 終了期間の終了日付 */
156
+ upperDate?: Date
157
+ /** Initial date range tuple for uncontrolled usage / 非制御時の初期選択期間タプル */
158
+ defaultRange?: [Date, Date]
159
+ /** Initial date range tuple alias / 非制御時の初期選択期間タプル (エイリアス) */
160
+ initialRange?: [Date, Date]
161
+ /** Initial lower date for uncontrolled usage / 非制御時の初期開始日付 */
162
+ defaultLowerDate?: Date
163
+ /** Initial lower date alias / 非制御時の初期開始日付 (エイリアス) */
164
+ initialLowerDate?: Date
165
+ /** Initial upper date for uncontrolled usage / 非制御時の初期終了日付 */
166
+ defaultUpperDate?: Date
167
+ /** Initial upper date alias / 非制御時の初期終了日付 (エイリアス) */
168
+ initialUpperDate?: Date
169
+ /** Callback triggered when range changes / 期間変更時コールバック */
170
+ onChangeRange?: (lower: Date, upper: Date) => void
171
+ /** Callback triggered with tuple [lower, upper] when range changes / 期間変更時タプルコールバック */
172
+ onChangeRangeTuple?: (range: [Date, Date]) => void
173
+ /** Standard tuple callback alias / 標準タプルコールバック */
174
+ onChange?: (range: [Date, Date]) => void
175
+ value?: never
176
+ valueDate?: never
177
+ onChangePoint?: never
178
+ onChangeValue?: never
179
+ macroRange?: never
180
+ onChangeMacroRange?: never
181
+ microRange?: never
182
+ }
183
+
184
+ export interface PeriodSliderPointProps extends BasePeriodSliderProps {
185
+ mode: "point"
186
+ /** Selected point date / 選択日付 */
187
+ value?: Date
188
+ /** Selected point date (legacy alias) / 選択日付(エイリアス) */
189
+ valueDate?: Date
190
+ /** Initial point date for uncontrolled usage / 非制御時の初期選択日付 */
191
+ defaultValue?: Date
192
+ /** Initial point date alias / 非制御時の初期選択日付 (セレクタ群と統一) */
193
+ initialDate?: Date
194
+ /** Callback triggered when point changes / ポイント変更時コールバック */
195
+ onChangePoint?: (value: Date) => void
196
+ /** Callback triggered when point changes (alias) / ポイント変更時コールバック(エイリアス) */
197
+ onChangeValue?: (value: Date) => void
198
+ /** Standard Date callback alias / 標準日付コールバック */
199
+ onChange?: (value: Date) => void
200
+ range?: never
201
+ lowerDate?: never
202
+ upperDate?: never
203
+ onChangeRange?: never
204
+ onChangeRangeTuple?: never
205
+ macroRange?: never
206
+ onChangeMacroRange?: never
207
+ microRange?: never
208
+ }
209
+
210
+ export interface PeriodSliderVernierProps extends BasePeriodSliderProps {
211
+ /** Vernier dual-scale integrated mode / ノギス型 2 段スケール一体型モード */
212
+ mode: "vernier"
213
+ /** Minimum selectable boundary date for entire macro range (required, no default) / 全期間マクロの下限日付 (必須) */
214
+ minDate: Date
215
+ /** Maximum selectable boundary date for entire macro range (required, no default) / 全期間マクロの上限日付 (必須) */
216
+ maxDate: Date
217
+ /** Macro window range [start, end] / マクロ側の広域表示窓 (必須) */
218
+ macroRange: [Date, Date]
219
+ /** Callback triggered when macro window changes / マクロ窓変更時コールバック */
220
+ onChangeMacroRange?: (lower: Date, upper: Date) => void
221
+ /** Callback triggered with tuple [lower, upper] when macro window changes / マクロ窓変更時タプルコールバック */
222
+ onChangeMacroRangeTuple?: (range: [Date, Date]) => void
223
+ /** Symmetrical alias for macro window changes / マクロ窓変更時コールバック (エイリアス) */
224
+ onChangeMacro?: (range: [Date, Date]) => void
225
+
226
+ /** Micro selected range tuple [lower, upper] / ミクロ側の最終確定期間タプル (優先指定) */
227
+ microRange?: [Date, Date]
228
+ /** Micro selected lower date / ミクロ側の最終確定開始日付 */
229
+ lowerDate?: Date
230
+ /** Micro selected upper date / ミクロ側の最終確定終了日付 */
231
+ upperDate?: Date
232
+ /** Initial micro range tuple for uncontrolled usage / 非制御時の初期ミクロ選択期間タプル */
233
+ defaultMicroRange?: [Date, Date]
234
+ /** Initial micro range tuple alias / 非制御時の初期ミクロ選択期間タプル (エイリアス) */
235
+ initialMicroRange?: [Date, Date]
236
+ /** Initial lower date for uncontrolled usage / 非制御時の初期ミクロ開始日付 */
237
+ defaultLowerDate?: Date
238
+ /** Initial lower date alias / 非制御時の初期ミクロ開始日付 (エイリアス) */
239
+ initialLowerDate?: Date
240
+ /** Initial upper date for uncontrolled usage / 非制御時の初期ミクロ終了日付 */
241
+ defaultUpperDate?: Date
242
+ /** Initial upper date alias / 非制御時の初期ミクロ終了日付 (エイリアス) */
243
+ initialUpperDate?: Date
244
+ /** Callback triggered when micro range changes / ミクロ選択範囲変更時コールバック */
245
+ onChangeRange?: (lower: Date, upper: Date) => void
246
+ /** Callback triggered with tuple [lower, upper] when micro range changes / ミクロ選択範囲変更時タプルコールバック */
247
+ onChangeRangeTuple?: (range: [Date, Date]) => void
248
+ /** Symmetrical callback for micro range / ミクロ選択範囲変更時コールバック (対称命名) */
249
+ onChangeMicroRange?: (lower: Date, upper: Date) => void
250
+ /** Symmetrical tuple callback for micro range / ミクロ選択範囲変更時タプルコールバック (対称命名) */
251
+ onChangeMicroRangeTuple?: (range: [Date, Date]) => void
252
+ /** Symmetrical alias for micro callback / ミクロ選択範囲変更時コールバック (エイリアス) */
253
+ onChangeMicro?: (range: [Date, Date]) => void
254
+
255
+ /** Vernier scale orientation: "macro-top" (default), "macro-bottom", "macro-left", or "macro-right" / ノギス配置方向 (既定: "macro-top") */
256
+ vernierOrientation?: "macro-top" | "macro-bottom" | "macro-left" | "macro-right"
257
+ /** Show semi-transparent trapezoid projection cone between macro and micro / 台形プロジェクション光の表示 (既定: true) */
258
+ showVernierProjection?: boolean
259
+ /** Show adaptive scale ticks on macro and micro rails / アダプティブ目盛線の表示 (既定: true) */
260
+ showVernierTicks?: boolean
261
+ /** Show 1px precision hairline pointer cursor on semicircles / 精密ヘアライン針の表示 (既定: true) */
262
+ showHairline?: boolean
263
+ /** Adaptive zoom expansion animation toggle / 自動適応ズーム展開アニメーション (既定: false) */
264
+ adaptiveExpand?: boolean
265
+
266
+ /** Macro scale unit (defaults to props.unit) / マクロ側の単位 (既定: props.unit) */
267
+ macroUnit?: PeriodSliderUnit
268
+ /** Micro scale unit (defaults to props.unit) / ミクロ側の単位 (既定: props.unit) */
269
+ microUnit?: PeriodSliderUnit
270
+ /** Macro discrete mode flag / マクロ側の離散モードフラグ */
271
+ macroIsDiscrete?: boolean
272
+ /** Micro discrete mode flag / ミクロ側の離散モードフラグ */
273
+ microIsDiscrete?: boolean
274
+ /** Macro allowed discrete dates / マクロ側の離散候補日付一覧 */
275
+ macroAllowedDates?: Date[]
276
+ /** Micro allowed discrete dates / ミクロ側の離散候補日付一覧 */
277
+ microAllowedDates?: Date[]
278
+ /** Custom label formatter for macro handles and tooltip / マクロ用カスタム日付フォーマッタ */
279
+ formatMacroLabel?: (date: Date) => string
280
+ /** Custom label formatter for micro handles and tooltip / ミクロ用カスタム日付フォーマッタ */
281
+ formatMicroLabel?: (date: Date) => string
282
+
283
+ range?: never
284
+ value?: never
285
+ valueDate?: never
286
+ onChangePoint?: never
287
+ onChangeValue?: never
288
+ }
289
+
290
+ export type PeriodSliderProps = PeriodSliderRangeProps | PeriodSliderPointProps | PeriodSliderVernierProps
291
+
292
+ // ======================================================================
293
+ // 2. Pure Date & Math Utilities
294
+ // ======================================================================
295
+
296
+ /**
297
+ * Normalizes a date to the start of the specified unit.
298
+ * 指定した単位 (year, month, day) の先頭に日付を正規化します。
299
+ */
300
+ export const normalizeDateByUnit = (unit: PeriodSliderUnit, d: Date): Date => {
301
+ if (!d || Number.isNaN(d.getTime())) return new Date()
302
+ const normalized = new Date(d.getTime())
303
+ if (unit === "year") {
304
+ normalized.setMonth(0, 1)
305
+ normalized.setHours(0, 0, 0, 0)
306
+ } else if (unit === "month") {
307
+ normalized.setDate(1)
308
+ normalized.setHours(0, 0, 0, 0)
309
+ } else {
310
+ normalized.setHours(0, 0, 0, 0)
311
+ }
312
+ return normalized
313
+ }
314
+
315
+ /**
316
+ * Encodes a normalized date into a numeric integer key for efficient comparison.
317
+ * 日付を比較用数値キーにエンコードします。
318
+ */
319
+ export const encode = (unit: PeriodSliderUnit, d: Date): number => {
320
+ if (!d || Number.isNaN(d.getTime())) return 0
321
+ const norm = normalizeDateByUnit(unit, d)
322
+ const y = norm.getFullYear()
323
+ const m = norm.getMonth() + 1
324
+ const day = norm.getDate()
325
+
326
+ if (unit === "year") return y
327
+ if (unit === "month") return y * 12 + (m - 1)
328
+ return Math.floor(Date.UTC(y, m - 1, day) / (24 * 60 * 60 * 1000))
329
+ }
330
+
331
+ /**
332
+ * Decodes a numeric integer key back to a normalized Date object.
333
+ * エンコードされた数値キーから Date オブジェクトを復元します。
334
+ */
335
+ export const decode = (unit: PeriodSliderUnit, val: number): Date => {
336
+ if (unit === "year") return new Date(val, 0, 1)
337
+ if (unit === "month") {
338
+ const y = Math.floor(val / 12)
339
+ const m = val % 12
340
+ return new Date(y, m, 1)
341
+ }
342
+ const utcDate = new Date(val * 24 * 60 * 60 * 1000)
343
+ return new Date(utcDate.getUTCFullYear(), utcDate.getUTCMonth(), utcDate.getUTCDate())
344
+ }
345
+
346
+ /**
347
+ * Adds or subtracts units from a given date.
348
+ * 日付に対して単位数を加減算します。
349
+ */
350
+ export const addUnit = (unit: PeriodSliderUnit, d: Date, amount: number): Date => {
351
+ const res = new Date(d.getTime())
352
+ if (unit === "year") res.setFullYear(res.getFullYear() + amount)
353
+ else if (unit === "month") res.setMonth(res.getMonth() + amount)
354
+ else res.setDate(res.getDate() + amount)
355
+ return res
356
+ }
357
+
358
+ /**
359
+ * Calculates the end boundary of a macro window in micro unit resolution.
360
+ * When the macro unit is coarser than the micro unit, expands the date to encompass
361
+ * the full terminal span (e.g. Month -> last day of month, Year -> Dec 31 or Dec).
362
+ * マクロ側の時間単位がミクロ側より粗い場合に、末尾期間全体を包含するように終了境界日を補正する関数。
363
+ *
364
+ * @param macroUnit - Macro scale unit / マクロ側の時間解像度単位
365
+ * @param microUnit - Micro scale unit / ミクロ側の時間解像度単位
366
+ * @param d - Macro range end date / マクロ範囲の終了日付
367
+ * @returns Corrected boundary Date in micro unit resolution / 補正後のミクロ解像度終了日付
368
+ */
369
+ export const getMacroWindowEndDate = (macroUnit: PeriodSliderUnit, microUnit: PeriodSliderUnit, d: Date): Date => {
370
+ if (!d || Number.isNaN(d.getTime())) return new Date()
371
+ if (macroUnit === microUnit) {
372
+ return normalizeDateByUnit(microUnit, d)
373
+ }
374
+ const y = d.getFullYear()
375
+ const m = d.getMonth()
376
+ if (macroUnit === "year") {
377
+ if (microUnit === "month") {
378
+ return new Date(y, 11, 1)
379
+ }
380
+ if (microUnit === "day") {
381
+ return new Date(y, 11, 31)
382
+ }
383
+ }
384
+ if (macroUnit === "month" && microUnit === "day") {
385
+ return new Date(y, m + 1, 0)
386
+ }
387
+ return normalizeDateByUnit(microUnit, d)
388
+ }
389
+
390
+ /**
391
+ * Formats a Date object into a readable localized string.
392
+ * 日付を表示用文字列にフォーマットします。
393
+ */
394
+ export const formatLabel = (unit: PeriodSliderUnit, d: Date, customFormat?: (date: Date) => string): string => {
395
+ if (!d || Number.isNaN(d.getTime())) return ""
396
+ if (customFormat) return customFormat(d)
397
+ const y = d.getFullYear()
398
+ const m = String(d.getMonth() + 1).padStart(2, "0")
399
+ const day = String(d.getDate()).padStart(2, "0")
400
+ if (unit === "year") return `${y}年`
401
+ if (unit === "month") return `${y}年${m}月`
402
+ return `${y}年${m}月${day}日`
403
+ }
404
+
405
+ /**
406
+ * Generates an accessible, human-friendly label for screen readers.
407
+ * スクリーンリーダー向けの自然言語アクセシブルラベルを生成します。
408
+ *
409
+ * @param unit - The time unit of the slider
410
+ * @param d - The target date
411
+ * @param customFormat - Optional custom formatter
412
+ * @returns Human-friendly string (e.g. "2026年 9月 11日")
413
+ */
414
+ export const formatScreenReaderLabel = (unit: PeriodSliderUnit, d: Date, customFormat?: (date: Date) => string): string => {
415
+ if (!d || Number.isNaN(d.getTime())) return ""
416
+ if (customFormat) return customFormat(d)
417
+ const y = d.getFullYear()
418
+ const m = d.getMonth() + 1
419
+ const day = d.getDate()
420
+ if (unit === "year") return `${y}年`
421
+ if (unit === "month") return `${y}年 ${m}月`
422
+ return `${y}年 ${m}月 ${day}日`
423
+ }
424
+
425
+ /**
426
+ * Finds the index of the date in a sorted array closest to the target date via binary search.
427
+ * 昇順ソート済み日付配列の中から、対象日付に最も近い要素のインデックスを二分探索 ($O(\log N)$) で算出します。
428
+ */
429
+ export const findNearestDateIndex = (dates: Date[], target: Date, unit: PeriodSliderUnit): number => {
430
+ if (!dates || dates.length === 0) return 0
431
+ if (dates.length === 1) return 0
432
+
433
+ const targetEnc = encode(unit, target)
434
+ let low = 0
435
+ let high = dates.length - 1
436
+
437
+ if (targetEnc <= encode(unit, dates[low])) return 0
438
+ if (targetEnc >= encode(unit, dates[high])) return high
439
+
440
+ while (low <= high) {
441
+ const mid = (low + high) >> 1
442
+ const midEnc = encode(unit, dates[mid])
443
+
444
+ if (midEnc === targetEnc) return mid
445
+ if (midEnc < targetEnc) {
446
+ low = mid + 1
447
+ } else {
448
+ high = mid - 1
449
+ }
450
+ }
451
+
452
+ const lowDiff = Math.abs(encode(unit, dates[low]) - targetEnc)
453
+ const highDiff = Math.abs(encode(unit, dates[high]) - targetEnc)
454
+ return lowDiff < highDiff ? low : high
455
+ }
456
+
457
+ /**
458
+ * Pre-processes, normalizes, deduplicates, and sorts discrete dates.
459
+ * 離散日付配列を事前処理・正規化・重複排除・昇順ソートします。
460
+ */
461
+ export const getSortedAllowedDates = (allowedDates: Date[] | undefined, unit: PeriodSliderUnit, minDate?: Date, maxDate?: Date): Date[] => {
462
+ if (!Array.isArray(allowedDates) || allowedDates.length === 0) return []
463
+
464
+ const validDates = allowedDates.filter((d) => d && !Number.isNaN(d.getTime())).map((d) => normalizeDateByUnit(unit, d))
465
+
466
+ if (validDates.length === 0) return []
467
+
468
+ const encMap = new Map<number, Date>()
469
+ for (const d of validDates) {
470
+ const enc = encode(unit, d)
471
+ if (!encMap.has(enc)) {
472
+ encMap.set(enc, d)
473
+ }
474
+ }
475
+
476
+ const sortedEncs = Array.from(encMap.keys()).sort((a, b) => a - b)
477
+ let filteredDates = sortedEncs.map((enc) => encMap.get(enc)).filter((d): d is Date => d !== undefined)
478
+
479
+ if (minDate && !Number.isNaN(minDate.getTime())) {
480
+ const minEnc = encode(unit, minDate)
481
+ filteredDates = filteredDates.filter((d) => encode(unit, d) >= minEnc)
482
+ }
483
+ if (maxDate && !Number.isNaN(maxDate.getTime())) {
484
+ const maxEnc = encode(unit, maxDate)
485
+ filteredDates = filteredDates.filter((d) => encode(unit, d) <= maxEnc)
486
+ }
487
+
488
+ return filteredDates
489
+ }
490
+
491
+ /**
492
+ * Calculates dragging values when dragging knob handles.
493
+ * ハンドルドラッグ時の数値を算出します。
494
+ */
495
+ export const calculateHandleDragValues = (handle: "low" | "high", clampedVal: number, startLowVal: number, startHighVal: number, rangeMin: number, rangeMax: number, isPointMode: boolean): [number, number] => {
496
+ let nextLow = startLowVal
497
+ let nextHigh = startHighVal
498
+
499
+ if (isPointMode) {
500
+ nextLow = clampedVal
501
+ nextHigh = clampedVal
502
+ } else if (handle === "low") {
503
+ if (clampedVal > startHighVal) {
504
+ nextLow = startHighVal
505
+ nextHigh = clampedVal
506
+ } else {
507
+ nextLow = clampedVal
508
+ }
509
+ } else {
510
+ if (clampedVal < startLowVal) {
511
+ nextHigh = startLowVal
512
+ nextLow = clampedVal
513
+ } else {
514
+ nextHigh = clampedVal
515
+ }
516
+ }
517
+
518
+ return [Math.max(rangeMin, Math.min(rangeMax, nextLow)), Math.max(rangeMin, Math.min(rangeMax, nextHigh))]
519
+ }
520
+
521
+ /**
522
+ * Determines which handle ('low' or 'high') is actively under the pointer when dragging.
523
+ * ドラッグ操作中にポインターが現在操作しているハンドル ('low' または 'high') の判定。
524
+ *
525
+ * @param originalHandle - Originally grabbed handle on pointerdown ('low' or 'high')
526
+ * @param pointerVal - Current value calculated from pointer position
527
+ * @param startLowVal - Initial low value when drag began
528
+ * @param startHighVal - Initial high value when drag began
529
+ * @param isPointMode - Whether slider is in single-point mode
530
+ * @returns Handle name corresponding to the active pointer position
531
+ */
532
+ export const getActiveDragHandle = (originalHandle: "low" | "high", pointerVal: number, startLowVal: number, startHighVal: number, isPointMode: boolean): "low" | "high" => {
533
+ if (isPointMode) return "low"
534
+ if (originalHandle === "low") {
535
+ return pointerVal > startHighVal ? "high" : "low"
536
+ }
537
+ return pointerVal < startLowVal ? "low" : "high"
538
+ }
539
+
540
+ /**
541
+ * Computes dragging values when translating/dragging the connection bar.
542
+ * 接続バー並進ドラッグ時の数値を算出します。
543
+ */
544
+ export const calculateConnectDragValues = (posDiffPct: number, startLowVal: number, startHighVal: number, rangeMin: number, rangeMax: number, isDiscrete: boolean, sortedAllowedDates: Date[]): [number, number] | null => {
545
+ const rangeSpan = rangeMax - rangeMin
546
+ if (rangeSpan <= 0) return null
547
+
548
+ if (isDiscrete) {
549
+ const indexShift = Math.round(posDiffPct * (sortedAllowedDates.length - 1))
550
+ if (indexShift === 0) return null
551
+
552
+ let nextLowIdx = startLowVal + indexShift
553
+ let nextHighIdx = startHighVal + indexShift
554
+
555
+ if (nextLowIdx < 0) {
556
+ nextHighIdx += -nextLowIdx
557
+ nextLowIdx = 0
558
+ }
559
+ if (nextHighIdx > sortedAllowedDates.length - 1) {
560
+ nextLowIdx -= nextHighIdx - (sortedAllowedDates.length - 1)
561
+ nextHighIdx = sortedAllowedDates.length - 1
562
+ }
563
+
564
+ nextLowIdx = Math.max(0, Math.min(sortedAllowedDates.length - 1, nextLowIdx))
565
+ nextHighIdx = Math.max(0, Math.min(sortedAllowedDates.length - 1, nextHighIdx))
566
+
567
+ return [nextLowIdx, nextHighIdx]
568
+ }
569
+
570
+ const encDiff = Math.round(posDiffPct * rangeSpan)
571
+ if (encDiff === 0) return null
572
+
573
+ let nextLowEnc = startLowVal + encDiff
574
+ let nextHighEnc = startHighVal + encDiff
575
+
576
+ if (nextLowEnc < rangeMin) {
577
+ nextHighEnc += rangeMin - nextLowEnc
578
+ nextLowEnc = rangeMin
579
+ }
580
+ if (nextHighEnc > rangeMax) {
581
+ nextLowEnc -= nextHighEnc - rangeMax
582
+ nextHighEnc = rangeMax
583
+ }
584
+
585
+ nextLowEnc = Math.max(rangeMin, Math.min(rangeMax, nextLowEnc))
586
+ nextHighEnc = Math.max(rangeMin, Math.min(rangeMax, nextHighEnc))
587
+
588
+ return [nextLowEnc, nextHighEnc]
589
+ }
590
+
591
+ /**
592
+ * Calculates the next [low, high] values based on keyboard input.
593
+ * キーボード操作時の移動先数値を算出します。
594
+ */
595
+ export const calculateKeyboardActionValues = (key: string, handle: "low" | "high", lowVal: number, highVal: number, rangeMin: number, rangeMax: number, isPointMode: boolean, step: number): [number, number] | null => {
596
+ let delta = 0
597
+ let isHome = false
598
+ let isEnd = false
599
+
600
+ switch (key) {
601
+ case "ArrowRight":
602
+ case "ArrowUp":
603
+ delta = step
604
+ break
605
+ case "ArrowLeft":
606
+ case "ArrowDown":
607
+ delta = -step
608
+ break
609
+ case "PageUp":
610
+ delta = step * 5
611
+ break
612
+ case "PageDown":
613
+ delta = -step * 5
614
+ break
615
+ case "Home":
616
+ isHome = true
617
+ break
618
+ case "End":
619
+ isEnd = true
620
+ break
621
+ default:
622
+ return null
623
+ }
624
+
625
+ if (isPointMode) {
626
+ let target = lowVal
627
+ if (isHome) target = rangeMin
628
+ else if (isEnd) target = rangeMax
629
+ else target = Math.max(rangeMin, Math.min(rangeMax, lowVal + delta))
630
+ return [target, target]
631
+ }
632
+
633
+ let targetLow = lowVal
634
+ let targetHigh = highVal
635
+
636
+ if (handle === "low") {
637
+ if (isHome) targetLow = rangeMin
638
+ else if (isEnd) targetLow = highVal
639
+ else targetLow = Math.max(rangeMin, Math.min(highVal, lowVal + delta))
640
+ } else {
641
+ if (isHome) targetHigh = lowVal
642
+ else if (isEnd) targetHigh = rangeMax
643
+ else targetHigh = Math.max(lowVal, Math.min(rangeMax, highVal + delta))
644
+ }
645
+
646
+ return [targetLow, targetHigh]
647
+ }
648
+
649
+ /**
650
+ * Mathematically calculates smooth rotation angle and offsets to prevent label collision in range mode.
651
+ * Range モードにおいて、2つのつまみラベルの重複を回避するための滑らかな回転角とオフセットを数学的に計算します。
652
+ *
653
+ * Ken Perlin's Smootherstep function S(u) = 6u^5 - 15u^4 + 10u^3 ensures C^2 continuity (smooth acceleration and zero jerk).
654
+ *
655
+ * @param lowPct - Percent position of lower handle (0-100)
656
+ * @param highPct - Percent position of upper handle (0-100)
657
+ * @param trackWidthPx - Measured pixel width of the track (falls back to 400 if 0 or unavailable)
658
+ * @param labelPosition - "top" or "bottom"
659
+ * @param unit - "year" | "month" | "day"
660
+ * @param config - Optional configuration for fine-tuning
661
+ */
662
+ export const calculateLabelSlant = (lowPct: number, highPct: number, trackWidthPx: number, labelPosition: PeriodSliderLabelPosition = "top", unit: PeriodSliderUnit = "day", config?: LabelSlantConfig): LabelSlantResult => {
663
+ const width = trackWidthPx > 0 ? trackWidthPx : 400
664
+ const pixelDistance = (Math.max(0, highPct - lowPct) / 100) * width
665
+
666
+ // Unit-based default label widths based on actual rendered dimensions
667
+ const defaultWidth = unit === "year" ? 48 : unit === "month" ? 68 : 90
668
+ const labelWidth = config?.estimatedWidthPx ?? defaultWidth
669
+ const labelHeight = config?.estimatedHeightPx ?? 16
670
+ const padding = config?.paddingPx ?? 12
671
+ const maxAngle = config?.maxAngleDeg ?? 90
672
+
673
+ // Knob radius is 8px (16px knob diameter). Target gap between knob edge and label is 2px.
674
+ // Unified baseline clearance from track center: knobRadius (8px) + visualGap (2px) = 10px.
675
+ const knobRadius = 8
676
+ const visualGap = config?.anchorGapY !== undefined ? config.anchorGapY : 2
677
+ const clearance = knobRadius + visualGap
678
+
679
+ // Base vertical center offset when horizontal (clearance 10px + labelHeight / 2 = 18px)
680
+ const baseCenterDist = clearance + labelHeight / 2
681
+ const baseOffsetY = labelPosition === "top" ? -baseCenterDist : baseCenterDist
682
+
683
+ // Threshold distance below which collision avoidance activates
684
+ const threshold = labelWidth + padding
685
+
686
+ if (pixelDistance >= threshold) {
687
+ return {
688
+ lowAngleDeg: 0,
689
+ highAngleDeg: 0,
690
+ lowOffsetX: 0,
691
+ highOffsetX: 0,
692
+ lowOffsetY: baseOffsetY,
693
+ highOffsetY: baseOffsetY,
694
+ isSlanted: false,
695
+ proximity: 0,
696
+ }
697
+ }
698
+
699
+ // Normalized proximity factor u in [0, 1]
700
+ const u = Math.max(0, Math.min(1, (threshold - pixelDistance) / threshold))
701
+
702
+ // Ken Perlin's Smootherstep function for continuous C^2 smooth transitions: S(u) = 6u^5 - 15u^4 + 10u^3
703
+ const smoothFactor = u * u * u * (u * (u * 6 - 15) + 10)
704
+
705
+ const angle = smoothFactor * maxAngle
706
+
707
+ // Same direction rotation for both labels:
708
+ // Top position: tilts counter-clockwise (upwards) up to -90deg
709
+ // Bottom position: tilts clockwise (downwards) up to +90deg
710
+ const signedAngle = labelPosition === "top" ? -angle : angle
711
+
712
+ // Mathematically calculate rotated bounding-box half-height: y'max(θ) = (W/2)*|sin θ| + (H/2)*|cos θ|
713
+ // The center offset needed when rotated to keep the lowest edge stationary at clearance (10px from track center)
714
+ // is (clearance + halfHeightRotated)
715
+ const rad = (angle * Math.PI) / 180
716
+ const halfHeightRotated = (labelWidth / 2) * Math.abs(Math.sin(rad)) + (labelHeight / 2) * Math.abs(Math.cos(rad))
717
+ const calculatedCenterDist = clearance + halfHeightRotated
718
+ const calculatedOffsetY = labelPosition === "top" ? -calculatedCenterDist : +calculatedCenterDist
719
+
720
+ // Parallel slit clearance when approaching 90 degrees:
721
+ // When vertical (90 deg), the label's horizontal occupation is labelHeight (16px).
722
+ // The required center-to-center clearance between parallel slits is minCenterDist = labelHeight + slitGap (20px).
723
+ // If the actual handle distance is smaller than this clearance, distribute the deficit horizontally.
724
+ const slitGap = 4
725
+ const minCenterDist = labelHeight + slitGap
726
+ const deficit = Math.max(0, minCenterDist - pixelDistance)
727
+ const shiftX = smoothFactor * (deficit / 2)
728
+
729
+ return {
730
+ lowAngleDeg: signedAngle,
731
+ highAngleDeg: signedAngle,
732
+ lowOffsetX: -shiftX,
733
+ highOffsetX: shiftX,
734
+ lowOffsetY: calculatedOffsetY,
735
+ highOffsetY: calculatedOffsetY,
736
+ isSlanted: u > 0.001,
737
+ proximity: u,
738
+ }
739
+ }
740
+
741
+ export type VernierHandle = "macro-low" | "macro-high" | "macro-connect" | "micro-low" | "micro-high" | "micro-connect"
742
+
743
+ /**
744
+ * Resolves the target Vernier handle based on pointer primary-axis ratio and cross-axis offset relative to track center.
745
+ * トラック中心線に対するポインターの直交軸オフセットと主軸比率から、操作対象となるノギスハンドル(マクロまたはミクロ)を判定します。
746
+ */
747
+ export function resolveVernierTargetHandle(
748
+ pointerPrimaryRatio: number,
749
+ pointerCrossAxisOffset: number,
750
+ macroLowRatio: number,
751
+ macroHighRatio: number,
752
+ microLowRatio: number,
753
+ microHighRatio: number,
754
+ orientation: "macro-top" | "macro-bottom" | "macro-left" | "macro-right" = "macro-top",
755
+ handleHitSlopRatio: number = 0.05,
756
+ ): VernierHandle {
757
+ // orientation に応じて第一レール(上段または左段)がマクロかミクロかを決定
758
+ const isFirstRailMacro = orientation === "macro-top" || orientation === "macro-left"
759
+ const isTargetingFirstRail = pointerCrossAxisOffset <= 0
760
+
761
+ if ((isFirstRailMacro && isTargetingFirstRail) || !(isFirstRailMacro || isTargetingFirstRail)) {
762
+ // マクロ操作ゾーン
763
+ const distLow = Math.abs(pointerPrimaryRatio - macroLowRatio)
764
+ const distHigh = Math.abs(pointerPrimaryRatio - macroHighRatio)
765
+
766
+ if (distLow <= handleHitSlopRatio && distLow <= distHigh) {
767
+ return "macro-low"
768
+ }
769
+ if (distHigh <= handleHitSlopRatio && distHigh < distLow) {
770
+ return "macro-high"
771
+ }
772
+ if (pointerPrimaryRatio >= macroLowRatio && pointerPrimaryRatio <= macroHighRatio) {
773
+ return "macro-connect"
774
+ }
775
+ return distLow < distHigh ? "macro-low" : "macro-high"
776
+ }
777
+
778
+ // ミクロ操作ゾーン
779
+ const distLow = Math.abs(pointerPrimaryRatio - microLowRatio)
780
+ const distHigh = Math.abs(pointerPrimaryRatio - microHighRatio)
781
+
782
+ if (distLow <= handleHitSlopRatio && distLow <= distHigh) {
783
+ return "micro-low"
784
+ }
785
+ if (distHigh <= handleHitSlopRatio && distHigh < distLow) {
786
+ return "micro-high"
787
+ }
788
+ if (pointerPrimaryRatio >= microLowRatio && pointerPrimaryRatio <= microHighRatio) {
789
+ return "micro-connect"
790
+ }
791
+ return distLow < distHigh ? "micro-low" : "micro-high"
792
+ }
793
+
794
+ /**
795
+ * Calculates updated macro window range when dragging a macro handle or connect bar, supporting crossover swapping.
796
+ * マクロハンドルまたはコネクトバードラッグ時の新マクロ範囲を算出します (上限下限反転スワップ対応)。
797
+ *
798
+ * @param handle - Dragged macro handle or connect bar
799
+ * @param pointerRatio - Current pointer ratio across track (0.0 - 1.0)
800
+ * @param startPointerRatio - Initial pointer ratio at drag start
801
+ * @param startMacroLowRatio - Initial macro low ratio at drag start
802
+ * @param startMacroHighRatio - Initial macro high ratio at drag start
803
+ * @returns Tuple of [nextLowRatio, nextHighRatio, activeHandle]
804
+ */
805
+ export function calculateVernierMacroDrag(handle: "macro-low" | "macro-high" | "macro-connect", pointerRatio: number, startPointerRatio: number, startMacroLowRatio: number, startMacroHighRatio: number): [number, number, "macro-low" | "macro-high" | "macro-connect"] {
806
+ if (handle === "macro-connect") {
807
+ const delta = pointerRatio - startPointerRatio
808
+ const width = startMacroHighRatio - startMacroLowRatio
809
+ const nextLow = Math.max(0, Math.min(1 - width, startMacroLowRatio + delta))
810
+ const nextHigh = nextLow + width
811
+ return [nextLow, nextHigh, "macro-connect"]
812
+ }
813
+ if (handle === "macro-low") {
814
+ const clamped = Math.max(0, Math.min(1, pointerRatio))
815
+ if (clamped > startMacroHighRatio) {
816
+ return [startMacroHighRatio, clamped, "macro-high"]
817
+ }
818
+ return [clamped, startMacroHighRatio, "macro-low"]
819
+ }
820
+ // macro-high
821
+ const clamped = Math.max(0, Math.min(1, pointerRatio))
822
+ if (clamped < startMacroLowRatio) {
823
+ return [clamped, startMacroLowRatio, "macro-low"]
824
+ }
825
+ return [startMacroLowRatio, clamped, "macro-high"]
826
+ }
827
+
828
+ /**
829
+ * Calculates updated micro selection range when dragging a micro handle or connect bar, supporting crossover swapping.
830
+ * ミクロハンドルまたはコネクトバードラッグ時の新ミクロ範囲を算出します (上限下限反転スワップ対応)。
831
+ *
832
+ * @param handle - Dragged micro handle or connect bar
833
+ * @param pointerRatio - Current pointer ratio across track (0.0 - 1.0)
834
+ * @param startPointerRatio - Initial pointer ratio at drag start
835
+ * @param startMicroLowRatio - Initial micro low ratio at drag start
836
+ * @param startMicroHighRatio - Initial micro high ratio at drag start
837
+ * @returns Tuple of [nextLowRatio, nextHighRatio, activeHandle]
838
+ */
839
+ export function calculateVernierMicroDrag(handle: "micro-low" | "micro-high" | "micro-connect", pointerRatio: number, startPointerRatio: number, startMicroLowRatio: number, startMicroHighRatio: number): [number, number, "micro-low" | "micro-high" | "micro-connect"] {
840
+ if (handle === "micro-connect") {
841
+ const delta = pointerRatio - startPointerRatio
842
+ const width = startMicroHighRatio - startMicroLowRatio
843
+ const nextLow = Math.max(0, Math.min(1 - width, startMicroLowRatio + delta))
844
+ const nextHigh = nextLow + width
845
+ return [nextLow, nextHigh, "micro-connect"]
846
+ }
847
+ if (handle === "micro-low") {
848
+ const clamped = Math.max(0, Math.min(1, pointerRatio))
849
+ if (clamped > startMicroHighRatio) {
850
+ return [startMicroHighRatio, clamped, "micro-high"]
851
+ }
852
+ return [clamped, startMicroHighRatio, "micro-low"]
853
+ }
854
+ // micro-high
855
+ const clamped = Math.max(0, Math.min(1, pointerRatio))
856
+ if (clamped < startMicroLowRatio) {
857
+ return [clamped, startMicroLowRatio, "micro-low"]
858
+ }
859
+ return [startMicroLowRatio, clamped, "micro-high"]
860
+ }
861
+
862
+ /**
863
+ * SVG vector semicircle knob for Vernier caliper handles.
864
+ * Rendered using mathematical arc commands to guarantee perfectly smooth round edges without raster distortion.
865
+ * ノギス半円つまみ用 SVG ベクター幾何学ドーム描画コンポーネント。
866
+ */
867
+ export const VernierKnobSvg = memo<{
868
+ type: "macro" | "micro"
869
+ isTop?: boolean
870
+ isVertical?: boolean
871
+ isLeft?: boolean
872
+ }>(({ type, isTop = true, isVertical = false, isLeft = true }) => {
873
+ // ストローク幅 1.25px において外径を厳密に 16.0px (半径 8.0px) に収める:
874
+ // パス中心半径 R = 8.0 - (1.25 / 2) = 7.375px
875
+ // 始点 = 0.625px, 終点 = 15.375px (スパン 14.75px + 1.25px = 16.0px)
876
+ // 底面境界はストロークのめり込みを防ぐため Y = 7.375 (外端 8.0px) にアライメント
877
+ let pathD: string
878
+ let knobClass: string
879
+
880
+ if (isVertical) {
881
+ pathD = isLeft ? "M 7.375 0.625 A 7.375 7.375 0 0 0 7.375 15.375 Z" : "M 0.625 0.625 A 7.375 7.375 0 0 1 0.625 15.375 Z"
882
+ knobClass = `period-slider-knob period-slider-knob-svg is-vertical ${isLeft ? "is-semicircle-left" : "is-semicircle-right"}`
883
+ } else {
884
+ pathD = isTop ? "M 0.625 7.375 A 7.375 7.375 0 0 1 15.375 7.375 Z" : "M 0.625 0.625 A 7.375 7.375 0 0 0 15.375 0.625 Z"
885
+ knobClass = `period-slider-knob period-slider-knob-svg ${isTop ? "is-semicircle-top" : "is-semicircle-bottom"}`
886
+ }
887
+
888
+ const pathClass = type === "macro" ? "period-slider-knob-path-macro" : "period-slider-knob-path-micro"
889
+
890
+ return (
891
+ <svg className={knobClass} width={isVertical ? "8" : "16"} height={isVertical ? "16" : "8"} viewBox={isVertical ? "0 0 8 16" : "0 0 16 8"} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
892
+ <path d={pathD} className={pathClass} shapeRendering="geometricPrecision" strokeWidth="1.25" />
893
+ </svg>
894
+ )
895
+ })
896
+ VernierKnobSvg.displayName = "VernierKnobSvg"
897
+
898
+ // ======================================================================
899
+ // 3. React Component Implementation
900
+ // ======================================================================
901
+
902
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Vernier integrated multi-mode scale requires comprehensive coordinate handling
903
+ const PeriodSliderComponent: React.FC<PeriodSliderProps> = (props) => {
904
+ const {
905
+ unit,
906
+ minDate,
907
+ maxDate,
908
+ allowedDates,
909
+ snapMode = "index",
910
+ disabled = false,
911
+ className = "",
912
+ showStepper = true,
913
+ tooltipStyle = "always",
914
+ labelPosition = "top",
915
+ autoSlantLabels = true,
916
+ isVertical = false,
917
+ hideConnectBar = false,
918
+ showTicks = false,
919
+ colorScheme = "blue-rose",
920
+ } = props
921
+
922
+ const palette = COLOR_SCHEME_PALETTES[colorScheme] ?? COLOR_SCHEME_PALETTES["blue-rose"]
923
+ const vernierGradId = useId()
924
+
925
+ const propsRef = useRef(props)
926
+ propsRef.current = props
927
+
928
+ const minTime = minDate?.getTime()
929
+ const maxTime = maxDate?.getTime()
930
+
931
+ // ------------------------------------------------------------------
932
+ // A. Pre-processed Discrete Dates & Range Bounds
933
+ // ------------------------------------------------------------------
934
+ const sortedAllowedDates = useMemo(() => {
935
+ return getSortedAllowedDates(allowedDates, unit, minDate, maxDate)
936
+ }, [allowedDates, unit, minTime, maxTime])
937
+
938
+ const isDiscrete = sortedAllowedDates.length > 0
939
+
940
+ const { rangeMin, rangeMax } = useMemo(() => {
941
+ if (isDiscrete) {
942
+ return { rangeMin: 0, rangeMax: sortedAllowedDates.length - 1 }
943
+ }
944
+ const defaultMin = normalizeDateByUnit(unit, minDate ?? new Date(2020, 0, 1))
945
+ let defaultMax = normalizeDateByUnit(unit, maxDate ?? new Date(2030, 0, 1))
946
+
947
+ const minEnc = encode(unit, defaultMin)
948
+ let maxEnc = encode(unit, defaultMax)
949
+
950
+ if (maxEnc <= minEnc) {
951
+ defaultMax = addUnit(unit, defaultMin, 1)
952
+ maxEnc = encode(unit, defaultMax)
953
+ }
954
+
955
+ return { rangeMin: minEnc, rangeMax: maxEnc }
956
+ }, [isDiscrete, sortedAllowedDates, unit, minTime, maxTime])
957
+
958
+ const isPointMode = props.mode === "point"
959
+
960
+ // ------------------------------------------------------------------
961
+ // B. Value Transformation Converters
962
+ // ------------------------------------------------------------------
963
+ const valueToDate = useCallback(
964
+ (val: number): Date => {
965
+ if (isDiscrete) {
966
+ const idx = Math.max(0, Math.min(sortedAllowedDates.length - 1, Math.round(val)))
967
+ return sortedAllowedDates[idx] ?? new Date()
968
+ }
969
+ return decode(unit, Math.round(val))
970
+ },
971
+ [isDiscrete, sortedAllowedDates, unit],
972
+ )
973
+
974
+ const dateToValue = useCallback(
975
+ (d?: Date): number => {
976
+ if (!d || Number.isNaN(d.getTime())) return rangeMin
977
+ const norm = normalizeDateByUnit(unit, d)
978
+ if (isDiscrete) {
979
+ return findNearestDateIndex(sortedAllowedDates, norm, unit)
980
+ }
981
+ return encode(unit, norm)
982
+ },
983
+ [isDiscrete, sortedAllowedDates, unit, rangeMin],
984
+ )
985
+
986
+ // ------------------------------------------------------------------
987
+ // C. Internal State Initialization & Sync
988
+ // ------------------------------------------------------------------
989
+ const effectiveLowerDate: Date | undefined =
990
+ props.mode === "range"
991
+ ? props.range
992
+ ? props.range[0]
993
+ : (props.lowerDate ?? props.defaultRange?.[0] ?? props.initialRange?.[0] ?? props.defaultLowerDate ?? props.initialLowerDate)
994
+ : props.mode === "vernier"
995
+ ? props.microRange
996
+ ? props.microRange[0]
997
+ : (props.lowerDate ?? props.defaultMicroRange?.[0] ?? props.initialMicroRange?.[0] ?? props.defaultLowerDate ?? props.initialLowerDate)
998
+ : undefined
999
+
1000
+ const effectiveUpperDate: Date | undefined =
1001
+ props.mode === "range"
1002
+ ? props.range
1003
+ ? props.range[1]
1004
+ : (props.upperDate ?? props.defaultRange?.[1] ?? props.initialRange?.[1] ?? props.defaultUpperDate ?? props.initialUpperDate)
1005
+ : props.mode === "vernier"
1006
+ ? props.microRange
1007
+ ? props.microRange[1]
1008
+ : (props.upperDate ?? props.defaultMicroRange?.[1] ?? props.initialMicroRange?.[1] ?? props.defaultUpperDate ?? props.initialUpperDate)
1009
+ : undefined
1010
+
1011
+ const effectivePointDate: Date | undefined = props.mode === "point" ? (props.value ?? props.valueDate ?? props.defaultValue ?? props.initialDate) : undefined
1012
+
1013
+ const safeLowerDate = effectiveLowerDate ?? (isDiscrete ? sortedAllowedDates[0] : decode(unit, rangeMin))
1014
+ const safeUpperDate = effectiveUpperDate ?? (isDiscrete ? sortedAllowedDates[sortedAllowedDates.length - 1] : decode(unit, rangeMax))
1015
+
1016
+ const propLowerMs = props.mode === "point" ? effectivePointDate?.getTime() : effectiveLowerDate?.getTime()
1017
+ const propUpperMs = props.mode === "range" ? effectiveUpperDate?.getTime() : propLowerMs
1018
+
1019
+ const [initLow, initHigh] = useMemo((): [number, number] => {
1020
+ if (props.mode === "point") {
1021
+ const val = dateToValue(effectivePointDate)
1022
+ return [val, val]
1023
+ }
1024
+ const lowVal = dateToValue(effectiveLowerDate)
1025
+ const highVal = dateToValue(effectiveUpperDate)
1026
+ return [Math.min(lowVal, highVal), Math.max(lowVal, highVal)]
1027
+ }, [props.mode, propLowerMs, propUpperMs, dateToValue, effectivePointDate, effectiveLowerDate, effectiveUpperDate])
1028
+
1029
+ // 非制御 (Uncontrolled) 運用時の自律ステート管理
1030
+ const isControlled =
1031
+ props.mode === "point"
1032
+ ? props.value !== undefined || props.valueDate !== undefined
1033
+ : props.mode === "range"
1034
+ ? props.range !== undefined || props.lowerDate !== undefined || props.upperDate !== undefined
1035
+ : props.microRange !== undefined || props.lowerDate !== undefined || props.upperDate !== undefined
1036
+
1037
+ const [uncontrolledValues, setUncontrolledValues] = useState<[number, number]>(() => [initLow, initHigh])
1038
+
1039
+ useEffect(() => {
1040
+ if (isControlled) {
1041
+ setUncontrolledValues([initLow, initHigh])
1042
+ }
1043
+ }, [isControlled, initLow, initHigh])
1044
+
1045
+ const [draggingValues, setDraggingValues] = useState<[number, number] | null>(null)
1046
+ const [activeHandle, setActiveHandle] = useState<"low" | "high" | "connect" | null>(null)
1047
+ const activeHandleRef = useRef<"low" | "high" | "connect" | null>(null)
1048
+ activeHandleRef.current = activeHandle
1049
+ const [frontHandle, setFrontHandle] = useState<"low" | "high">("high")
1050
+
1051
+ const [hoverValue, setHoverValue] = useState<number | null>(null)
1052
+ const [hoverPct, setHoverPct] = useState<number | null>(null)
1053
+
1054
+ const currentLowVal = draggingValues ? draggingValues[0] : isControlled ? initLow : uncontrolledValues[0]
1055
+ const currentHighVal = draggingValues ? draggingValues[1] : isControlled ? initHigh : uncontrolledValues[1]
1056
+
1057
+ // ------------------------------------------------------------------
1058
+ // C-2. Vernier Scale Bounds & Drag State
1059
+ // ------------------------------------------------------------------
1060
+ const isVernierMode = props.mode === "vernier"
1061
+ const vernierOrientation = props.mode === "vernier" ? (props.vernierOrientation ?? (isVertical ? "macro-left" : "macro-top")) : "macro-top"
1062
+ const isMacroFirstRail = vernierOrientation === "macro-top" || vernierOrientation === "macro-left"
1063
+ const showVernierProjection = props.mode === "vernier" ? (props.showVernierProjection ?? true) : false
1064
+ const showVernierTicks = props.mode === "vernier" ? (props.showVernierTicks ?? true) : false
1065
+ const showHairline = props.mode === "vernier" ? (props.showHairline ?? true) : false
1066
+
1067
+ const macroUnit: PeriodSliderUnit = isVernierMode ? ((props as PeriodSliderVernierProps).macroUnit ?? unit) : unit
1068
+ const microUnit: PeriodSliderUnit = isVernierMode ? ((props as PeriodSliderVernierProps).microUnit ?? unit) : unit
1069
+
1070
+ const macroIsDiscrete = isVernierMode ? ((props as PeriodSliderVernierProps).macroIsDiscrete ?? false) : isDiscrete
1071
+ const microIsDiscrete = isVernierMode ? ((props as PeriodSliderVernierProps).microIsDiscrete ?? false) : isDiscrete
1072
+
1073
+ const macroAllowedDates = isVernierMode ? ((props as PeriodSliderVernierProps).macroAllowedDates ?? allowedDates) : allowedDates
1074
+ const microAllowedDates = isVernierMode ? ((props as PeriodSliderVernierProps).microAllowedDates ?? allowedDates) : allowedDates
1075
+
1076
+ const formatMacroLabel = isVernierMode ? ((props as PeriodSliderVernierProps).formatMacroLabel ?? props.formatLabel) : props.formatLabel
1077
+ const formatMicroLabel = isVernierMode ? ((props as PeriodSliderVernierProps).formatMicroLabel ?? props.formatLabel) : props.formatLabel
1078
+
1079
+ const macroRangeStartMs = isVernierMode && (props as PeriodSliderVernierProps).macroRange ? (props as PeriodSliderVernierProps).macroRange[0]?.getTime() : undefined
1080
+ const macroRangeEndMs = isVernierMode && (props as PeriodSliderVernierProps).macroRange ? (props as PeriodSliderVernierProps).macroRange[1]?.getTime() : undefined
1081
+ const lowerDateMs = props.mode !== "point" ? props.lowerDate?.getTime() : undefined
1082
+ const upperDateMs = props.mode !== "point" ? props.upperDate?.getTime() : undefined
1083
+
1084
+ const [activeVernierHandle, setActiveVernierHandle] = useState<VernierHandle | null>(null)
1085
+ const activeVernierHandleRef = useRef<VernierHandle | null>(null)
1086
+ activeVernierHandleRef.current = activeVernierHandle
1087
+ const [frontVernierHandle, setFrontVernierHandle] = useState<VernierHandle>("micro-high")
1088
+
1089
+ // マクロ境界
1090
+ const vernierMacroMinEnc = useMemo(() => {
1091
+ if (!isVernierMode) return 0
1092
+ return encode(macroUnit, normalizeDateByUnit(macroUnit, minDate ?? new Date(2020, 0, 1)))
1093
+ }, [isVernierMode, minTime, macroUnit, minDate])
1094
+
1095
+ const vernierMacroMaxEnc = useMemo(() => {
1096
+ if (!isVernierMode) return 1
1097
+ const maxNorm = normalizeDateByUnit(macroUnit, maxDate ?? new Date(2030, 0, 1))
1098
+ const maxEnc = encode(macroUnit, maxNorm)
1099
+ return maxEnc <= vernierMacroMinEnc ? vernierMacroMinEnc + 1 : maxEnc
1100
+ }, [isVernierMode, maxTime, vernierMacroMinEnc, macroUnit, maxDate])
1101
+
1102
+ const sortedMacroAllowedDates = useMemo(() => {
1103
+ if (!isVernierMode) return []
1104
+ return getSortedAllowedDates(macroAllowedDates, macroUnit, minDate, maxDate)
1105
+ }, [isVernierMode, macroAllowedDates, macroUnit, minDate, maxDate])
1106
+
1107
+ const sortedMicroAllowedDates = useMemo(() => {
1108
+ if (!isVernierMode) return []
1109
+ return getSortedAllowedDates(microAllowedDates, microUnit, minDate, maxDate)
1110
+ }, [isVernierMode, microAllowedDates, microUnit, minDate, maxDate])
1111
+
1112
+ const vernierMacroLowEnc = useMemo(() => {
1113
+ if (!(isVernierMode && props.macroRange)) return vernierMacroMinEnc
1114
+ return encode(macroUnit, normalizeDateByUnit(macroUnit, props.macroRange[0]))
1115
+ }, [isVernierMode, macroRangeStartMs, vernierMacroMinEnc, macroUnit])
1116
+
1117
+ const vernierMacroHighEnc = useMemo(() => {
1118
+ if (!(isVernierMode && props.macroRange)) return vernierMacroMaxEnc
1119
+ return encode(macroUnit, normalizeDateByUnit(macroUnit, props.macroRange[1]))
1120
+ }, [isVernierMode, macroRangeEndMs, vernierMacroMaxEnc, macroUnit])
1121
+
1122
+ // ミクロ境界 (マクロ窓がミクロのスケール範囲)
1123
+ const vernierMicroMinEnc = useMemo(() => {
1124
+ if (!(isVernierMode && props.macroRange)) return 0
1125
+ return encode(microUnit, normalizeDateByUnit(microUnit, props.macroRange[0]))
1126
+ }, [isVernierMode, macroRangeStartMs, microUnit])
1127
+
1128
+ const vernierMicroMaxEnc = useMemo(() => {
1129
+ if (!(isVernierMode && props.macroRange)) return 1
1130
+ const macroEnd = getMacroWindowEndDate(macroUnit, microUnit, props.macroRange[1])
1131
+ const maxEnc = encode(microUnit, normalizeDateByUnit(microUnit, macroEnd))
1132
+ return maxEnc <= vernierMicroMinEnc ? vernierMicroMinEnc + 1 : maxEnc
1133
+ }, [isVernierMode, macroRangeEndMs, vernierMicroMinEnc, macroUnit, microUnit])
1134
+
1135
+ const vernierMicroLowEnc = useMemo(() => {
1136
+ if (!(isVernierMode && effectiveLowerDate)) return vernierMicroMinEnc
1137
+ return encode(microUnit, normalizeDateByUnit(microUnit, effectiveLowerDate))
1138
+ }, [isVernierMode, lowerDateMs, vernierMicroMinEnc, microUnit, effectiveLowerDate])
1139
+
1140
+ const vernierMicroHighEnc = useMemo(() => {
1141
+ if (!(isVernierMode && effectiveUpperDate)) return vernierMicroMaxEnc
1142
+ return encode(microUnit, normalizeDateByUnit(microUnit, effectiveUpperDate))
1143
+ }, [isVernierMode, upperDateMs, vernierMicroMaxEnc, microUnit, effectiveUpperDate])
1144
+
1145
+ // 比率 (0.0 〜 1.0)
1146
+ const macroSpan = Math.max(1, vernierMacroMaxEnc - vernierMacroMinEnc)
1147
+ const macroLowRatio = Math.max(0, Math.min(1, (vernierMacroLowEnc - vernierMacroMinEnc) / macroSpan))
1148
+ const macroHighRatio = Math.max(macroLowRatio, Math.min(1, (vernierMacroHighEnc - vernierMacroMinEnc) / macroSpan))
1149
+
1150
+ const microSpan = Math.max(1, vernierMicroMaxEnc - vernierMicroMinEnc)
1151
+ const microLowRatio = Math.max(0, Math.min(1, (vernierMicroLowEnc - vernierMicroMinEnc) / microSpan))
1152
+ const microHighRatio = Math.max(microLowRatio, Math.min(1, (vernierMicroHighEnc - vernierMicroMinEnc) / microSpan))
1153
+
1154
+ // ------------------------------------------------------------------
1155
+ // D. Debounce & Callback Notification
1156
+ // ------------------------------------------------------------------
1157
+ const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
1158
+
1159
+ // Clean up timer on unmount to prevent memory leaks
1160
+ useEffect(() => {
1161
+ return () => {
1162
+ if (debounceTimerRef.current) {
1163
+ clearTimeout(debounceTimerRef.current)
1164
+ }
1165
+ }
1166
+ }, [])
1167
+
1168
+ const lastEmittedKeyRef = useRef<string | null>(null)
1169
+
1170
+ const notifyChange = useCallback(
1171
+ (nextLow: number, nextHigh: number, immediate = false) => {
1172
+ const p = propsRef.current
1173
+ const lowDate = valueToDate(nextLow)
1174
+ const highDate = valueToDate(nextHigh)
1175
+
1176
+ const key = p.mode === "point" ? `${lowDate.getTime()}` : `${lowDate.getTime()}-${highDate.getTime()}`
1177
+
1178
+ if (key === lastEmittedKeyRef.current && !debounceTimerRef.current) {
1179
+ return
1180
+ }
1181
+
1182
+ const doEmit = () => {
1183
+ lastEmittedKeyRef.current = key
1184
+ if (p.mode === "point") {
1185
+ p.onChangePoint?.(lowDate)
1186
+ p.onChangeValue?.(lowDate)
1187
+ p.onChange?.(lowDate)
1188
+ } else if (p.mode === "range") {
1189
+ p.onChangeRange?.(lowDate, highDate)
1190
+ p.onChangeRangeTuple?.([lowDate, highDate])
1191
+ p.onChange?.([lowDate, highDate])
1192
+ } else if (p.mode === "vernier") {
1193
+ p.onChangeRange?.(lowDate, highDate)
1194
+ p.onChangeRangeTuple?.([lowDate, highDate])
1195
+ p.onChangeMicroRange?.(lowDate, highDate)
1196
+ p.onChangeMicroRangeTuple?.([lowDate, highDate])
1197
+ p.onChangeMicro?.([lowDate, highDate])
1198
+ }
1199
+ }
1200
+
1201
+ if (immediate || !p.debounceMs || p.debounceMs === 0) {
1202
+ if (debounceTimerRef.current) {
1203
+ clearTimeout(debounceTimerRef.current)
1204
+ debounceTimerRef.current = null
1205
+ }
1206
+ doEmit()
1207
+ } else {
1208
+ if (debounceTimerRef.current) {
1209
+ clearTimeout(debounceTimerRef.current)
1210
+ }
1211
+ debounceTimerRef.current = setTimeout(() => {
1212
+ doEmit()
1213
+ debounceTimerRef.current = null
1214
+ }, p.debounceMs)
1215
+ }
1216
+ },
1217
+ [valueToDate],
1218
+ )
1219
+
1220
+ // ------------------------------------------------------------------
1221
+ // E. Percentage Math & Position Calculations
1222
+ // ------------------------------------------------------------------
1223
+ const valueToPct = useCallback(
1224
+ (val: number): number => {
1225
+ if (isDiscrete && snapMode === "time" && sortedAllowedDates.length > 1) {
1226
+ const idx = Math.max(0, Math.min(sortedAllowedDates.length - 1, Math.round(val)))
1227
+ const firstMs = sortedAllowedDates[0].getTime()
1228
+ const lastMs = sortedAllowedDates[sortedAllowedDates.length - 1].getTime()
1229
+ const totalMs = lastMs - firstMs
1230
+ if (totalMs <= 0) return 0
1231
+ const currentMs = sortedAllowedDates[idx].getTime()
1232
+ return Math.max(0, Math.min(100, ((currentMs - firstMs) / totalMs) * 100))
1233
+ }
1234
+
1235
+ const range = rangeMax - rangeMin
1236
+ if (range <= 0) return 0
1237
+ const pct = ((val - rangeMin) / range) * 100
1238
+ return Math.max(0, Math.min(100, pct))
1239
+ },
1240
+ [isDiscrete, snapMode, sortedAllowedDates, rangeMin, rangeMax],
1241
+ )
1242
+
1243
+ const pctToValue = useCallback(
1244
+ (pct: number): number => {
1245
+ const clampedPct = Math.max(0, Math.min(100, pct))
1246
+
1247
+ if (isDiscrete) {
1248
+ if (snapMode === "time" && sortedAllowedDates.length > 1) {
1249
+ const firstMs = sortedAllowedDates[0].getTime()
1250
+ const lastMs = sortedAllowedDates[sortedAllowedDates.length - 1].getTime()
1251
+ const totalMs = lastMs - firstMs
1252
+ const targetMs = firstMs + (clampedPct / 100) * totalMs
1253
+ return findNearestDateIndex(sortedAllowedDates, new Date(targetMs), unit)
1254
+ }
1255
+ const idx = Math.round((clampedPct / 100) * (sortedAllowedDates.length - 1))
1256
+ return Math.max(0, Math.min(sortedAllowedDates.length - 1, idx))
1257
+ }
1258
+
1259
+ const val = rangeMin + (clampedPct / 100) * (rangeMax - rangeMin)
1260
+ return Math.round(val)
1261
+ },
1262
+ [isDiscrete, snapMode, sortedAllowedDates, rangeMin, rangeMax, unit],
1263
+ )
1264
+
1265
+ // ------------------------------------------------------------------
1266
+ // F. Pointer Coordinate Tracking & Track Dimension Observer
1267
+ // ------------------------------------------------------------------
1268
+ const trackRef = useRef<HTMLDivElement | null>(null)
1269
+ const [trackLength, setTrackLength] = useState<number>(0)
1270
+ const trackWidth = trackLength // 後方互換性エイリアス
1271
+
1272
+ useEffect(() => {
1273
+ const el = trackRef.current
1274
+ if (!el) return
1275
+
1276
+ const updateDimensions = () => {
1277
+ const rect = el.getBoundingClientRect()
1278
+ const length = isVertical ? rect.height : rect.width
1279
+ if (length > 0) setTrackLength((prev) => (Math.abs(prev - length) < 0.5 ? prev : length))
1280
+ }
1281
+
1282
+ updateDimensions()
1283
+
1284
+ if (typeof ResizeObserver !== "undefined") {
1285
+ const ro = new ResizeObserver((entries) => {
1286
+ for (const entry of entries) {
1287
+ const length = isVertical ? entry.contentRect.height : entry.contentRect.width
1288
+ if (length > 0) {
1289
+ setTrackLength((prev) => (Math.abs(prev - length) < 0.5 ? prev : length))
1290
+ }
1291
+ }
1292
+ })
1293
+ ro.observe(el)
1294
+ return () => ro.disconnect()
1295
+ }
1296
+
1297
+ window.addEventListener("resize", updateDimensions)
1298
+ return () => window.removeEventListener("resize", updateDimensions)
1299
+ }, [isVertical])
1300
+
1301
+ const calcPercentFromPos = useCallback(
1302
+ (clientX: number, clientY: number, rect: DOMRect) => {
1303
+ if (isVertical) {
1304
+ const height = rect.height > 0 ? rect.height : 100
1305
+ const diff = rect.bottom - clientY
1306
+ return Math.max(0, Math.min(100, (diff / height) * 100))
1307
+ }
1308
+ const width = rect.width > 0 ? rect.width : 100
1309
+ const diff = clientX - rect.left
1310
+ return Math.max(0, Math.min(100, (diff / width) * 100))
1311
+ },
1312
+ [isVertical],
1313
+ )
1314
+
1315
+ const getTrackPctFromPointer = useCallback(
1316
+ (clientX: number, clientY: number): number => {
1317
+ if (!trackRef.current) return 0
1318
+ return calcPercentFromPos(clientX, clientY, trackRef.current.getBoundingClientRect())
1319
+ },
1320
+ [calcPercentFromPos],
1321
+ )
1322
+
1323
+ // ------------------------------------------------------------------
1324
+ // G. Drag Operation Handling & Event Subscriptions
1325
+ // ------------------------------------------------------------------
1326
+ const dragContextRef = useRef<{
1327
+ pointerId: number
1328
+ handle: "low" | "high" | "connect"
1329
+ startPointerPos: number
1330
+ startLowVal: number
1331
+ startHighVal: number
1332
+ } | null>(null)
1333
+
1334
+ const vernierDragContextRef = useRef<{
1335
+ pointerId: number
1336
+ handle: VernierHandle
1337
+ startPointerRatio: number
1338
+ startMacroLowRatio: number
1339
+ startMacroHighRatio: number
1340
+ startMicroLowRatio: number
1341
+ startMicroHighRatio: number
1342
+ startMacroLowEnc: number
1343
+ startMacroHighEnc: number
1344
+ startMicroLowEnc: number
1345
+ startMicroHighEnc: number
1346
+ startMacroLowDate: Date
1347
+ startMacroHighDate: Date
1348
+ initialMicroLowDate: Date
1349
+ initialMicroHighDate: Date
1350
+ } | null>(null)
1351
+
1352
+ const latestDraggingValuesRef = useRef<[number, number] | null>(null)
1353
+ const lastEmittedMacroRangeRef = useRef<string | null>(null)
1354
+ const lastEmittedMicroRangeRef = useRef<string | null>(null)
1355
+
1356
+ const handleGlobalPointerMove = useCallback(
1357
+ (e: PointerEvent) => {
1358
+ if (disabled) return
1359
+
1360
+ if (isVernierMode) {
1361
+ const vCtx = vernierDragContextRef.current
1362
+ if (!vCtx || (e.pointerId !== 0 && e.pointerId !== vCtx.pointerId)) return
1363
+ if (!trackRef.current) return
1364
+ const rect = trackRef.current.getBoundingClientRect()
1365
+ const trackLength = isVertical ? rect.height : rect.width
1366
+ if (trackLength <= 0) return
1367
+
1368
+ const currentPos = isVertical ? e.clientY : e.clientX
1369
+ const pointerRatio = Math.max(0, Math.min(1, isVertical ? (rect.bottom - currentPos) / trackLength : (currentPos - rect.left) / trackLength))
1370
+
1371
+ const p = propsRef.current as PeriodSliderVernierProps
1372
+ if (!p) return
1373
+
1374
+ if (vCtx.handle === "macro-low" || vCtx.handle === "macro-high" || vCtx.handle === "macro-connect") {
1375
+ const [nextMacroLowRatio, nextMacroHighRatio, activeMacroHandle] = calculateVernierMacroDrag(vCtx.handle, pointerRatio, vCtx.startPointerRatio, vCtx.startMacroLowRatio, vCtx.startMacroHighRatio)
1376
+ if (activeMacroHandle !== activeVernierHandleRef.current) {
1377
+ activeVernierHandleRef.current = activeMacroHandle
1378
+ setActiveVernierHandle(activeMacroHandle)
1379
+ setFrontVernierHandle(activeMacroHandle)
1380
+ }
1381
+
1382
+ let nextMacroLowDate: Date
1383
+ let nextMacroHighDate: Date
1384
+ if (macroIsDiscrete && sortedMacroAllowedDates.length > 0) {
1385
+ const maxIdx = sortedMacroAllowedDates.length - 1
1386
+ const lowIdx = Math.max(0, Math.min(maxIdx, Math.round(nextMacroLowRatio * maxIdx)))
1387
+ const highIdx = Math.max(lowIdx, Math.min(maxIdx, Math.round(nextMacroHighRatio * maxIdx)))
1388
+ nextMacroLowDate = sortedMacroAllowedDates[lowIdx] ?? new Date()
1389
+ nextMacroHighDate = sortedMacroAllowedDates[highIdx] ?? new Date()
1390
+ } else {
1391
+ const nextLowEnc = Math.round(vernierMacroMinEnc + nextMacroLowRatio * macroSpan)
1392
+ const nextHighEnc = Math.round(vernierMacroMinEnc + nextMacroHighRatio * macroSpan)
1393
+ nextMacroLowDate = decode(macroUnit, nextLowEnc)
1394
+ nextMacroHighDate = decode(macroUnit, nextHighEnc)
1395
+ }
1396
+
1397
+ const macroKey = `${nextMacroLowDate.getTime()}_${nextMacroHighDate.getTime()}`
1398
+ if (macroKey !== lastEmittedMacroRangeRef.current) {
1399
+ lastEmittedMacroRangeRef.current = macroKey
1400
+ p.onChangeMacroRange?.(nextMacroLowDate, nextMacroHighDate)
1401
+ p.onChangeMacroRangeTuple?.([nextMacroLowDate, nextMacroHighDate])
1402
+ p.onChangeMacro?.([nextMacroLowDate, nextMacroHighDate])
1403
+ }
1404
+
1405
+ // 異単位スケール間(例: 月×日)でのパン操作時の日数ズレを防ぐため、マクロ単位の暦月・暦年差分に基づいて平行移動
1406
+ let nextMicroLowDate: Date
1407
+ let nextMicroHighDate: Date
1408
+
1409
+ if (vCtx.handle === "macro-connect") {
1410
+ const curMacroLowDate = normalizeDateByUnit(microUnit, nextMacroLowDate)
1411
+ const curMacroHighDate = getMacroWindowEndDate(macroUnit, microUnit, nextMacroHighDate)
1412
+
1413
+ let shiftedLowDate: Date
1414
+ let shiftedHighDate: Date
1415
+ if (macroUnit === "year") {
1416
+ const yearDelta = nextMacroLowDate.getFullYear() - vCtx.startMacroLowDate.getFullYear()
1417
+ shiftedLowDate = addUnit("year", vCtx.initialMicroLowDate, yearDelta)
1418
+ shiftedHighDate = addUnit("year", vCtx.initialMicroHighDate, yearDelta)
1419
+ } else if (macroUnit === "month") {
1420
+ const monthDelta = (nextMacroLowDate.getFullYear() - vCtx.startMacroLowDate.getFullYear()) * 12 + (nextMacroLowDate.getMonth() - vCtx.startMacroLowDate.getMonth())
1421
+ shiftedLowDate = addUnit("month", vCtx.initialMicroLowDate, monthDelta)
1422
+ shiftedHighDate = addUnit("month", vCtx.initialMicroHighDate, monthDelta)
1423
+ } else {
1424
+ const dayDelta = Math.round((nextMacroLowDate.getTime() - vCtx.startMacroLowDate.getTime()) / (24 * 60 * 60 * 1000))
1425
+ shiftedLowDate = addUnit("day", vCtx.initialMicroLowDate, dayDelta)
1426
+ shiftedHighDate = addUnit("day", vCtx.initialMicroHighDate, dayDelta)
1427
+ }
1428
+
1429
+ const minMs = curMacroLowDate.getTime()
1430
+ const maxMs = curMacroHighDate.getTime()
1431
+ const durationMs = vCtx.initialMicroHighDate.getTime() - vCtx.initialMicroLowDate.getTime()
1432
+ let targetLowMs = shiftedLowDate.getTime()
1433
+ let targetHighMs = shiftedHighDate.getTime()
1434
+
1435
+ if (targetLowMs < minMs) {
1436
+ targetLowMs = minMs
1437
+ targetHighMs = Math.min(maxMs, targetLowMs + durationMs)
1438
+ }
1439
+ if (targetHighMs > maxMs) {
1440
+ targetHighMs = maxMs
1441
+ targetLowMs = Math.max(minMs, targetHighMs - durationMs)
1442
+ }
1443
+
1444
+ nextMicroLowDate = normalizeDateByUnit(microUnit, new Date(targetLowMs))
1445
+ nextMicroHighDate = normalizeDateByUnit(microUnit, new Date(targetHighMs))
1446
+ } else {
1447
+ // マクロ窓境界変更時の弾性復元 (Elastic Range Restoration & Push Clamp)
1448
+ // 操作開始時の選択幅を維持しつつ、マクロ窓拡張時に記憶した初期境界まで自然復元
1449
+ const minMs = nextMacroLowDate.getTime()
1450
+ const maxMs = getMacroWindowEndDate(macroUnit, microUnit, nextMacroHighDate).getTime()
1451
+ const targetLowMs = vCtx.initialMicroLowDate.getTime()
1452
+ const targetHighMs = vCtx.initialMicroHighDate.getTime()
1453
+
1454
+ const clampedLowMs = Math.max(minMs, Math.min(maxMs, targetLowMs))
1455
+ const clampedHighMs = Math.max(clampedLowMs, Math.min(maxMs, targetHighMs))
1456
+
1457
+ nextMicroLowDate = normalizeDateByUnit(microUnit, new Date(clampedLowMs))
1458
+ nextMicroHighDate = normalizeDateByUnit(microUnit, new Date(clampedHighMs))
1459
+ }
1460
+
1461
+ const microKey = `${nextMicroLowDate.getTime()}_${nextMicroHighDate.getTime()}`
1462
+ if (microKey !== lastEmittedMicroRangeRef.current) {
1463
+ lastEmittedMicroRangeRef.current = microKey
1464
+ p.onChangeRange?.(nextMicroLowDate, nextMicroHighDate)
1465
+ p.onChangeRangeTuple?.([nextMicroLowDate, nextMicroHighDate])
1466
+ }
1467
+ } else if (vCtx.handle === "micro-low" || vCtx.handle === "micro-high" || vCtx.handle === "micro-connect") {
1468
+ const [nextMicroLowRatio, nextMicroHighRatio, activeMicroHandle] = calculateVernierMicroDrag(vCtx.handle, pointerRatio, vCtx.startPointerRatio, vCtx.startMicroLowRatio, vCtx.startMicroHighRatio)
1469
+ if (activeMicroHandle !== activeVernierHandleRef.current) {
1470
+ activeVernierHandleRef.current = activeMicroHandle
1471
+ setActiveVernierHandle(activeMicroHandle)
1472
+ setFrontVernierHandle(activeMicroHandle)
1473
+ }
1474
+
1475
+ let nextMicroLowDate: Date
1476
+ let nextMicroHighDate: Date
1477
+ if (microIsDiscrete && sortedMicroAllowedDates.length > 0) {
1478
+ const maxIdx = sortedMicroAllowedDates.length - 1
1479
+ const lowIdx = Math.max(0, Math.min(maxIdx, Math.round(nextMicroLowRatio * maxIdx)))
1480
+ const highIdx = Math.max(lowIdx, Math.min(maxIdx, Math.round(nextMicroHighRatio * maxIdx)))
1481
+ nextMicroLowDate = sortedMicroAllowedDates[lowIdx] ?? new Date()
1482
+ nextMicroHighDate = sortedMicroAllowedDates[highIdx] ?? new Date()
1483
+ } else {
1484
+ const nextMicroLowEnc = Math.round(vernierMicroMinEnc + nextMicroLowRatio * microSpan)
1485
+ const nextMicroHighEnc = Math.round(vernierMicroMinEnc + nextMicroHighRatio * microSpan)
1486
+ nextMicroLowDate = decode(microUnit, nextMicroLowEnc)
1487
+ nextMicroHighDate = decode(microUnit, nextMicroHighEnc)
1488
+ }
1489
+
1490
+ const microKey = `${nextMicroLowDate.getTime()}_${nextMicroHighDate.getTime()}`
1491
+ if (microKey !== lastEmittedMicroRangeRef.current) {
1492
+ lastEmittedMicroRangeRef.current = microKey
1493
+ p.onChangeRange?.(nextMicroLowDate, nextMicroHighDate)
1494
+ p.onChangeRangeTuple?.([nextMicroLowDate, nextMicroHighDate])
1495
+ }
1496
+ }
1497
+ return
1498
+ }
1499
+
1500
+ const ctx = dragContextRef.current
1501
+ if (!ctx || (e.pointerId !== 0 && e.pointerId !== ctx.pointerId)) return
1502
+
1503
+ if (!trackRef.current) return
1504
+ const rect = trackRef.current.getBoundingClientRect()
1505
+ const currentPos = isVertical ? e.clientY : e.clientX
1506
+ const trackLength = isVertical ? rect.height : rect.width
1507
+ if (trackLength <= 0) return
1508
+
1509
+ if (ctx.handle === "connect") {
1510
+ const rawDiffPct = isVertical ? (ctx.startPointerPos - currentPos) / trackLength : (currentPos - ctx.startPointerPos) / trackLength
1511
+
1512
+ const res = calculateConnectDragValues(rawDiffPct, ctx.startLowVal, ctx.startHighVal, rangeMin, rangeMax, isDiscrete, sortedAllowedDates)
1513
+ if (res) {
1514
+ if (latestDraggingValuesRef.current && latestDraggingValuesRef.current[0] === res[0] && latestDraggingValuesRef.current[1] === res[1]) {
1515
+ return
1516
+ }
1517
+ latestDraggingValuesRef.current = res
1518
+ setDraggingValues(res)
1519
+ notifyChange(res[0], res[1], false)
1520
+ }
1521
+ return
1522
+ }
1523
+
1524
+ const pct = getTrackPctFromPointer(e.clientX, e.clientY)
1525
+ const clickedVal = pctToValue(pct)
1526
+
1527
+ const [nextLow, nextHigh] = calculateHandleDragValues(ctx.handle, clickedVal, ctx.startLowVal, ctx.startHighVal, rangeMin, rangeMax, isPointMode)
1528
+ if (!latestDraggingValuesRef.current || latestDraggingValuesRef.current[0] !== nextLow || latestDraggingValuesRef.current[1] !== nextHigh) {
1529
+ latestDraggingValuesRef.current = [nextLow, nextHigh]
1530
+ setDraggingValues([nextLow, nextHigh])
1531
+ notifyChange(nextLow, nextHigh, false)
1532
+ }
1533
+
1534
+ if (!isPointMode && (ctx.handle === "low" || ctx.handle === "high")) {
1535
+ const currentActive = getActiveDragHandle(ctx.handle, clickedVal, ctx.startLowVal, ctx.startHighVal, isPointMode)
1536
+ if (activeHandleRef.current !== currentActive) {
1537
+ activeHandleRef.current = currentActive
1538
+ setActiveHandle(currentActive)
1539
+ setFrontHandle(currentActive)
1540
+ }
1541
+ }
1542
+ },
1543
+ [
1544
+ disabled,
1545
+ isVernierMode,
1546
+ isVertical,
1547
+ macroUnit,
1548
+ microUnit,
1549
+ macroIsDiscrete,
1550
+ microIsDiscrete,
1551
+ sortedMacroAllowedDates,
1552
+ sortedMicroAllowedDates,
1553
+ vernierMacroMinEnc,
1554
+ macroSpan,
1555
+ vernierMicroMinEnc,
1556
+ microSpan,
1557
+ rangeMin,
1558
+ rangeMax,
1559
+ isDiscrete,
1560
+ sortedAllowedDates,
1561
+ getTrackPctFromPointer,
1562
+ pctToValue,
1563
+ notifyChange,
1564
+ isPointMode,
1565
+ ],
1566
+ )
1567
+
1568
+ const handleGlobalPointerUp = useCallback(
1569
+ (e: PointerEvent) => {
1570
+ if (isVernierMode) {
1571
+ lastEmittedMacroRangeRef.current = null
1572
+ lastEmittedMicroRangeRef.current = null
1573
+ vernierDragContextRef.current = null
1574
+ activeVernierHandleRef.current = null
1575
+ setActiveVernierHandle(null)
1576
+ return
1577
+ }
1578
+
1579
+ const ctx = dragContextRef.current
1580
+ if (!ctx || (e.pointerId !== 0 && e.pointerId !== ctx.pointerId)) return
1581
+
1582
+ const finalVals = latestDraggingValuesRef.current ?? draggingValues
1583
+ if (finalVals) {
1584
+ notifyChange(finalVals[0], finalVals[1], true)
1585
+ setUncontrolledValues(finalVals)
1586
+ }
1587
+
1588
+ latestDraggingValuesRef.current = null
1589
+ setDraggingValues(null)
1590
+ dragContextRef.current = null
1591
+ activeHandleRef.current = null
1592
+ setActiveHandle(null)
1593
+ },
1594
+ [isVernierMode, draggingValues, notifyChange],
1595
+ )
1596
+
1597
+ const handlePointerMoveRef = useRef(handleGlobalPointerMove)
1598
+ handlePointerMoveRef.current = handleGlobalPointerMove
1599
+
1600
+ const handlePointerUpRef = useRef(handleGlobalPointerUp)
1601
+ handlePointerUpRef.current = handleGlobalPointerUp
1602
+
1603
+ const isDragging = activeHandle !== null || activeVernierHandle !== null
1604
+
1605
+ useEffect(() => {
1606
+ if (!isDragging) return
1607
+
1608
+ const onMove = (e: PointerEvent) => handlePointerMoveRef.current(e)
1609
+ const onUp = (e: PointerEvent) => handlePointerUpRef.current(e)
1610
+
1611
+ window.addEventListener("pointermove", onMove)
1612
+ window.addEventListener("pointerup", onUp)
1613
+ window.addEventListener("pointercancel", onUp)
1614
+
1615
+ return () => {
1616
+ window.removeEventListener("pointermove", onMove)
1617
+ window.removeEventListener("pointerup", onUp)
1618
+ window.removeEventListener("pointercancel", onUp)
1619
+ }
1620
+ }, [isDragging])
1621
+
1622
+ const startDrag = useCallback(
1623
+ (pointerId: number, handle: "low" | "high" | "connect", startPointerPos: number) => {
1624
+ dragContextRef.current = {
1625
+ pointerId,
1626
+ handle,
1627
+ startPointerPos,
1628
+ startLowVal: currentLowVal,
1629
+ startHighVal: currentHighVal,
1630
+ }
1631
+ activeHandleRef.current = handle
1632
+ setActiveHandle(handle)
1633
+ if (handle !== "connect") {
1634
+ setFrontHandle(handle)
1635
+ }
1636
+ },
1637
+ [currentLowVal, currentHighVal],
1638
+ )
1639
+
1640
+ const startVernierDrag = useCallback(
1641
+ (pointerId: number, handle: VernierHandle, startPointerRatio: number) => {
1642
+ const p = propsRef.current as PeriodSliderVernierProps
1643
+ vernierDragContextRef.current = {
1644
+ pointerId,
1645
+ handle,
1646
+ startPointerRatio,
1647
+ startMacroLowRatio: macroLowRatio,
1648
+ startMacroHighRatio: macroHighRatio,
1649
+ startMicroLowRatio: microLowRatio,
1650
+ startMicroHighRatio: microHighRatio,
1651
+ startMacroLowEnc: vernierMacroLowEnc,
1652
+ startMacroHighEnc: vernierMacroHighEnc,
1653
+ startMicroLowEnc: vernierMicroLowEnc,
1654
+ startMicroHighEnc: vernierMicroHighEnc,
1655
+ startMacroLowDate: p.macroRange[0],
1656
+ startMacroHighDate: p.macroRange[1],
1657
+ initialMicroLowDate: safeLowerDate,
1658
+ initialMicroHighDate: safeUpperDate,
1659
+ }
1660
+ activeVernierHandleRef.current = handle
1661
+ setActiveVernierHandle(handle)
1662
+ setFrontVernierHandle(handle)
1663
+ },
1664
+ [macroLowRatio, macroHighRatio, microLowRatio, microHighRatio, vernierMacroLowEnc, vernierMacroHighEnc, vernierMicroLowEnc, vernierMicroHighEnc],
1665
+ )
1666
+
1667
+ const handleKnobPointerDown = (handle: "low" | "high") => (e: React.PointerEvent<HTMLDivElement>) => {
1668
+ if (disabled) return
1669
+ e.stopPropagation()
1670
+ e.preventDefault()
1671
+ setFrontHandle(handle)
1672
+ const pos = isVertical ? e.clientY : e.clientX
1673
+ startDrag(e.pointerId, handle, pos)
1674
+ }
1675
+
1676
+ const handleVernierKnobPointerDown = (handle: VernierHandle) => (e: React.PointerEvent<HTMLDivElement>) => {
1677
+ if (disabled) return
1678
+ e.stopPropagation()
1679
+ e.preventDefault()
1680
+ if (!trackRef.current) return
1681
+ const rect = trackRef.current.getBoundingClientRect()
1682
+ const pointerRatio = isVertical ? Math.max(0, Math.min(1, (rect.bottom - e.clientY) / (rect.height > 0 ? rect.height : 100))) : Math.max(0, Math.min(1, (e.clientX - rect.left) / (rect.width > 0 ? rect.width : 100)))
1683
+ startVernierDrag(e.pointerId, handle, pointerRatio)
1684
+ }
1685
+
1686
+ const handleConnectPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
1687
+ if (disabled || hideConnectBar) return
1688
+ e.stopPropagation()
1689
+ e.preventDefault()
1690
+ const pos = isVertical ? e.clientY : e.clientX
1691
+ startDrag(e.pointerId, "connect", pos)
1692
+ }
1693
+
1694
+ const handleTrackPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
1695
+ if (disabled) return
1696
+
1697
+ if (isVernierMode) {
1698
+ if (!trackRef.current) return
1699
+ const rect = trackRef.current.getBoundingClientRect()
1700
+ const pointerRatio = isVertical ? Math.max(0, Math.min(1, (rect.bottom - e.clientY) / (rect.height > 0 ? rect.height : 100))) : Math.max(0, Math.min(1, (e.clientX - rect.left) / (rect.width > 0 ? rect.width : 100)))
1701
+ const pointerCrossAxisOffset = isVertical ? e.clientX - (rect.left + rect.width / 2) : e.clientY - (rect.top + rect.height / 2)
1702
+ const targetHandle = resolveVernierTargetHandle(pointerRatio, pointerCrossAxisOffset, macroLowRatio, macroHighRatio, microLowRatio, microHighRatio, vernierOrientation)
1703
+ startVernierDrag(e.pointerId, targetHandle, pointerRatio)
1704
+ return
1705
+ }
1706
+
1707
+ const pct = getTrackPctFromPointer(e.clientX, e.clientY)
1708
+ const clickedVal = pctToValue(pct)
1709
+
1710
+ let chosenHandle: "low" | "high" = "low"
1711
+ if (!isPointMode) {
1712
+ const distLow = Math.abs(clickedVal - currentLowVal)
1713
+ const distHigh = Math.abs(clickedVal - currentHighVal)
1714
+ if (distLow < distHigh) {
1715
+ chosenHandle = "low"
1716
+ } else if (distHigh < distLow) {
1717
+ chosenHandle = "high"
1718
+ } else {
1719
+ chosenHandle = clickedVal > currentHighVal ? "high" : "low"
1720
+ }
1721
+ }
1722
+
1723
+ setFrontHandle(chosenHandle)
1724
+ const [nextLow, nextHigh] = calculateHandleDragValues(chosenHandle, clickedVal, currentLowVal, currentHighVal, rangeMin, rangeMax, isPointMode)
1725
+ setDraggingValues([nextLow, nextHigh])
1726
+ notifyChange(nextLow, nextHigh, true)
1727
+
1728
+ const pos = isVertical ? e.clientY : e.clientX
1729
+ startDrag(e.pointerId, chosenHandle, pos)
1730
+ }
1731
+
1732
+ const handleTrackPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
1733
+ if (disabled || activeHandle !== null) return
1734
+ const pct = getTrackPctFromPointer(e.clientX, e.clientY)
1735
+ const val = pctToValue(pct)
1736
+ setHoverValue(val)
1737
+ setHoverPct(valueToPct(val))
1738
+ }
1739
+
1740
+ const handleTrackPointerLeave = () => {
1741
+ setHoverValue(null)
1742
+ setHoverPct(null)
1743
+ }
1744
+
1745
+ // ------------------------------------------------------------------
1746
+ // H. Keyboard & Stepper Operations
1747
+ // ------------------------------------------------------------------
1748
+ const handleKeyDown = (handle: "low" | "high") => (e: React.KeyboardEvent<HTMLDivElement>) => {
1749
+ if (disabled) return
1750
+ setFrontHandle(handle)
1751
+
1752
+ const res = calculateKeyboardActionValues(e.key, handle, currentLowVal, currentHighVal, rangeMin, rangeMax, isPointMode, 1)
1753
+ if (res) {
1754
+ e.preventDefault()
1755
+ if (!isControlled) {
1756
+ setUncontrolledValues(res)
1757
+ }
1758
+ notifyChange(res[0], res[1], true)
1759
+ }
1760
+ }
1761
+
1762
+ /**
1763
+ * Handles keyboard navigation (ArrowLeft, ArrowRight, PageUp, PageDown, Home, End) for Vernier Caliper handles.
1764
+ * ノギス (Vernier Caliper) ハンドルのキーボード操作 (ArrowLeft, ArrowRight, PageUp, PageDown, Home, End) を処理するハンドラ。
1765
+ *
1766
+ * @param handle - The Vernier handle being manipulated
1767
+ */
1768
+ const handleVernierKeyDown = (handle: "macro-low" | "macro-high" | "micro-low" | "micro-high") => (e: React.KeyboardEvent<HTMLDivElement>) => {
1769
+ if (disabled || !isVernierMode || props.mode !== "vernier") return
1770
+ setFrontVernierHandle(handle)
1771
+ let delta = 0
1772
+ let isHome = false
1773
+ let isEnd = false
1774
+ switch (e.key) {
1775
+ case "ArrowRight":
1776
+ case "ArrowUp":
1777
+ delta = 1
1778
+ break
1779
+ case "ArrowLeft":
1780
+ case "ArrowDown":
1781
+ delta = -1
1782
+ break
1783
+ case "PageUp":
1784
+ delta = 5
1785
+ break
1786
+ case "PageDown":
1787
+ delta = -5
1788
+ break
1789
+ case "Home":
1790
+ isHome = true
1791
+ break
1792
+ case "End":
1793
+ isEnd = true
1794
+ break
1795
+ default:
1796
+ return
1797
+ }
1798
+ e.preventDefault()
1799
+
1800
+ const notifyMacro = (low: Date, high: Date) => {
1801
+ props.onChangeMacroRange?.(low, high)
1802
+ props.onChangeMacroRangeTuple?.([low, high])
1803
+ props.onChangeMacro?.([low, high])
1804
+ }
1805
+
1806
+ const notifyMicro = (low: Date, high: Date) => {
1807
+ props.onChangeRange?.(low, high)
1808
+ props.onChangeRangeTuple?.([low, high])
1809
+ props.onChangeMicroRange?.(low, high)
1810
+ props.onChangeMicroRangeTuple?.([low, high])
1811
+ props.onChangeMicro?.([low, high])
1812
+ }
1813
+
1814
+ if (handle === "macro-low") {
1815
+ let next: number
1816
+ if (isHome) next = vernierMacroMinEnc
1817
+ else if (isEnd) next = vernierMacroHighEnc
1818
+ else next = Math.max(vernierMacroMinEnc, Math.min(vernierMacroHighEnc, vernierMacroLowEnc + delta))
1819
+ notifyMacro(decode(macroUnit, next), decode(macroUnit, vernierMacroHighEnc))
1820
+ } else if (handle === "macro-high") {
1821
+ let next: number
1822
+ if (isHome) next = vernierMacroLowEnc
1823
+ else if (isEnd) next = vernierMacroMaxEnc
1824
+ else next = Math.max(vernierMacroLowEnc, Math.min(vernierMacroMaxEnc, vernierMacroHighEnc + delta))
1825
+ notifyMacro(decode(macroUnit, vernierMacroLowEnc), decode(macroUnit, next))
1826
+ } else if (handle === "micro-low") {
1827
+ let next: number
1828
+ if (isHome) next = vernierMicroMinEnc
1829
+ else if (isEnd) next = vernierMicroHighEnc
1830
+ else next = Math.max(vernierMicroMinEnc, Math.min(vernierMicroHighEnc, vernierMicroLowEnc + delta))
1831
+ notifyMicro(decode(microUnit, next), decode(microUnit, vernierMicroHighEnc))
1832
+ } else if (handle === "micro-high") {
1833
+ let next: number
1834
+ if (isHome) next = vernierMicroLowEnc
1835
+ else if (isEnd) next = vernierMicroMaxEnc
1836
+ else next = Math.max(vernierMicroLowEnc, Math.min(vernierMicroMaxEnc, vernierMicroHighEnc + delta))
1837
+ notifyMicro(decode(microUnit, vernierMicroLowEnc), decode(microUnit, next))
1838
+ }
1839
+ }
1840
+
1841
+ const shift = useCallback(
1842
+ (delta: number) => {
1843
+ const p = propsRef.current
1844
+ if (p.disabled) return
1845
+
1846
+ if (p.mode === "point") {
1847
+ const nextVal = Math.max(rangeMin, Math.min(rangeMax, currentLowVal + delta))
1848
+ if (!isControlled) {
1849
+ setUncontrolledValues([nextVal, nextVal])
1850
+ }
1851
+ notifyChange(nextVal, nextVal, true)
1852
+ } else if (p.mode === "vernier") {
1853
+ const curLowEnc = vernierMicroLowEnc
1854
+ const curHighEnc = vernierMicroHighEnc
1855
+ const minEnc = vernierMicroMinEnc
1856
+ const maxEnc = vernierMicroMaxEnc
1857
+ const span = curHighEnc - curLowEnc
1858
+ let nextLow = curLowEnc + delta
1859
+ let nextHigh = curHighEnc + delta
1860
+ if (delta < 0 && nextLow < minEnc) {
1861
+ nextLow = minEnc
1862
+ nextHigh = Math.min(maxEnc, nextLow + span)
1863
+ } else if (delta > 0 && nextHigh > maxEnc) {
1864
+ nextHigh = maxEnc
1865
+ nextLow = Math.max(minEnc, nextHigh - span)
1866
+ }
1867
+ if (nextLow !== curLowEnc || nextHigh !== curHighEnc) {
1868
+ const lowD = decode(microUnit, nextLow)
1869
+ const highD = decode(microUnit, nextHigh)
1870
+ p.onChangeRange?.(lowD, highD)
1871
+ p.onChangeRangeTuple?.([lowD, highD])
1872
+ }
1873
+ } else {
1874
+ const span = currentHighVal - currentLowVal
1875
+ let nextLow = currentLowVal + delta
1876
+ let nextHigh = currentHighVal + delta
1877
+ if (delta < 0 && nextLow < rangeMin) {
1878
+ nextLow = rangeMin
1879
+ nextHigh = Math.min(rangeMax, nextLow + span)
1880
+ } else if (delta > 0 && nextHigh > rangeMax) {
1881
+ nextHigh = rangeMax
1882
+ nextLow = Math.max(rangeMin, nextHigh - span)
1883
+ }
1884
+ if (nextLow <= nextHigh) {
1885
+ if (!isControlled) {
1886
+ setUncontrolledValues([nextLow, nextHigh])
1887
+ }
1888
+ notifyChange(nextLow, nextHigh, true)
1889
+ }
1890
+ }
1891
+ },
1892
+ [currentLowVal, currentHighVal, rangeMin, rangeMax, isControlled, notifyChange, vernierMicroLowEnc, vernierMicroHighEnc, vernierMicroMinEnc, vernierMicroMaxEnc, microUnit],
1893
+ )
1894
+
1895
+ // ------------------------------------------------------------------
1896
+ // I. Visual Position & Style Calculations
1897
+ // ------------------------------------------------------------------
1898
+ const lowPct = valueToPct(currentLowVal)
1899
+ const highPct = valueToPct(currentHighVal)
1900
+
1901
+ const lowDate = valueToDate(currentLowVal)
1902
+ const highDate = valueToDate(currentHighVal)
1903
+
1904
+ // Mathematical collision avoidance for range mode handles
1905
+ const slantResult: LabelSlantResult = useMemo(() => {
1906
+ // Unified baseline: clearance 10px from track center + labelHeight / 2 (8px) = 18px
1907
+ const baseOffsetY = labelPosition === "top" ? -18 : 18
1908
+ if (isPointMode || !autoSlantLabels || isVertical) {
1909
+ return {
1910
+ lowAngleDeg: 0,
1911
+ highAngleDeg: 0,
1912
+ lowOffsetX: 0,
1913
+ highOffsetX: 0,
1914
+ lowOffsetY: baseOffsetY,
1915
+ highOffsetY: baseOffsetY,
1916
+ isSlanted: false,
1917
+ proximity: 0,
1918
+ }
1919
+ }
1920
+ return calculateLabelSlant(lowPct, highPct, trackWidth, labelPosition, unit)
1921
+ }, [isPointMode, autoSlantLabels, isVertical, lowPct, highPct, trackWidth, labelPosition, unit])
1922
+
1923
+ const isLowFront = activeHandle === "low" || (activeHandle !== "high" && frontHandle === "low")
1924
+ const isHighFront = !isPointMode && (activeHandle === "high" || (activeHandle !== "low" && frontHandle === "high"))
1925
+
1926
+ const lowTooltipStyle: CSSProperties = useMemo(() => {
1927
+ if (isVertical) {
1928
+ return {
1929
+ "--ps-tooltip-origin": "100% 50%",
1930
+ "--ps-tooltip-tx": "0px",
1931
+ "--ps-tooltip-ty": "-50%",
1932
+ "--ps-tooltip-rot": "0deg",
1933
+ } as CSSProperties
1934
+ }
1935
+
1936
+ return {
1937
+ "--ps-tooltip-origin": "50% 50%",
1938
+ "--ps-tooltip-tx": `calc(-50% + ${slantResult.lowOffsetX}px)`,
1939
+ "--ps-tooltip-ty": `calc(-50% + ${slantResult.lowOffsetY}px)`,
1940
+ "--ps-tooltip-rot": `${slantResult.lowAngleDeg}deg`,
1941
+ } as CSSProperties
1942
+ }, [isVertical, slantResult.lowOffsetX, slantResult.lowOffsetY, slantResult.lowAngleDeg])
1943
+
1944
+ const highTooltipStyle: CSSProperties = useMemo(() => {
1945
+ if (isVertical) {
1946
+ return {
1947
+ "--ps-tooltip-origin": "100% 50%",
1948
+ "--ps-tooltip-tx": "0px",
1949
+ "--ps-tooltip-ty": "-50%",
1950
+ "--ps-tooltip-rot": "0deg",
1951
+ } as CSSProperties
1952
+ }
1953
+
1954
+ return {
1955
+ "--ps-tooltip-origin": "50% 50%",
1956
+ "--ps-tooltip-tx": `calc(-50% + ${slantResult.highOffsetX}px)`,
1957
+ "--ps-tooltip-ty": `calc(-50% + ${slantResult.highOffsetY}px)`,
1958
+ "--ps-tooltip-rot": `${slantResult.highAngleDeg}deg`,
1959
+ } as CSSProperties
1960
+ }, [isVertical, slantResult.highOffsetX, slantResult.highOffsetY, slantResult.highAngleDeg])
1961
+
1962
+ const minPct = Math.min(lowPct, highPct)
1963
+ const maxPct = Math.max(lowPct, highPct)
1964
+ const connectStyle: CSSProperties = isVertical
1965
+ ? {
1966
+ bottom: `${minPct}%`,
1967
+ height: `${maxPct - minPct}%`,
1968
+ top: "auto",
1969
+ left: "0",
1970
+ right: "0",
1971
+ }
1972
+ : {
1973
+ left: `${minPct}%`,
1974
+ width: `${maxPct - minPct}%`,
1975
+ top: "0",
1976
+ bottom: "0",
1977
+ }
1978
+
1979
+ // 光束減衰モデル: マクロ窓比率に応じたエネルギー保存モデル
1980
+ const macroSpanRatio = Math.max(0.01, macroHighRatio - macroLowRatio)
1981
+ const targetMicroOpacity = Math.max(0.06, Math.min(0.25, 0.28 * Math.sqrt(macroSpanRatio)))
1982
+
1983
+ const lowHandleStyle: CSSProperties = isVertical ? { bottom: `${lowPct}%`, left: "50%", transform: "translate(-50%, 50%)", zIndex: isLowFront ? 40 : 30 } : { left: `${lowPct}%`, top: "50%", transform: "translate(-50%, -50%)", zIndex: isLowFront ? 40 : 30 }
1984
+
1985
+ const highHandleStyle: CSSProperties = isVertical ? { bottom: `${highPct}%`, left: "50%", transform: "translate(-50%, 50%)", zIndex: isHighFront ? 40 : 30 } : { left: `${highPct}%`, top: "50%", transform: "translate(-50%, -50%)", zIndex: isHighFront ? 40 : 30 }
1986
+
1987
+ const hoverGuideStyle: CSSProperties = isVertical ? { bottom: `${hoverPct}%`, left: "50%", transform: "translate(-50%, 50%)" } : { left: `${hoverPct}%`, top: "50%", transform: "translate(-50%, -50%)" }
1988
+
1989
+ const hoverDate = hoverValue !== null ? valueToDate(hoverValue) : null
1990
+
1991
+ const stepperPrevDisabled = disabled || (isVernierMode ? vernierMicroLowEnc <= vernierMicroMinEnc : isPointMode ? currentLowVal <= rangeMin : currentLowVal <= rangeMin && currentHighVal <= rangeMin)
1992
+ const stepperNextDisabled = disabled || (isVernierMode ? vernierMicroHighEnc >= vernierMicroMaxEnc : isPointMode ? currentHighVal >= rangeMax : currentLowVal >= rangeMax && currentHighVal >= rangeMax)
1993
+
1994
+ const cursorClass = disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"
1995
+
1996
+ // ------------------------------------------------------------------
1997
+ // J. JSX Render Assembly
1998
+ // ------------------------------------------------------------------
1999
+ return (
2000
+ <div
2001
+ style={props.style}
2002
+ className={`period-slider flex select-none items-center gap-2 ${isVertical ? "flex-col" : "flex-row"} ${className}`}
2003
+ data-disabled={disabled ? "true" : undefined}
2004
+ data-unit={unit}
2005
+ data-mode={props.mode}
2006
+ data-orientation={isVertical ? "vertical" : "horizontal"}
2007
+ data-label-position={labelPosition}
2008
+ data-color-scheme={colorScheme}>
2009
+ {/* ◀ 1ステップ戻るボタン / 垂直時は ▲ 1ステップ進むボタン */}
2010
+ {showStepper && (
2011
+ <button
2012
+ type="button"
2013
+ className={`period-slider-stepper-btn relative after:absolute after:inset-[-10px] after:content-[''] ${isVertical ? "period-slider-stepper-next period-slider-stepper-up" : "period-slider-stepper-prev"} flex h-6 w-6 shrink-0 items-center justify-center rounded-md border border-slate-300 bg-white font-bold text-[10px] text-slate-700 leading-none shadow-2xs transition-all hover:bg-slate-100 hover:text-indigo-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 active:scale-95 disabled:cursor-not-allowed disabled:opacity-30 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700 ${cursorClass}`}
2014
+ onClick={() => shift(isVertical ? 1 : -1)}
2015
+ disabled={isVertical ? stepperNextDisabled : stepperPrevDisabled}
2016
+ aria-label={isVertical ? "1つ後へ" : "1つ前へ"}>
2017
+ {isVertical ? "▲" : "◀"}
2018
+ </button>
2019
+ )}
2020
+
2021
+ {/* スライダートラック */}
2022
+ <div
2023
+ ref={trackRef}
2024
+ data-testid="period-slider-track"
2025
+ data-orientation={isVertical ? "vertical" : "horizontal"}
2026
+ data-vernier-orientation={isVernierMode ? vernierOrientation : undefined}
2027
+ className={`period-slider-track relative flex-1 touch-none rounded-full bg-slate-200 dark:bg-slate-700 ${isVertical ? "h-48 w-2" : "h-2 w-full"} ${cursorClass}`}
2028
+ onPointerDown={handleTrackPointerDown}
2029
+ onPointerMove={handleTrackPointerMove}
2030
+ onPointerLeave={handleTrackPointerLeave}>
2031
+ {isVernierMode ? (
2032
+ <>
2033
+ {/* 台形プロジェクション (光のコーン: マクロ窓からミクロ全幅へ) */}
2034
+ {showVernierProjection &&
2035
+ (isVertical ? (
2036
+ <svg className="period-slider-vernier-projection is-vertical" role="presentation" aria-hidden="true" width="32" height="100%" viewBox="0 0 32 100" preserveAspectRatio="none">
2037
+ <defs>
2038
+ <linearGradient id={vernierGradId} x1="0" y1="0" x2="1" y2="0">
2039
+ <stop offset="0%" stopColor={isMacroFirstRail ? palette.macro : palette.micro} stopOpacity="0.28" />
2040
+ <stop offset="100%" stopColor={isMacroFirstRail ? palette.micro : palette.macro} stopOpacity={targetMicroOpacity} />
2041
+ </linearGradient>
2042
+ </defs>
2043
+ <polygon points={isMacroFirstRail ? `12,${(1 - macroHighRatio) * 100} 12,${(1 - macroLowRatio) * 100} 20,100 20,0` : `12,0 12,100 20,${(1 - macroLowRatio) * 100} 20,${(1 - macroHighRatio) * 100}`} fill={`url(#${vernierGradId})`} />
2044
+ </svg>
2045
+ ) : (
2046
+ <svg className="period-slider-vernier-projection" role="presentation" aria-hidden="true" width="100%" height="32" viewBox="0 0 100 32" preserveAspectRatio="none">
2047
+ <defs>
2048
+ <linearGradient id={vernierGradId} x1="0" y1="0" x2="0" y2="1">
2049
+ <stop offset="0%" stopColor={isMacroFirstRail ? palette.macro : palette.micro} stopOpacity="0.28" />
2050
+ <stop offset="100%" stopColor={isMacroFirstRail ? palette.micro : palette.macro} stopOpacity={targetMicroOpacity} />
2051
+ </linearGradient>
2052
+ </defs>
2053
+ <polygon points={isMacroFirstRail ? `${macroLowRatio * 100},12 ${macroHighRatio * 100},12 100,20 0,20` : `0,12 100,12 ${macroHighRatio * 100},20 ${macroLowRatio * 100},20`} fill={`url(#${vernierGradId})`} />
2054
+ </svg>
2055
+ ))}
2056
+
2057
+ {/* マクロ選択帯 & ミクロ選択帯 (ノギス時は半円つまみの直径16pxを完全に埋める長さに拡張) */}
2058
+ <div
2059
+ data-testid="period-slider-connect-macro"
2060
+ className="period-slider-connect-macro"
2061
+ style={
2062
+ isVertical
2063
+ ? {
2064
+ bottom: `calc(${macroLowRatio * 100}% - 8px)`,
2065
+ height: `calc(${Math.max(0, (macroHighRatio - macroLowRatio) * 100)}% + 16px)`,
2066
+ }
2067
+ : {
2068
+ left: `calc(${macroLowRatio * 100}% - 8px)`,
2069
+ width: `calc(${Math.max(0, (macroHighRatio - macroLowRatio) * 100)}% + 16px)`,
2070
+ }
2071
+ }
2072
+ onPointerDown={handleVernierKnobPointerDown("macro-connect")}
2073
+ />
2074
+ <div
2075
+ data-testid="period-slider-connect-micro"
2076
+ className="period-slider-connect-micro"
2077
+ style={
2078
+ isVertical
2079
+ ? {
2080
+ bottom: `calc(${microLowRatio * 100}% - 8px)`,
2081
+ height: `calc(${Math.max(0, (microHighRatio - microLowRatio) * 100)}% + 16px)`,
2082
+ }
2083
+ : {
2084
+ left: `calc(${microLowRatio * 100}% - 8px)`,
2085
+ width: `calc(${Math.max(0, (microHighRatio - microLowRatio) * 100)}% + 16px)`,
2086
+ }
2087
+ }
2088
+ onPointerDown={handleVernierKnobPointerDown("micro-connect")}
2089
+ />
2090
+
2091
+ {/* アダプティブ目盛線 (Ticks) */}
2092
+ {showVernierTicks && (
2093
+ <div className="period-slider-vernier-ticks pointer-events-none absolute inset-0">
2094
+ {[0.2, 0.4, 0.6, 0.8].map((t) => (
2095
+ <div key={`macro-tick-${t}`} className="period-slider-tick period-slider-tick-macro" style={isVertical ? { bottom: `${t * 100}%` } : { left: `${t * 100}%` }} />
2096
+ ))}
2097
+ {[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9].map((t) => (
2098
+ <div key={`micro-tick-${t}`} className="period-slider-tick period-slider-tick-micro" style={isVertical ? { bottom: `${t * 100}%` } : { left: `${t * 100}%` }} />
2099
+ ))}
2100
+ </div>
2101
+ )}
2102
+
2103
+ {/* マクロ下限ハンドル (上半円爪 / 左半円爪) */}
2104
+ <div
2105
+ tabIndex={disabled ? -1 : 0}
2106
+ role="slider"
2107
+ aria-label={props.macroLowerAriaLabel ?? "マクロ開始時期"}
2108
+ aria-disabled={disabled ? "true" : undefined}
2109
+ aria-valuemin={vernierMacroMinEnc}
2110
+ aria-valuemax={vernierMacroHighEnc}
2111
+ aria-valuenow={vernierMacroLowEnc}
2112
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(props.macroRange[0], macroUnit) : formatScreenReaderLabel(macroUnit, props.macroRange[0], formatMacroLabel)}
2113
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2114
+ className={`period-slider-handle period-slider-handle-vernier ${isVertical ? "is-vertical" : ""} group absolute touch-none ${
2115
+ isVertical
2116
+ ? isMacroFirstRail
2117
+ ? "after:absolute after:-inset-y-3 after:right-0 after:-left-3"
2118
+ : "after:absolute after:-inset-y-3 after:-right-3 after:left-0"
2119
+ : isMacroFirstRail
2120
+ ? "after:absolute after:-inset-x-3 after:-top-3 after:bottom-0"
2121
+ : "after:absolute after:-inset-x-3 after:top-0 after:-bottom-3"
2122
+ } after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 ${cursorClass}`}
2123
+ style={
2124
+ isVertical
2125
+ ? {
2126
+ bottom: `${macroLowRatio * 100}%`,
2127
+ left: isMacroFirstRail ? 0 : "auto",
2128
+ right: isMacroFirstRail ? "auto" : 0,
2129
+ transform: isMacroFirstRail ? "translate(-100%, 50%)" : "translate(100%, 50%)",
2130
+ zIndex: activeVernierHandle === "macro-low" || frontVernierHandle === "macro-low" ? 30 : 15,
2131
+ }
2132
+ : {
2133
+ left: `${macroLowRatio * 100}%`,
2134
+ top: isMacroFirstRail ? 0 : "auto",
2135
+ bottom: isMacroFirstRail ? "auto" : 0,
2136
+ transform: isMacroFirstRail ? "translate(-50%, -100%)" : "translate(-50%, 100%)",
2137
+ zIndex: activeVernierHandle === "macro-low" || frontVernierHandle === "macro-low" ? 30 : 15,
2138
+ }
2139
+ }
2140
+ onPointerDown={handleVernierKnobPointerDown("macro-low")}
2141
+ onKeyDown={handleVernierKeyDown("macro-low")}
2142
+ data-active={activeVernierHandle === "macro-low" ? "true" : undefined}
2143
+ data-front={frontVernierHandle === "macro-low" ? "true" : undefined}
2144
+ data-vernier-pos={isVertical ? (isMacroFirstRail ? "left" : "right") : isMacroFirstRail ? "top" : "bottom"}
2145
+ data-handle-type="macro-low">
2146
+ <VernierKnobSvg type="macro" isTop={isMacroFirstRail} isVertical={isVertical} isLeft={isMacroFirstRail} />
2147
+ {showHairline && <div className="period-slider-hairline" />}
2148
+ <div className="period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800">{formatLabel(macroUnit, props.macroRange[0], formatMacroLabel)}</div>
2149
+ </div>
2150
+
2151
+ {/* マクロ上限ハンドル (上半円爪 / 左半円爪) */}
2152
+ <div
2153
+ tabIndex={disabled ? -1 : 0}
2154
+ role="slider"
2155
+ aria-label={props.macroUpperAriaLabel ?? "マクロ終了時期"}
2156
+ aria-disabled={disabled ? "true" : undefined}
2157
+ aria-valuemin={vernierMacroLowEnc}
2158
+ aria-valuemax={vernierMacroMaxEnc}
2159
+ aria-valuenow={vernierMacroHighEnc}
2160
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(props.macroRange[1], macroUnit) : formatScreenReaderLabel(macroUnit, props.macroRange[1], formatMacroLabel)}
2161
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2162
+ className={`period-slider-handle period-slider-handle-vernier ${isVertical ? "is-vertical" : ""} group absolute touch-none ${
2163
+ isVertical
2164
+ ? isMacroFirstRail
2165
+ ? "after:absolute after:-inset-y-3 after:right-0 after:-left-3"
2166
+ : "after:absolute after:-inset-y-3 after:-right-3 after:left-0"
2167
+ : isMacroFirstRail
2168
+ ? "after:absolute after:-inset-x-3 after:-top-3 after:bottom-0"
2169
+ : "after:absolute after:-inset-x-3 after:top-0 after:-bottom-3"
2170
+ } after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 ${cursorClass}`}
2171
+ style={
2172
+ isVertical
2173
+ ? {
2174
+ bottom: `${macroHighRatio * 100}%`,
2175
+ left: isMacroFirstRail ? 0 : "auto",
2176
+ right: isMacroFirstRail ? "auto" : 0,
2177
+ transform: isMacroFirstRail ? "translate(-100%, 50%)" : "translate(100%, 50%)",
2178
+ zIndex: activeVernierHandle === "macro-high" || frontVernierHandle === "macro-high" ? 30 : 15,
2179
+ }
2180
+ : {
2181
+ left: `${macroHighRatio * 100}%`,
2182
+ top: isMacroFirstRail ? 0 : "auto",
2183
+ bottom: isMacroFirstRail ? "auto" : 0,
2184
+ transform: isMacroFirstRail ? "translate(-50%, -100%)" : "translate(-50%, 100%)",
2185
+ zIndex: activeVernierHandle === "macro-high" || frontVernierHandle === "macro-high" ? 30 : 15,
2186
+ }
2187
+ }
2188
+ onPointerDown={handleVernierKnobPointerDown("macro-high")}
2189
+ onKeyDown={handleVernierKeyDown("macro-high")}
2190
+ data-active={activeVernierHandle === "macro-high" ? "true" : undefined}
2191
+ data-front={frontVernierHandle === "macro-high" ? "true" : undefined}
2192
+ data-vernier-pos={isVertical ? (isMacroFirstRail ? "left" : "right") : isMacroFirstRail ? "top" : "bottom"}
2193
+ data-handle-type="macro-high">
2194
+ <VernierKnobSvg type="macro" isTop={isMacroFirstRail} isVertical={isVertical} isLeft={isMacroFirstRail} />
2195
+ {showHairline && <div className="period-slider-hairline" />}
2196
+ <div className="period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800">{formatLabel(macroUnit, props.macroRange[1], formatMacroLabel)}</div>
2197
+ </div>
2198
+
2199
+ {/* ミクロ下限ハンドル (下半円爪 / 右半円爪) */}
2200
+ <div
2201
+ tabIndex={disabled ? -1 : 0}
2202
+ role="slider"
2203
+ aria-label={props.lowerAriaLabel ?? "ミクロ開始時期"}
2204
+ aria-disabled={disabled ? "true" : undefined}
2205
+ aria-valuemin={vernierMicroMinEnc}
2206
+ aria-valuemax={vernierMicroHighEnc}
2207
+ aria-valuenow={vernierMicroLowEnc}
2208
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(safeLowerDate, microUnit) : formatScreenReaderLabel(microUnit, safeLowerDate, formatMicroLabel)}
2209
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2210
+ className={`period-slider-handle period-slider-handle-vernier ${isVertical ? "is-vertical" : ""} group absolute touch-none ${
2211
+ isVertical
2212
+ ? isMacroFirstRail
2213
+ ? "after:absolute after:-inset-y-3 after:-right-3 after:left-0"
2214
+ : "after:absolute after:-inset-y-3 after:right-0 after:-left-3"
2215
+ : isMacroFirstRail
2216
+ ? "after:absolute after:-inset-x-3 after:top-0 after:-bottom-3"
2217
+ : "after:absolute after:-inset-x-3 after:-top-3 after:bottom-0"
2218
+ } after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 ${cursorClass}`}
2219
+ style={
2220
+ isVertical
2221
+ ? {
2222
+ bottom: `${microLowRatio * 100}%`,
2223
+ left: isMacroFirstRail ? "auto" : 0,
2224
+ right: isMacroFirstRail ? 0 : "auto",
2225
+ transform: isMacroFirstRail ? "translate(100%, 50%)" : "translate(-100%, 50%)",
2226
+ zIndex: activeVernierHandle === "micro-low" || frontVernierHandle === "micro-low" ? 30 : 20,
2227
+ }
2228
+ : {
2229
+ left: `${microLowRatio * 100}%`,
2230
+ top: isMacroFirstRail ? "auto" : 0,
2231
+ bottom: isMacroFirstRail ? 0 : "auto",
2232
+ transform: isMacroFirstRail ? "translate(-50%, 100%)" : "translate(-50%, -100%)",
2233
+ zIndex: activeVernierHandle === "micro-low" || frontVernierHandle === "micro-low" ? 30 : 20,
2234
+ }
2235
+ }
2236
+ onPointerDown={handleVernierKnobPointerDown("micro-low")}
2237
+ onKeyDown={handleVernierKeyDown("micro-low")}
2238
+ data-active={activeVernierHandle === "micro-low" ? "true" : undefined}
2239
+ data-front={frontVernierHandle === "micro-low" ? "true" : undefined}
2240
+ data-vernier-pos={isVertical ? (isMacroFirstRail ? "right" : "left") : isMacroFirstRail ? "bottom" : "top"}
2241
+ data-handle-type="micro-low">
2242
+ <VernierKnobSvg type="micro" isTop={!isMacroFirstRail} isVertical={isVertical} isLeft={!isMacroFirstRail} />
2243
+ {showHairline && <div className="period-slider-hairline" />}
2244
+ <div className="period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800">{formatLabel(microUnit, safeLowerDate, formatMicroLabel)}</div>
2245
+ </div>
2246
+
2247
+ {/* ミクロ上限ハンドル (下半円爪 / 右半円爪) */}
2248
+ <div
2249
+ tabIndex={disabled ? -1 : 0}
2250
+ role="slider"
2251
+ aria-label={props.upperAriaLabel ?? "ミクロ終了時期"}
2252
+ aria-disabled={disabled ? "true" : undefined}
2253
+ aria-valuemin={vernierMicroLowEnc}
2254
+ aria-valuemax={vernierMicroMaxEnc}
2255
+ aria-valuenow={vernierMicroHighEnc}
2256
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(safeUpperDate, microUnit) : formatScreenReaderLabel(microUnit, safeUpperDate, formatMicroLabel)}
2257
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2258
+ className={`period-slider-handle period-slider-handle-vernier ${isVertical ? "is-vertical" : ""} group absolute touch-none ${
2259
+ isVertical
2260
+ ? isMacroFirstRail
2261
+ ? "after:absolute after:-inset-y-3 after:-right-3 after:left-0"
2262
+ : "after:absolute after:-inset-y-3 after:right-0 after:-left-3"
2263
+ : isMacroFirstRail
2264
+ ? "after:absolute after:-inset-x-3 after:top-0 after:-bottom-3"
2265
+ : "after:absolute after:-inset-x-3 after:-top-3 after:bottom-0"
2266
+ } after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 ${cursorClass}`}
2267
+ style={
2268
+ isVertical
2269
+ ? {
2270
+ bottom: `${microHighRatio * 100}%`,
2271
+ left: isMacroFirstRail ? "auto" : 0,
2272
+ right: isMacroFirstRail ? 0 : "auto",
2273
+ transform: isMacroFirstRail ? "translate(100%, 50%)" : "translate(-100%, 50%)",
2274
+ zIndex: activeVernierHandle === "micro-high" || frontVernierHandle === "micro-high" ? 30 : 20,
2275
+ }
2276
+ : {
2277
+ left: `${microHighRatio * 100}%`,
2278
+ top: isMacroFirstRail ? "auto" : 0,
2279
+ bottom: isMacroFirstRail ? 0 : "auto",
2280
+ transform: isMacroFirstRail ? "translate(-50%, 100%)" : "translate(-50%, -100%)",
2281
+ zIndex: activeVernierHandle === "micro-high" || frontVernierHandle === "micro-high" ? 30 : 20,
2282
+ }
2283
+ }
2284
+ onPointerDown={handleVernierKnobPointerDown("micro-high")}
2285
+ onKeyDown={handleVernierKeyDown("micro-high")}
2286
+ data-active={activeVernierHandle === "micro-high" ? "true" : undefined}
2287
+ data-front={frontVernierHandle === "micro-high" ? "true" : undefined}
2288
+ data-vernier-pos={isVertical ? (isMacroFirstRail ? "right" : "left") : isMacroFirstRail ? "bottom" : "top"}
2289
+ data-handle-type="micro-high">
2290
+ <VernierKnobSvg type="micro" isTop={!isMacroFirstRail} isVertical={isVertical} isLeft={!isMacroFirstRail} />
2291
+ {showHairline && <div className="period-slider-hairline" />}
2292
+ <div className="period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800">{formatLabel(microUnit, safeUpperDate, formatMicroLabel)}</div>
2293
+ </div>
2294
+ </>
2295
+ ) : (
2296
+ <>
2297
+ {/* 選択範囲バー (Connect) */}
2298
+ {!hideConnectBar && <div data-testid="period-slider-connect" className="period-slider-connect absolute rounded-full bg-blue-500 hover:bg-blue-600 dark:bg-blue-400" style={connectStyle} onPointerDown={handleConnectPointerDown} />}
2299
+
2300
+ {/* 離散モード用 Tick (目盛り点) 描画 */}
2301
+ {showTicks && isDiscrete && sortedAllowedDates.length > 1 && (
2302
+ <div className="period-slider-ticks pointer-events-none absolute inset-0">
2303
+ {sortedAllowedDates.map((d) => {
2304
+ const enc = encode(unit, d)
2305
+ const idx = sortedAllowedDates.findIndex((item) => encode(unit, item) === enc)
2306
+ const pct = valueToPct(idx)
2307
+ const tickStyle: CSSProperties = isVertical ? { bottom: `${pct}%`, left: "50%", transform: "translate(-50%, 50%)" } : { left: `${pct}%`, top: "50%", transform: "translate(-50%, -50%)" }
2308
+ return <div key={`tick-${enc}`} className="period-slider-tick absolute h-1.5 w-1.5 rounded-full bg-slate-400/60 dark:bg-slate-500/60" style={tickStyle} />
2309
+ })}
2310
+ </div>
2311
+ )}
2312
+
2313
+ {/* トラック上のマウスホバーガイド & ツールチップ */}
2314
+ {!disabled && hoverValue !== null && hoverPct !== null && activeHandle === null && hoverDate && (
2315
+ <div data-testid="period-slider-hover-guide" className="period-slider-hover-guide pointer-events-none absolute z-20 h-2 w-2" style={hoverGuideStyle}>
2316
+ <div className="period-slider-hover-dot h-full w-full rounded-full border border-white/80 bg-sky-400/80 shadow-[0_0_6px_#38bdf8] dark:border-slate-800 dark:bg-sky-300/80" />
2317
+ <div
2318
+ className={`period-slider-hover-tooltip ${labelPosition === "bottom" && !isVertical ? "period-slider-hover-tooltip-bottom" : ""} rounded bg-slate-800/90 px-2 py-0.5 font-medium text-white text-xs shadow-lg backdrop-blur-xs dark:bg-slate-900/90`}>
2319
+ {formatLabel(unit, hoverDate, props.formatLabel)}
2320
+ </div>
2321
+ </div>
2322
+ )}
2323
+
2324
+ {/* 開始つまみ (Point モード、または Range モードの Lower) */}
2325
+ <div
2326
+ tabIndex={disabled ? -1 : 0}
2327
+ role="slider"
2328
+ aria-label={isPointMode ? (props.pointAriaLabel ?? "選択時期") : (props.lowerAriaLabel ?? "開始時期")}
2329
+ aria-disabled={disabled ? "true" : undefined}
2330
+ aria-valuemin={rangeMin}
2331
+ aria-valuemax={isPointMode ? rangeMax : currentHighVal}
2332
+ aria-valuenow={currentLowVal}
2333
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(lowDate, unit) : formatScreenReaderLabel(unit, lowDate, props.formatLabel)}
2334
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2335
+ className={`period-slider-handle group absolute h-4 w-4 touch-none after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:outline-none ${cursorClass}`}
2336
+ style={lowHandleStyle}
2337
+ onPointerDown={handleKnobPointerDown("low")}
2338
+ onKeyDown={handleKeyDown("low")}
2339
+ data-active={activeHandle === "low" ? "true" : undefined}
2340
+ data-front={isLowFront ? "true" : undefined}>
2341
+ <div className="period-slider-knob h-full w-full rounded-full border-2 border-white bg-blue-600 shadow-md group-focus-visible:ring-2 group-focus-visible:ring-blue-600 group-focus-visible:ring-offset-2 dark:border-slate-800 dark:bg-blue-400" />
2342
+ {tooltipStyle !== "hover" && (
2343
+ <div
2344
+ className={`period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800 ${tooltipStyle === "balloon" ? "period-slider-tooltip-balloon" : ""}`}
2345
+ data-tooltip-style={tooltipStyle}
2346
+ data-label-position={labelPosition}
2347
+ data-slanted={slantResult.isSlanted ? "true" : undefined}
2348
+ data-front={isLowFront ? "true" : undefined}
2349
+ style={lowTooltipStyle}>
2350
+ {formatLabel(unit, lowDate, props.formatLabel)}
2351
+ </div>
2352
+ )}
2353
+ </div>
2354
+
2355
+ {/* 終了つまみ (Range モードの Upper) */}
2356
+ {!isPointMode && (
2357
+ <div
2358
+ tabIndex={disabled ? -1 : 0}
2359
+ role="slider"
2360
+ aria-label={props.upperAriaLabel ?? "終了時期"}
2361
+ aria-disabled={disabled ? "true" : undefined}
2362
+ aria-valuemin={currentLowVal}
2363
+ aria-valuemax={rangeMax}
2364
+ aria-valuenow={currentHighVal}
2365
+ aria-valuetext={props.formatAriaValueText ? props.formatAriaValueText(highDate, unit) : formatScreenReaderLabel(unit, highDate, props.formatLabel)}
2366
+ aria-orientation={isVertical ? "vertical" : "horizontal"}
2367
+ className={`period-slider-handle group absolute h-4 w-4 touch-none after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:outline-none ${cursorClass}`}
2368
+ style={highHandleStyle}
2369
+ onPointerDown={handleKnobPointerDown("high")}
2370
+ onKeyDown={handleKeyDown("high")}
2371
+ data-active={activeHandle === "high" ? "true" : undefined}
2372
+ data-front={isHighFront ? "true" : undefined}>
2373
+ <div className="period-slider-knob h-full w-full rounded-full border-2 border-white bg-blue-600 shadow-md group-focus-visible:ring-2 group-focus-visible:ring-blue-600 group-focus-visible:ring-offset-2 dark:border-slate-800 dark:bg-blue-400" />
2374
+ {tooltipStyle !== "hover" && (
2375
+ <div
2376
+ className={`period-slider-tooltip absolute whitespace-nowrap rounded bg-slate-900 px-2 py-0.5 font-medium text-white text-xs shadow-md dark:bg-slate-800 ${tooltipStyle === "balloon" ? "period-slider-tooltip-balloon" : ""}`}
2377
+ data-tooltip-style={tooltipStyle}
2378
+ data-label-position={labelPosition}
2379
+ data-slanted={slantResult.isSlanted ? "true" : undefined}
2380
+ data-front={isHighFront ? "true" : undefined}
2381
+ style={highTooltipStyle}>
2382
+ {formatLabel(unit, highDate, props.formatLabel)}
2383
+ </div>
2384
+ )}
2385
+ </div>
2386
+ )}
2387
+ </>
2388
+ )}
2389
+ </div>
2390
+
2391
+ {/* ▶ 1ステップ進むボタン / 垂直時は ▼ 1ステップ戻るボタン */}
2392
+ {showStepper && (
2393
+ <button
2394
+ type="button"
2395
+ className={`period-slider-stepper-btn relative after:absolute after:inset-[-10px] after:content-[''] ${isVertical ? "period-slider-stepper-prev period-slider-stepper-down" : "period-slider-stepper-next"} flex h-6 w-6 shrink-0 items-center justify-center rounded-md border border-slate-300 bg-white font-bold text-[10px] text-slate-700 leading-none shadow-2xs transition-all hover:bg-slate-100 hover:text-indigo-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 active:scale-95 disabled:cursor-not-allowed disabled:opacity-30 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700 ${cursorClass}`}
2396
+ onClick={() => shift(isVertical ? -1 : 1)}
2397
+ disabled={isVertical ? stepperPrevDisabled : stepperNextDisabled}
2398
+ aria-label={isVertical ? "1つ前へ" : "1つ後へ"}>
2399
+ {isVertical ? "▼" : "▶"}
2400
+ </button>
2401
+ )}
2402
+ </div>
2403
+ )
2404
+ }
2405
+
2406
+ /**
2407
+ * Helper to check whether two Date arrays contain equivalent timestamps.
2408
+ * 2 つの Date 配列が同一のタイムスタンプを保持しているかを判定するヘルパー関数。
2409
+ *
2410
+ * @param a - First date array
2411
+ * @param b - Second date array
2412
+ * @returns True if arrays are equivalent
2413
+ */
2414
+ const areDateArraysEqual = (a?: Date[], b?: Date[]): boolean => {
2415
+ if (a === b) return true
2416
+ if (!(a && b)) return false
2417
+ if (a.length !== b.length) return false
2418
+ for (let i = 0; i < a.length; i++) {
2419
+ if (a[i].getTime() !== b[i].getTime()) return false
2420
+ }
2421
+ return true
2422
+ }
2423
+
2424
+ /**
2425
+ * Helper to shallowly compare two CSSProperties style objects.
2426
+ * 2 つの CSSProperties オブジェクトの浅い同値性を判定するヘルパー関数。
2427
+ *
2428
+ * @param a - First style object
2429
+ * @param b - Second style object
2430
+ * @returns True if style objects have identical keys and values
2431
+ */
2432
+ export const areStylesEqual = (a?: React.CSSProperties, b?: React.CSSProperties): boolean => {
2433
+ if (a === b) return true
2434
+ if (!(a && b)) return false
2435
+ const keysA = Object.keys(a) as (keyof React.CSSProperties)[]
2436
+ const keysB = Object.keys(b) as (keyof React.CSSProperties)[]
2437
+ if (keysA.length !== keysB.length) return false
2438
+ for (const key of keysA) {
2439
+ if (a[key] !== b[key]) return false
2440
+ }
2441
+ return true
2442
+ }
2443
+
2444
+ /**
2445
+ * Compares previous and next props for PeriodSlider to prevent unnecessary re-renders.
2446
+ * PeriodSlider の不要な再レンダリングを防止するための Props 比較関数。
2447
+ *
2448
+ * @param prev - Previous props
2449
+ * @param next - Next props
2450
+ * @returns True if props are functionally equivalent, false otherwise
2451
+ */
2452
+ export const arePeriodSliderPropsEqual = (prev: PeriodSliderProps, next: PeriodSliderProps): boolean => {
2453
+ if (prev === next) return true
2454
+ if (prev.mode !== next.mode) return false
2455
+ if (prev.unit !== next.unit) return false
2456
+
2457
+ if ((prev.minDate?.getTime() ?? null) !== (next.minDate?.getTime() ?? null)) return false
2458
+ if ((prev.maxDate?.getTime() ?? null) !== (next.maxDate?.getTime() ?? null)) return false
2459
+
2460
+ if (
2461
+ prev.labelPosition !== next.labelPosition ||
2462
+ prev.autoSlantLabels !== next.autoSlantLabels ||
2463
+ prev.preventCollisionSlant !== next.preventCollisionSlant ||
2464
+ prev.isVertical !== next.isVertical ||
2465
+ prev.hideConnectBar !== next.hideConnectBar ||
2466
+ prev.showTicks !== next.showTicks ||
2467
+ prev.disabled !== next.disabled ||
2468
+ prev.showStepper !== next.showStepper ||
2469
+ prev.debounceMs !== next.debounceMs ||
2470
+ prev.tooltipStyle !== next.tooltipStyle ||
2471
+ prev.colorScheme !== next.colorScheme ||
2472
+ prev.className !== next.className ||
2473
+ !areStylesEqual(prev.style, next.style) ||
2474
+ prev.snapMode !== next.snapMode ||
2475
+ prev.formatLabel !== next.formatLabel ||
2476
+ prev.lowerAriaLabel !== next.lowerAriaLabel ||
2477
+ prev.upperAriaLabel !== next.upperAriaLabel ||
2478
+ prev.pointAriaLabel !== next.pointAriaLabel ||
2479
+ prev.macroLowerAriaLabel !== next.macroLowerAriaLabel ||
2480
+ prev.macroUpperAriaLabel !== next.macroUpperAriaLabel ||
2481
+ prev.formatAriaValueText !== next.formatAriaValueText
2482
+ ) {
2483
+ return false
2484
+ }
2485
+
2486
+ if (!areDateArraysEqual(prev.allowedDates, next.allowedDates)) return false
2487
+
2488
+ if (prev.mode === "point" && next.mode === "point") {
2489
+ const prevVal = prev.value?.getTime() ?? prev.valueDate?.getTime() ?? null
2490
+ const nextVal = next.value?.getTime() ?? next.valueDate?.getTime() ?? null
2491
+ if (prevVal !== nextVal) return false
2492
+ if (prev.onChangePoint !== next.onChangePoint) return false
2493
+ if (prev.onChangeValue !== next.onChangeValue) return false
2494
+ if (prev.onChange !== next.onChange) return false
2495
+ return true
2496
+ }
2497
+
2498
+ if (prev.mode === "range" && next.mode === "range") {
2499
+ const prevLow = prev.range?.[0]?.getTime() ?? prev.lowerDate?.getTime() ?? null
2500
+ const prevHigh = prev.range?.[1]?.getTime() ?? prev.upperDate?.getTime() ?? null
2501
+ const nextLow = next.range?.[0]?.getTime() ?? next.lowerDate?.getTime() ?? null
2502
+ const nextHigh = next.range?.[1]?.getTime() ?? next.upperDate?.getTime() ?? null
2503
+ if (prevLow !== nextLow || prevHigh !== nextHigh) return false
2504
+ if (prev.onChangeRange !== next.onChangeRange) return false
2505
+ if (prev.onChangeRangeTuple !== next.onChangeRangeTuple) return false
2506
+ if (prev.onChange !== next.onChange) return false
2507
+ return true
2508
+ }
2509
+
2510
+ if (prev.mode === "vernier" && next.mode === "vernier") {
2511
+ const prevMicroLow = prev.microRange?.[0]?.getTime() ?? prev.lowerDate?.getTime() ?? null
2512
+ const prevMicroHigh = prev.microRange?.[1]?.getTime() ?? prev.upperDate?.getTime() ?? null
2513
+ const nextMicroLow = next.microRange?.[0]?.getTime() ?? next.lowerDate?.getTime() ?? null
2514
+ const nextMicroHigh = next.microRange?.[1]?.getTime() ?? next.upperDate?.getTime() ?? null
2515
+ if (prevMicroLow !== nextMicroLow || prevMicroHigh !== nextMicroHigh) return false
2516
+
2517
+ const prevMacro0 = prev.macroRange?.[0]?.getTime() ?? null
2518
+ const prevMacro1 = prev.macroRange?.[1]?.getTime() ?? null
2519
+ const nextMacro0 = next.macroRange?.[0]?.getTime() ?? null
2520
+ const nextMacro1 = next.macroRange?.[1]?.getTime() ?? null
2521
+ if (prevMacro0 !== nextMacro0 || prevMacro1 !== nextMacro1) return false
2522
+
2523
+ if (
2524
+ prev.vernierOrientation !== next.vernierOrientation ||
2525
+ prev.showVernierProjection !== next.showVernierProjection ||
2526
+ prev.showVernierTicks !== next.showVernierTicks ||
2527
+ prev.showHairline !== next.showHairline ||
2528
+ prev.adaptiveExpand !== next.adaptiveExpand ||
2529
+ prev.macroUnit !== next.macroUnit ||
2530
+ prev.microUnit !== next.microUnit ||
2531
+ prev.macroIsDiscrete !== next.macroIsDiscrete ||
2532
+ prev.microIsDiscrete !== next.microIsDiscrete ||
2533
+ prev.formatMacroLabel !== next.formatMacroLabel ||
2534
+ prev.formatMicroLabel !== next.formatMicroLabel ||
2535
+ prev.onChangeRange !== next.onChangeRange ||
2536
+ prev.onChangeRangeTuple !== next.onChangeRangeTuple ||
2537
+ prev.onChangeMicroRange !== next.onChangeMicroRange ||
2538
+ prev.onChangeMicroRangeTuple !== next.onChangeMicroRangeTuple ||
2539
+ prev.onChangeMicro !== next.onChangeMicro ||
2540
+ prev.onChangeMacroRange !== next.onChangeMacroRange ||
2541
+ prev.onChangeMacroRangeTuple !== next.onChangeMacroRangeTuple ||
2542
+ prev.onChangeMacro !== next.onChangeMacro
2543
+ ) {
2544
+ return false
2545
+ }
2546
+
2547
+ if (!areDateArraysEqual(prev.macroAllowedDates, next.macroAllowedDates)) return false
2548
+ if (!areDateArraysEqual(prev.microAllowedDates, next.microAllowedDates)) return false
2549
+
2550
+ return true
2551
+ }
2552
+
2553
+ return false
2554
+ }
2555
+
2556
+ export const PeriodSlider = memo(PeriodSliderComponent, arePeriodSliderPropsEqual)
2557
+ PeriodSlider.displayName = "PeriodSlider"