Skip to content

Commit e686149

Browse files
committed
Merge meta#8635 (c258015: the shared touch hit area's current head) under the button group's tracking
2 parents dbcc3d9 + c258015 commit e686149

2 files changed

Lines changed: 248 additions & 21 deletions

File tree

‎packages/core/src/utils/hitArea.test.ts‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
type HitInsets,
2121
type HitRect,
2222
NO_HIT_INSETS,
23+
resetHitAreaForTests,
2324
resolveHitTarget,
2425
watchHitArea,
2526
writeHitInsets,
@@ -241,6 +242,8 @@ describe('watchHitArea', () => {
241242
});
242243

243244
afterEach(() => {
245+
resetHitAreaForTests();
246+
vi.restoreAllMocks();
244247
vi.unstubAllGlobals();
245248
document.body.innerHTML = '';
246249
});
@@ -463,6 +466,145 @@ describe('watchHitArea', () => {
463466
stop();
464467
});
465468

469+
it('swallows a touch inside the fresh area that an offset neighbour is nearer (a corner)', () => {
470+
const control = byId('switch');
471+
// A tall link beside it, 8 px to the right, reaching far below.
472+
place(control, rect(100, 100, 24, 24));
473+
place(byId('link'), rect(132, 100, 60, 80));
474+
const stop = watchHitArea(control, () => {});
475+
show(control);
476+
flush();
477+
// Inside the area (right inset 4, bottom 10), below the switch: 5 px from
478+
// the link, 9.5 px from the switch.
479+
const press = new Event('pointerdown', {bubbles: true});
480+
Object.assign(press, {pointerType: 'touch', clientX: 127, clientY: 133});
481+
control.dispatchEvent(press);
482+
const click = new MouseEvent('click', {
483+
bubbles: true,
484+
cancelable: true,
485+
detail: 1,
486+
});
487+
control.dispatchEvent(click);
488+
expect(click.defaultPrevented).toBe(true);
489+
stop();
490+
});
491+
492+
it('counts tree items, menu checkbox and radio items as neighbours', () => {
493+
document.body.innerHTML =
494+
'<span id="switch" role="switch" tabindex="0"></span>' +
495+
'<div id="item" role="treeitem"></div>';
496+
const control = byId('switch');
497+
place(control, rect(100, 100, 24, 24));
498+
place(byId('item'), rect(132, 100, 60, 24));
499+
const heard: HitInsets[] = [];
500+
const stop = watchHitArea(control, insets => heard.push(insets));
501+
show(control);
502+
flush();
503+
expect(heard.at(-1)?.right).toBe(4);
504+
stop();
505+
});
506+
507+
it('leaves a touch the browser hands a lone control a few px past its area to it: only a nearer neighbour swallows', () => {
508+
const control = byId('switch');
509+
place(control, rect(100, 100, 24, 24));
510+
place(byId('link'), rect(400, 400, 60, 24));
511+
const stop = watchHitArea(control, () => {});
512+
show(control);
513+
flush();
514+
// 3 px right of the 44 px area (10 px of growth), nothing near.
515+
const press = new Event('pointerdown', {bubbles: true});
516+
Object.assign(press, {pointerType: 'touch', clientX: 137, clientY: 112});
517+
control.dispatchEvent(press);
518+
const click = new MouseEvent('click', {
519+
bubbles: true,
520+
cancelable: true,
521+
detail: 1,
522+
});
523+
control.dispatchEvent(click);
524+
expect(click.defaultPrevented).toBe(false);
525+
stop();
526+
});
527+
528+
it('measures a watched neighbour by its own box, not by its grown input', () => {
529+
document.body.innerHTML =
530+
'<div id="a"><input id="ia" role="switch"></div>' +
531+
'<div id="b"><input id="ib" role="switch"></div>';
532+
const a = byId('a');
533+
const b = byId('b');
534+
place(a, rect(100, 100, 32, 20));
535+
place(b, rect(100, 128, 32, 20));
536+
// Each input is grown to its hit area: 44 px tall.
537+
place(byId('ia'), rect(94, 88, 44, 44));
538+
place(byId('ib'), rect(94, 116, 44, 44));
539+
const heard: HitInsets[] = [];
540+
const stopA = watchHitArea(a, insets => heard.push(insets));
541+
const stopB = watchHitArea(b, () => {});
542+
show(a, b);
543+
flush();
544+
// Half the 8 px gap to b's box, not a quarter (b's input reaches a).
545+
expect(heard.at(-1)?.bottom).toBe(4);
546+
stopA();
547+
stopB();
548+
});
549+
550+
it('listens for presses once, on the document: a watched control, row or handle gets no listener of its own (spec:AST-103 FR5)', () => {
551+
const elements = ['switch', 'other'].map(byId);
552+
const onElements = elements.map(element =>
553+
vi.spyOn(element, 'addEventListener'),
554+
);
555+
const onDocument = vi.spyOn(document, 'addEventListener');
556+
const stops = elements.map(element => watchHitArea(element, () => {}));
557+
for (const spy of onElements) {
558+
expect(spy).not.toHaveBeenCalled();
559+
}
560+
expect(
561+
onDocument.mock.calls.filter(([type]) => type === 'pointerdown'),
562+
).toHaveLength(1);
563+
stops.forEach(stop => stop());
564+
});
565+
566+
it('removes its document listener when the last watch stops (spec:AST-094 FR24)', () => {
567+
const offDocument = vi.spyOn(document, 'removeEventListener');
568+
const stops = ['switch', 'other'].map(id =>
569+
watchHitArea(byId(id), () => {}),
570+
);
571+
stops[0]();
572+
expect(
573+
offDocument.mock.calls.filter(([type]) => type === 'pointerdown'),
574+
).toHaveLength(0);
575+
stops[1]();
576+
expect(
577+
offDocument.mock.calls.filter(([type]) => type === 'pointerdown'),
578+
).toHaveLength(1);
579+
});
580+
581+
it('leaves nothing behind after resetHitAreaForTests, even from a watch never stopped', () => {
582+
watchHitArea(byId('switch'), () => {});
583+
const offDocument = vi.spyOn(document, 'removeEventListener');
584+
resetHitAreaForTests();
585+
expect(
586+
offDocument.mock.calls.filter(([type]) => type === 'pointerdown'),
587+
).toHaveLength(1);
588+
coarse = false;
589+
const onDocument = vi.spyOn(document, 'addEventListener');
590+
const stop = watchHitArea(byId('other'), () => {});
591+
expect(onDocument).not.toHaveBeenCalled();
592+
stop();
593+
});
594+
595+
it('reads the pointer query at each watch, so a watch never left behind keeps a stale coarse answer', () => {
596+
const left = watchHitArea(byId('switch'), () => {});
597+
// The environment's pointer turns fine through a new query object (a
598+
// test's stub), and the earlier watch never stopped.
599+
coarse = false;
600+
const other = byId('other');
601+
const onElement = vi.spyOn(other, 'addEventListener');
602+
const stop = watchHitArea(other, () => {});
603+
expect(onElement).not.toHaveBeenCalled();
604+
stop();
605+
left();
606+
});
607+
466608
it('stops hearing a control after its function runs', () => {
467609
const control = byId('switch');
468610
place(control, rect(100, 100, 24, 24));

‎packages/core/src/utils/hitArea.ts‎

Lines changed: 106 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,13 @@ const INTERACTIVE = [
229229
'[role="switch"]',
230230
'[role="tab"]',
231231
'[role="menuitem"]',
232+
'[role="menuitemcheckbox"]',
233+
'[role="menuitemradio"]',
234+
'[role="treeitem"]',
235+
'[role="combobox"]',
236+
'[role="textbox"]',
237+
'[role="searchbox"]',
238+
'[role="spinbutton"]',
232239
'[role="option"]',
233240
'[role="slider"]',
234241
'[tabindex]:not([tabindex="-1"])',
@@ -330,19 +337,43 @@ interface Candidate {
330337
readonly rect: HitRect;
331338
}
332339

333-
/** The page's interactive elements and their rects: one read. */
340+
/** The watched element `element` belongs to, if any (itself included). */
341+
function watchedOwner(element: Element): Element | null {
342+
for (
343+
let node: Element | null = element;
344+
node != null;
345+
node = node.parentElement
346+
) {
347+
if (watched.has(node)) {
348+
return node;
349+
}
350+
}
351+
return null;
352+
}
353+
354+
/**
355+
* The page's interactive elements and their rects: one read. A watched
356+
* control counts by its own box, never by a part inside it (its invisible
357+
* input is grown by its hit area, which must not shrink a neighbour's).
358+
*/
334359
function readCandidates(doc: Document): Candidate[] {
335-
return [...doc.querySelectorAll(INTERACTIVE)].map(element => ({
336-
element,
337-
rect: plainRect(element),
338-
}));
360+
const seen = new Set<Element>();
361+
const candidates: Candidate[] = [];
362+
for (const found of doc.querySelectorAll(INTERACTIVE)) {
363+
const element = watchedOwner(found) ?? found;
364+
if (!seen.has(element)) {
365+
seen.add(element);
366+
candidates.push({element, rect: plainRect(element)});
367+
}
368+
}
369+
return candidates;
339370
}
340371

341372
/** A control's rect and clamped insets, from candidates already read. */
342373
function measureOne(
343374
watch: Watch,
344375
candidates: ReadonlyArray<Candidate>,
345-
): {target: HitRect; insets: HitInsets} {
376+
): {target: HitRect; insets: HitInsets; neighbours: HitRect[]} {
346377
const target = plainRect(watch.element);
347378
// Two targets each growing up to half the minimum reach each other from a
348379
// minimum apart.
@@ -362,7 +393,11 @@ function measureOne(
362393
!isOwn(watch, element),
363394
)
364395
.map(({rect}) => rect);
365-
return {target, insets: clampedHitInsets(target, neighbours, watch.minSize)};
396+
return {
397+
target,
398+
insets: clampedHitInsets(target, neighbours, watch.minSize),
399+
neighbours,
400+
};
366401
}
367402

368403
/** One pass: every pending control's reads, then every write. */
@@ -424,25 +459,48 @@ function scheduleAll(): void {
424459
* neighbour, and the next tap uses the fresh insets.
425460
*/
426461
function onPress(event: Event): void {
427-
const element = event.currentTarget as Element;
462+
// One listener for every watched control, on the document: a control, a
463+
// row or a handle carries none of its own (a list's listeners stay the
464+
// list's, spec:AST-103 FR5). The innermost watched element the press
465+
// lands in is the one it is for.
466+
for (
467+
let node: Element | null =
468+
event.target instanceof Element ? event.target : null;
469+
node != null;
470+
node = node.parentElement
471+
) {
472+
if (watched.has(node)) {
473+
checkPress(node, event as PointerEvent);
474+
return;
475+
}
476+
}
477+
}
478+
479+
function checkPress(element: Element, event: PointerEvent): void {
428480
const entry = watched.get(element);
429481
if (entry == null) {
430482
return;
431483
}
432484
// A swallower left from a touch that sent no click goes with the next one.
433485
entry.disarm?.();
434-
const press = event as PointerEvent;
486+
const press = event;
435487
if (!isCoarse || press.pointerType !== 'touch') {
436488
return;
437489
}
438490
const candidates = readCandidates(element.ownerDocument);
439-
let isInside = false;
491+
const x = press.clientX;
492+
const y = press.clientY;
493+
// The touch is the control's unless a neighbour is nearer it: inside the
494+
// fresh area too (a corner beside an offset or diagonal neighbour), and
495+
// a few px past it, where a browser's own touch adjustment reaches.
496+
let isNearerNeighbour = false;
440497
for (const watch of entry.watches) {
441-
const {target, insets} = measureOne(watch, candidates);
498+
const {target, insets, neighbours} = measureOne(watch, candidates);
442499
deliver(watch, insets);
443-
isInside ||= contains(grown(target, insets), press.clientX, press.clientY);
500+
const own = distanceTo(target, x, y);
501+
isNearerNeighbour ||= neighbours.some(rect => distanceTo(rect, x, y) < own);
444502
}
445-
if (!isInside) {
503+
if (isNearerNeighbour) {
446504
const swallow = (click: Event) => {
447505
disarm();
448506
// A keyboard or assistive-technology activation (detail 0) is never
@@ -501,7 +559,6 @@ function observe(element: Element, entry: Watched): void {
501559
}
502560
const stopScope =
503561
parent == null ? null : observeContent(parent, () => onScopeChange(parent));
504-
element.addEventListener('pointerdown', onPress, PASSIVE_CAPTURE);
505562
entry.release = () => {
506563
visibility?.unobserve(element);
507564
resize?.unobserve(element);
@@ -517,7 +574,6 @@ function observe(element: Element, entry: Watched): void {
517574
}
518575
}
519576
stopScope?.();
520-
element.removeEventListener('pointerdown', onPress, PASSIVE_CAPTURE);
521577
entry.disarm?.();
522578
};
523579
}
@@ -532,6 +588,7 @@ function startObserving(): void {
532588
return;
533589
}
534590
view.addEventListener('resize', scheduleAll);
591+
view.document.addEventListener('pointerdown', onPress, PASSIVE_CAPTURE);
535592
if (typeof IntersectionObserver === 'function') {
536593
visibility = new IntersectionObserver(entries => {
537594
for (const entry of entries) {
@@ -587,6 +644,7 @@ function stopObserving(): void {
587644
entry.release = null;
588645
}
589646
view?.removeEventListener('resize', scheduleAll);
647+
view?.document.removeEventListener('pointerdown', onPress, PASSIVE_CAPTURE);
590648
visibility?.disconnect();
591649
resize?.disconnect();
592650
visibility = null;
@@ -616,6 +674,29 @@ function onPointerChange(): void {
616674
}
617675
}
618676

677+
/** Options of `watchHitArea`. */
678+
export interface WatchHitAreaOptions {
679+
/** The size to grow toward, px. @default 44 */
680+
readonly minSize?: number;
681+
}
682+
683+
/**
684+
* Stops every watch and forgets them, for tests: no observer, listener or
685+
* answer outlives a test that left a watch behind.
686+
*/
687+
export function resetHitAreaForTests(): void {
688+
stopObserving();
689+
for (const entry of watched.values()) {
690+
entry.disarm?.();
691+
}
692+
watched.clear();
693+
pending.clear();
694+
pointer?.removeEventListener('change', onPointerChange);
695+
pointer = null;
696+
view = null;
697+
isCoarse = false;
698+
}
699+
619700
/**
620701
* Keeps `element`'s hit insets live until the returned function runs:
621702
* `onInsets` hears each change (typically `writeHitInsets` on the control).
@@ -628,19 +709,23 @@ function onPointerChange(): void {
628709
export function watchHitArea(
629710
element: Element,
630711
onInsets: (insets: HitInsets) => void,
631-
minSize: number = MIN_TOUCH_TARGET,
712+
{minSize = MIN_TOUCH_TARGET}: WatchHitAreaOptions = {},
632713
): () => void {
633714
const owner = element.ownerDocument.defaultView;
634715
if (owner == null) {
635716
return () => {};
636717
}
637-
if (watched.size === 0) {
638-
view = owner;
639-
pointer = owner.matchMedia?.(TOUCH_QUERY) ?? null;
718+
view = owner;
719+
// Read the pointer query at every watch, not only the first: an
720+
// environment that replaces matchMedia (a test) must not leave a stale
721+
// answer behind from a watch that never stopped.
722+
const query = owner.matchMedia?.(TOUCH_QUERY) ?? null;
723+
if (query !== pointer) {
724+
pointer?.removeEventListener('change', onPointerChange);
725+
pointer = query;
640726
pointer?.addEventListener('change', onPointerChange);
641-
isCoarse = false;
642-
onPointerChange();
643727
}
728+
onPointerChange();
644729
const watch: Watch = {
645730
element,
646731
minSize,

0 commit comments

Comments
 (0)