Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/primitives/useMouse.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ You can configure `useMouse` to apply custom states to elements when they are ho

To use this, pass the `customStates` option to `useMouse`.

### Elements Outside Their Parent (`respectClipping`)

By default, the hit test stops at any element the pointer is not over, so a child drawn outside its parent's bounds (a parent without `clipping`) cannot be hovered or clicked. Pass `respectClipping: true` to hit-test those children too:

```jsx
useMouse(undefined, 100, { respectClipping: true });
```

With it on, a subtree is cut off only where an element has `clipping` set, which matches what is drawn on screen. Among overlapping elements, higher `zIndex` wins, then the later sibling. The tradeoff: most elements don't clip, so each pointer move searches most of the tree instead of one path down it. Check pointer responsiveness on target hardware with your largest pages.

### Click Handling

When an element is clicked, `useMouse` handles the interaction as follows:
Expand Down
79 changes: 73 additions & 6 deletions src/primitives/useMouse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,16 @@ interface MouseStateOptions {
pressedState: CustomState;
}

type UseMouseOptions =
| { customStates: MouseStateOptions }
| { customStates: undefined };
interface UseMouseOptions {
customStates?: MouseStateOptions;
/**
* Hit-test children that draw outside their parent's bounds. A subtree is
* cut off only where a node has `clipping` set; otherwise the search keeps
* descending even when the pointer misses the node itself. Off by default:
* the default search stops at any node the pointer misses.
*/
respectClipping?: boolean;
}

