An open source design system that's fully customizable and agent ready
TypeScript
fix(gestures): keep a trackpad flick's late, coalesced wheels in the flick (spec:AST-094 FR43) (#9912)
Christopher Chedeau6c3507a3b2da
diff --git a/.changeset/wheel-late-trackpad-glide.md b/.changeset/wheel-late-trackpad-glide.mdnew file mode 100644index 0000000000..f382364ef6--- /dev/null+++ b/.changeset/wheel-late-trackpad-glide.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Gestures: a late or merged trackpad wheel that keeps the glide falling stays in the flick. When the next wheel grows instead, the new gesture keeps the late wheel's travel. A mouse wheel's notches keep their rules.++@vjeuxdiff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex dcdca813ff..f01a260ee8 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -698,7 +698,9 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 andof a shrinking run, once the run has lost a fifth of its size; momentum afterthe lift never moves a surface or continues a gesture; and during momentum areversal, a delta that rises against the decay, or a 50 ms gap starts a new- gesture without a pointer move. While the splitter has not yet decided+ gesture without a pointer move; a late, coalesced wheel event that continues+ the glide's deceleration belongs to the same flick. While the splitter has+ not yet decidedbetween a lift and fingers still moving, the surface keeps moving at thefingers' last speed, never farther than that speed carries it over the helddeltas; a lift then continues without a stop, and fingers that keep movingdiff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.tsindex 69b5cb6ea3..d7afee7006 100644--- a/packages/core/src/gestures/GestureHost.ts+++ b/packages/core/src/gestures/GestureHost.ts@@ -2292,17 +2292,20 @@ export class GestureHost {};this.wheel = gesture;}- const {dx, dy} = wheelPixels(wheel, this.doc.defaultView);+ let {dx, dy} = wheelPixels(wheel, this.doc.defaultView);const horizontal = Math.abs(dx) > Math.abs(dy);// The splitter reads a pan's stream only. A ctrl-wheel pinch has no// fingers' phase or momentum to tell apart, and ends 100 ms after its// last wheel.let seg: WheelSegment | null = null;if (kind === 'pan') {+ // Only a trackpad's wheel can join its glide late; a mouse wheel's+ // notches keep the splitter's other rules.seg = this.segmenter.push(time,horizontal ? dx : dy,horizontal ? WHEEL_FOLLOW_END_MS : WHEEL_FOLLOW_END_V_MS,+ scrollTypeOf(wheel) === 'continuous',);} else {this.segmenter.end();@@ -2314,6 +2317,14 @@ export class GestureHost {gesture = null;}}+ // A late wheel the glide took was the fingers' first when this one grows.+ if (seg != null && seg.carried !== 0) {+ if (horizontal) {+ dx += seg.carried;+ } else {+ dy += seg.carried;+ }+ }if (gesture == null) {gesture = this.beginWheel(wheel, kind, dx, dy, time);this.wheel = gesture;diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.mdindex 83a7159509..c523b58ccc 100644--- a/packages/core/src/gestures/README.md+++ b/packages/core/src/gestures/README.md@@ -529,7 +529,11 @@ it never moves it; when the fingers carry on instead, their moves absorbwhat the pan showed past their travel, or short of it, so it never stepsback and ends on their travel. Fingers that stop release still, once the endtime passes. In momentum, a reversal, a delta that grows-against the decay, or a 50 ms pause starts a new gesture. A finger, mouse or+against the decay, or a 50 ms pause starts a new gesture; a late, coalesced+trackpad wheel that continues the glide's deceleration (at or below the next+step, or near the sum of the next steps its stall spans) belongs to the same+flick. When the next wheel grows instead, it starts a new gesture with the late+wheel's travel. A finger, mouse orpen that comes down ends it, and a wheel claim keeps the page's textselection. A gesture arecognizer took is latched to it, as a browser latches a scroller: while itdiff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.tsindex ee7e73e5fb..6625e96a07 100644--- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts+++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts@@ -1963,11 +1963,11 @@ test.describe('where the primary pointer is fine', () => {page,[12, 12, 12, 12, 11, 10, 9, 8, 7, 6, 5, 4],);- // The splitter starts a new gesture at a momentum pause of 50 ms or more.- // A loaded page can deliver one, and the proof then judges the wheels- // before it. Each wheel logs itself after the host handled it. WebKit's- // injected wheels carry only real dispatch time, so a harness that cannot- // keep pace can still stall the finger phase and fail this proof.+ // A loaded page can deliver the momentum after a pause of 50 ms or more,+ // and the proof then judges the wheels before it. Each wheel logs itself+ // after the host handled it. WebKit's injected wheels carry only real+ // dispatch time, so a harness that cannot keep pace can still stall the+ // finger phase and fail this proof.const pause = times.findIndex((time, i) => i > lift && time - times[i - 1] >= 50,);diff --git a/packages/core/src/gestures/__tests__/wheel.test.ts b/packages/core/src/gestures/__tests__/wheel.test.tsindex 58c2b45fad..5368ac207e 100644--- a/packages/core/src/gestures/__tests__/wheel.test.ts+++ b/packages/core/src/gestures/__tests__/wheel.test.ts@@ -1757,6 +1757,37 @@ describe("a trackpad scroll through the splitter's undecided stretch (spec:AST-0},);+ it("follows a swipe that resumes 100 ms after a flick's glide for all of its travel: six 30 px wheels", () => {+ const {box, seen} = followed();+ // The lift is read at the 8 px wheel, and the glide goes on at 7 px.+ let time = stream(box, [12, 12, 12, 12, 11, 10, 9, 8, 7]);+ // The fingers come back 100 ms after the glide's last wheel.+ time += 100 - 16;+ for (let i = 0; i < 6; i++) {+ wheel(box, {trackpad: true, dx: 30, time});+ time += 16;+ }+ clock.runDue(time + 500);+ expect(seen.filter(entry => entry.state === 'began')).toHaveLength(2);+ const ended = seen.filter(entry => entry.state === 'ended');+ // All 180 px of the swipe, past the 10 px hysteresis.+ expect(ended[ended.length - 1].x).toBeCloseTo(-170, 6);+ });++ it("follows a swipe that resumes after a flick's glide for all of its travel when its first two wheels arrive merged", () => {+ const {box, seen} = followed();+ let time = stream(box, [12, 12, 12, 12, 11, 10, 9, 8, 7]);+ time += 100 - 16;+ const times = [0, 0.5, 16, 32, 48, 64].map(offset => time + offset);+ for (const at of times) {+ wheel(box, {trackpad: true, dx: 30, time: at});+ }+ clock.runDue(times[times.length - 1] + 500);+ expect(seen.filter(entry => entry.state === 'began')).toHaveLength(2);+ const ended = seen.filter(entry => entry.state === 'ended');+ expect(ended[ended.length - 1].x).toBeCloseTo(-170, 6);+ });+it("never moves or releases faster than the fingers when a stall's bunch of shrinking wheels arrives 1 ms apart", () => {const {box, seen} = followed();// 12 px every 16 ms. A step comes 60 ms late, then 11, 10 and 9 px wheelsdiff --git a/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts b/packages/core/src/gestures/__tests__/wheelSegmenter.test.tsindex 44f1a24389..715634a7b3 100644--- a/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts+++ b/packages/core/src/gestures/__tests__/wheelSegmenter.test.ts@@ -299,3 +299,319 @@ describe('WheelSegmenter: a slowing drag with a merged wheel', () => {expect(liftTime(10)).toBe(control);});});++/** Wheel times from the gaps between them, from 0 ms. */+function timesOf(gaps: ReadonlyArray<number>): number[] {+ const times = [0];+ for (const gap of gaps) {+ times.push(times[times.length - 1] + gap);+ }+ return times;+}++/**+ * Two trackpad flicks a stalled page received in WebKit: 12 px steps, then a+ * glide shrinking 1 px a frame. The page received some of the glide late and+ * merged the wheels it held.+ */+const STALLED_FLICKS = [+ {+ name: 'a late step, then a merge of the rest',+ deltas: [12, 12, 12, 12, 12, 12, 12, 36, 12, 12, 11, 10, 17, 7, 11, 4, 6],+ gaps: [16, 27, 0, 12, 18, 94, 0, 10, 0, 58, 31, 0, 16, 0, 86, 0],+ late: 15,+ },+ {+ name: 'a late merge of the next two steps',+ deltas: [+ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 11, 10, 9, 8, 7, 6, 5, 7,+ 2, 1,+ ],+ gaps: [+ 16, 25, 0, 28, 12, 17, 14, 17, 16, 16, 16, 16, 16, 16, 16, 17, 16, 52, 0,+ 12, 17,+ ],+ late: 18,+ },+] as const;++/** Push a recorded stream as trackpad wheels, or as a mouse wheel's. */+function replay(+ deltas: ReadonlyArray<number>,+ gaps: ReadonlyArray<number>,+ continuous: boolean,+) {+ const segmenter = new WheelSegmenter();+ const times = timesOf(gaps);+ return deltas.map((delta, i) =>+ segmenter.push(times[i], delta, 180, continuous),+ );+}++describe("WheelSegmenter: a late, coalesced trackpad wheel that continues the glide's deceleration belongs to the same flick (spec:AST-094 FR43)", () => {+ it.each(STALLED_FLICKS)(+ 'keeps a stalled flick one gesture: $name',+ ({deltas, gaps}) => {+ const seen = replay(deltas, gaps, true);+ expect(seen.filter(segment => segment.liftNow)).toHaveLength(1);+ expect(seen.slice(1).filter(segment => segment.boundary != null)).toEqual(+ [],+ );+ expect(seen[seen.length - 1].phase).toBe('momentum');+ },+ );++ it.each(STALLED_FLICKS)(+ "splits the same stream at its late wheel when it is a mouse wheel's, as before: $name",+ ({deltas, gaps, late}) => {+ const seen = replay(deltas, gaps, false);+ expect(seen[late].boundary).toBe('gap');+ },+ );++ /**+ * A glide of 1 px less a frame from 10 px, the lift read at its 8 px wheel.+ */+ function glide() {+ const segmenter = new WheelSegmenter();+ const seen = feed(segmenter, [10, 10, 10, 10, 9.5, 9, 8.5, 8]).map(+ segment => segment.liftNow,+ );+ expect(seen[7]).toBe(true);+ return segmenter;+ }++ it('keeps a trackpad wheel that carries the next two steps after a skipped frame', () => {+ const segment = glide().push(7 * 16 + 32, 15, 180, true);+ expect({boundary: segment.boundary, phase: segment.phase}).toEqual({+ boundary: null,+ phase: 'momentum',+ });+ });++ it('still starts a new gesture at a trackpad wheel one frame later that rises against the decay', () => {+ expect(glide().push(7 * 16 + 16, 15, 180, true).boundary).toBe('jump');+ });++ it('still starts a new gesture at a trackpad wheel after a pause that no sum of the glide explains: fingers come back', () => {+ // Larger than every sum of the steps the pause spans.+ expect(glide().push(7 * 16 + 60, 40, 180, true).boundary).toBe('gap');+ });++ it('keeps a late trackpad wheel at or below the next step, and starts a new gesture at the next one that grows: a slow drag speeds up', () => {+ const segmenter = glide();+ expect(segmenter.push(7 * 16 + 120, 2, 180, true).boundary).toBeNull();+ const next = segmenter.push(7 * 16 + 136, 3, 180, true);+ expect(next.boundary).toBe('jump');+ expect(next.carried).toBe(2);+ });++ it('still starts a new gesture at a trackpad wheel after a pause that reverses', () => {+ expect(glide().push(7 * 16 + 60, -7, 180, true).boundary).toBe('reversal');+ });++ it("starts a new gesture at a trackpad wheel that grows after a late one joined the glide, with the late one's travel: fingers come back", () => {+ const segmenter = glide();+ expect(segmenter.push(7 * 16 + 60, 7, 180, true).boundary).toBeNull();+ const next = segmenter.push(7 * 16 + 76, 8, 180, true);+ expect(next.boundary).toBe('jump');+ expect(next.carried).toBe(7);+ });++ it('hands over only the late wheel just before: a wheel that grows two wheels after it carries nothing', () => {+ const segmenter = glide();+ expect(segmenter.push(7 * 16 + 60, 7, 180, true).boundary).toBeNull();+ expect(segmenter.push(7 * 16 + 76, 6, 180, true).boundary).toBeNull();+ const grows = segmenter.push(7 * 16 + 92, 9, 180, true);+ expect(grows.boundary).toBe('jump');+ expect(grows.carried).toBe(0);+ });++ it('keeps a whole-pixel glide one flick when it repeats a step after a late wheel joined it', () => {+ const segmenter = new WheelSegmenter();+ const seen = [12, 12, 12, 12, 11, 10, 9, 8, 8].map((delta, i) =>+ segmenter.push(i * 16, delta, 180, true),+ );+ expect(seen.filter(segment => segment.liftNow)).toHaveLength(1);+ // A whole-pixel glide slows by repeating steps: 7, 7, 6, 6, 5.+ const late = 8 * 16 + 70;+ expect(+ [7, 7, 6, 6, 5].map(+ (delta, i) => segmenter.push(late + i * 16, delta, 180, true).boundary,+ ),+ ).toEqual([null, null, null, null, null]);+ });++ /** A glide that ends at 7 px a frame, the lift read at its 8 px wheel. */+ function glideToSeven() {+ const segmenter = new WheelSegmenter();+ const seen = [12, 12, 12, 12, 11, 10, 9, 8, 7].map((delta, i) =>+ segmenter.push(i * 16, delta, 180, true),+ );+ expect(seen.findIndex(segment => segment.liftNow)).toBe(7);+ return segmenter;+ }++ it.each([+ [20, 100],+ [25, 110],+ [30, 120],+ ])(+ 'hands a %i px trackpad wheel %i ms after a glide that ends at 7 px to the next wheel, which grows into a new gesture: a swipe resumes',+ (size, after) => {+ const segmenter = glideToSeven();+ const time = 8 * 16 + after;+ expect(segmenter.push(time, size, 180, true).boundary).toBeNull();+ const next = segmenter.push(time + 16, size, 180, true);+ expect(next.boundary).toBe('jump');+ expect(next.carried).toBe(size);+ },+ );++ it('hands nothing to a new gesture that starts late after a late wheel: a merged glide wheel looks the same', () => {+ const segmenter = glideToSeven();+ const time = 8 * 16 + 100;+ expect(segmenter.push(time, 30, 180, true).boundary).toBeNull();+ const next = segmenter.push(time + 60, 30, 180, true);+ expect(next.boundary).toBe('gap');+ expect(next.carried).toBe(0);+ });++ it("hands a resumed swipe's first two wheels to the new gesture when they arrive merged", () => {+ const segmenter = glideToSeven();+ const time = 8 * 16 + 100;+ expect(segmenter.push(time, 30, 180, true).boundary).toBeNull();+ expect(segmenter.push(time + 0.5, 30, 180, true).boundary).toBeNull();+ const next = segmenter.push(time + 16, 30, 180, true);+ expect(next.boundary).toBe('jump');+ expect(next.carried).toBe(60);+ });++ it('starts a new gesture at a swipe on pace right after a whole-pixel glide, after an earlier gesture showed a 10 ms gap', () => {+ const segmenter = new WheelSegmenter();+ // An earlier gesture whose page delivered one wheel 10 ms after another.+ for (const time of [0, 16, 26, 42]) {+ segmenter.push(time, 12, 180, true);+ }+ const start = 342;+ const deltas = [12, 12, 12, 12, 11, 10, 9, 8, 8, 7, 7];+ const seen = deltas.map((delta, i) =>+ segmenter.push(start + i * 16, delta, 180, true),+ );+ expect(seen[0].boundary).toBe('idle');+ expect(seen.filter(segment => segment.liftNow)).toHaveLength(1);+ expect(+ segmenter.push(start + deltas.length * 16, 14, 180, true).boundary,+ ).toBe('jump');+ });++ it("starts a new gesture at a swipe 16 ms after a stall delivered the glide's held wheels 3 ms apart", () => {+ const segmenter = glideToSeven();+ let time = 8 * 16;+ for (const delta of [6, 6, 5, 5, 4, 4]) {+ time += 3;+ segmenter.push(time, delta, 180, true);+ }+ expect(segmenter.push(time + 16, 12, 180, true).boundary).toBe('jump');+ });++ it('keeps a 16 ms frame when a gesture starts with squeezed wheels', () => {+ const segmenter = new WheelSegmenter();+ const times = [0, 3, 6, ...Array.from({length: 9}, (_, i) => 22 + i * 16)];+ const deltas = [12, 12, 12, 12, 12, 12, 11, 10, 9, 8, 7, 7];+ const seen = deltas.map((delta, i) =>+ segmenter.push(times[i], delta, 180, true),+ );+ expect(seen.filter(segment => segment.liftNow)).toHaveLength(1);+ expect(+ segmenter.push(times[times.length - 1] + 16, 14, 180, true).boundary,+ ).toBe('jump');+ });++ it('keeps a 27 px trackpad wheel 100 ms after a glide that ends at 7 px in the flick: a six-frame stall merges its steps', () => {+ const segmenter = glideToSeven();+ expect(segmenter.push(8 * 16 + 100, 27, 180, true).boundary).toBeNull();+ expect(segmenter.push(8 * 16 + 116, 3, 180, true).boundary).toBeNull();+ });++ it('hands a 20 px trackpad wheel 100 ms after a whole-pixel tail to the next wheel, which grows', () => {+ const segmenter = new WheelSegmenter();+ const seen = [12, 12, 12, 12, 11, 10, 9, 8, 8, 7, 7].map((delta, i) =>+ segmenter.push(i * 16, delta, 180, true),+ );+ expect(seen.filter(segment => segment.liftNow)).toHaveLength(1);+ // Steady 7 px steps fit the 20 px wheel as three of them.+ expect(segmenter.push(10 * 16 + 100, 20, 180, true).boundary).toBeNull();+ const next = segmenter.push(10 * 16 + 116, 24, 180, true);+ expect(next.boundary).toBe('jump');+ expect(next.carried).toBe(20);+ });++ it('keeps a trackpad glide that goes on falling after a late wheel joined it', () => {+ const segmenter = glide();+ expect(+ [60, 76, 92].map(+ (time, i) => segmenter.push(7 * 16 + time, 7 - i, 180, true).boundary,+ ),+ ).toEqual([null, null, null]);+ });++ /**+ * Two flicks a stalled page received in WebKit with a merge of the+ * shrinking run's steps, which the decay explains better than steady steps.+ */+ const MERGED_RUNS = [+ {+ name: 'three shrinking steps merged, then a late step',+ deltas: [12, 12, 12, 24, 12, 36, 12, 12, 12, 11, 27, 7, 6, 5, 4, 6],+ gaps: [25, 45, 0, 64, 0, 32, 0, 60, 31, 0, 14, 1, 65, 26, 0],+ lift: 12,+ before: 14,+ },+ {+ name: 'late steps with the next ones merged after them',+ deltas: [12, 12, 12, 12, 36, 12, 12, 12, 12, 50, 7, 11, 4, 5, 1],+ gaps: [32, 0, 85, 0, 12, 0, 17, 90, 0, 82, 0, 9, 0, 17],+ lift: 13,+ before: -1,+ },+ ] as const;++ it.each(MERGED_RUNS)(+ "reads a stalled flick's lift where its shrinking run shows it: $name",+ ({deltas, gaps, lift}) => {+ const seen = replay(deltas, gaps, true);+ expect(seen.findIndex(segment => segment.liftNow)).toBe(lift);+ expect(seen.slice(1).filter(segment => segment.boundary != null)).toEqual(+ [],+ );+ },+ );++ it.each(MERGED_RUNS)(+ "reads the same stream's lift as before when it is a mouse wheel's: $name",+ ({deltas, gaps, before}) => {+ const seen = replay(deltas, gaps, false);+ expect(seen.findIndex(segment => segment.liftNow)).toBe(before);+ },+ );++ it("keeps a mouse wheel's rules for every wheel without the trackpad signature", () => {+ // The trackpad wheels above that stay in the flick.+ expect(glide().push(7 * 16 + 32, 15, 180).boundary).toBe('jump');+ expect(glide().push(7 * 16 + 60, 7, 180).boundary).toBe('gap');+ expect(glide().push(7 * 16 + 60, 7, 180, true).boundary).toBeNull();+ // After a late trackpad wheel joined, a notch that stops falling keeps+ // today's rule too.+ const resumed = glide();+ expect(resumed.push(7 * 16 + 60, 7, 180, true).boundary).toBeNull();+ expect(resumed.push(7 * 16 + 76, 7, 180).boundary).toBeNull();+ });++ it('keeps a merge that a stall delivers after a late wheel in the glide: the steps of the whole stall', () => {+ const segmenter = glide();+ // The 6, 5 and 4 px steps arrive merged, 30 ms after a late 7.+ expect(segmenter.push(7 * 16 + 65, 7, 180, true).boundary).toBeNull();+ expect(segmenter.push(7 * 16 + 95, 15, 180, true).boundary).toBeNull();+ });+});diff --git a/packages/core/src/gestures/wheelSegmenter.ts b/packages/core/src/gestures/wheelSegmenter.tsindex 39ff5eb0c1..eee6f6a538 100644--- a/packages/core/src/gestures/wheelSegmenter.ts+++ b/packages/core/src/gestures/wheelSegmenter.ts@@ -5,6 +5,7 @@* @input A wheel stream's deltas along one axis, with their event times* @output Exports WheelSegmenter and isBunched. WheelSegmenter splits the* stream into gestures and reads a trackpad's lift (the onset of momentum).+ * It keeps a trackpad's late or merged glide wheels in their flick.* isBunched tells one stall's merge from a frame.* @position Read by GestureHost.ts's wheel input: the web reports no* trackpad contact or phase, so both are inferred.@@ -25,6 +26,12 @@ export interface WheelSegment {readonly decaying: boolean;/** This event came so soon after the one before that it is a merge. */readonly bunched: boolean;+ /**+ * The signed travel of the late wheel before this one, with any wheel+ * merged with it. It is handed over when that wheel joined the glide and+ * this one grows into a new gesture; else 0.+ */+ readonly carried: number;}/** Momentum arrives at frame rate: a pause this long ends it. */@@ -38,6 +45,25 @@ const BUNCHED_MS = 1.5;const LIFT_RUN = 4;/** And how much of its size the run has lost by then. */const LIFT_DECAY = 0.8;+/** How near a wheel must lie to a sum of the glide's next steps, px. */+const FIT_PX = 1;+/** Or as a share of that sum, when the share is larger. */+const FIT_SHARE = 0.25;+/** The most glide steps one wheel is read as carrying. */+const MAX_STEPS = 64;+/** How near a late or rising wheel must lie to the glide's sum, as a share. */+const LATE_FIT_SHARE = 0.15;+/**+ * How far a wheel may grow past the last unbunched one and still be the+ * glide, px.+ */+const RISE_PX = 0.5;+/** A stream's frame interval until it shows its own, ms. */+const FRAME_MS = 16;+/** The longest frame interval a trackpad reports at: 60 Hz, ms. */+const SLOWEST_FRAME_MS = 1000 / 60;+/** The intervals that set a gesture's frame before its window applies. */+const FIRST_PACES = 3;/*** Whether a wheel `intervalMs` after the one before is one stall's merge, not@@ -59,6 +85,16 @@ export function isBunched(intervalMs: number): boolean {* decay, or a pause of 50 ms starts a new gesture. A bunched wheel is never* a jump. The decay reads it by its last step. Momentum never pauses,* reverses or grows.+ *+ * A stalled page receives a trackpad's glide late, and the engine merges the+ * wheels it held. In momentum, a trackpad wheel that the glide's decay+ * explains stays in the flick. It may come after a pause, or rise after more+ * than a frame. It is at or below the next step, or near the sum of the next+ * steps its stall spans. After such a wheel, a trackpad wheel that grows+ * starts a new gesture and takes the late wheel's travel. The decay also+ * reads a trackpad merge in momentum, by its last step. It reads one in a+ * shrinking run too, where it explains the merge better than steady steps+ * do. Other wheels keep the rules above.*/export class WheelSegmenter {gesture = 0;@@ -69,44 +105,137 @@ export class WheelSegmenter {private count = 0;private run = 0;private runStart = 0;+ /** The decay's step-to-step ratio, from the last two one-step wheels. */+ private ratio = 1;+ /** The gesture's last on-pace intervals, ms: their median is its frame. */+ private paces: number[] = [];+ /** The intervals in a row that came slower than the frame allows, ms. */+ private slower: number[] = [];+ /** When the gesture's last wheel within two frames of the one before came. */+ private onPace = -Infinity;+ /** The gesture's last wheel that was not bunched, px. */+ private paced = 0;+ /** A wheel joined the glide late: a later one that grows is the fingers'. */+ private resumed = false;+ /**+ * The signed travel of the last wheel that joined the glide late, with any+ * wheel merged with it.+ */+ private joined = 0;- push(time: number, delta: number, idleMs: number): WheelSegment {+ /**+ * Reads one wheel. `continuous` is whether it carries a trackpad's+ * signature (`scrollTypeOf`). Only those wheels can join a glide late.+ */+ push(+ time: number,+ delta: number,+ idleMs: number,+ continuous = false,+ ): WheelSegment {const size = Math.abs(delta);const sign = Math.sign(delta);const gap = time - this.last;const bunched = this.count > 0 && isBunched(gap);+ const frame = this.frameMs();let boundary: WheelBoundary | null = null;+ let carriedSteps: number | null = null;if (this.count === 0) {boundary = this.gesture === 0 ? 'first' : 'idle';} else if (this.phase === 'finger' && gap >= idleMs) {boundary = 'idle';} else if (this.phase === 'momentum') {+ // A late wheel carries the steps of its whole stall, which began at the+ // last wheel that came on pace.+ const frames = Math.round((time - this.onPace) / frame);+ const late = gap >= MOMENTUM_GAP_MS;+ const rises = !bunched && size >= 2 && size > this.previous * 1.3 + 0.5;if (sign !== 0 && this.sign !== 0 && sign !== this.sign) {boundary = 'reversal';- } else if (gap >= MOMENTUM_GAP_MS) {- boundary = 'gap';- } else if (!bunched && size >= 2 && size > this.previous * 1.3 + 0.5) {+ } else if (late || rises) {+ // A wheel that rises on pace is the fingers'. One that rises after a+ // skipped frame may carry the frames its stall held.+ if (continuous && sign === this.sign && (late || gap >= 1.5 * frame)) {+ carriedSteps = this.glideSteps(+ size,+ Math.max(1, frames),+ LATE_FIT_SHARE,+ );+ }+ if (carriedSteps == null) {+ boundary = late ? 'gap' : 'jump';+ }+ } else if (+ continuous &&+ this.resumed &&+ !bunched &&+ size > FIT_PX &&+ size > this.paced + RISE_PX+ ) {+ // A glide only falls, so after a late wheel one that grows is the+ // fingers'. A whole-pixel glide repeats a step as it slows.boundary = 'jump';}}+ if (carriedSteps == null && boundary == null && bunched && continuous) {+ if (this.phase === 'momentum') {+ carriedSteps = this.glideSteps(size, MAX_STEPS);+ } else if (this.run > 0) {+ // In a shrinking run, the decay reads a merge only where it explains+ // the merge better than steady steps do.+ const decay = this.glideSteps(size, MAX_STEPS);+ if (+ decay != null &&+ decay > 1 &&+ Math.abs(size - this.glideSum(decay)) < this.steadyOff(size)+ ) {+ carriedSteps = decay;+ }+ }+ }// A bunched wheel carries the steps of the frames it merged. The decay// goes on from its last step, so the steps after it read as they are.const steps =- boundary == null && bunched && this.previous > 0+ carriedSteps ??+ (boundary == null && bunched && this.previous > 0? Math.max(1, Math.round(size / this.previous))- : 1;+ : 1);+ // On the decay, a wheel of several steps ends at the decay's own step.+ const onDecay = carriedSteps != null && carriedSteps > 1;+ // A bunched wheel is read by its last step, as the decay goes on from it.+ const step = onDecay ? this.previous * this.ratio ** steps : size / steps;if (boundary != null) {this.gesture += 1;this.phase = 'finger';this.count = 0;this.run = 0;+ this.ratio = 1;+ this.resumed = false;+ this.paces = [];+ this.slower = [];+ }+ // The late wheel was the fingers' when the next one grows: the new+ // gesture takes its travel.+ const carried = boundary === 'jump' ? this.joined : 0;+ const joinedLate = boundary == null && carriedSteps != null && !bunched;+ if (joinedLate) {+ this.resumed = true;+ }+ // A wheel merged with the late one is the same dispatch: it adds to it.+ this.joined = joinedLate+ ? delta+ : bunched && boundary == null && this.joined !== 0+ ? this.joined + delta+ : 0;+ if (!bunched) {+ this.paced = size;}let liftNow = false;let decaying = false;if (this.phase === 'finger' && this.count >= 3 && size > 0) {- // A bunched wheel is read by its last step, as the decay goes on from it.- const step = size / steps;- decaying = step <= this.previous * 0.995 && step >= this.previous * 0.5;+ decaying = onDecay+ ? this.ratio <= 0.995+ : step <= this.previous * 0.995 && step >= this.previous * 0.5;if (decaying) {if (this.run === 0) {this.runStart = this.previous;@@ -120,8 +249,17 @@ export class WheelSegmenter {liftNow = true;}}+ if (steps === 1 && this.count > 0 && this.previous > 0 && step > 0) {+ this.ratio = Math.min(1, Math.max(0.5, step / this.previous));+ }+ if (!bunched && boundary == null && gap < MOMENTUM_GAP_MS) {+ this.notePace(gap, frame);+ }+ if (boundary != null || (!bunched && gap < 2 * frame)) {+ this.onPace = time;+ }this.count += 1;- this.previous = size / steps;+ this.previous = step;if (sign !== 0) {this.sign = sign;}@@ -133,9 +271,104 @@ export class WheelSegmenter {liftNow,decaying: decaying && !liftNow,bunched: boundary == null && bunched,+ carried,};}+ /**+ * Keep an interval for the frame. The gesture's first FIRST_PACES set it.+ * After them, only an interval within half a frame and one and a half+ * frames counts: a stall's squeezed wheels come faster. FIRST_PACES slower+ * intervals in a row set the frame again, so a squeezed start cannot hold+ * it down.+ */+ private notePace(gap: number, frame: number): void {+ const inWindow = gap >= 0.5 * frame && gap <= 1.5 * frame;+ if (this.paces.length < FIRST_PACES || inWindow) {+ this.paces = [...this.paces.slice(-7), gap];+ this.slower = [];+ return;+ }+ this.slower = gap > 1.5 * frame ? [...this.slower, gap] : [];+ if (this.slower.length >= FIRST_PACES) {+ this.paces = this.slower;+ this.slower = [];+ }+ }++ /**+ * The gesture's frame interval: the median of its last on-pace intervals,+ * or FRAME_MS before it shows one. A trackpad reports at 60 Hz or faster,+ * so a longer median is a stall's.+ */+ private frameMs(): number {+ if (this.paces.length === 0) {+ return FRAME_MS;+ }+ const sorted = [...this.paces].sort((a, b) => a - b);+ const middle = sorted.length >> 1;+ const median =+ sorted.length % 2 === 1+ ? sorted[middle]+ : (sorted[middle - 1] + sorted[middle]) / 2;+ return Math.min(median, SLOWEST_FRAME_MS);+ }++ /** The sum of the decay's next `count` steps from `previous`. */+ private glideSum(count: number): number {+ let next = this.previous * this.ratio;+ let sum = 0;+ for (let i = 0; i < count; i++) {+ sum += next;+ next *= this.ratio;+ }+ return sum;+ }++ /**+ * How far a merge of `size` lies from whole steps of the run's steady+ * size, or of its last step, whichever lies nearer.+ */+ private steadyOff(size: number): number {+ return Math.min(+ ...[this.runStart, this.previous]+ .filter(step => step > 0)+ .map(step =>+ Math.abs(size - Math.max(1, Math.round(size / step)) * step),+ ),+ );+ }++ /**+ * How many of the decay's next steps a trackpad wheel of `size` carries,+ * at most `most`. A wheel at or below the next step carries one. A larger+ * one carries the fewest steps whose sum lies within FIT_PX or `share` of+ * it. The decay goes on from `previous` at `ratio` a step. Null when+ * no sum lies that near.+ */+ private glideSteps(+ size: number,+ most: number,+ share = FIT_SHARE,+ ): number | null {+ if (this.previous <= 0 || size <= 0) {+ return null;+ }+ let next = this.previous * this.ratio;+ if (size <= next + FIT_PX) {+ return 1;+ }+ let sum = next;+ for (let count = 2; count <= Math.min(most, MAX_STEPS); count++) {+ next *= this.ratio;+ sum += next;+ if (Math.abs(size - sum) <= Math.max(FIT_PX, sum * share)) {+ return count;+ }+ }+ return null;+ }+/** The gesture ended on its own (its timer): the next event starts one. */end(): void {this.count = 0;