From e3f1c20840a00d1fd99343dbf0554da693a60e0f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 06:09:50 -0700 Subject: [PATCH 1/4] chore(core): UIPickerView's values in the UIKit table motion/uikit/picker.ts holds UIPickerView's measured values, each sourced: 32 pt rows on a 97.2 pt cylinder at perspective 900, a 34 pt band inset 9 pt, the band row magnified 23.5/21, dimmed rows at 0.447, a 291 pt rubber band, the coast's stop speed and velocity floor, the snap at rest, a 0.3 s tap spin and a 40 ms tick (iOS 26.2 simulator, real HID touches, Oct 23 2026). Every value is an internal constant: spec:AST-094 FR4 names none of them, so nothing registers this table (DEC-11). The UIKit index exports it, and MEASUREMENTS.md and the motion README list it. --- packages/core/src/motion/MEASUREMENTS.md | 14 ++ packages/core/src/motion/README.md | 1 + packages/core/src/motion/uikit/index.ts | 6 +- packages/core/src/motion/uikit/picker.ts | 170 +++++++++++++++++++++++ 4 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 packages/core/src/motion/uikit/picker.ts diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md index 96b5578d38fb0..e2c8c3fc12b72 100644 --- a/packages/core/src/motion/MEASUREMENTS.md +++ b/packages/core/src/motion/MEASUREMENTS.md @@ -269,3 +269,17 @@ fades in, with Prefer Cross-Fade Transitions on or off. | M-CM4 | Reduce Motion press feedback | Probe app with Reduce Motion on: long press, then dismiss | press feedback, lift and dismiss animations under Reduce Motion | A, B | | M-CM5 | Commit haptic stand-in | An Android device: `navigator.vibrate` patterns against the platform's HapticFeedbackConstants for the context-click moment | the pattern that matches; not a UIKit parity value (as M-G18) | H | | M-CM6 | Press thresholds | Probe app: repeated long presses at random vsync phases | from touch receipt and from the HID timestamp, the tick before and the tick at the press observer's began and at the click commit; the intersection pins the 150 ms and 400 ms thresholds | C | + +## Picker (UIPickerView) + +Values the Wheel reads from its own table (`uikit/picker.ts`). + +Done (UIKit lab, iOS 26.2 simulator, Oct 23 2026; in the picker's table): the +geometry (row pitch, cylinder, perspective, band, the band copy's +magnification, the dimmed copies' opacity), the rubber band's dimension, the +coast's stop speed, the velocity floor, the snap at rest, the tap spin and +the selection tick. Measured and kept by the gesture system instead: the +scroll view coasts with 0.25 × the pan's velocity plus 0.75 × its value one +event earlier (four HID releases; `velocity.scrollReleaseWeight`, which a +pan's `scrollVelocity()` reads). On UIKit, Reduce Motion with Prefer Cross-Fade changes +nothing on a picker; the Wheel follows design:reduced-motion instead. diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 8b8fa725a524a..b3b2447f282ac 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -19,6 +19,7 @@ so each keeps its measured value; no shipped component reads the roles yet. | `uikit/timing.ts` | Non-spring clocks and curves: press highlight, Core Animation's named curves, keyboard, Reduced Motion cross-fade. | | `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. | | `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). | +| `uikit/picker.ts` | UIPickerView: wheel geometry and band, velocity floor, the coast's stop speed, snap at rest, tap spin, tick. | | `MEASUREMENTS.md` | The UIKit reference captures each unconfirmed value still needs. | | `spring.ts` | Closed-form damped spring, every Apple parameterization, settling duration, a spring chasing a moving target. | | `decay.ts` | UIScrollView's momentum coast. | diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index 317b51207a562..372eb45221ca4 100644 --- a/packages/core/src/motion/uikit/index.ts +++ b/packages/core/src/motion/uikit/index.ts @@ -3,9 +3,8 @@ /** * @file index.ts * @input The domain files of the UIKit constants table - * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`, - * …), `scroll`, `timing`, `navigation` and the - * gesture thresholds (one `UIKIT_*` group per recognizer, their union + * @output Re-exports `springs`, `scroll`, `timing`, `navigation`, `picker` and + * the gesture thresholds (one `UIKIT_*` group per recognizer, their union * `UIKIT_GESTURES`, and the haptic tables) * @position Entry of the UIKit constants table (motion/uikit). Internal to * core: not exported from the package entry point @@ -39,6 +38,7 @@ export { type HapticFeedbackKind, } from './gestures'; export {navigation, registerNavigationTable} from './navigation'; +export {picker} from './picker'; export {registerScrollTable, scroll} from './scroll'; export { ACTION_SHEET_DISMISS_SPRING, diff --git a/packages/core/src/motion/uikit/picker.ts b/packages/core/src/motion/uikit/picker.ts new file mode 100644 index 0000000000000..1c8b477acfe1f --- /dev/null +++ b/packages/core/src/motion/uikit/picker.ts @@ -0,0 +1,170 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file picker.ts + * @input Nothing; data only + * @output Exports `picker`, the UIPickerView constants: the cylinder the rows + * sit on, the selection band, the release rule (velocity, target, coast), + * the snap at rest, the tap spin and the selection tick + * @position The picker domain of the UIKit constants table (motion/uikit); + * read by DateInput/wheelPhysics.ts and DateInput/wheelDrum.ts + * + * Every leaf carries one `@source` (apple-docs | wwdc | webkit | measured | + * GUESS); webkit and GUESS values also carry the `@measure` task that will + * confirm or replace them (listed in motion/MEASUREMENTS.md). uikit.test.ts + * enforces both. + * + * Lengths are in pt at UIKit's scale (the Wheel scales them to its row + * pitch), times in ms, velocities in pt/ms (UIScrollView's own unit). + * + * The measurements are a 402 × 216 pt UIPickerView with two columns (24 and + * 60 rows) in an instrumented host app on the iOS 26.2 simulator (iPhone 17 + * Pro), driven by real HID touches: per-frame offsets, the table views' and + * cells' layers, the delegate calls and the haptics, Oct 23 2026. + * + * Every value here is an internal constant, not a motion role: spec:AST-094 + * FR4 names none of them, so nothing registers this table. The tap spin's + * curve is the shared role `timing.curves.move`, and the bounce at an end is + * `scroll.bounce`. + * + * SYNC: When modified, update: + * - /packages/core/src/motion/MEASUREMENTS.md (measurement tasks) + */ + +export const picker = { + geometry: { + /** + * Row pitch: rows sit at k × 32 pt in each column's table. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIPickerView table offsets and cell frames, Oct 23 2026 + */ + rowHeight: 32, + /** + * The picker's height (its intrinsic content size). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIPickerView frame, Oct 23 2026 + */ + height: 216, + /** + * Radius of the cylinder the rows are drawn on. Each cell is a rotation + * about x by its distance from the band over this radius (18.85°, + * 37.8°, 56.7°, 75.7° for rows ±1 to ±4), moved onto the cylinder + * (R sin θ, R (cos θ − 1)). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, cell CATransform3D of the outer table copies at rest + * (m22 = m33 = cos θ, m23 = −m32 = sin θ; m42, m43), Oct 23 2026 + */ + cylinderRadius: 97.2, + /** + * Perspective distance of the dimmed copies above and below the band: + * their tables' sublayerTransform has m34 = −1/900, centred on the + * picker (every column's table is centred on it, so all columns share + * one vanishing point). The band's own copy has none. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIPickerTableView layer sublayerTransform, Oct 23 2026 + */ + perspective: 900, + /** + * Height of the selection band, centred on the picker. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, the band UIView (384 × 34 pt at 9, 291), Oct 23 2026 + */ + bandHeight: 34, + /** + * The band's inset from the picker's sides: one band spans every column. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, the band UIView (384 × 34 pt at 9, 291 in a 402 pt + * picker), Oct 23 2026 + */ + bandInset: 9, + /** + * The band's copy of the rows is magnified about the picker's centre: + * its labels are 23.5 pt against 21 pt in the dimmed copies, and its + * columns sit that much further from the centre (band digits ≈ 11 pt + * outward of the rows above and below, on screen). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, label fonts of the three table copies and the + * rendered digits' extents in a screenshot, Oct 23 2026 + */ + bandMagnification: 23.5 / 21, + /** + * Opacity of the rows in the copies above and below the band (the band's + * copy is opaque); the same at every angle. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, label alpha in the outer table copies, Oct 23 2026 + */ + outerOpacity: 0.447, + /** + * d of the rubber band past the first or last row: the column's table + * view is 291 pt tall in a 216 pt picker (scroll.rubberBand's formula + * with c = 0.55 puts 10, 50 and 110 pt of finger travel past the end at + * 5.4, 25.1 and 50.1 pt; measured 5.3, 25 and 50). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, UIPickerTableView frame and offsets during drags + * 20, 60 and 120 pt past the last row, Oct 23 2026 + */ + rubberBandDimension: 291, + }, + release: { + /** + * The speed at which a coast ends. The scroll view's projected target is + * offset + (v − this) × r ÷ (1 − r) with r = scroll.decelerationRate + * .normal (461.33, 502.67 and 266.67 pt for v = 0.9334, 1.0162 and + * 0.5436, all three to 0.3 pt). The coast onto the row it snaps to keeps + * the release velocity and re-solves the rate so that the speed reaches + * this exactly at that row, where it stops (0.4 and 0.3 pt RMS over two + * coasts, ending within 30 ms of the measured end). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, scrollViewWillEndDragging targets and per-frame + * offsets to rest, Oct 23 2026 + */ + stopSpeed: 0.0089, + /** + * Below this release speed (pt/ms, a scroll view's release velocity) a + * release inside the rows carries no velocity: the wheel snaps to the + * nearest row instead of coasting. Past the first or last row the + * velocity is kept, however small (0.0816 kept). A pause before the lift + * does not zero it: the velocity changes only when the finger moves. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, steady 100 pt drags mid-list lifted while moving: zeroed + * at 100 to 250 pt/s both ways, passed from 260 pt/s (0.2577 the + * smallest velocity handed on); a 300 pt/s drag held still 300 ms + * still coasted, Oct 23 2026 + */ + minimumSpeed: 0.25, + }, + /** + * A release without velocity (or a coast already on a row) eases onto the + * nearest row exponentially, at this fraction of the distance left per + * millisecond: e^(−0.011 t), done in about 0.3 s (fitted 0.0099, 0.0107 + * and 0.0123 for snaps of 4, 6 and 8 pt). + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, per-frame offsets after three slow releases between + * rows, Oct 23 2026 + */ + snapRate: 0.011, + tapSpin: { + /** + * A tap on a row turns the wheel onto it (setContentOffset animated) in + * this long, on Core Animation's ease-in-ease-out + * (timing.curves.move), and selects it on arrival; a tap on the + * band's row does nothing. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, per-frame offsets after a tap two rows below the band + * (6.8, 25.1, 50.2, 75.4, 93.7 % at 50 ms steps, arriving at 300 ms; + * the same with Reduce Motion and Prefer Cross-Fade on), Oct 23 2026 + */ + durationMs: 300, + }, + selectionTick: { + /** + * One selection haptic per row whose centre reaches the band's centre, + * at most one per this interval. Not during a tap's spin. + * @source measured: UIKit lab (injected host app), iOS 26.2 simulator, + * iPhone 17 Pro, selectionChangedAtLocation: and the feedback + * generator's minimum interval (0.040 s) logged during drags and + * coasts, Oct 23 2026 + */ + minimumIntervalMs: 40, + }, +} as const; From a279dbfedc1003471ab05aa24c37e90c8d95774f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 06:09:50 -0700 Subject: [PATCH 2/4] chore(core): the picker wheel's pure math and drum, checked against UIKit's recordings wheelPhysics.ts plans a release as UIPickerView does: it projects the rest at the normal deceleration rate (0.998), snaps it to a row and coasts with the rate re-solved to stop there; a slow release snaps; a release past an end bounces on scroll.bounce, and a bounce spring not settled by the animator's 30 s limit snaps onto its end there. It also draws the rubber band, the tap spin and the row crossings that tick. wheelDrum.ts puts rows on the cylinder, finds the row under a point and bakes a curve into per-row keyframes. Their tests replay UIKit's recorded releases: coasts within 0.8 pt RMS, snaps within 0.4 pt, transforms within 0.3 degrees. Nothing imports them yet; the touch picker wheel does. --- .changeset/wheel-uikit-picker-values.md | 7 + packages/core/src/DateInput/wheelDrum.test.ts | 207 ++++++++ packages/core/src/DateInput/wheelDrum.ts | 297 ++++++++++++ .../core/src/DateInput/wheelPhysics.test.ts | 418 +++++++++++++++++ packages/core/src/DateInput/wheelPhysics.ts | 441 ++++++++++++++++++ 5 files changed, 1370 insertions(+) create mode 100644 .changeset/wheel-uikit-picker-values.md create mode 100644 packages/core/src/DateInput/wheelDrum.test.ts create mode 100644 packages/core/src/DateInput/wheelDrum.ts create mode 100644 packages/core/src/DateInput/wheelPhysics.test.ts create mode 100644 packages/core/src/DateInput/wheelPhysics.ts diff --git a/.changeset/wheel-uikit-picker-values.md b/.changeset/wheel-uikit-picker-values.md new file mode 100644 index 0000000000000..5d8378d0d8d71 --- /dev/null +++ b/.changeset/wheel-uikit-picker-values.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: UIPickerView's values measured on iOS 26.2 join the touch motion tables as internal constants: the wheel's geometry (row pitch, cylinder radius, perspective, the selection band, the band row's magnification), the coast's stop speed and velocity floor, the snap at rest, the tap spin and the selection tick. The pure math a wheel moves and draws with comes with them. It projects the row a release rests on as UIScrollView sums its deceleration, coasts with the rate re-solved to stop on that row, snaps, bounces at an end, rubber-bands, spins to a tapped row, and turns each row onto the cylinder. It is checked against UIKit's recorded frames. Nothing public changes: none of it is exported from the package entry point, and themes do not set these values. + +@vjeux diff --git a/packages/core/src/DateInput/wheelDrum.test.ts b/packages/core/src/DateInput/wheelDrum.test.ts new file mode 100644 index 0000000000000..a5f88a8f7deff --- /dev/null +++ b/packages/core/src/DateInput/wheelDrum.test.ts @@ -0,0 +1,207 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file wheelDrum.test.ts + * @input wheelDrum.ts and wheelPhysics.ts, and a UIPickerView's cell + * transforms read at rest + * @output Proves the drum puts rows where UIKit's cylinder does, and that a + * baked motion stays within tolerance, never sweeps a parked row across the + * front, and leaves rows that never show without animations + * @position Unit coverage for DateInput/wheelDrum.ts + */ + +import {describe, expect, it} from 'vitest'; +import { + BAKE_TOLERANCE, + PARKED_ANGLE, + drumGeometry, + isRowVisible, + rowAngle, + rowAtPoint, + rowDistance, + rowKeyframes, + rowOrigin, + rowTransform, + sampleCurve, + stripKeyframes, + stripTranslation, +} from './wheelDrum'; +import {planRelease, spinCurve, type WheelLayout} from './wheelPhysics'; + +const MINUTES: WheelLayout = {rowHeight: 32, rowCount: 60}; +const LOOPING: WheelLayout = {...MINUTES, looping: true}; +const GEOMETRY = drumGeometry(32); + +/** Where CSS puts a row's centre: rotateX(−θ) about an origin R behind it. */ +function cylinderPosition(angle: number, radius: number) { + return {y: radius * Math.sin(angle), z: radius * (Math.cos(angle) - 1)}; +} + +describe('the drum at rest', () => { + it('turns rows ±1 to ±4 as UIPickerView does', () => { + // UIKit's cell transforms: rotations of 18.85, 37.8, 56.7 and 75.7° + // (18.92° a row; its depths fit R = 97.2, which gives 18.86°). + const measured = [18.85, 37.8, 56.7, 75.7]; + measured.forEach((degrees, i) => { + const angle = rowAngle( + rowDistance(31 + i + 1, 31 * 32, MINUTES), + GEOMETRY, + ); + expect(Math.abs((angle * 180) / Math.PI - degrees)).toBeLessThan(0.3); + const above = rowAngle( + rowDistance(31 - i - 1, 31 * 32, MINUTES), + GEOMETRY, + ); + expect(above).toBeCloseTo(-angle, 12); + }); + }); + + it('moves rows onto the cylinder where UIKit’s cells sit', () => { + // UIKit's cells, relative to the band: depth −5.2, −20.4, −43.9, −73.2 + // pt; along y 32k minus 0.41, 4.23, 14.5, 33.6 pt (at a rest offset a + // fraction of a point off the row). + const depth = [-5.2, -20.4, -43.9, -73.2]; + const pull = [0.41, 4.23, 14.5, 33.6]; + depth.forEach((z, i) => { + const k = i + 1; + const position = cylinderPosition( + rowAngle(k * 32, GEOMETRY), + GEOMETRY.radius, + ); + expect(Math.abs(position.z - z)).toBeLessThan(0.5); + expect(Math.abs(position.y - (32 * k - pull[i]))).toBeLessThan(0.4); + }); + }); + + it('writes the turn as one rotation about an origin R behind the row', () => { + expect(rowOrigin(GEOMETRY)).toBe('50% 50% -97.2px'); + expect(rowTransform(32 / 97.2)).toBe('rotateX(-0.32922rad)'); + }); + + it('parks rows past a quarter turn instead of turning them round', () => { + const angle = rowAngle(400, GEOMETRY); + expect(angle).toBe(PARKED_ANGLE); + expect(isRowVisible(angle)).toBe(false); + expect(isRowVisible(rowAngle(140, GEOMETRY))).toBe(true); + }); + + it('scales the whole drum with the row height', () => { + const geometry = drumGeometry(28); + expect(geometry.radius).toBeCloseTo(85.05, 2); + expect(geometry.height).toBe(189); + expect(rowAngle(28, geometry)).toBeCloseTo(rowAngle(32, GEOMETRY), 12); + }); + + it('shows each row of a looping wheel once, at the copy nearest the band', () => { + // Minute 0 at an offset on minute 58 sits two rows below the band. + expect(rowDistance(0, 58 * 32, LOOPING)).toBe(64); + expect(rowDistance(58, 0, LOOPING)).toBe(-64); + expect(rowDistance(30, 0, LOOPING)).toBe(-960); + }); +}); + +describe('which row is under a point', () => { + it('inverts the cylinder', () => { + const y = GEOMETRY.radius * Math.sin(32 / GEOMETRY.radius); + expect(rowAtPoint(y, 31 * 32, MINUTES, GEOMETRY)).toBe(32); + expect(rowAtPoint(-y, 31 * 32, MINUTES, GEOMETRY)).toBe(30); + expect(rowAtPoint(0, 31 * 32, MINUTES, GEOMETRY)).toBe(31); + }); + + it('finds nothing past the drum or past the rows', () => { + expect( + rowAtPoint(GEOMETRY.radius + 1, 31 * 32, MINUTES, GEOMETRY), + ).toBeNull(); + expect(rowAtPoint(-40, 0, MINUTES, GEOMETRY)).toBeNull(); + expect(rowAtPoint(-40, 0, LOOPING, GEOMETRY)).toBe(59); + }); +}); + +describe('a baked motion', () => { + const coast = planRelease(1110, 1016.2, MINUTES).curve; + + it('stays within the tolerance between samples', () => { + const samples = sampleCurve(coast); + expect(samples[0].t).toBe(0); + expect(samples[samples.length - 1].t).toBe(coast.duration); + expect(samples.length).toBeLessThan(400); + for (let i = 1; i < samples.length; i++) { + const a = samples[i - 1]; + const b = samples[i]; + for (const f of [0.1, 0.33, 0.5, 0.66, 0.9]) { + const t = a.t + (b.t - a.t) * f; + const linear = a.value + (b.value - a.value) * f; + expect(Math.abs(coast.value(t) - linear)).toBeLessThanOrEqual( + BAKE_TOLERANCE * 1.5, + ); + } + } + }); + + it('animates only the rows that show during the motion', () => { + const samples = sampleCurve(coast); + // Rows 30 to 55 show at some point between row 34.7 and row 50. + expect( + rowKeyframes(10, samples, coast.duration, MINUTES, GEOMETRY), + ).toBeNull(); + expect( + rowKeyframes(59, samples, coast.duration, MINUTES, GEOMETRY), + ).toBeNull(); + const row40 = rowKeyframes(40, samples, coast.duration, MINUTES, GEOMETRY); + expect(row40).not.toBeNull(); + expect(row40![0].offset).toBe(0); + expect(row40![row40!.length - 1].offset).toBe(1); + // It ends parked above the band, where row 40 sits when row 50 is on it. + expect(row40![row40!.length - 1].transform).toBe( + rowTransform(-PARKED_ANGLE), + ); + const row50 = rowKeyframes(50, samples, coast.duration, MINUTES, GEOMETRY); + expect(row50![row50!.length - 1].transform).toBe(rowTransform(0)); + }); + + it('steps a looping row to its other copy while it is out of sight', () => { + // From minute 58 across 0 to minute 3: minute 30 changes sides behind + // the drum and must never be drawn on the front on the way. + const spin = spinCurve(58 * 32, 63 * 32); + const samples = sampleCurve(spin); + const frames = rowKeyframes(28, samples, spin.duration, LOOPING, GEOMETRY); + expect(frames).toBeNull(); + const minute1 = rowKeyframes(1, samples, spin.duration, LOOPING, GEOMETRY)!; + for (const frame of minute1) { + expect(frame.transform).not.toContain('NaN'); + } + // Minute 33 is at the back the whole time: no keyframes. Minute 0 comes + // into view from below and passes the band. + const minute0 = rowKeyframes(0, samples, spin.duration, LOOPING, GEOMETRY)!; + expect(minute0[0].transform).toBe(rowTransform(rowAngle(64, GEOMETRY))); + expect(minute0[minute0.length - 1].transform).toBe( + rowTransform(rowAngle(-96, GEOMETRY)), + ); + }); + + it('jumps a parked looping row with two keyframes at the same progress', () => { + // A long looping spin: row 0 goes once round the back. + const spin = spinCurve(0, 40 * 32); + const samples = sampleCurve(spin); + const frames = rowKeyframes(0, samples, spin.duration, LOOPING, GEOMETRY)!; + const steps = frames.filter( + (frame, i) => i > 0 && frame.offset === frames[i - 1].offset, + ); + expect(steps.length).toBe(1); + for (let i = 1; i < frames.length; i++) { + expect(frames[i].offset).toBeGreaterThanOrEqual(frames[i - 1].offset); + } + }); + + it('translates the band strip with the offset, folding a looping strip', () => { + expect(stripTranslation(992, MINUTES)).toBe(-992); + expect(stripTranslation(992, LOOPING)).toBe(-(992 + 1920)); + expect(stripTranslation(-32, LOOPING)).toBe(-(1888 + 1920)); + const spin = spinCurve(58 * 32, 63 * 32); + const frames = stripKeyframes(sampleCurve(spin), spin.duration, LOOPING); + const steps = frames.filter( + (frame, i) => i > 0 && frame.offset === frames[i - 1].offset, + ); + expect(steps.length).toBe(1); + }); +}); diff --git a/packages/core/src/DateInput/wheelDrum.ts b/packages/core/src/DateInput/wheelDrum.ts new file mode 100644 index 0000000000000..e63582531daf3 --- /dev/null +++ b/packages/core/src/DateInput/wheelDrum.ts @@ -0,0 +1,297 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file wheelDrum.ts + * @input A wheel's rows, its offset or a curve of it (wheelPhysics.ts), and + * the UIKit picker geometry (motion/uikit/picker.ts) + * @output Exports the drum's geometry: each row's angle on the cylinder and + * its CSS transform, the band copy's translation, which row is under a + * point, and the curve baked into keyframes per row so a motion runs on the + * compositor + * @position Rendering math of the touch picker wheel; pure, no DOM + * + * UIPickerView draws each row on a cylinder: a row whose centre is d px from + * the band's (along the list) is turned about x by θ = d ÷ R and moved onto + * the cylinder, (R sin θ, R (cos θ − 1)). In CSS that is one rotation, + * `rotateX(−θ)`, about an origin R behind the row + * (`transform-origin: 50% 50% −R`), the row laid out at the band's centre. + * The copies above and below the band see it through the picker's + * perspective; the band's own copy does not, and close to the band the + * cylinder is flat to a tenth of a pixel, so that copy is a plain strip of + * rows that translates. + * + * Rows beyond a quarter turn face away. They are parked at `PARKED_ANGLE` + * with `backface-visibility: hidden` rather than turned further: a row two + * thirds of a turn away would otherwise come round to the front again. + * + * SYNC: When modified, update: + * - /packages/core/src/DateInput/wheelDrum.test.ts + */ + +import {picker} from '../motion/uikit/picker'; +import { + scaleFor, + wrapIndex, + type WheelCurve, + type WheelLayout, +} from './wheelPhysics'; + +/** A row turned this far is edge-on or beyond: hidden by its back face. */ +export const PARKED_ANGLE = (95 * Math.PI) / 180; + +/** Linear interpolation between baked samples stays within this, px. */ +export const BAKE_TOLERANCE = 0.05; + +/** The drum's size for a wheel with `rowHeight` px rows. */ +export interface DrumGeometry { + readonly rowHeight: number; + /** Cylinder radius, px. */ + readonly radius: number; + /** Perspective distance of the dimmed copies, px. */ + readonly perspective: number; + readonly bandHeight: number; + readonly bandInset: number; + /** The picker's height, px. */ + readonly height: number; + readonly rubberBandDimension: number; +} + +/** UIKit's picker geometry scaled to rows `rowHeight` px tall. */ +export function drumGeometry(rowHeight: number): DrumGeometry { + const scale = scaleFor(rowHeight); + const {geometry} = picker; + return { + rowHeight, + radius: geometry.cylinderRadius * scale, + perspective: geometry.perspective * scale, + bandHeight: geometry.bandHeight * scale, + bandInset: geometry.bandInset * scale, + height: geometry.height * scale, + rubberBandDimension: geometry.rubberBandDimension * scale, + }; +} + +/** + * Row `index`'s distance below the band's centre (px) at `offset`. A looping + * wheel shows each row once, at the copy nearest the band. + */ +export function rowDistance( + index: number, + offset: number, + layout: WheelLayout, +): number { + const distance = index * layout.rowHeight - offset; + if (!layout.looping) { + return distance; + } + const cycle = layout.rowCount * layout.rowHeight; + // Fold into [−cycle / 2, cycle / 2). + return distance - cycle * Math.floor(distance / cycle + 0.5); +} + +/** The angle (radians, positive below the band) of a row `distance` away. */ +export function rowAngle(distance: number, geometry: DrumGeometry): number { + const angle = distance / geometry.radius; + return Math.max(-PARKED_ANGLE, Math.min(PARKED_ANGLE, angle)); +} + +/** Whether a row at `angle` faces the viewer. */ +export function isRowVisible(angle: number): boolean { + return Math.abs(angle) < Math.PI / 2; +} + +/** CSS transform of a row at `angle` (its origin R behind it). */ +export function rowTransform(angle: number): string { + return `rotateX(${round(-angle, 5)}rad)`; +} + +/** CSS transform-origin that puts a row on the cylinder. */ +export function rowOrigin(geometry: DrumGeometry): string { + return `50% 50% ${round(-geometry.radius, 3)}px`; +} + +/** + * The band copy's strip translation for `offset`. A looping strip carries + * three cycles of rows and translates within the middle one. + */ +export function stripTranslation(offset: number, layout: WheelLayout): number { + if (!layout.looping) { + return -offset; + } + const cycle = layout.rowCount * layout.rowHeight; + const folded = offset - cycle * Math.floor(offset / cycle); + return -(folded + cycle); +} + +/** + * The row whose cylinder position is under a point `dy` px below the band's + * centre, or null past the drum's top or bottom. Orthographic: the + * perspective moves rows by under a pixel along y. + */ +export function rowAtPoint( + dy: number, + offset: number, + layout: WheelLayout, + geometry: DrumGeometry, +): number | null { + if (Math.abs(dy) >= geometry.radius) { + return null; + } + const distance = geometry.radius * Math.asin(dy / geometry.radius); + const index = Math.round((offset + distance) / layout.rowHeight); + if (layout.looping) { + return wrapIndex(index, layout.rowCount); + } + return index >= 0 && index < layout.rowCount ? index : null; +} + +/** One baked sample of a curve. */ +export interface CurveSample { + /** Seconds. */ + readonly t: number; + readonly value: number; +} + +/** + * Samples `curve` over [0, duration] so that linear interpolation between + * consecutive samples stays within `tolerance` px: bisection wherever the + * midpoint (and the quarter points) stray further. + */ +export function sampleCurve( + curve: WheelCurve, + tolerance: number = BAKE_TOLERANCE, + maxSamples = 1200, +): CurveSample[] { + const end = curve.duration; + if (!(end > 0)) { + return [{t: 0, value: curve.value(0)}]; + } + const samples: CurveSample[] = [{t: 0, value: curve.value(0)}]; + const refine = (a: CurveSample, b: CurveSample, depth: number) => { + const span = b.t - a.t; + const fits = [0.25, 0.5, 0.75].every(f => { + const t = a.t + span * f; + const linear = a.value + (b.value - a.value) * f; + return Math.abs(curve.value(t) - linear) <= tolerance; + }); + if (fits || depth >= 16 || samples.length >= maxSamples) { + samples.push(b); + return; + } + const mid = {t: a.t + span / 2, value: curve.value(a.t + span / 2)}; + refine(a, mid, depth + 1); + refine(mid, b, depth + 1); + }; + // Start from 1/60 s segments so a curve with a kink (an edge hit) is + // never stepped over. + const segments = Math.max(1, Math.ceil(end * 60)); + let previous = samples[0]; + for (let i = 1; i <= segments; i++) { + const t = i === segments ? end : (end * i) / segments; + const next = {t, value: curve.value(t)}; + refine(previous, next, 0); + previous = next; + } + return samples; +} + +/** A keyframe of one row's motion. */ +export interface RowKeyframe { + /** Progress through the motion, 0 to 1. */ + readonly offset: number; + readonly transform: string; +} + +/** + * Row `index`'s keyframes along `samples` (a baked curve lasting `duration` + * seconds), or null when the row stays parked out of sight throughout. + * Runs of identical angles collapse to their ends; a looping row that jumps + * to its other copy while parked gets two keyframes at the same progress, so + * it never sweeps across the front on the way. + */ +export function rowKeyframes( + index: number, + samples: ReadonlyArray, + duration: number, + layout: WheelLayout, + geometry: DrumGeometry, +): RowKeyframe[] | null { + const frames: RowKeyframe[] = []; + let everVisible = false; + let previousAngle: number | null = null; + let pendingParked: RowKeyframe | null = null; + const progress = (t: number) => + duration > 0 ? Math.min(1, t / duration) : 1; + for (const sample of samples) { + const angle = rowAngle(rowDistance(index, sample.value, layout), geometry); + const frame = {offset: progress(sample.t), transform: rowTransform(angle)}; + if (isRowVisible(angle)) { + everVisible = true; + } + if (previousAngle != null && angle === previousAngle) { + // Still parked (or not moving): remember the run's end. + pendingParked = frame; + continue; + } + if (pendingParked != null) { + frames.push(pendingParked); + pendingParked = null; + } + if ( + previousAngle != null && + Math.abs(angle - previousAngle) > Math.PI && + frames.length > 0 + ) { + // A looping row jumping to its other copy: step at this progress. + frames.push({ + offset: frame.offset, + transform: frames[frames.length - 1].transform, + }); + } + frames.push(frame); + previousAngle = angle; + } + if (pendingParked != null) { + frames.push(pendingParked); + } + if (!everVisible) { + return null; + } + if (frames.length === 1) { + frames.push({offset: 1, transform: frames[0].transform}); + } + return frames; +} + +/** The band strip's keyframes along `samples`. */ +export function stripKeyframes( + samples: ReadonlyArray, + duration: number, + layout: WheelLayout, +): {offset: number; transform: string}[] { + const frames: {offset: number; transform: string}[] = []; + let previous: number | null = null; + const cycle = layout.rowCount * layout.rowHeight; + for (const sample of samples) { + const y = stripTranslation(sample.value, layout); + const offset = duration > 0 ? Math.min(1, sample.t / duration) : 1; + if ( + previous != null && + layout.looping && + Math.abs(y - previous) > cycle / 2 + ) { + frames.push({offset, transform: `translateY(${round(previous, 3)}px)`}); + } + frames.push({offset, transform: `translateY(${round(y, 3)}px)`}); + previous = y; + } + if (frames.length === 1) { + frames.push({offset: 1, transform: frames[0].transform}); + } + return frames; +} + +function round(value: number, digits: number): number { + const factor = 10 ** digits; + return Math.round(value * factor) / factor; +} diff --git a/packages/core/src/DateInput/wheelPhysics.test.ts b/packages/core/src/DateInput/wheelPhysics.test.ts new file mode 100644 index 0000000000000..7e6d5342962c8 --- /dev/null +++ b/packages/core/src/DateInput/wheelPhysics.test.ts @@ -0,0 +1,418 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file wheelPhysics.test.ts + * @input wheelPhysics.ts and per-frame offsets recorded from a UIPickerView, + * with the release velocity UIKit handed its delegate + * @output Proves the Wheel's curves reproduce UIKit's measured picker: the + * projected target, the coast onto the row, the coast into an end, the + * snap, the rubber band, the tap spin and the ticks + * @position Unit coverage for DateInput/wheelPhysics.ts + * + * The recordings: a 216 pt UIPickerView column of 60 rows, 32 pt each, on the + * iOS 26.2 simulator (iPhone 17 Pro) driven by real HID touches, Oct 23 2026. + * Offsets are converted to this file's convention (row k centred at k × 32): + * UIKit's contentOffset + 129.67. Frames are [ms after the lift, offset]. + */ + +import {describe, expect, it} from 'vitest'; +import {sampleCurve} from './wheelDrum'; +import { + MAX_PLAN_SECONDS, + coastCurve, + dragOffset, + nearestIndex, + planRelease, + projectRelease, + reachesRow, + snapCurve, + spinCurve, + tickTimes, + wrapIndex, + type WheelLayout, +} from './wheelPhysics'; + +const MINUTES: WheelLayout = {rowHeight: 32, rowCount: 60}; + +interface Recording { + /** Offset at the lift. */ + readonly offset: number; + /** The velocity UIKit handed scrollViewWillEndDragging, px/s. */ + readonly velocity: number; + /** Its projected target, and the row it snapped that to. */ + readonly targetIn: number; + readonly targetOut: number; + /** ms after the lift. */ + readonly didSelect: number; + readonly frames: ReadonlyArray; +} + +const SWIPE_200_IN_50MS: Recording = { + offset: 1093.33, + velocity: 933.4, + targetIn: 1554.67, + targetOut: 1568, + didSelect: 2314, + frames: [], +}; + +const SWIPE_200_IN_100MS: Recording = { + offset: 1143.33, + velocity: 2114, + targetIn: 1888, + targetOut: 1888, + didSelect: 1220, + frames: [], +}; + +const SWIPE_200_IN_200MS: Recording = { + offset: 1110, + velocity: 1016.2, + targetIn: 1612.67, + targetOut: 1600, + didSelect: 2316, + frames: [ + [15, 1126.67], + [81.4, 1187.67], + [149.2, 1241], + [215.6, 1287.67], + [282.2, 1328], + [351.3, 1363.33], + [415, 1394.33], + [481.6, 1421], + [550.8, 1444.67], + [617.3, 1465], + [681.5, 1482.67], + [749, 1498.33], + [815.9, 1512], + [882.6, 1523.67], + [949.1, 1534], + [1015.5, 1543], + [1084, 1551], + [1149.7, 1557.67], + [1214.9, 1563.67], + [1282.1, 1569], + [1351.5, 1573.33], + [1415.2, 1577.33], + [1481.7, 1581], + [1549, 1584], + [1614.7, 1586.33], + [1684.1, 1588.67], + [1748.1, 1590.67], + [1815.2, 1592.33], + [1883.9, 1594], + [1948.2, 1595.33], + [2014.9, 1596.33], + [2081.6, 1597.33], + [2149.5, 1598.33], + [2216.3, 1599], + [2282.4, 1599.67], + [2315.2, 1600], + ], +}; + +const FLICK_90: Recording = { + offset: 1014, + velocity: 543.6, + targetIn: 1280.67, + targetOut: 1280, + didSelect: 2032, + frames: [ + [19.4, 1023], + [81.4, 1055.67], + [151.9, 1084.33], + [215.5, 1109.33], + [281.4, 1131.33], + [352.9, 1150.67], + [415.1, 1167.33], + [482, 1182], + [548.2, 1195], + [615.9, 1206], + [682.6, 1216], + [748.2, 1224.67], + [816.8, 1232], + [883.1, 1238.67], + [949.1, 1244.33], + [1016, 1249.33], + [1081.5, 1254], + [1149.7, 1257.67], + [1214.8, 1261], + [1281.9, 1264], + [1350.8, 1266.67], + [1415.7, 1269], + [1483.9, 1271], + [1548.4, 1272.67], + [1616.4, 1274], + [1682.3, 1275.33], + [1750.6, 1276.67], + [1815, 1277.67], + [1882.9, 1278.67], + [1949.6, 1279.33], + [2015.2, 1280], + [2031.5, 1280], + ], +}; + +/** A slow drag up, held still 300 ms: no velocity, 6 px past row 31. */ +const STILL_6PX_PAST: Recording = { + offset: 998, + velocity: 0, + targetIn: 998, + targetOut: 992, + didSelect: 300, + frames: [ + [16.1, 997], + [34.2, 996], + [50.7, 995.33], + [66.2, 994.67], + [82.9, 994.33], + [102.3, 994], + [116.3, 993.67], + [133.2, 993.33], + [152.4, 993.33], + [166.2, 993], + [184.1, 993], + [199.5, 992.67], + [216.1, 992.67], + [232.8, 992.67], + [249.5, 992.33], + [267.3, 992.33], + [283, 992], + [299.7, 992], + ], +}; + +/** RMS distance between a curve and recorded frames, in px. */ +function rms( + value: (t: number) => number, + frames: Recording['frames'], +): number { + let sum = 0; + for (const [ms, offset] of frames) { + sum += (value(ms / 1000) - offset) ** 2; + } + return Math.sqrt(sum / frames.length); +} + +describe('the projected target', () => { + it.each([ + ['200 pt in 50 ms', SWIPE_200_IN_50MS], + ['200 pt in 200 ms', SWIPE_200_IN_200MS], + ['a 90 pt flick', FLICK_90], + ])('matches UIKit’s targetContentOffset for %s', (_name, recording) => { + expect( + Math.abs( + projectRelease(recording.offset, recording.velocity) - + recording.targetIn, + ), + ).toBeLessThan(0.3); + }); + + it('snaps to the row UIKit snapped to', () => { + for (const recording of [SWIPE_200_IN_50MS, SWIPE_200_IN_200MS, FLICK_90]) { + const plan = planRelease(recording.offset, recording.velocity, MINUTES); + expect(plan.kind).toBe('coast'); + expect(plan.index * 32).toBe(recording.targetOut); + } + }); +}); + +describe('the coast onto a row', () => { + it.each([ + ['200 pt in 200 ms', SWIPE_200_IN_200MS, 0.8], + ['a 90 pt flick', FLICK_90, 0.8], + ])( + 'follows UIKit’s frames for %s and stops on the row', + (_name, recording, tolerance) => { + const {curve} = planRelease( + recording.offset, + recording.velocity, + MINUTES, + ); + expect(rms(curve.value, recording.frames)).toBeLessThan(tolerance); + expect(curve.value(curve.duration)).toBe(recording.targetOut); + // didSelect lands in the frame of the last offset change. + expect( + Math.abs(curve.duration * 1000 - recording.didSelect), + ).toBeLessThan(50); + }, + ); + + it('keeps the release velocity at the lift and ends at the stop speed', () => { + const curve = coastCurve(1110, 1016.2, 1600); + expect(curve.velocity(0)).toBeCloseTo(1016.2, 6); + expect(curve.velocity(curve.duration - 1e-9)).toBeCloseTo(8.9, 3); + expect(curve.velocity(curve.duration)).toBe(0); + }); + + it('is never re-solved backwards: a target behind the velocity snaps', () => { + const curve = coastCurve(1010, 500, 992); + expect(curve.value(curve.duration)).toBe(992); + expect(curve.velocity(0)).toBeLessThan(0); + }); +}); + +describe('a coast into an end', () => { + it('decays at the normal rate into the last row, then bounces back to it', () => { + const plan = planRelease( + SWIPE_200_IN_100MS.offset, + SWIPE_200_IN_100MS.velocity, + MINUTES, + ); + expect(plan.kind).toBe('edge'); + expect(plan.index).toBe(59); + const end = 59 * 32; + // UIKit's frames: past the end about 600 ms after the lift, a 20.7 pt + // overshoot around 700 ms, back on the row by about 1.2 s. + let hit = 0; + let peak = end; + for (let t = 0; t < plan.curve.duration; t += 1 / 240) { + const value = plan.curve.value(t); + if (hit === 0 && value >= end) { + hit = t; + } + peak = Math.max(peak, value); + } + expect(hit).toBeGreaterThan(0.55); + expect(hit).toBeLessThan(0.65); + expect(peak - end).toBeGreaterThan(10); + expect(peak - end).toBeLessThan(30); + expect(plan.curve.value(plan.curve.duration)).toBe(end); + }); +}); + +describe('a release without velocity', () => { + it('eases onto the nearest row as UIKit does', () => { + const plan = planRelease(STILL_6PX_PAST.offset, 0, MINUTES); + expect(plan.kind).toBe('snap'); + expect(plan.index).toBe(31); + expect(rms(plan.curve.value, STILL_6PX_PAST.frames)).toBeLessThan(0.4); + expect( + Math.abs(plan.curve.duration * 1000 - STILL_6PX_PAST.didSelect), + ).toBeLessThan(60); + }); + + it('treats a release below the velocity floor as no velocity', () => { + // 244.7 pt/s was zeroed by UIKit; 257.7 was handed on. + expect(planRelease(1000, 240, MINUTES).kind).toBe('snap'); + expect(planRelease(1000, -240, MINUTES).kind).toBe('snap'); + expect(planRelease(1000, 260, MINUTES).kind).toBe('coast'); + }); + + it('is already at rest on a row', () => { + const curve = snapCurve(992, 992); + expect(curve.duration).toBe(0); + expect(curve.value(0)).toBe(992); + }); +}); + +describe('past an end', () => { + it('rubber-bands a drag past the last row as UIPickerView does', () => { + const end = 59 * 32; + // 10, 50 and 110 px of finger travel past the end; UIKit showed 5.3, 25 + // and 50. + expect(dragOffset(end + 10, MINUTES) - end).toBeCloseTo(5.4, 1); + expect(dragOffset(end + 50, MINUTES) - end).toBeCloseTo(25.1, 1); + expect(dragOffset(end + 110, MINUTES) - end).toBeCloseTo(50.1, 1); + expect(dragOffset(-50, MINUTES)).toBeCloseTo(-25.1, 1); + expect(dragOffset(500, MINUTES)).toBe(500); + }); + + it('returns to the end it was released past, keeping any velocity', () => { + const plan = planRelease(-37.33, -147.8, MINUTES); + expect(plan.kind).toBe('return'); + expect(plan.index).toBe(0); + expect(plan.curve.velocity(0)).toBeCloseTo(-147.8, 6); + expect(plan.curve.value(plan.curve.duration)).toBe(0); + }); + + it('never has an end when looping', () => { + const looping = {...MINUTES, looping: true}; + expect(dragOffset(-50, looping)).toBe(-50); + expect(planRelease(-37.33, 0, looping).index).toBe(-1); + expect(nearestIndex(70 * 32, looping)).toBe(70); + expect(wrapIndex(70, 60)).toBe(10); + expect(wrapIndex(-1, 60)).toBe(59); + }); +}); + +describe('the tap spin', () => { + it('turns onto the row on Core Animation’s ease-in-ease-out in 0.3 s', () => { + const curve = spinCurve(0, 64); + expect(curve.duration).toBe(0.3); + // UIKit, a tap two rows below the band: 6.8, 25.1, 50.2, 75.4 and 93.7 % + // of the way at 50 ms steps (the recording starts a few ms early). + const measured = [0.068, 0.251, 0.502, 0.754, 0.937]; + measured.forEach((fraction, i) => { + expect( + Math.abs(curve.value((i + 1) * 0.05) / 64 - fraction), + ).toBeLessThan(0.025); + }); + expect(curve.value(0.3)).toBe(64); + expect(curve.velocity(0.15)).toBeGreaterThan(0); + }); +}); + +describe('the selection tick', () => { + it('fires when a row’s centre reaches the band, not when it leaves it', () => { + expect(reachesRow(31.9 * 32, 32 * 32, 32)).toBe(true); + expect(reachesRow(32 * 32, 32.4 * 32, 32)).toBe(false); + expect(reachesRow(32.1 * 32, 32 * 32, 32)).toBe(true); + expect(reachesRow(32 * 32, 31.6 * 32, 32)).toBe(false); + }); + + it('ticks once per row on a coast, at most every 40 ms', () => { + const {curve} = planRelease(1110, 1016.2, MINUTES); + const ticks = tickTimes(curve, 32); + // From row 34.7 to row 50: rows 35 to 50. + expect(ticks.length).toBeLessThanOrEqual(16); + expect(ticks.length).toBeGreaterThan(12); + for (let i = 1; i < ticks.length; i++) { + expect(ticks[i] - ticks[i - 1]).toBeGreaterThanOrEqual(0.04 - 1e-9); + } + }); +}); + +describe('the bounce spring it is handed', () => { + it('returns from past an end on the spring it is handed', () => { + const layout: WheelLayout = {rowHeight: 32, rowCount: 60}; + const table = planRelease(-60, 0, layout); + const stiff = planRelease(-60, 0, layout, {duration: 0.2, bounce: 0}); + expect(table.kind).toBe('return'); + expect(stiff.kind).toBe('return'); + expect(stiff.curve.to).toBe(0); + expect(stiff.curve.duration).toBeLessThan(table.curve.duration); + }); + + // An undamped bounce spring (bounce 1, or a physical spring with no + // damping) never settles, and a plan that never ends cannot be baked. It snaps onto its end at the animator's limit, as the + // animator's own motion does. + it('ends a plan whose bounce never settles at the animator limit', () => { + const springs = [ + {duration: 0.5, bounce: 1}, + {stiffness: 300, damping: 0}, + {duration: 0.5, bounce: 0.999}, + ]; + for (const bounce of springs) { + const back = planRelease(-60, 0, MINUTES, bounce); + const into = planRelease( + SWIPE_200_IN_100MS.offset, + SWIPE_200_IN_100MS.velocity, + MINUTES, + bounce, + ); + expect([back.kind, into.kind]).toEqual(['return', 'edge']); + for (const {curve} of [back, into]) { + expect(curve.duration, JSON.stringify(bounce)).toBeLessThanOrEqual( + MAX_PLAN_SECONDS, + ); + expect(curve.value(curve.duration)).toBe(curve.to); + expect(curve.velocity(curve.duration)).toBe(0); + expect(sampleCurve(curve).at(-1)).toEqual({ + t: curve.duration, + value: curve.to, + }); + } + } + }); +}); diff --git a/packages/core/src/DateInput/wheelPhysics.ts b/packages/core/src/DateInput/wheelPhysics.ts new file mode 100644 index 0000000000000..ba23d994719b8 --- /dev/null +++ b/packages/core/src/DateInput/wheelPhysics.ts @@ -0,0 +1,441 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file wheelPhysics.ts + * @input A wheel's offset and release velocity, its rows, and the UIKit + * picker constants (motion/uikit/picker.ts) + * @output Exports the curves a picker wheel moves on: the release plan (a + * coast onto a row, a snap, a coast into an end and its bounce, a return + * from past an end), the tap spin, the rubber band while dragging, and the + * row crossings that tick + * @position Pure math of the touch picker wheel; the drum (wheelDrum.ts) + * renders whatever curve this returns + * + * Units follow the motion foundation: positions in px, time in seconds, + * velocities in px/s. The offset is the distance the rows have travelled up: + * row k sits under the band when the offset is k × the row height. The + * constants are UIKit's, in pt, scaled by `scale` (the row height over + * UIKit's 32 pt), so a theme that changes the row height keeps UIKit's + * motion relative to its rows. + * + * What UIKit does, as measured (picker.ts has the numbers and sources): + * + * - The release velocity is a scroll view's, read at lift: its pan + * recognizer's last two velocities, blended (a pan's `scrollVelocity()`); + * the wheel adds no estimator of its own. + * - Inside the rows, a release slower than `release.minimumSpeed` carries no + * velocity. Past an end, the velocity is kept. + * - The scroll view projects the coast to offset + (v − stopSpeed) × r ÷ + * (1 − r), r = scroll.decelerationRate.normal (motion/projection.ts), and + * the picker snaps that to the nearest row. A target among the rows is reached by a coast + * that keeps the release velocity and re-solves the rate so that the + * speed falls to `stopSpeed` exactly there, where it stops. A projection + * past an end is not re-solved: the coast decays at the normal rate into + * the end, and the bounce takes its velocity there. + * - A release without velocity eases onto the nearest row at `snapRate`. + * - A release past an end returns on the bounce spring. + * - A spring that has not settled by the animator's limit (an undamped + * bounce spring) snaps onto its end there, as the animator's own motion + * does (motion/animator.ts). + * + * SYNC: When modified, update: + * - /packages/core/src/DateInput/wheelPhysics.test.ts + */ + +import {cubicBezier} from '../motion/bezier'; +import {projectDistance} from '../motion/projection'; +import {solveDecay} from '../motion/decay'; +import {rubberBand} from '../motion/rubberBand'; +import {solveSpring, toSpring, type SpringDescription} from '../motion/spring'; +import {picker} from '../motion/uikit/picker'; +import {scroll} from '../motion/uikit/scroll'; +import {timing} from '../motion/uikit/timing'; + +/** A motion of the wheel's offset, from t = 0 to `duration` (seconds). */ +export interface WheelCurve { + /** Seconds until the wheel is at rest on `to`. */ + readonly duration: number; + /** Where the motion ends. */ + readonly to: number; + /** Offset at `t` seconds; `to` from `duration` on. */ + value(t: number): number; + /** Velocity at `t` seconds, px/s; 0 from `duration` on. */ + velocity(t: number): number; +} + +/** How a release moves the wheel. */ +export type WheelPlanKind = 'coast' | 'snap' | 'edge' | 'return'; + +/** What a release does: the curve, and the row it ends on. */ +export interface WheelPlan { + readonly kind: WheelPlanKind; + /** + * The row the wheel comes to rest on. With `looping` it can be any + * integer: the row it shows is `index` modulo the row count. + */ + readonly index: number; + readonly curve: WheelCurve; +} + +/** The rows a wheel moves over. */ +export interface WheelLayout { + /** Row height, px. */ + readonly rowHeight: number; + readonly rowCount: number; + /** Whether the rows repeat without end (minutes, hours). */ + readonly looping?: boolean; +} + +/** UIKit's row height in pt: the unit the picker constants are measured in. */ +const UIKIT_ROW_HEIGHT = picker.geometry.rowHeight; + +/** Below half a device pixel at 3×, a motion is on its row. */ +const AT_REST_PT = 1 / 6; + +/** + * The longest a plan runs, s: the animator's limit (`MAX_DURATION_MS` in + * motion/animator.ts). A spring that has not settled by then (an undamped + * one, which never does) snaps onto its end. + */ +export const MAX_PLAN_SECONDS = 30; + +/** The constants' scale for a wheel whose rows are `rowHeight` px tall. */ +export function scaleFor(rowHeight: number): number { + return rowHeight / UIKIT_ROW_HEIGHT; +} + +/** The wheel at rest on `offset`: a curve that does not move. */ +export function restCurve(offset: number): WheelCurve { + return { + duration: 0, + to: offset, + value: () => offset, + velocity: () => 0, + }; +} + +/** The offsets of the first and last rows; unbounded when looping. */ +export function offsetBounds({rowHeight, rowCount, looping}: WheelLayout): { + min: number; + max: number; +} { + if (looping) { + return {min: -Infinity, max: Infinity}; + } + return {min: 0, max: Math.max(0, rowCount - 1) * rowHeight}; +} + +/** + * The offset a drag shows for the finger's `offset`: past the first or last + * row it is rubber-banded, as a UIPickerView's table is. + */ +export function dragOffset(offset: number, layout: WheelLayout): number { + const {min, max} = offsetBounds(layout); + const dimension = + picker.geometry.rubberBandDimension * scaleFor(layout.rowHeight); + if (offset < min) { + return min + rubberBand(offset - min, dimension); + } + if (offset > max) { + return max + rubberBand(offset - max, dimension); + } + return offset; +} + +/** The nearest row to `offset` (clamped to the rows unless looping). */ +export function nearestIndex(offset: number, layout: WheelLayout): number { + const index = Math.round(offset / layout.rowHeight); + if (layout.looping) { + return index; + } + return Math.min(Math.max(index, 0), Math.max(0, layout.rowCount - 1)); +} + +/** `index` folded onto the rows: the row a looping wheel shows there. */ +export function wrapIndex(index: number, rowCount: number): number { + if (rowCount <= 0) { + return 0; + } + return ((index % rowCount) + rowCount) % rowCount; +} + +/** + * Ease from `from` onto `to` as UIKit does after a release without + * velocity: e^(−k t) of the distance left, done once within half a device + * pixel. + */ +export function snapCurve(from: number, to: number, scale = 1): WheelCurve { + const distance = from - to; + const rate = picker.snapRate * 1000; + const epsilon = AT_REST_PT * scale; + if (Math.abs(distance) <= epsilon) { + return { + duration: 0, + to, + value: () => to, + velocity: () => 0, + }; + } + const duration = Math.log(Math.abs(distance) / epsilon) / rate; + return { + duration, + to, + value: t => (t >= duration ? to : to + distance * Math.exp(-rate * t)), + velocity: t => (t >= duration ? 0 : -rate * distance * Math.exp(-rate * t)), + }; +} + +/** + * A coast from `from` at `velocity` that keeps the velocity and ends on `to` + * at the stop speed: the rate is re-solved so that the speed falls from + * |velocity| to the stop speed over exactly `to − from`. + */ +export function coastCurve( + from: number, + velocity: number, + to: number, + scale = 1, +): WheelCurve { + const stopSpeed = picker.release.stopSpeed * 1000 * scale; + const distance = to - from; + const speed = Math.abs(velocity); + if ( + distance === 0 || + Math.sign(distance) !== Math.sign(velocity) || + speed <= stopSpeed + ) { + return snapCurve(from, to, scale); + } + const direction = Math.sign(distance); + // Per second: the speed falls by λ × the distance covered. + const lambda = (speed - stopSpeed) / Math.abs(distance); + const duration = Math.log(speed / stopSpeed) / lambda; + return { + duration, + to, + value: t => + t >= duration + ? to + : from + (direction * speed * -Math.expm1(-lambda * t)) / lambda, + velocity: t => + t >= duration ? 0 : direction * speed * Math.exp(-lambda * t), + }; +} + +/** + * The bounce spring, from `from` with `velocity`, onto `to`. `bounce` is + * `scroll.bounce`'s spring as the wheel resolves it (motion/resolveMotion.ts). + */ +export function bounceCurve( + from: number, + velocity: number, + to: number, + scale = 1, + bounce: SpringDescription = scroll.bounce, +): WheelCurve { + const spring = solveSpring(toSpring(bounce), { + from, + to, + velocity, + }); + const duration = Math.min( + MAX_PLAN_SECONDS, + spring.settleTime(AT_REST_PT * scale), + ); + return { + duration, + to, + value: t => (t >= duration ? to : spring.value(t)), + velocity: t => (t >= duration ? 0 : spring.velocity(t)), + }; +} + +/** + * A coast that runs into an end: the normal decay until the offset reaches + * `edge`, then the bounce spring with the velocity it has there. + */ +export function edgeCurve( + from: number, + velocity: number, + edge: number, + scale = 1, + bounceSpring: SpringDescription = scroll.bounce, +): WheelCurve { + const decay = solveDecay({from, velocity}); + const hit = decay.timeToReach(edge); + if (hit == null) { + return bounceCurve(from, velocity, edge, scale, bounceSpring); + } + const bounce = bounceCurve( + edge, + decay.velocity(hit), + edge, + scale, + bounceSpring, + ); + const duration = Math.min(MAX_PLAN_SECONDS, hit + bounce.duration); + return { + duration, + to: edge, + value: t => + t >= duration ? edge : t < hit ? decay.value(t) : bounce.value(t - hit), + velocity: t => + t >= duration + ? 0 + : t < hit + ? decay.velocity(t) + : bounce.velocity(t - hit), + }; +} + +/** + * Where the scroll view projects a release: the coast's rest point at the + * normal rate, short of the stop speed, as UIScrollView sums it + * (`projectDistance`: r ÷ (1 − r) ms of the speed). + */ +export function projectRelease( + offset: number, + velocity: number, + scale = 1, +): number { + const stopSpeed = picker.release.stopSpeed * 1000 * scale; + const speed = Math.abs(velocity); + if (speed <= stopSpeed) { + return offset; + } + return offset + Math.sign(velocity) * projectDistance(speed - stopSpeed); +} + +/** + * What the wheel does when the finger lifts at `offset` with `velocity` + * (px/s, positive when the rows move up). `bounce` is `scroll.bounce`'s + * spring as the wheel resolves it. + * + * @example + * ``` + * const plan = planRelease(963.67, 933.4, {rowHeight: 32, rowCount: 60}); + * plan.index; // 45: the coast stops on row 45 after about 2.3 s + * ``` + */ +export function planRelease( + offset: number, + velocity: number, + layout: WheelLayout, + bounce: SpringDescription = scroll.bounce, +): WheelPlan { + const scale = scaleFor(layout.rowHeight); + const {min, max} = offsetBounds(layout); + if (offset < min || offset > max) { + const edge = offset < min ? min : max; + return { + kind: 'return', + index: nearestIndex(edge, layout), + curve: bounceCurve(offset, velocity, edge, scale, bounce), + }; + } + const minimumSpeed = picker.release.minimumSpeed * 1000 * scale; + const speed = Math.abs(velocity) < minimumSpeed ? 0 : velocity; + const projected = projectRelease(offset, speed, scale); + if (projected < min || projected > max) { + const edge = projected < min ? min : max; + return { + kind: 'edge', + index: nearestIndex(edge, layout), + curve: edgeCurve(offset, speed, edge, scale, bounce), + }; + } + const index = nearestIndex(projected, layout); + const target = index * layout.rowHeight; + if (speed === 0) { + return {kind: 'snap', index, curve: snapCurve(offset, target, scale)}; + } + const curve = coastCurve(offset, speed, target, scale); + return {kind: curve.duration > 0 ? 'coast' : 'snap', index, curve}; +} + +/** + * The tap spin onto a row: setContentOffset animated, 0.3 s on Core + * Animation's ease-in-ease-out. + */ +export function spinCurve( + from: number, + to: number, + duration: number = picker.tapSpin.durationMs / 1000, + curve: readonly [number, number, number, number] = timing.curves.move, +): WheelCurve { + if (from === to || !(duration > 0)) { + return restCurve(to); + } + const ease = cubicBezier(curve); + const distance = to - from; + // Velocity from the eased progress's slope, by a central difference. + const step = 1e-4; + return { + duration, + to, + value: t => (t >= duration ? to : from + distance * ease(t / duration)), + velocity: t => { + if (t >= duration || t < 0) { + return 0; + } + const a = ease(Math.max(0, t / duration - step)); + const b = ease(Math.min(1, t / duration + step)); + return (distance * (b - a)) / (2 * step * duration); + }, + }; +} + +/** + * The times (seconds, ascending) at which a row's centre reaches the band's + * centre during `curve`, after `after` and up to `until`, thinned so that two + * are never closer than the selection tick's minimum interval. `last` is the + * time of the previous tick, if any. Leaving the row the wheel starts on is + * not a tick; reaching the next one is. + */ +export function tickTimes( + curve: WheelCurve, + rowHeight: number, + { + after = 0, + until = curve.duration, + last = -Infinity, + step = 1 / 240, + }: {after?: number; until?: number; last?: number; step?: number} = {}, +): number[] { + const interval = picker.selectionTick.minimumIntervalMs / 1000; + const times: number[] = []; + let previous = curve.value(after); + let lastTick = last; + for (let t = after + step; t < until + step; t += step) { + const time = Math.min(t, until); + const value = curve.value(time); + if (reachesRow(previous, value, rowHeight) && time - lastTick >= interval) { + times.push(time); + lastTick = time; + } + previous = value; + if (time === until) { + break; + } + } + return times; +} + +/** + * Whether moving from offset `from` to `to` brings a row's centre onto the + * band's: a multiple of `rowHeight` in (from, to] moving up, or in [to, from) + * moving down. + */ +export function reachesRow( + from: number, + to: number, + rowHeight: number, +): boolean { + if (to > from) { + return Math.floor(to / rowHeight) > Math.floor(from / rowHeight); + } + if (to < from) { + return Math.ceil(to / rowHeight) < Math.ceil(from / rowHeight); + } + return false; +} From 7aff6386c2eda81055d75b07badb189d8dbc1336 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 06:26:36 -0700 Subject: [PATCH 3/4] docs(core): the UIKit index's header keeps main's per-spring constants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Moving onto main carried an older header for the UIKit index: it dropped the one constant per spring (SHEET_PRESENT_SPRING, …) that main's header lists. The header is main's again, with `picker` added. The bounce curve's comment no longer names motion/resolveMotion.ts, which is not on main: its caller resolves the spring. --- packages/core/src/DateInput/wheelPhysics.ts | 2 +- packages/core/src/motion/uikit/index.ts | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/core/src/DateInput/wheelPhysics.ts b/packages/core/src/DateInput/wheelPhysics.ts index ba23d994719b8..bdd4fbb62040e 100644 --- a/packages/core/src/DateInput/wheelPhysics.ts +++ b/packages/core/src/DateInput/wheelPhysics.ts @@ -224,7 +224,7 @@ export function coastCurve( /** * The bounce spring, from `from` with `velocity`, onto `to`. `bounce` is - * `scroll.bounce`'s spring as the wheel resolves it (motion/resolveMotion.ts). + * `scroll.bounce`'s spring as its caller resolves it. */ export function bounceCurve( from: number, diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts index 372eb45221ca4..3fde1f9e283b9 100644 --- a/packages/core/src/motion/uikit/index.ts +++ b/packages/core/src/motion/uikit/index.ts @@ -3,8 +3,9 @@ /** * @file index.ts * @input The domain files of the UIKit constants table - * @output Re-exports `springs`, `scroll`, `timing`, `navigation`, `picker` and - * the gesture thresholds (one `UIKIT_*` group per recognizer, their union + * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`, + * …), `scroll`, `timing`, `navigation`, `picker` and the + * gesture thresholds (one `UIKIT_*` group per recognizer, their union * `UIKIT_GESTURES`, and the haptic tables) * @position Entry of the UIKit constants table (motion/uikit). Internal to * core: not exported from the package entry point From e5bb4b6aeaa43fd7ca461a9b62266dd6d719ebd5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 26 Oct 2026 07:51:19 -0700 Subject: [PATCH 4/4] fix(Wheel): a tap on the drum finds the row drawn under it, through the perspective rowAtPoint inverted the cylinder orthographically, but the rows above and below the band are drawn through the picker's 900 px perspective, which draws them nearer the band: the fourth row from the band spans 84.7-89.3 px, and rowAtPoint answered the third row for 89% of it, middle included. rowExtent now gives where CSS draws a row (laid out at the band's centre, turned by rowTransform about rowOrigin's origin, seen through the perspective from the band's centre), and rowAtPoint answers the row drawn under the point: inside the band, the band's flat strip; outside it, the drum row whose drawn extent holds the point, the nearer one in the sliver between two rows, and nothing past the outermost row. The tests compose the CSS transforms from the strings the drum hands CSS and sweep every 0.25 px of the column at two offsets; without the fix the fourth row's middle answered row 34 instead of 35. In Chromium, painting the rows as the drum tells CSS to, every painted device pixel down the drum answers its row (2,866 of 2,869 at DPR 4, the other three on the seams between two rows), against 392 misses before. --- packages/core/src/DateInput/wheelDrum.test.ts | 117 +++++++++++++++++- packages/core/src/DateInput/wheelDrum.ts | 103 +++++++++++++-- 2 files changed, 205 insertions(+), 15 deletions(-) diff --git a/packages/core/src/DateInput/wheelDrum.test.ts b/packages/core/src/DateInput/wheelDrum.test.ts index a5f88a8f7deff..19dde1734e232 100644 --- a/packages/core/src/DateInput/wheelDrum.test.ts +++ b/packages/core/src/DateInput/wheelDrum.test.ts @@ -4,9 +4,10 @@ * @file wheelDrum.test.ts * @input wheelDrum.ts and wheelPhysics.ts, and a UIPickerView's cell * transforms read at rest - * @output Proves the drum puts rows where UIKit's cylinder does, and that a - * baked motion stays within tolerance, never sweeps a parked row across the - * front, and leaves rows that never show without animations + * @output Proves the drum puts rows where UIKit's cylinder does, that a tap + * finds the row drawn under it through the perspective, and that a baked + * motion stays within tolerance, never sweeps a parked row across the front, + * and leaves rows that never show without animations * @position Unit coverage for DateInput/wheelDrum.ts */ @@ -19,6 +20,7 @@ import { rowAngle, rowAtPoint, rowDistance, + rowExtent, rowKeyframes, rowOrigin, rowTransform, @@ -100,7 +102,116 @@ describe('the drum at rest', () => { }); }); +type Matrix = number[][]; + +function multiply(a: Matrix, b: Matrix): Matrix { + return a.map(row => + b[0].map((_, j) => row.reduce((sum, value, k) => sum + value * b[k][j], 0)), + ); +} + +const translateZ = (z: number): Matrix => [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, z], + [0, 0, 0, 1], +]; + +/** + * Where CSS draws a row's edges along y, from the band's centre: the row laid + * out there with `transform: rowTransform(angle)` and `transform-origin: + * rowOrigin(geometry)`, its parent's `perspective` seen from the band's + * centre. Composed as CSS Transforms 2 does, from the strings the drum hands + * CSS, not from `rowExtent`'s algebra. + */ +function cssExtent(angle: number) { + const turn = Number( + /rotateX\((-?[\d.e-]+)rad\)/.exec(rowTransform(angle))?.[1], + ); + const originZ = Number(/(-?[\d.]+)px$/.exec(rowOrigin(GEOMETRY))?.[1]); + const rotateX: Matrix = [ + [1, 0, 0, 0], + [0, Math.cos(turn), -Math.sin(turn), 0], + [0, Math.sin(turn), Math.cos(turn), 0], + [0, 0, 0, 1], + ]; + const perspective: Matrix = [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, -1 / GEOMETRY.perspective, 1], + ]; + const drawn = multiply( + perspective, + multiply(translateZ(originZ), multiply(rotateX, translateZ(-originZ))), + ); + const at = (y: number) => { + const [, screenY, , w] = drawn.map(row => row[1] * y + row[3]); + return screenY / w; + }; + return {top: at(-GEOMETRY.rowHeight / 2), bottom: at(GEOMETRY.rowHeight / 2)}; +} + describe('which row is under a point', () => { + it('draws each row where CSS draws it, nearer the band than the cylinder alone near the edge', () => { + for (let row = -4; row <= 4; row++) { + const angle = rowAngle(row * 32, GEOMETRY); + const css = cssExtent(angle); + const extent = rowExtent(angle, GEOMETRY); + // The CSS strings round the turn to 1e-5 rad and the origin to 1e-3 px, + // which moves an edge by under 1e-3 px. + expect(extent.top).toBeCloseTo(css.top, 3); + expect(extent.bottom).toBeCloseTo(css.bottom, 3); + } + // The fourth row below the band spans 84.7–89.3 px, where the cylinder + // without its perspective puts the third row. + const fourth = rowExtent(rowAngle(4 * 32, GEOMETRY), GEOMETRY); + expect(fourth.top).toBeCloseTo(84.67, 2); + expect(fourth.bottom).toBeCloseTo(89.34, 2); + }); + + it('finds the row CSS draws under every point of the column', () => { + // A tap in the middle of the fourth row below or above the band turns + // to that row, not the third. + const fourth = rowExtent(rowAngle(4 * 32, GEOMETRY), GEOMETRY); + const middle = (fourth.top + fourth.bottom) / 2; + expect(rowAtPoint(middle, 31 * 32, MINUTES, GEOMETRY)).toBe(35); + expect(rowAtPoint(-middle, 31 * 32, MINUTES, GEOMETRY)).toBe(27); + for (const offset of [31 * 32, 31 * 32 + 11.5]) { + // Each drawn row by its position along the wheel. + const drawn = Array.from({length: 13}, (_, k) => { + const position = Math.round(offset / 32) - 6 + k; + const angle = rowAngle(position * 32 - offset, GEOMETRY); + return {position, visible: isRowVisible(angle), ...cssExtent(angle)}; + }).filter(row => row.visible); + const half = GEOMETRY.height / 2; + for (let dy = -half; dy <= half; dy += 0.25) { + let expected: number | null; + if (Math.abs(dy) < GEOMETRY.bandHeight / 2) { + // The band's flat strip, the drum cut away behind it. + expected = Math.round((offset + dy) / 32); + } else { + const under = drawn.find(row => dy >= row.top && dy <= row.bottom); + const above = drawn.filter(row => row.bottom < dy); + const below = drawn.filter(row => row.top > dy); + if (under != null) { + expected = under.position; + } else if (above.length > 0 && below.length > 0) { + const a = above.reduce((x, y) => (y.bottom > x.bottom ? y : x)); + const b = below.reduce((x, y) => (y.top < x.top ? y : x)); + expected = dy - a.bottom <= b.top - dy ? a.position : b.position; + } else { + expected = null; + } + } + expect( + rowAtPoint(dy, offset, MINUTES, GEOMETRY), + `dy ${dy} at ${offset}`, + ).toBe(expected); + } + } + }); + it('inverts the cylinder', () => { const y = GEOMETRY.radius * Math.sin(32 / GEOMETRY.radius); expect(rowAtPoint(y, 31 * 32, MINUTES, GEOMETRY)).toBe(32); diff --git a/packages/core/src/DateInput/wheelDrum.ts b/packages/core/src/DateInput/wheelDrum.ts index e63582531daf3..a605a6987c092 100644 --- a/packages/core/src/DateInput/wheelDrum.ts +++ b/packages/core/src/DateInput/wheelDrum.ts @@ -5,9 +5,9 @@ * @input A wheel's rows, its offset or a curve of it (wheelPhysics.ts), and * the UIKit picker geometry (motion/uikit/picker.ts) * @output Exports the drum's geometry: each row's angle on the cylinder and - * its CSS transform, the band copy's translation, which row is under a - * point, and the curve baked into keyframes per row so a motion runs on the - * compositor + * its CSS transform, where a row is drawn through the perspective, the band + * copy's translation, which row is drawn under a point, and the curve baked + * into keyframes per row so a motion runs on the compositor * @position Rendering math of the touch picker wheel; pure, no DOM * * UIPickerView draws each row on a cylinder: a row whose centre is d px from @@ -123,10 +123,39 @@ export function stripTranslation(offset: number, layout: WheelLayout): number { return -(folded + cycle); } +/** Where a row is drawn along y, from the band's centre, px. */ +export interface RowExtent { + readonly top: number; + readonly bottom: number; +} + +/** + * Where a row at `angle` is drawn: laid out at the band's centre, turned by + * `rowTransform(angle)` about the origin `rowOrigin` puts R behind it, and + * seen through the picker's perspective from the band's centre. Near the + * drum's edge the perspective draws a row several px nearer the band than + * the cylinder alone would (7 px for the fourth row). + */ +export function rowExtent(angle: number, geometry: DrumGeometry): RowExtent { + const {radius, perspective, rowHeight} = geometry; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + // An edge `y` from the row's centre, R in front of the origin, turned + // about x by −angle; then its depth from the layout plane sets its scale. + const drawn = (y: number) => { + const turnedY = y * cos + radius * sin; + const depth = radius * cos - y * sin - radius; + return (turnedY * perspective) / (perspective - depth); + }; + return {top: drawn(-rowHeight / 2), bottom: drawn(rowHeight / 2)}; +} + /** - * The row whose cylinder position is under a point `dy` px below the band's - * centre, or null past the drum's top or bottom. Orthographic: the - * perspective moves rows by under a pixel along y. + * The row drawn under a point `dy` px below the band's centre, or null where + * none is. Inside the band its flat copy shows (the drum is cut away there), + * so the band strip's row. Outside it, the drum's rows where `rowExtent` + * draws them; a point in the sliver between two of them takes the nearer, + * and a point past the outermost one finds nothing. */ export function rowAtPoint( dy: number, @@ -134,15 +163,65 @@ export function rowAtPoint( layout: WheelLayout, geometry: DrumGeometry, ): number | null { - if (Math.abs(dy) >= geometry.radius) { - return null; + const {rowHeight} = layout; + if (Math.abs(dy) < geometry.bandHeight / 2) { + return rowAtPosition(Math.round((offset + dy) / rowHeight), layout); } - const distance = geometry.radius * Math.asin(dy / geometry.radius); - const index = Math.round((offset + distance) / layout.rowHeight); + // Rows within a quarter turn face the viewer; the rest are not drawn. + const reach = Math.ceil((geometry.radius * Math.PI) / 2 / rowHeight) + 1; + const centre = Math.round(offset / rowHeight); + let nearest: number | null = null; + let nearestGap = Infinity; + let drawnAbove = false; + let drawnBelow = false; + for (let position = centre - reach; position <= centre + reach; position++) { + const distance = position * rowHeight - offset; + if (!isDrawnAt(position, distance, layout)) { + continue; + } + const angle = rowAngle(distance, geometry); + if (!isRowVisible(angle)) { + continue; + } + const {top, bottom} = rowExtent(angle, geometry); + if (dy >= top && dy <= bottom) { + return rowAtPosition(position, layout); + } + drawnAbove ||= bottom < dy; + drawnBelow ||= top > dy; + const gap = dy < top ? top - dy : dy - bottom; + if (gap < nearestGap) { + nearestGap = gap; + nearest = position; + } + } + return drawnAbove && drawnBelow && nearest != null + ? rowAtPosition(nearest, layout) + : null; +} + +/** + * Whether the drum draws a row at `position` (`distance` px from the band): + * a list's own rows, and on a looping wheel the copy nearest the band. + */ +function isDrawnAt( + position: number, + distance: number, + layout: WheelLayout, +): boolean { + if (!layout.looping) { + return position >= 0 && position < layout.rowCount; + } + const cycle = layout.rowCount * layout.rowHeight; + return distance >= -cycle / 2 && distance < cycle / 2; +} + +/** The option at `position` along the wheel, or null past a list's ends. */ +function rowAtPosition(position: number, layout: WheelLayout): number | null { if (layout.looping) { - return wrapIndex(index, layout.rowCount); + return wrapIndex(position, layout.rowCount); } - return index >= 0 && index < layout.rowCount ? index : null; + return position >= 0 && position < layout.rowCount ? position : null; } /** One baked sample of a curve. */