Skip to content

Commit 4931e65

Browse files
committed
refactor(core): one tracker for a held finger across any group of targets
`createActionGroupTracker` (#8110) becomes the one tracker for a held finger that slides onto an action, for menus and alerts and also for a row of segments or dots. Every option is additive; today's callers are unchanged: - `resolveTarget(x, y, targets)`: the owner picks the target from the rects read at the begin (the nearest segment along an axis, the end one past the ends); the default stays the hit test with the highlight expansion. - `onMove(x, y)`: every finger position, before it is resolved (a lens that chases the finger). - `onHighlightChange(next, previous)` and `beganOn`: the target each highlight replaces, and the one the press began on. - `remeasure()`: read the rects again (a scroll the owner did not run) and resolve the finger's last position. - `onActivated(item, cancelled)`: whether a click handler cancelled the activation (`preventDefault()` vetoes). - `swallowsNativeClick`: the browser's own click for an unclaimed touch is taken once after the lift, by listeners that exist only until that click or the next press or key.
1 parent 70c9abd commit 4931e65

2 files changed

Lines changed: 404 additions & 48 deletions

File tree

‎packages/core/src/hooks/actionGroupTracker.test.ts‎

Lines changed: 215 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@
1010
* it leaves; end fades and runs only the action under the finger, once;
1111
* cancel and an inert press run nothing; disabled actions are skipped;
1212
* several roots are one group; offsetBy shifts the cached rects; the
13-
* highlight callback and the opt-out of the paint
13+
* highlight callback (with the target it replaces) and the opt-out of the
14+
* paint; an owner's own target resolution (a row of segments, past its
15+
* ends), the finger's raw moves, the begin target, remeasure, a cancelled
16+
* click reported, and the browser's own click swallowed once
1417
* @position jsdom tests of packages/core/src/hooks/actionGroupTracker.ts; the
1518
* hook binding is covered by useActionGroupTracking.test.tsx
1619
*/
@@ -20,6 +23,7 @@ import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
2023
import {PRESS_FADE_MS} from '../utils/pressGesture';
2124
import {
2225
createActionGroupTracker,
26+
type ActionGroupTarget,
2327
type ActionGroupTrackerOptions,
2428
} from './actionGroupTracker';
2529

@@ -125,11 +129,12 @@ describe('createActionGroupTracker', () => {
125129
});
126130

