@aiquants/period-slider 0.9.0 → 0.10.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,251 @@
1
+ /**
2
+ * @fileoverview One-unit step button shared by the PeriodSlider steppers and the selectors' previous / next buttons
3
+ * @package @aiquants/period-slider
4
+ *
5
+ * Every step button in the package is drawn, sized, coloured and made unavailable here once. Geometry follows one module:
6
+ * a 22px box (the height of a text-xs form control at the default root font size), a target of `--ps-target-size`
7
+ * (44px, WCAG 2.5.5), and a row gap of half the difference between them, which lands the centred target's inner edge
8
+ * exactly on the neighbour's edge. Beside a bare rail the inner edge stops earlier still, at the knob disc, and the
9
+ * outward reach that buys is reserved inside the slider root. A button that cannot step stays focusable and is announced
10
+ * as unavailable through `aria-disabled`, and its activation is swallowed in the capture phase rather than dropped, so
11
+ * nothing below the React root container sees the `mousedown` / `mouseup` / `click` a native `disabled` button would
12
+ * never have dispatched, and the press takes no focus; only a disabled control takes its buttons out of the tab order.
13
+ *
14
+ * Which quantities are written as `calc(var(--ps-target-size)…)` and which are hand-evaluated is decided by where the
15
+ * class lands, not by taste: the variable is scoped to `.period-slider` and `.period-slider-step` (never the document
16
+ * root, whose host declarations would silently rewrite every hit target), so only classes that land on the slider root
17
+ * or on the button itself can read it. The row gap lands on a selector root, which carries neither hook - a `var()`
18
+ * there is invalid at computed-value time and collapses the row - so it and the inner edges derived from the knob
19
+ * radius are hand-evaluated, and `stepperButtonContract.spec.tsx` reads the shipped `--ps-target-size` to keep the two
20
+ * representations from drifting.
21
+ * どの量を `calc(var(--ps-target-size)…)` で書き、どれを手計算の数値で書くかは、そのクラスがどこへ載るかが決める。
22
+ * 変数のスコープは `.period-slider` と `.period-slider-step` (文書のルートへは置かない。ホストの同名宣言が全ての
23
+ * 当たり判定を書き換えるため) であり、読めるのはスライダーのルートかボタン自身へ載るクラスだけ。行の間隔は
24
+ * どちらのフックも持たないセレクタのルートへ載るため (そこでの `var()` は算出時に無効となり行が潰れる)、
25
+ * 間隔とつまみ半径から導く内縁は手計算の数値で書き、2 つの表現のずれは `stepperButtonContract.spec.tsx` が
26
+ * 配布シートの `--ps-target-size` を読んで固定する。
27
+ *
28
+ * パッケージ内の全ての 1 単位移動ボタンの描画・寸法・配色・使用不可状態を 1 か所に持つモジュール。幾何は 1 つの単位に従う
29
+ * (箱 22px = 既定のルートフォントサイズでの text-xs のフォーム部品の高さ、当たり判定 `--ps-target-size` = 44px (WCAG 2.5.5)、
30
+ * 行の間隔はその差の半分で、中心に置いた当たり判定の内縁がちょうど隣の部品の縁に届く)。素のレールの隣では内縁をさらに手前の
31
+ * つまみ円盤で止め、その分外へ伸びる量はスライダーのルートの中へ確保する。
32
+ * 動けないボタンはフォーカスを保ったまま `aria-disabled` で使用不可を伝え、活性化は捨てるのではなく捕捉フェーズで飲み込むため、
33
+ * ネイティブの `disabled` なら配送されない `mousedown` / `mouseup` / `click` を React のルートコンテナより下のものが
34
+ * 受け取ることはなく、押下がフォーカスを奪うこともない。タブ順から外れるのはコントロール全体が無効な時だけ。
35
+ */
36
+
37
+ import type React from "react"
38
+ import type { Ref } from "react"
39
+
40
+ /**
41
+ * Direction the arrow points on screen.
42
+ * 矢印が画面上で指す向き。
43
+ */
44
+ export type StepArrowDirection = "left" | "right" | "up" | "down"
45
+
46
+ /**
47
+ * What the button stands beside: a framed form control, or a bare rail whose knob disc reaches into the gap.
48
+ * ボタンの隣にあるもの (枠付きのフォーム部品、またはつまみの円盤が間隔へはみ出す素のレール)。
49
+ */
50
+ export type StepperNeighbour = "control" | "rail"
51
+
52
+ /** Row gap between a step button and the control it steps: half of (target - box), so the centred target reaches exactly to the control's edge / ボタンと隣の部品の間隔 ((当たり判定 - 箱) の半分。中心に置いた当たり判定がちょうど部品の縁に届く) */
53
+ export const STEPPER_ROW_GAP_CLASS = "gap-[11px]"
54
+
55
+ /** Apex-to-base depth of the arrow in pixels / 矢印の頂点から底辺までの深さ (ピクセル) */
56
+ const ARROW_DEPTH_PX = 6
57
+
58
+ /** Base of the arrow: twice the depth makes the apex a right angle / 矢印の底辺 (深さの 2 倍で頂角が直角) */
59
+ const ARROW_BASE_PX = ARROW_DEPTH_PX * 2
60
+
61
+ /** Arrow box along the pointing axis: the centroid lies 2D/3 from the apex, so twice that centres it / 指す軸方向の矢印の箱 (重心は頂点から 2D/3 にあり、その 2 倍で箱の中心へ来る) */
62
+ const ARROW_BOX_DEPTH_PX = (ARROW_DEPTH_PX * 4) / 3
63
+
64
+ /** Polygon vertices per direction, in arrow box coordinates / 向きごとの三角形の頂点 (矢印の箱の座標) */
65
+ const ARROW_POINTS: Record<StepArrowDirection, string> = {
66
+ left: `0,${ARROW_BASE_PX / 2} ${ARROW_DEPTH_PX},0 ${ARROW_DEPTH_PX},${ARROW_BASE_PX}`,
67
+ right: `${ARROW_BOX_DEPTH_PX},${ARROW_BASE_PX / 2} ${ARROW_BOX_DEPTH_PX - ARROW_DEPTH_PX},0 ${ARROW_BOX_DEPTH_PX - ARROW_DEPTH_PX},${ARROW_BASE_PX}`,
68
+ up: `${ARROW_BASE_PX / 2},0 0,${ARROW_DEPTH_PX} ${ARROW_BASE_PX},${ARROW_DEPTH_PX}`,
69
+ down: `${ARROW_BASE_PX / 2},${ARROW_BOX_DEPTH_PX} 0,${ARROW_BOX_DEPTH_PX - ARROW_DEPTH_PX} ${ARROW_BASE_PX},${ARROW_BOX_DEPTH_PX - ARROW_DEPTH_PX}`,
70
+ }
71
+
72
+ /**
73
+ * Ends an activation of a button that cannot step, so it reaches nothing beyond the guard itself.
74
+ * 動けないボタンの活性化をその場で終わらせ、ガードより先へ一切届かせない関数。
75
+ *
76
+ * An `aria-disabled` button is a fully interactive button: dropping the handler stops the step but still lets the
77
+ * press be dispatched, so a host's clickable card, toolbar delegation, outside-press dismissal or click tracking
78
+ * fires from an arrow that is painted faded and announced unavailable. A native `disabled` button dispatches no
79
+ * mouse event and takes no focus, and that is the behaviour the unavailable state has to keep while staying focusable.
80
+ * `aria-disabled` のボタンは完全に操作可能なボタンであり、ハンドラを外すだけでは移動は止まっても押下は配送される。
81
+ * 淡く塗られ使用不可と読み上げられる矢印から、ホストのクリック可能なカード・ツールバーの委譲・外側押下による閉じ処理・
82
+ * クリック計測が発火する。ネイティブの `disabled` はマウスイベントを一切配送せずフォーカスも奪わないため、
83
+ * フォーカスを保ったままその挙動を保つ必要がある。
84
+ *
85
+ * @param event - Mouse press or click on an unavailable step button / 使用不可の移動ボタンへのマウス押下またはクリック
86
+ * @returns Nothing / 戻り値なし
87
+ */
88
+ const swallowActivation = (event: React.MouseEvent<HTMLButtonElement>): void => {
89
+ event.preventDefault()
90
+ event.stopPropagation()
91
+ }
92
+
93
+ /**
94
+ * Handlers an unavailable step button carries, which swallow the press before it is dispatched any further.
95
+ * 使用不可の移動ボタンが持つ、押下がそれ以上配送される前に飲み込むハンドラの組。
96
+ *
97
+ * React dispatches these from the React root container while the native event is still descending, so stopping
98
+ * propagation there ends the event before the button and every host element between the two ever sees it. The same
99
+ * guard on the bubble phase could only stop what is above the root container: the native event has by then already
100
+ * passed every ancestor inside it, which is where a host's own listeners sit. `preventDefault` on `mousedown` is
101
+ * what keeps the press from taking focus, exactly as a native `disabled` button does.
102
+ * Pointer events are deliberately not guarded: a native `disabled` button dispatches `pointerdown` / `pointerup` too.
103
+ * React はこれらをネイティブのイベントが下降している間に React のルートコンテナから配送するため、そこで伝播を止めれば
104
+ * ボタン自身にも、ボタンとルートコンテナの間にあるホストの要素にも届く前にイベントが終わる。同じガードをバブルフェーズへ
105
+ * 置くとルートコンテナより外側しか止められない (その時点でネイティブのイベントは内側の祖先を通過済みであり、
106
+ * ホスト自身のリスナーはそこに居る)。`mousedown` の `preventDefault` が、ネイティブの `disabled` と同じく押下にフォーカスを
107
+ * 奪わせない部分。ポインターイベントを意図的に外してあるのは、ネイティブの `disabled` も `pointerdown` / `pointerup` を配送するため。
108
+ */
109
+ const UNAVAILABLE_ACTIVATION_GUARDS: Pick<React.ComponentProps<"button">, "onMouseDownCapture" | "onMouseUpCapture" | "onClickCapture"> = {
110
+ onMouseDownCapture: swallowActivation,
111
+ onMouseUpCapture: swallowActivation,
112
+ onClickCapture: swallowActivation,
113
+ }
114
+
115
+ /** Package hook every step button carries; the stylesheet scopes `--ps-target-size` to it so a selector rendered outside any slider root still reads it / 全ボタンが持つパッケージのフック (スライダーのルートの外へ置かれたセレクタでも `--ps-target-size` が届くよう、スタイルシートがこのクラスへ変数を載せる) */
116
+ const STEPPER_HOOK_CLASS = "period-slider-step"
117
+
118
+ /** Box, arrow centring and the transparent target every step button shares / 全ボタン共通の箱・矢印の中央寄せ・透明な当たり判定 */
119
+ const STEPPER_BASE_CLASSES = `${STEPPER_HOOK_CLASS} relative inline-flex size-[22px] shrink-0 items-center justify-center rounded-md after:absolute after:content-['']`
120
+
121
+ /**
122
+ * Interaction grammar every step button shares: pointer feedback only while the button can act, colour-only motion,
123
+ * and a focus ring that survives forced colours. Every unavailable look reads `aria-disabled`, which a disabled control sets too.
124
+ * 全ボタン共通の操作文法 (ポインターへの反応は動ける間だけ、動きは色だけ、強制カラーでも残るフォーカスリング)。
125
+ * 使用不可の見た目は全て `aria-disabled` から読む (コントロール全体の無効時もこの属性が付く)。
126
+ */
127
+ const STEPPER_STATE_CLASSES =
128
+ "transition-colors motion-reduce:transition-none not-aria-disabled:cursor-pointer aria-disabled:cursor-not-allowed focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-600 dark:focus-visible:ring-blue-400 forced-colors:not-aria-disabled:hover:text-[Highlight] forced-colors:aria-disabled:text-[GrayText]"
129
+
130
+ /**
131
+ * Surface and tone per neighbour: bare beside a framed control, boxed beside a bare rail. The unavailable look fades
132
+ * each colour to 40% instead of fading the element, because element opacity would also fade the focus ring of a
133
+ * focused unavailable button below the 3:1 a focus indicator needs. Hover and press inks are opaque colours only: a
134
+ * faded ink is the unavailable look, so fading it on hover would make an available button look unavailable.
135
+ * 隣ごとの面と配色 (枠付き部品の隣は枠なし、素のレールの隣は枠付き)。使用不可の見た目は要素ではなく各色を 40% へ落とす。
136
+ * 要素の不透明度を落とすと、フォーカス中の使用不可ボタンのリングまで薄まり、フォーカス表示に要る 3:1 を割るため。
137
+ * ホバー・押下の文字色は不透明な色だけ (淡い文字色は使用不可の見た目であり、ホバーで淡くすると押せるボタンが使用不可に見えるため)。
138
+ */
139
+ const STEPPER_SURFACE_CLASSES: Record<StepperNeighbour, string> = {
140
+ control:
141
+ "text-slate-500 not-aria-disabled:hover:bg-slate-500/15 not-aria-disabled:hover:text-slate-900 not-aria-disabled:active:bg-slate-500/25 aria-disabled:text-slate-500/40 dark:text-slate-400 dark:not-aria-disabled:hover:text-slate-50 dark:aria-disabled:text-slate-400/40",
142
+ rail: "border border-slate-300 bg-white text-slate-700 shadow-2xs not-aria-disabled:hover:border-slate-400 not-aria-disabled:hover:bg-slate-100 not-aria-disabled:hover:text-slate-900 not-aria-disabled:active:bg-slate-200 aria-disabled:border-slate-300/40 aria-disabled:bg-white/40 aria-disabled:text-slate-700/40 aria-disabled:shadow-none dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:not-aria-disabled:hover:border-slate-500 dark:not-aria-disabled:hover:bg-slate-700 dark:not-aria-disabled:hover:text-white dark:not-aria-disabled:active:bg-slate-600 dark:aria-disabled:border-slate-700/40 dark:aria-disabled:bg-slate-800/40 dark:aria-disabled:text-slate-200/40",
143
+ }
144
+
145
+ /** Target of `--ps-target-size` centred on the box, whatever the box size (percent insets resolve against the padding box) / 箱の寸法に依らず、箱の中心に置いた `--ps-target-size` 四方の当たり判定 (百分率の inset はパディングボックス基準) */
146
+ const CENTRED_TARGET_CLASS = "after:inset-[calc((100%-var(--ps-target-size))/2)]"
147
+
148
+ /**
149
+ * Reserve, inside the slider root, of the distance a rail stepper's target reaches past its own box along the rail:
150
+ * target 44 - box 22 - inward reach 3 = 19px. Without it the target hit-tests outside the component, where it takes the
151
+ * presses of a host control, of an adjacent selector's arrow and of a neighbouring slider's stepper, and adds the same
152
+ * amount of scrollable overflow to a tight host. With it the root box is the interactive footprint along the rail.
153
+ * レールのステッパーの当たり判定が自分の箱の外へレール方向に伸びる量 (当たり判定 44 − 箱 22 − 内側の到達距離 3 = 19px) を
154
+ * スライダーのルートの中へ確保するクラス。確保しないと当たり判定がコンポーネントの外でヒットテストに答え、ホストの部品・
155
+ * 隣のセレクタの矢印・隣のスライダーのステッパーの押下を奪い、余裕のないホストへ同じ量のスクロールのはみ出しを足す。
156
+ * 確保すれば、レール方向ではルートの箱がそのまま操作面積になる。
157
+ */
158
+ export const STEPPER_OUTWARD_RESERVE_CLASSES: Record<"horizontal" | "vertical", string> = { horizontal: "px-[19px]", vertical: "py-[19px]" }
159
+
160
+ /**
161
+ * Target per neighbour and direction. Across the row the target is centred; along the row its inner edge is where the
162
+ * neighbour's drawing begins. Beside a control that is the control's edge, so the centred target already stops there.
163
+ * Beside the rail it is the knob disc edge: 11px gap - 8px knob radius = 3px into the gap, plus the 1px border because
164
+ * a boxed button positions its target from the padding box, hence 4px inward; the outer edge makes the target
165
+ * `--ps-target-size` long. That outward reach is reserved inside the slider root by `STEPPER_OUTWARD_RESERVE_CLASSES`,
166
+ * so no target leaves the root box along the rail. The enabled target's layer above the front knob lives in the
167
+ * stylesheet beside the knob layers: the knob's own target is the same square and would otherwise cover the half of the
168
+ * button nearest the rail.
169
+ * Hit testing grows the pointer into the 1px square to its right and below, so a target whose inner edge faces left or up
170
+ * still takes under 1px of the neighbour it is painted above; the geometry is not bent around that browser rule.
171
+ * 隣と向きごとの当たり判定。行と直交する向きは中心寄せ、行方向の内縁は隣の描画が始まる位置。部品の隣では部品の縁で、
172
+ * 中心寄せのまま止まる。レールの隣ではつまみ円盤の縁 (間隔 11px − つまみ半径 8px = 間隔へ 3px、枠付きボタンの疑似要素は
173
+ * パディングボックス基準のため枠線 1px を加えて内側 4px)、外縁は長さが `--ps-target-size` になる位置。
174
+ * 外へ伸びる分は `STEPPER_OUTWARD_RESERVE_CLASSES` がスライダーのルートの中へ確保するため、レール方向でルートの箱の外へ出る当たり判定は無い。
175
+ * 押せる当たり判定を前面のつまみより上に置く層は、つまみの層と並べてスタイルシートが持つ (つまみの当たり判定も同じ四方で、
176
+ * そのままではボタンのレール側の半分を覆うため)。
177
+ * ヒットテストはポインターを右と下へ 1px の正方形に広げるため、内縁が左か上を向く当たり判定は上に描かれている相手の
178
+ * 1px 未満をなお取る。幾何はこのブラウザの規則に合わせて曲げない。
179
+ */
180
+ const STEPPER_TARGET_CLASSES: Record<StepperNeighbour, Record<StepArrowDirection, string>> = {
181
+ control: {
182
+ left: CENTRED_TARGET_CLASS,
183
+ right: CENTRED_TARGET_CLASS,
184
+ up: CENTRED_TARGET_CLASS,
185
+ down: CENTRED_TARGET_CLASS,
186
+ },
187
+ rail: {
188
+ left: "after:inset-y-[calc((100%-var(--ps-target-size))/2)] after:left-[calc(100%-var(--ps-target-size)+4px)] after:-right-[4px]",
189
+ right: "after:inset-y-[calc((100%-var(--ps-target-size))/2)] after:-left-[4px] after:right-[calc(100%-var(--ps-target-size)+4px)]",
190
+ up: "after:inset-x-[calc((100%-var(--ps-target-size))/2)] after:top-[calc(100%-var(--ps-target-size)+4px)] after:-bottom-[4px]",
191
+ down: "after:inset-x-[calc((100%-var(--ps-target-size))/2)] after:-top-[4px] after:bottom-[calc(100%-var(--ps-target-size)+4px)]",
192
+ },
193
+ }
194
+
195
+ /**
196
+ * Props of the shared step button.
197
+ * 共有 1 単位移動ボタンの Props。
198
+ */
199
+ export interface StepperButtonProps {
200
+ /** Direction the arrow points / 矢印の向き */
201
+ direction: StepArrowDirection
202
+ /** What the button stands beside / ボタンの隣にあるもの */
203
+ neighbour: StepperNeighbour
204
+ /** Whether the whole control is disabled; the button then leaves the tab order together with the control it steps / コントロール全体が無効か (無効時はボタンも隣の部品と共にタブ順から外れる) */
205
+ disabled: boolean
206
+ /** Whether one step can move the value; a button that cannot keeps its focus and is announced as unavailable / 1 単位の移動で値が動くか (動けないボタンはフォーカスを保ったまま使用不可として読み上げられる) */
207
+ canStep: boolean
208
+ /** Step action, called only while the button is available / 1 単位移動の動作 (使用可能な間だけ呼ばれる) */
209
+ onStep: () => void
210
+ /** Accessible name / アクセシブル名 */
211
+ ariaLabel: string
212
+ /** Hook and grid placement classes owned by the caller / 呼び出し側が持つフック・グリッド配置クラス */
213
+ className?: string
214
+ /** Button element reference / ボタン要素の参照 */
215
+ ref?: Ref<HTMLButtonElement>
216
+ }
217
+
218
+ /**
219
+ * Renders one step button whose arrow centroid sits on the box centre and paints only with the button's ink (no class
220
+ * reaches the arrow through a child or descendant variant), whose target never covers its neighbour, which keeps keyboard
221
+ * focus when it reaches a bound, and which never submits an enclosing form.
222
+ * 矢印の重心が箱の中心にあってボタンの文字色だけで塗られ (子や子孫を選ぶバリアントで矢印へ届くクラスは無い)、当たり判定が隣の部品を覆わず、
223
+ * 境界に着いてもキーボードフォーカスを保ち、囲むフォームを送信しない 1 単位移動ボタンを描画するコンポーネント。
224
+ *
225
+ * @param props - Step button props / ボタンの Props
226
+ * @returns Button element / ボタン要素
227
+ */
228
+ export const StepperButton = ({ direction, neighbour, disabled, canStep, onStep, ariaLabel, className, ref }: StepperButtonProps): React.JSX.Element => {
229
+ const isVerticalArrow = direction === "up" || direction === "down"
230
+ const widthPx = isVerticalArrow ? ARROW_BASE_PX : ARROW_BOX_DEPTH_PX
231
+ const heightPx = isVerticalArrow ? ARROW_BOX_DEPTH_PX : ARROW_BASE_PX
232
+ // 境界でネイティブの disabled を付けると、押していたボタンが無効になった瞬間にフォーカスが文書へ落ち、キーボード利用者が位置を失う。
233
+ // 境界では aria-disabled と押下の無効化だけを行い、ネイティブの disabled はコントロール全体の無効化 (隣の部品も触れない時) に限る
234
+ const isUnavailable = disabled || !canStep
235
+ return (
236
+ <button
237
+ ref={ref}
238
+ type="button"
239
+ aria-label={ariaLabel}
240
+ disabled={disabled}
241
+ aria-disabled={isUnavailable ? true : undefined}
242
+ {...(isUnavailable ? UNAVAILABLE_ACTIVATION_GUARDS : null)}
243
+ onClick={isUnavailable ? undefined : onStep}
244
+ className={`${className === undefined ? "" : `${className} `}${STEPPER_BASE_CLASSES} ${STEPPER_STATE_CLASSES} ${STEPPER_SURFACE_CLASSES[neighbour]} ${STEPPER_TARGET_CLASSES[neighbour][direction]}`}>
245
+ {/* 疑似要素の当たり判定が矢印の上に載るため矢印自身の :hover は発火しない。色はボタンの currentColor から受ける */}
246
+ <svg aria-hidden="true" focusable="false" data-arrow={direction} width={widthPx} height={heightPx} viewBox={`0 0 ${widthPx} ${heightPx}`} fill="currentColor" className="pointer-events-none block shrink-0">
247
+ <polygon points={ARROW_POINTS[direction]} />
248
+ </svg>
249
+ </button>
250
+ )
251
+ }
@@ -5,14 +5,17 @@
5
5
  * Provides a year selector rendered as a dropdown flanked by stepper buttons that move the