export function addCustomStateToElement(
element: RenderableNode,
Expand Down Expand Up @@ -133,8 +140,9 @@ function findElementWithCustomState<TApp extends ElementNode>(
x: number,
y: number,
customState: CustomState,
respectClipping: boolean,
): ElementNode | undefined {
const path = getChildrenByPosition(myApp, x, y);
const path = getChildrenByPosition(myApp, x, y, respectClipping);
let element: ElementNode | undefined;
for (let i = path.length - 1; i >= 0; i--) {
if (hasCustomState(path[i]!, customState)) {
Expand Down Expand Up @@ -235,6 +243,7 @@ function handleElementClick(

function createHandleClick<TApp extends ElementNode>(
myApp: TApp,
respectClipping: boolean,
customStates?: MouseStateOptions,
pressedElementRef?: { current: ElementNode | null },
) {
Expand All @@ -245,6 +254,7 @@ function createHandleClick<TApp extends ElementNode>(
e.clientX,
e.clientY,
customStates.hoverState,
respectClipping,
)
: findElementByActiveElement(e);

Expand All @@ -258,6 +268,7 @@ function createHandleClick<TApp extends ElementNode>(

function createHandleMouseDown<TApp extends ElementNode>(
myApp: TApp,
respectClipping: boolean,
customStates?: MouseStateOptions,
pressedElementRef?: { current: ElementNode | null },
) {
Expand All @@ -271,6 +282,7 @@ function createHandleMouseDown<TApp extends ElementNode>(
e.clientX,
e.clientY,
customStates.hoverState,
respectClipping,
);

if (!pressedElement) {
Expand Down Expand Up @@ -318,16 +330,64 @@ function isNodeAtPosition(
);
}

// Depth-first search for the topmost hit, used when `respectClipping` is on.
// Descends through nodes the pointer misses unless they clip; pushes only
// nodes the pointer is over onto `path` (ancestors first). Returns whether
// anything in this subtree was hit.
function collectHitPath(
node: ElementNode | ElementText | TextNode,
px: number,
py: number,
path: ElementNode[],
): boolean {
if (!isElementNode(node) || node.alpha === 0 || node.skipFocus) {
return false;
}

const hit = testCollision(
px,
py,
(node.lng.absX as number) || 0,
(node.lng.absY as number) || 0,
node.width || 0,
node.height || 0,
);
if (!hit && node.clipping) return false;
if (hit) path.push(node);

// Topmost first: higher zIndex, then later sibling (as in the default
// search). Index tiebreak, since old webOS engines have no stable sort.
const children = node.children;
const order: number[] = [];
for (let i = children.length - 1; i >= 0; i--) order.push(i);
order.sort(
(a, b) =>
((children[b] as ElementNode).zIndex ?? -1) -
((children[a] as ElementNode).zIndex ?? -1) || b - a,
);
for (const i of order) {
if (collectHitPath(children[i]!, px, py, path)) return true;
}

return hit;
}

function getChildrenByPosition<TElement extends ElementNode = ElementNode>(
node: TElement,
x: number,
y: number,
respectClipping = false,
): TElement[] {
const result: TElement[] = [];
const precision = Config.rendererOptions?.deviceLogicalPixelRatio || 1;
const px = x / precision;
const py = y / precision;

if (respectClipping) {
collectHitPath(node, px, py, result);
return result;
}

let current: ElementNode | ElementText | TextNode | undefined = node;
while (current && isNodeAtPosition(current, px, py)) {
result.push(current as TElement);
Expand Down Expand Up @@ -360,9 +420,16 @@ export function useMouse<TApp extends ElementNode = ElementNode>(
const pressedElementRef: { current: ElementNode | null } = { current: null };
const customStates = options?.customStates;
const hoverState = customStates?.hoverState;
const handleClick = createHandleClick(myApp, customStates, pressedElementRef);
const respectClipping = options?.respectClipping ?? false;
const handleClick = createHandleClick(
myApp,
respectClipping,
customStates,
pressedElementRef,
);
const handleMouseDown = createHandleMouseDown(
myApp,
respectClipping,
customStates,
pressedElementRef,
);
Expand All @@ -382,7 +449,7 @@ export function useMouse<TApp extends ElementNode = ElementNode>(
createEffect(() => {
if (!scheduled()) return;

const path = getChildrenByPosition(myApp, pos.x, pos.y);
const path = getChildrenByPosition(myApp, pos.x, pos.y, respectClipping);
let activeElm: ElementNode | undefined;
for (let i = path.length - 1; i >= 0; i--) {
const el = path[i]!;
Expand Down
145 changes: 145 additions & 0 deletions tests/useMouse.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -574,3 +574,148 @@ v.describe('synthetic keyboard events (legacy KeyboardEvent constructors)', () =
dispose();
});
});

v.describe('useMouse respectClipping', () => {
const renderOverflow = (
parentClipping: boolean,
respectClipping: boolean | undefined,
) => {
let app!: lng.ElementNode;
let child!: lng.ElementNode;
const dispose = renderer.render(() => {
const root = (
<view ref={app} width={1920} height={1080}>
<view
x={100}
y={100}
width={200}
height={200}
clipping={parentClipping}
>
{/* child spans 400–500 absolute: entirely outside its parent */}
<view
ref={child}
x={300}
y={300}
width={100}
height={100}
onFocus={() => {}}
/>
</view>
</view>
);
useMouse(app, 5, { respectClipping });
return root;
});
return { dispose, child: () => child };
};

v.test('default: a child outside its parent is not hit', async () => {
const { dispose, child } = renderOverflow(false, undefined);
await wait(20);
dispatchMouseMove(450, 450);
await wait(80);
v.assert.notEqual(lng.activeElement(), child());
dispose();
});

v.test('on: a child outside a non-clipping parent is hit', async () => {
const { dispose, child } = renderOverflow(false, true);
await wait(20);
dispatchMouseMove(450, 450);
await wait(80);
v.assert.equal(lng.activeElement(), child());
dispose();
});

v.test('on: a clipping parent still blocks children outside it', async () => {
const { dispose, child } = renderOverflow(true, true);
await wait(20);
dispatchMouseMove(450, 450);
await wait(80);
v.assert.notEqual(lng.activeElement(), child());
dispose();
});

v.test('on: hover and click reach a child outside its parent', async () => {
let app!: lng.ElementNode;
let btn!: lng.ElementNode;
const onClick = v.vi.fn();

const dispose = renderer.render(() => {
const root = (
<view ref={app} width={1920} height={1080}>
<view x={0} y={0} width={100} height={100}>
<view
ref={btn}
x={150}
y={150}
width={200}
height={100}
$hover={{ color: 0x00ff00ff }}
onMouseClick={onClick}
/>
</view>
</view>
);
useMouse(app, 5, {
customStates: { hoverState: '$hover', pressedState: '$pressed' },
respectClipping: true,
});
return root;
});

await wait(20);
dispatchMouseMove(200, 200);
await wait(80);
v.assert.ok(btn.states.has('$hover'), 'btn receives hover');

dispatchClick(200, 200);
v.assert.equal(onClick.mock.calls.length, 1, 'click reaches btn');
dispose();
});

v.test(
'on: a higher-z sibling overflow wins over a lower sibling',
async () => {
let app!: lng.ElementNode;
let low!: lng.ElementNode;
let overflow!: lng.ElementNode;

const dispose = renderer.render(() => {
const root = (
<view ref={app} width={1920} height={1080}>
<view
ref={low}
x={300}
y={300}
width={200}
height={200}
zIndex={1}
onFocus={() => {}}
/>
{/* misses the pointer itself; its child overflows onto low */}
<view x={0} y={0} width={100} height={100} zIndex={5}>
<view
ref={overflow}
x={350}
y={350}
width={100}
height={100}
onFocus={() => {}}
/>
</view>
</view>
);
useMouse(app, 5, { respectClipping: true });
return root;
});

await wait(20);
dispatchMouseMove(400, 400);
await wait(80);
v.assert.equal(lng.activeElement(), overflow);
dispose();
},
);
});