127131
it('cancel cuts the highlight, reports it gone and runs nothing', () => {
128-
const onHighlightChange = vi.fn<(item: HTMLElement | null) => void>();
132+
const onHighlightChange =
133+
vi.fn<(item: HTMLElement | null, previous: HTMLElement | null) => void>();
129134
const group = tracker({onHighlightChange});
130135
group.begin(100, 20);
131136
group.cancel();
132-
expect(onHighlightChange).toHaveBeenLastCalledWith(null);
137+
expect(onHighlightChange).toHaveBeenLastCalledWith(null, first.button);
133138
expect(first.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
134139
expect(group.isTracking).toBe(false);
135140
expect(group.end()).toBeNull();
@@ -255,3 +260,210 @@ describe('createActionGroupTracker', () => {
255260
expect(group.highlighted).toBe(first.button);
256261
});
257262
});
263+
264+
describe('createActionGroupTracker: options for other trackers', () => {
265+
// A row of two segments, side by side with a 2 px gap: x 0-99 and 101-200.
266+
let left: ReturnType<typeof action>;
267+
let right: ReturnType<typeof action>;
268+
beforeEach(() => {
269+
left = action('Left', {left: 0, top: 0, width: 99, height: 30});
270+
right = action('Right', {left: 101, top: 0, width: 99, height: 30});
271+
root.replaceChildren(left.button, right.button);
272+
});
273+
274+
/** The nearest segment along x: the gap counts for the nearer one, past the ends the end one. */
275+
const nearestAlongX = (
276+
x: number,
277+
_y: number,
278+
targets: ReadonlyArray<ActionGroupTarget>,
279+
) => {
280+
let best: ActionGroupTarget | null = null;
281+
let bestDistance = Infinity;
282+
for (const target of targets) {
283+
const distance =
284+
x < target.left
285+
? target.left - x
286+
: x > target.right
287+
? x - target.right
288+
: 0;
289+
if (distance < bestDistance) {
290+
best = target;
291+
bestDistance = distance;
292+
}
293+
}
294+
return best?.element ?? null;
295+
};
296+
297+
it('resolves the target with the owner\u2019s rule, from the rects read at the begin', () => {
298+
const group = tracker({resolveTarget: nearestAlongX});
299+
group.begin(99.6, 200);
300+
expect(group.highlighted).toBe(left.button);
301+
group.move(100.6, 200);
302+
expect(group.highlighted).toBe(right.button);
303+
// Past the end (and far below the row) the end segment is the target, and
304+
// the lift runs it wherever the finger lifts.
305+
group.move(400, 300);
306+
expect(group.highlighted).toBe(right.button);
307+
expect(group.end()).toBe(right.button);
308+
expect(right.onClick).toHaveBeenCalledTimes(1);
309+
expect(left.rectSpy).toHaveBeenCalledTimes(1);
310+
});
311+
312+
it('hands every finger position to onMove before resolving it', () => {
313+
const order: string[] = [];
314+
const group = tracker({
315+
onMove: (x, y) => order.push(`move ${x},${y}`),
316+
onHighlightChange: item => order.push(`highlight ${item?.textContent}`),
317+
});
318+
group.begin(50, 10);
319+
group.move(150, 12);
320+
group.move(160, 14);
321+
expect(order).toEqual([
322+
'move 50,10',
323+
'highlight Left',
324+
'move 150,12',
325+
'highlight Right',
326+
'move 160,14',
327+
]);
328+
});
329+
330+
it('reports the target each highlight replaces, and the target the press began on', () => {
331+
const onHighlightChange =
332+
vi.fn<(item: HTMLElement | null, previous: HTMLElement | null) => void>();
333+
const group = tracker({onHighlightChange});
334+
group.begin(50, 10);
335+
expect(group.beganOn).toBe(left.button);
336+
group.move(150, 10);
337+
group.move(150, 100);
338+
expect(group.beganOn).toBe(left.button);
339+
expect(onHighlightChange.mock.calls).toEqual([
340+
[left.button, null],
341+
[right.button, left.button],
342+
[null, right.button],
343+
]);
344+
group.cancel();
345+
expect(group.beganOn).toBeNull();
346+
// An inert press began on nothing.
347+
group.begin(50, 10, {inert: true});
348+
expect(group.beganOn).toBeNull();
349+
});
350+
351+
it('remeasure reads the targets again and resolves the finger\u2019s last position', () => {
352+
const group = tracker();
353+
group.begin(50, 10);
354+
expect(group.highlighted).toBe(left.button);
355+
// The row moved 120 px down under the still finger (a scroll the owner
356+
// did not run): the finger is now over neither segment.
357+
place(left.button, {left: 0, top: 120, width: 99, height: 30});
358+
place(right.button, {left: 101, top: 120, width: 99, height: 30});
359+
group.remeasure();
360+
expect(group.highlighted).toBeNull();
361+
expect(left.button.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
362+
group.move(150, 130);
363+
expect(group.highlighted).toBe(right.button);
364+
});
365+
366+
it('reports whether a click handler cancelled the activation', () => {
367+
const onActivated = vi.fn();
368+
right.button.addEventListener('click', event => event.preventDefault());
369+
const group = tracker({onActivated});
370+
group.begin(50, 10);
371+
group.end();
372+
group.begin(150, 10);
373+
group.end();
374+
expect(onActivated.mock.calls).toEqual([
375+
[left.button, false],
376+
[right.button, true],
377+
]);
378+
// With onActivate the owner runs the action; there is no click to report.
379+
const onActivate = vi.fn();
380+
const owned = tracker({onActivate, onActivated});
381+
owned.begin(50, 10);
382+
owned.end();
383+
expect(onActivate).toHaveBeenCalledWith(left.button);
384+
expect(onActivated).toHaveBeenCalledTimes(2);
385+
});
386+
387+
it('swallows the browser\u2019s own click after the lift once, listening only until then', () => {
388+
const add = vi.spyOn(window, 'addEventListener');
389+
const remove = vi.spyOn(window, 'removeEventListener');
390+
try {
391+
const group = tracker({swallowsNativeClick: true});
392+
group.begin(50, 10);
393+
add.mockClear();
394+
group.end();
395+
// The tracker's own click ran inside end, before the swallower.
396+
expect(left.onClick).toHaveBeenCalledTimes(1);
397+
// Listening now: what end added and did not take off again (the
398+
// capture that reads its own click comes and goes inside the call).
399+
const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
400+
const armed = add.mock.calls.filter(
401+
([, listener, capture]) => capture === true && !gone.has(listener),
402+
);
403+
expect(armed.map(([type]) => type).sort()).toEqual([
404+
'click',
405+
'keydown',
406+
'pointerdown',
407+
]);
408+
remove.mockClear();
409+
// A script's click is not the browser's: it passes.
410+
const onDocumentClick = vi.fn();
411+
document.addEventListener('click', onDocumentClick);
412+
left.button.click();
413+
expect(onDocumentClick).toHaveBeenCalledTimes(1);
414+
// The browser's click for the touch is taken once, and the swallower goes.
415+
const swallow = armed.find(([type]) => type === 'click')?.[1] as (
416+
event: unknown,
417+
) => void;
418+
const trusted = {
419+
isTrusted: true,
420+
preventDefault: vi.fn(),
421+
stopImmediatePropagation: vi.fn(),
422+
};
423+
swallow(trusted);
424+
expect(trusted.preventDefault).toHaveBeenCalled();
425+
expect(trusted.stopImmediatePropagation).toHaveBeenCalled();
426+
const removed = remove.mock.calls
427+
.filter(([, , capture]) => capture === true)
428+
.map(([type]) => type)
429+
.sort();
430+
expect(removed).toEqual(['click', 'keydown', 'pointerdown']);
431+
document.removeEventListener('click', onDocumentClick);
432+
} finally {
433+
add.mockRestore();
434+
remove.mockRestore();
435+
}
436+
});
437+
438+
it('a press or a key before the browser\u2019s click ends the swallowing; without the option nothing stays listening', () => {
439+
const add = vi.spyOn(window, 'addEventListener');
440+
const remove = vi.spyOn(window, 'removeEventListener');
441+
const listening = () => {
442+
const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
443+
return add.mock.calls
444+
.filter(([, listener]) => !gone.has(listener))
445+
.map(([type]) => type)
446+
.sort();
447+
};
448+
try {
449+
const plain = tracker();
450+
plain.begin(50, 10);
451+
plain.end();
452+
expect(listening()).toEqual([]);
453+
const group = tracker({swallowsNativeClick: true});
454+
group.begin(50, 10);
455+
group.end();
456+
expect(listening()).toEqual(['click', 'keydown', 'pointerdown']);
457+
// The next press comes first (the browser gave no click): disarmed.
458+
window.dispatchEvent(new PointerEvent('pointerdown'));
459+
expect(listening()).toEqual([]);
460+
group.begin(50, 10);
461+
group.end();
462+
window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
463+
expect(listening()).toEqual([]);
464+
} finally {
465+
add.mockRestore();
466+
remove.mockRestore();
467+
}
468+
});
469+
});

0 commit comments

Comments
 (0)