6
6
  * selection by one year. Missing and invalid inputs fail fast rather than being substituted.
7
7
  * Option text is locale-independent ISO 8601 until a `locale` tag opts into Intl formatting.
8
+ * The ◀▶ buttons are drawn by `StepperButton`.
8
9
  *
9
10
  * ドロップダウンと ±1 年ステッパーによる年セレクタ。欠落値・不正値は代替せず即時エラー。
10
11
  * 選択肢テキストは既定でロケール非依存の ISO 8601 表記、`locale` 指定時のみ Intl 書式。
12
+ * ◀▶ は `StepperButton` が描く。
11
13
  */
12
14
 
13
15
  import type React from "react"
14
16
  import { memo, useEffect, useMemo, useState } from "react"
15
17
  import { formatLabel } from "./PeriodSlider"
18
+ import { STEPPER_ROW_GAP_CLASS, StepperButton } from "./StepperButton"
16
19
 
17
20
  /**
18
21
  * Props of the year-resolution selector.
@@ -26,9 +29,9 @@ import { formatLabel } from "./PeriodSlider"
26
29
  * 通じた利用側の選択。
27
30
  */
28
31
  export interface YearSelectorProps {
29
- /** Controlled selected date; required unless `initialDate` is supplied / 選択日付(外部制御用・`initialDate` 未指定時は必須) */
32
+ /** Controlled selected date; required unless `initialDate` is supplied / 選択日付 (外部制御用・`initialDate` 未指定時は必須) */
30
33
  value?: Date
31
- /** Initial selected date; required unless `value` is supplied / 選択日付(非制御用・`value` 未指定時は必須) */
34
+ /** Initial selected date; required unless `value` is supplied / 選択日付 (非制御用・`value` 未指定時は必須) */
32
35
  initialDate?: Date
33
36
  /** Callback triggered when year changes / 年変更時コールバック */
34
37
  onChange?(date: Date, year: number): void
@@ -210,9 +213,6 @@ const YearSelectorComponent = (props: YearSelectorProps): React.JSX.Element => {
210
213
  const prevYear = isWithinBounds(currentYear - 1) ? currentYear - 1 : null
211
214
  const nextYear = isWithinBounds(currentYear + 1) ? currentYear + 1 : null
212
215
 
213
- const isPrevDisabled = disabled || prevYear === null
214
- const isNextDisabled = disabled || nextYear === null
215
-
216
216
  const handlePrevious = () => {
217
217
  if (prevYear !== null) emit(prevYear)
218
218
  }
@@ -236,19 +236,12 @@ const YearSelectorComponent = (props: YearSelectorProps): React.JSX.Element => {
236
236
  }, [minYearBound, maxYearBound, isSelectionOutsideBounds, currentYear])
237
237
 
238
238
  return (
239
- <div className={`inline-flex w-32 items-center ${className}`} style={style}>
240
- <button
241
- type="button"
242
- aria-label={prevYearAriaLabel}
243
- disabled={isPrevDisabled}
244
- className="relative my-auto inline-flex h-5 w-4 cursor-pointer items-center justify-center rounded p-0 after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 disabled:opacity-40"
245
- onClick={handlePrevious}>
246
- <span className="h-0 w-0 border-y-[6px] border-y-transparent border-r-[6px] border-r-slate-500 border-solid hover:border-r-slate-700 dark:border-r-slate-400 dark:hover:border-r-slate-200" />
247
- </button>
239
+ <div className={`inline-flex items-center ${STEPPER_ROW_GAP_CLASS} ${className}`} style={style}>
240
+ <StepperButton neighbour="control" direction="left" disabled={disabled} canStep={prevYear !== null} onStep={handlePrevious} ariaLabel={prevYearAriaLabel} />
248
241
  <select
249
242
  aria-label={selectAriaLabel}
250
243
  disabled={disabled}
251
- className="mx-1 my-auto w-18 appearance-none rounded-md border border-gray-300 bg-gray-100 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums [text-align-last:center] [text-align:center] focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100 dark:focus:border-blue-500 dark:focus:ring-blue-500"
244
+ className="w-18 appearance-none rounded-md border border-gray-300 bg-gray-100 px-1 py-0.5 text-center font-mono text-gray-900 text-xs tabular-nums [text-align-last:center] [text-align:center] focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-700 dark:text-slate-100 dark:focus:border-blue-500 dark:focus:ring-blue-500"
252
245
  value={currentYear}
253
246
  onChange={(e) => {
254
247
  // 空値の change は選択解除であり、年として解釈しない
@@ -263,14 +256,7 @@ const YearSelectorComponent = (props: YearSelectorProps): React.JSX.Element => {
263
256
  </option>
264
257
  ))}
265
258
  </select>
266
- <button
267
- type="button"
268
- aria-label={nextYearAriaLabel}
269
- disabled={isNextDisabled}
270
- className="relative my-auto inline-flex h-5 w-4 cursor-pointer items-center justify-center rounded p-0 after:absolute after:inset-[-14px] after:content-[''] focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 disabled:opacity-40"
271
- onClick={handleNext}>
272
- <span className="h-0 w-0 border-y-[6px] border-y-transparent border-l-[6px] border-l-slate-500 border-solid hover:border-l-slate-700 dark:border-l-slate-400 dark:hover:border-l-slate-200" />
273
- </button>
259
+ <StepperButton neighbour="control" direction="right" disabled={disabled} canStep={nextYear !== null} onStep={handleNext} ariaLabel={nextYearAriaLabel} />
274
260
  {children}
275
261
  </div>
276
262
  )
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @fileoverview Presentation tier of a pointer drag: where the dragged parts are drawn while the pointer is down
3
+ * @package @aiquants/period-slider
4
+ *
5
+ * A drag has two tiers. The domain tier is the published selection: it snaps to the unit or to the allowed
6
+ * candidates, it drives every callback and every `aria-value*`, and this module does not touch it. The
7
+ * presentation tier is where the grabbed parts are drawn meanwhile, and it is the pointer's own floating-point
8
+ * position on the rail, so a rail whose step is tens of pixels wide stops freezing and jumping under the finger.
9
+ *
10
+ * The tier reaches the DOM as CSS custom properties written on the track element, which every drawn part reads as
11
+ * `var(<variable>, <committed position>)`. The committed position is therefore the fallback: removing the variable
12
+ * puts the part back where its value says it is, with no second write and no chance of an override outliving the
13
+ * drag. The variables are internal (`--ps-*`), never a styling API, and the shipped stylesheet resets every one of
14
+ * them on the track so a host declaration of the same name can never reach a part.
15
+ *
16
+ * Every quantity that depends on where a part is drawn travels this path, the anti-collision placement of the two
17
+ * indicator labels included: solving it from the committed positions would separate the labels for a distance that
18
+ * is up to half a step away from the one they are drawn at.
19
+ *
20
+ * ポインタードラッグの 2 層のうち「描画される位置」を受け持つモジュール。
21
+ * 値層は公表される選択そのもの (単位や候補へスナップし、全コールバックと `aria-value*` を決める) で、本モジュールは触れない。
22
+ * 表示層はその間に掴んだ部品が描かれる位置であり、レール上のポインター位置そのもの (浮動小数)。
23
+ * これにより 1 目盛りが数十ピクセルあるレールでも、つまみが固まってから跳ぶことがなくなる。
24
+ *
25
+ * 表示層はトラック要素へ書き込む CSS カスタムプロパティとして DOM へ届き、描かれる部品は
26
+ * `var(<変数>, <確定位置>)` の形でそれを読む。確定位置が常にフォールバックであるため、
27
+ * 変数を消した瞬間に部品は値どおりの位置へ戻り、二度目の書き込みも、ドラッグより長生きする上書きも起こらない。
28
+ * 変数は内部用 (`--ps-*`) であり、スタイリング API ではない。
29
+ */
30
+
31
+ /**
32
+ * Rail whose pair of parts one drag moves.
33
+ * 1 回のドラッグが動かす対を持つレール。
34
+ */
35
+ export type DragPresentationRail = "flat" | "macro" | "micro"
36
+
37
+ /**
38
+ * What an edge drag grabbed: one edge of a pair, or the zero-width point handle.
39
+ * 縁のドラッグが掴んだ対象 (対の片方の縁、または幅ゼロの時点つまみ)。
40
+ */
41
+ export type DragEdgeKind = "low" | "high" | "point"
42
+
43
+ /** Duration of the snap back to the committed position, in milliseconds; the sole source of both the CSS duration and the timer that closes the window / 確定位置へ収め戻す時間 (ミリ秒。CSS の継続時間と窓を閉じるタイマーの唯一の出典) */
44
+ export const DRAG_SNAP_BACK_MS = 120
45
+
46
+ /** Attribute the track carries while the parts are settling back onto their committed positions / 部品が確定位置へ収まる間だけトラックが持つ属性 */
47
+ export const DRAG_SNAP_ATTRIBUTE = "data-drag-snap"
48
+
49
+ /** Custom property the snap-back transition reads its duration from; absent, the whole declaration is invalid and nothing moves / 収め戻しの遷移が継続時間を読むカスタムプロパティ (無ければ宣言ごと無効になり、何も動かない) */
50
+ export const DRAG_SNAP_DURATION_VARIABLE = "--ps-drag-snap-duration"
51
+
52
+ /** Lower and upper custom property of each rail, in that order / レールごとの下限・上限カスタムプロパティ (この順) */
53
+ export const DRAG_PRESENTATION_VARIABLES: Record<DragPresentationRail, readonly [string, string]> = {
54
+ flat: ["--ps-drag-low", "--ps-drag-high"],
55
+ macro: ["--ps-drag-macro-low", "--ps-drag-macro-high"],
56
+ micro: ["--ps-drag-micro-low", "--ps-drag-micro-high"],
57
+ }
58
+
59
+ /** Side one label of a pair stands on / 対のうちラベル 1 枚が立つ側 */
60
+ export type DragLabelSide = "low" | "high"
61
+
62
+ /** Both sides of a pair, in ascending order / 対の両側 (昇順) */
63
+ export const DRAG_LABEL_SIDES: readonly DragLabelSide[] = ["low", "high"]
64
+
65
+ /** Placement quantities one label reads, in the order the tooltip transform composes them / ラベル 1 枚が読む配置量 (ツールチップの transform が合成する順) */
66
+ export const DRAG_LABEL_PLACEMENT_PARTS = ["tx", "ty", "rot"] as const
67
+
68
+ /** One of the three placement quantities of a label / ラベルの配置量 3 つのうちの 1 つ */
69
+ export type DragLabelPlacementPart = (typeof DRAG_LABEL_PLACEMENT_PARTS)[number]
70
+
71
+ /** Custom property prefix carrying one label's live placement, per rail and side; each part appends its own name / レールと側ごとに、ラベル 1 枚の実時間の配置を運ぶカスタムプロパティの接頭辞 (成分名を後置する) */
72
+ export const DRAG_LABEL_VARIABLE_PREFIXES: Record<DragPresentationRail, Record<DragLabelSide, string>> = {
73
+ flat: { low: "--ps-drag-label-low", high: "--ps-drag-label-high" },
74
+ macro: { low: "--ps-drag-macro-label-low", high: "--ps-drag-macro-label-high" },
75
+ micro: { low: "--ps-drag-micro-label-low", high: "--ps-drag-micro-label-high" },
76
+ }
77
+
78
+ /**
79
+ * Placement of one label, in the same terms its committed inline style writes.
80
+ * ラベル 1 枚の配置を、確定インラインスタイルが書くものと同じ量で表したもの。
81
+ */
82
+ export interface DragLabelPlacement {
83
+ /** Horizontal translation the transform applies / transform が与える水平平行移動量 */
84
+ tx: string
85
+ /** Vertical translation the transform applies / transform が与える垂直平行移動量 */
86
+ ty: string
87
+ /** Rotation the transform applies / transform が与える回転角 */
88
+ rot: string
89
+ }
90
+
91
+ /** Live placement of both labels of one pair, or null when the pair reads no live placement / 1 対の両枚の実時間の配置 (対が実時間の配置を読まないなら null) */
92
+ export type DragLabelPlacementPair = Record<DragLabelSide, DragLabelPlacement> | null
93
+
94
+ /**
95
+ * Names the custom property one placement quantity of one label is carried by.
96
+ * ラベル 1 枚の配置量 1 つを運ぶカスタムプロパティの名前を返す関数。
97
+ *
98
+ * @param prefix - Prefix of the label, from `DRAG_LABEL_VARIABLE_PREFIXES` / `DRAG_LABEL_VARIABLE_PREFIXES` が与えるラベルの接頭辞
99
+ * @param part - Placement quantity / 配置量
100
+ * @returns Custom property name / カスタムプロパティ名
101
+ */
102
+ export const dragLabelVariable = (prefix: string, part: DragLabelPlacementPart): string => `${prefix}-${part}`
103
+
104
+ /**
105
+ * Builds the inline style value of one placement quantity: the live variable, falling back to the committed value.
106
+ * 配置量 1 つ分のインラインスタイル値 (実時間の変数と、その既定値としての確定値) を組み立てる関数。
107
+ *
108
+ * @param prefix - Prefix of the label / ラベルの接頭辞
109
+ * @param part - Placement quantity / 配置量
110
+ * @param committed - Value the committed placement names / 確定配置が名指す値
111
+ * @returns Style value reading the variable with the committed value as its fallback / 確定値を既定値として変数を読むスタイル値
112
+ */
113
+ export const dragLabelPlacementValue = (prefix: string, part: DragLabelPlacementPart, committed: string): string => `var(${dragLabelVariable(prefix, part)}, ${committed})`
114
+
115
+ /**
116
+ * Writes the live placement of one rail's label pair onto the track.
117
+ * 1 つのレールのラベルの対について、実時間の配置をトラックへ書き込む関数。
118
+ *
119
+ * The anti-collision geometry is solved for the distance the labels are actually drawn at, so it has to travel the
120
+ * same path the positions do: a custom property on the track, read by each label as `var(<variable>, <committed>)`.
121
+ * 重なり回避の幾何はラベルが実際に描かれる距離に対して解くため、位置と同じ経路を通る
122
+ * (トラックへ書くカスタムプロパティを、各ラベルが `var(<変数>, <確定値>)` の形で読む)。
123
+ *
124
+ * @param track - Track element every drawn part descends from / 描かれる部品すべての祖先であるトラック要素
125
+ * @param rail - Rail the drag moves / ドラッグが動かすレール
126
+ * @param pair - Placement of both labels of the pair / 対の両枚の配置
127
+ * @returns Nothing / 戻り値なし
128
+ */
129
+ export const writeDragLabelPlacement = (track: HTMLElement, rail: DragPresentationRail, pair: Record<DragLabelSide, DragLabelPlacement>): void => {
130
+ const prefixes = DRAG_LABEL_VARIABLE_PREFIXES[rail]
131
+ for (const side of DRAG_LABEL_SIDES) {
132
+ for (const part of DRAG_LABEL_PLACEMENT_PARTS) track.style.setProperty(dragLabelVariable(prefixes[side], part), pair[side][part])
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Confines a pointer ratio to the rail it is drawn on.
138
+ * ポインター比率を、描画されるレールの範囲へ収める関数。
139
+ *
140
+ * @param ratio - Raw pointer ratio / 生のポインター比率
141
+ * @returns Ratio between 0 and 1 / 0 から 1 の比率
142
+ */
143
+ const clampToRail = (ratio: number): number => Math.max(0, Math.min(1, ratio))
144
+
145
+ /**
146
+ * Resolves the pair of 0-1 positions the parts take while one edge (or the point handle) is dragged.
147
+ * 縁 (または時点つまみ) をドラッグしている間に部品が取る 0-1 位置の対を解決する関数。
148
+ *
149
+ * The edge that was not grabbed is the pivot the grabbed one crosses, so the returned pair is always ascending and
150
+ * the swap happens at exactly the pivot's drawn ratio - the same ratio `resolveDraggedEdge` names the moving edge at,
151
+ * which is what keeps the highlighted and frontmost handle the one drawn under the pointer. A point handle carries no
152
+ * width and resolves to the bare pointer ratio in both slots.
153
+ * 掴んでいない側が、掴んだ側が越える支点となるため、戻り値の対は常に昇順であり、入れ替わりは支点が描かれている比率そのもので起こる
154
+ * (`resolveDraggedEdge` が動いている縁を名指す比率と同一であり、これにより強調表示と最前面が常にポインターの下に描かれたつまみになる)。
155
+ * 時点つまみは幅を持たないため両スロットとも素のポインター比率。
156
+ *
157
+ * @param kind - What the drag grabbed / ドラッグが掴んだ対象
158
+ * @param pointerRatio - Current pointer position along the rail as a 0-1 ratio / レール上の現在のポインター位置 (0-1 比率)
159
+ * @param startLowRatio - Lower part position when the drag began / ドラッグ開始時の下限側の位置
160
+ * @param startHighRatio - Upper part position when the drag began / ドラッグ開始時の上限側の位置
161
+ * @returns Ascending [lower, upper] position pair / 昇順の [下限, 上限] 位置の対
162
+ */
163
+ export const resolveEdgeDragRatios = (kind: DragEdgeKind, pointerRatio: number, startLowRatio: number, startHighRatio: number): [number, number] => {
164
+ const clamped = clampToRail(pointerRatio)
165
+ if (kind === "point") return [clamped, clamped]
166
+ const pivot = kind === "low" ? startHighRatio : startLowRatio
167
+ return [Math.min(clamped, pivot), Math.max(clamped, pivot)]
168
+ }
169
+
170
+ /**
171
+ * Resolves the pair of 0-1 positions the parts take while the band between them is dragged.
172
+ * 2 つの縁が挟む帯をドラッグしている間に部品が取る 0-1 位置の対を解決する関数。
173
+ *
174
+ * @param pointerDeltaRatio - Pointer translation along the rail as a fraction of the rail length / レール長に対するポインター移動量の比率
175
+ * @param startLowRatio - Lower part position when the drag began / ドラッグ開始時の下限側の位置
176
+ * @param startHighRatio - Upper part position when the drag began / ドラッグ開始時の上限側の位置
177
+ * @returns Ascending [lower, upper] position pair of the same width as at drag start / 開始時と同じ幅を持つ昇順の [下限, 上限] 位置の対
178
+ */
179
+ export const resolveBandDragRatios = (pointerDeltaRatio: number, startLowRatio: number, startHighRatio: number): [number, number] => {
180
+ const width = startHighRatio - startLowRatio
181
+ // 幅を先に確定させ、下限だけをレールへ収める。両端を別々に収めると、端に着いた帯が細る
182
+ const lowRatio = Math.max(0, Math.min(1 - width, startLowRatio + pointerDeltaRatio))
183
+ return [lowRatio, lowRatio + width]
184
+ }
185
+
186
+ /**
187
+ * Resolves which edge the pointer is dragging once crossings are taken into account.
188
+ * 交差を織り込んだうえで、ポインターがいまどちらの縁を動かしているかを解決する関数。
189
+ *
190
+ * @param kind - Edge the press originally grabbed / 押下が最初に掴んだ縁
191
+ * @param pointerRatio - Current pointer position along the rail as a 0-1 ratio / レール上の現在のポインター位置 (0-1 比率)
192
+ * @param startLowRatio - Lower part position when the drag began / ドラッグ開始時の下限側の位置
193
+ * @param startHighRatio - Upper part position when the drag began / ドラッグ開始時の上限側の位置
194
+ * @returns Edge the pointer is moving now / いまポインターが動かしている縁
195
+ */
196
+ export const resolveDraggedEdge = (kind: "low" | "high", pointerRatio: number, startLowRatio: number, startHighRatio: number): "low" | "high" => {
197
+ const clamped = clampToRail(pointerRatio)
198
+ if (kind === "low") return clamped > startHighRatio ? "high" : "low"
199
+ return clamped < startLowRatio ? "low" : "high"
200
+ }
201
+
202
+ /**
203
+ * Builds the SVG path of the vernier projection cone for one macro window.
204
+ * 指定のマクロ窓に対する、ノギスの台形プロジェクションの SVG パスを構築する関数。
205
+ *
206
+ * Both the committed geometry React renders and the live geometry the drag writes come from here, so the cone can
207
+ * never disagree with the macro band it springs from. Every orientation emits the same four commands, which is what
208
+ * lets the snap back interpolate between two of these strings.
209
+ * React が描く確定形状も、ドラッグが書き込む実時間の形状も本関数から出るため、
210
+ * コーンが根元のマクロ帯と食い違うことがない。どの向きでも命令列が同一であり、それが収め戻しの補間を成立させる。
211
+ *
212
+ * @param macroLowRatio - Macro window start as a 0-1 ratio / マクロ窓開始位置の比率 (0-1)
213
+ * @param macroHighRatio - Macro window end as a 0-1 ratio / マクロ窓終了位置の比率 (0-1)
214
+ * @param isVertical - Whether the slider is drawn vertically / 縦向き描画か
215
+ * @param isMacroFirstRail - Whether the macro scale owns the first rail (top or left) / マクロスケールが第一レール (上段または左段) を持つか
216
+ * @returns Path data of the cone in the projection viewBox / プロジェクションの viewBox 座標系におけるコーンのパスデータ
217
+ */
218
+ export const buildVernierProjectionPath = (macroLowRatio: number, macroHighRatio: number, isVertical: boolean, isMacroFirstRail: boolean): string => {
219
+ if (isVertical) {
220
+ // 縦向きは下端が定義域の下限。viewBox は上が原点なので、比率をそのまま Y に使うと上下が逆になる
221
+ const lowY = (1 - macroLowRatio) * 100
222
+ const highY = (1 - macroHighRatio) * 100
223
+ return isMacroFirstRail ? `M 12 ${highY} L 12 ${lowY} L 20 100 L 20 0 Z` : `M 12 0 L 12 100 L 20 ${lowY} L 20 ${highY} Z`
224
+ }
225
+ const lowX = macroLowRatio * 100
226
+ const highX = macroHighRatio * 100
227
+ return isMacroFirstRail ? `M ${lowX} 12 L ${highX} 12 L 100 20 L 0 20 Z` : `M 0 12 L 100 12 L ${highX} 20 L ${lowX} 20 Z`
228
+ }
229
+
230
+ /**
231
+ * Builds the inline style value of one position: the live variable, falling back to the committed position.
232
+ * 位置 1 つ分のインラインスタイル値 (実時間の変数と、その既定値としての確定位置) を組み立てる関数。
233
+ *
234
+ * @param variable - Custom property the presentation tier writes / 表示層が書き込むカスタムプロパティ
235
+ * @param committedPercent - Position the committed value names, in percent / 確定値が名指す位置 (百分率)
236
+ * @returns Style value reading the variable with the committed position as its fallback / 確定位置を既定値として変数を読むスタイル値
237
+ */
238
+ export const dragPresentationValue = (variable: string, committedPercent: number): string => `var(${variable}, ${committedPercent}%)`
239
+
240
+ /**
241
+ * Writes the live position pair of one rail onto the track.
242
+ * 1 つのレールの実時間の位置の対を、トラックへ書き込む関数。
243
+ *
244
+ * @param track - Track element every drawn part descends from / 描かれる部品すべての祖先であるトラック要素
245
+ * @param rail - Rail the drag moves / ドラッグが動かすレール
246
+ * @param lowRatio - Lower part position as a 0-1 ratio / 下限側の位置 (0-1 比率)
247
+ * @param highRatio - Upper part position as a 0-1 ratio / 上限側の位置 (0-1 比率)
248
+ * @returns Nothing / 戻り値なし
249
+ */
250
+ export const writeDragPresentation = (track: HTMLElement, rail: DragPresentationRail, lowRatio: number, highRatio: number): void => {
251
+ const [lowVariable, highVariable] = DRAG_PRESENTATION_VARIABLES[rail]
252
+ track.style.setProperty(lowVariable, `${lowRatio * 100}%`)
253
+ track.style.setProperty(highVariable, `${highRatio * 100}%`)
254
+ }
255
+
256
+ /**
257
+ * Removes every live position from the track, returning all parts to their committed positions.
258
+ * 実時間の位置をすべてトラックから取り除き、全部品を確定位置へ戻す関数。
259
+ *
260
+ * @param track - Track element every drawn part descends from / 描かれる部品すべての祖先であるトラック要素
261
+ * @returns Nothing / 戻り値なし
262
+ */
263
+ export const clearDragPresentation = (track: HTMLElement): void => {
264
+ for (const [lowVariable, highVariable] of Object.values(DRAG_PRESENTATION_VARIABLES)) {
265
+ track.style.removeProperty(lowVariable)
266
+ track.style.removeProperty(highVariable)
267
+ }
268
+ for (const prefixes of Object.values(DRAG_LABEL_VARIABLE_PREFIXES)) {
269
+ for (const side of DRAG_LABEL_SIDES) {
270
+ for (const part of DRAG_LABEL_PLACEMENT_PARTS) track.style.removeProperty(dragLabelVariable(prefixes[side], part))
271
+ }
272
+ }
273
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  export type { DateSelectorProps } from "./DateSelector"
20
20
  export { DateSelector } from "./DateSelector"
21
+ export { resolveDraggedEdge } from "./dragPresentation"
21
22
  export type { MonthSelectorProps } from "./MonthSelector"
22
23
  export { MonthSelector } from "./MonthSelector"
23
24
  export type {
@@ -56,7 +57,6 @@ export {
56
57
  findNearestDateIndex,
57
58
  formatLabel,
58
59
  formatScreenReaderLabel,
59
- getActiveDragHandle,
60
60
  getMacroWindowEndDate,
61
61
  getMacroWindowStartDate,
62
62
  getSortedAllowedDates,