Skip to content

Commit 287cfeb

Browse files
committed
Add initial hook
0 parents  commit 287cfeb

13 files changed

+421
-0
lines changed

.gitattributes

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Auto detect text files and perform LF normalization
2+
* text=auto

.gitignore

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
lerna-debug.log*
8+
.pnpm-debug.log*
9+
10+
# Diagnostic reports (https://nodejs.org/api/report.html)
11+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12+
13+
# Runtime data
14+
pids
15+
*.pid
16+
*.seed
17+
*.pid.lock
18+
19+
# Directory for instrumented libs generated by jscoverage/JSCover
20+
lib-cov
21+
22+
# Coverage directory used by tools like istanbul
23+
coverage
24+
*.lcov
25+
26+
# nyc test coverage
27+
.nyc_output
28+
29+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30+
.grunt
31+
32+
# Bower dependency directory (https://bower.io/)
33+
bower_components
34+
35+
# node-waf configuration
36+
.lock-wscript
37+
38+
# Compiled binary addons (https://nodejs.org/api/addons.html)
39+
build/Release
40+
41+
# Dependency directories
42+
node_modules/
43+
jspm_packages/
44+
45+
# Snowpack dependency directory (https://snowpack.dev/)
46+
web_modules/
47+
48+
# TypeScript cache
49+
*.tsbuildinfo
50+
51+
# Optional npm cache directory
52+
.npm
53+
54+
# Optional eslint cache
55+
.eslintcache
56+
57+
# Optional stylelint cache
58+
.stylelintcache
59+
60+
# Microbundle cache
61+
.rpt2_cache/
62+
.rts2_cache_cjs/
63+
.rts2_cache_es/
64+
.rts2_cache_umd/
65+
66+
# Optional REPL history
67+
.node_repl_history
68+
69+
# Output of 'npm pack'
70+
*.tgz
71+
72+
# Yarn Integrity file
73+
.yarn-integrity
74+
75+
# dotenv environment variable files
76+
.env
77+
.env.development.local
78+
.env.test.local
79+
.env.production.local
80+
.env.local
81+
82+
# parcel-bundler cache (https://parceljs.org/)
83+
.cache
84+
.parcel-cache
85+
86+
# Next.js build output
87+
.next
88+
out
89+
90+
# Nuxt.js build / generate output
91+
.nuxt
92+
dist
93+
94+
# Gatsby files
95+
.cache/
96+
# Comment in the public line in if your project uses Gatsby and not Next.js
97+
# https://nextjs.org/blog/next-9-1#public-directory-support
98+
# public
99+
100+
# vuepress build output
101+
.vuepress/dist
102+
103+
# vuepress v2.x temp and cache directory
104+
.temp
105+
.cache
106+
107+
# Serverless directories
108+
.serverless/
109+
110+
# FuseBox cache
111+
.fusebox/
112+
113+
# DynamoDB Local files
114+
.dynamodb/
115+
116+
# TernJS port file
117+
.tern-port
118+
119+
# Stores VSCode versions used for testing VSCode extensions
120+
.vscode-test
121+
122+
# yarn v2
123+
.yarn/cache
124+
.yarn/unplugged
125+
.yarn/build-state.yml
126+
.yarn/install-state.gz
127+
.pnp.*

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Chris Garrett
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# @hyperlaunch/react-use-virtual-cursor
2+
3+
The useVirtualCursor hook creates a virtual cursor that can be moved freely within the viewport with arrow key presses, and trigger click events on elements like buttons and links with the enter key. It's designed for environments such as touch screen kiosks, allowing D-pad navigation to enhance accessibility without requiring additional UI modifications.
4+
5+
## Installation
6+
7+
Install the package via npm or yarn:
8+
9+
```bash
10+
npm install @hyperlaunch/react-use-virtual-cursor
11+
# or
12+
pnpm add @hyperlaunch/react-use-virtual-cursor
13+
# or
14+
bun add @hyperlaunch/react-use-virtual-cursor
15+
```
16+
17+
## Usage
18+
19+
To use the `useVirtualCursor` hook, add it to your React component by attaching the `cursorRef` to the element you want to control, and using `position` to update the elements position. Configure the movement speed through the `moveMultiplier`, which scales the cursor's movement relative to its width for each key press.
20+
21+
### Arguments
22+
23+
- **moveMultiplier** (`number`): Adjusts the scale of movement of the cursor. The movement distance per arrow key press is calculated as a fraction of the cursor's width, allowing for adjustable responsiveness.
24+
25+
### Returns
26+
27+
- **cursorRef** (`React.RefObject<HTMLDivElement>`): A ref to be attached to the cursor element, allowing the hook to manage its position based on keyboard interactions.
28+
- **position** (`{ x: number, y: number }`): The current x and y coordinates of the cursor, useful for positioning the cursor element in an absolute layout.
29+
- **canInteract** (`boolean`): Indicates whether the cursor is currently over an interactive element like links or buttons, enabling dynamic styling changes.
30+
31+
The cursor will be positioned in the center of the screen, initially.
32+
33+
### Example
34+
35+
Here’s an example of how to use `useVirtualCursor` in a component:
36+
37+
```jsx
38+
function Cursor() {
39+
const { cursorRef, position, canInteract } = useVirtualCursor({
40+
moveMultiplier: 0.8
41+
});
42+
43+
const classNames = `
44+
absolute pointer-events-none fixed h-8 w-8 rounded-full transition-transform duration-200 z-50
45+
${canInteract ? "bg-gray-500 border-2 border-white ring-1 ring-gray-400 shadow-lg origin-center scale-75" : "bg-gray-900/40"}
46+
`;
47+
48+
return (
49+
<div
50+
ref={cursorRef}
51+
className={classNames}
52+
style={{
53+
left: `${position.x}px`,
54+
top: `${position.y}px`
55+
}}
56+
/>
57+
);
58+
}
59+
```
60+
61+
This component sets up a custom cursor that responds to keyboard inputs. It applies contextual class names if the cursor is over interactive elements, demonstrating how `useVirtualCursor` can be applied to enhance accessibility and interactivity in your React applications.

biome.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"$schema": "https://biomejs.dev/schemas/1.7.1/schema.json",
3+
"organizeImports": {
4+
"enabled": true
5+
},
6+
"linter": {
7+
"enabled": true,
8+
"rules": {
9+
"recommended": true
10+
}
11+
}
12+
}

bun.lockb

8.6 KB
Binary file not shown.

package.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "use-virtual-cursor",
3+
"module": "src/index.ts",
4+
"type": "module",
5+
"devDependencies": {
6+
"@biomejs/biome": "^1.7.1",
7+
"@types/bun": "latest",
8+
"@types/react": "^18.2.79",
9+
"react": "^18.2.0"
10+
},
11+
"peerDependencies": {
12+
"react": "^18.2.0",
13+
"typescript": "^5.0.0"
14+
}
15+
}

src/index.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { useCallback, useEffect, useRef, useState } from "react";
2+
import findNearestClickableElement from "./utils/find-nearest-clickable-element";
3+
import getLiveCursorPosition from "./utils/get-live-cursor-position";
4+
import calculateNextPosition from "./utils/calculate-next-position";
5+
import isElementOutOfViewport from "./utils/is-element-out-of-viewport";
6+
7+
const ArrowKeys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
8+
9+
function simulateClick({ x, y }: { x: number; y: number }) {
10+
const element = findNearestClickableElement({ x, y });
11+
12+
if (element instanceof HTMLElement) return element.click();
13+
}
14+
15+
export default function useVirtualCursor({
16+
moveMultiplier = 1,
17+
}: { moveMultiplier?: number }) {
18+
const cursorRef = useRef<HTMLDivElement>(null);
19+
const [position, setPosition] = useState({ x: 0, y: 0 });
20+
const [canInteract, setcanInteract] = useState<boolean>(false);
21+
const [cursorDimensions, setCursorDimensions] = useState({
22+
width: 0,
23+
height: 0,
24+
});
25+
26+
const handleKeyPress = useCallback(
27+
(e: KeyboardEvent) => {
28+
if (!cursorDimensions || !moveMultiplier || !position) return;
29+
30+
const key = e.key;
31+
32+
if (ArrowKeys.includes(key))
33+
return setPosition((currentPosition) => {
34+
const nextPosition = calculateNextPosition({
35+
currentPosition,
36+
cursorDimensions,
37+
moveMultiplier,
38+
key,
39+
});
40+
41+
if (
42+
!nextPosition ||
43+
isElementOutOfViewport({ position: nextPosition, cursorDimensions })
44+
)
45+
return currentPosition;
46+
47+
return nextPosition;
48+
});
49+
50+
if (key === "Enter" && cursorRef.current)
51+
return simulateClick(getLiveCursorPosition(cursorRef.current));
52+
},
53+
[cursorDimensions, moveMultiplier, position],
54+
);
55+
56+
useEffect(() => {
57+
window.addEventListener("keydown", handleKeyPress);
58+
59+
return () => window.removeEventListener("keydown", handleKeyPress);
60+
}, [handleKeyPress]);
61+
62+
// Set the cursor in the center of the screen initially
63+
useEffect(() => {
64+
if (!cursorRef.current) return;
65+
66+
const { width, height } = cursorRef.current.getBoundingClientRect();
67+
68+
setCursorDimensions({ width, height });
69+
70+
setPosition({
71+
x: (window.innerWidth - width) / 2,
72+
y: (window.innerHeight - height) / 2,
73+
});
74+
}, []);
75+
76+
// Update state of cursor is/isn't over clickable element
77+
// biome-ignore lint/correctness/useExhaustiveDependencies: triggered by changes to position
78+
useEffect(() => {
79+
if (cursorRef.current) {
80+
const cursorPosition = getLiveCursorPosition(cursorRef.current);
81+
const element = findNearestClickableElement(cursorPosition);
82+
83+
setcanInteract(Boolean(element));
84+
}
85+
}, [position]);
86+
87+
return { cursorRef, position, setPosition, canInteract, cursorDimensions };
88+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
export default function calculateNextPosition({
2+
currentPosition,
3+
cursorDimensions,
4+
moveMultiplier,
5+
key,
6+
}: {
7+
currentPosition: { x: number; y: number };
8+
cursorDimensions: { width: number; height: number };
9+
moveMultiplier: number;
10+
key: string;
11+
}) {
12+
const increment =
13+
Math.max(cursorDimensions.width, cursorDimensions.height) * moveMultiplier;
14+
15+
if (key === "ArrowUp")
16+
return { ...currentPosition, y: currentPosition.y - increment };
17+
if (key === "ArrowDown")
18+
return { ...currentPosition, y: currentPosition.y + increment };
19+
if (key === "ArrowLeft")
20+
return { ...currentPosition, x: currentPosition.x - increment };
21+
if (key === "ArrowRight")
22+
return { ...currentPosition, x: currentPosition.x + increment };
23+
24+
return currentPosition;
25+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function findNearestElements({ x, y }: { x: number; y: number }) {
2+
return document.elementsFromPoint(x, y);
3+
}
4+
5+
function clickable(element: Element) {
6+
return element.matches(
7+
'a, button, input[type="button"], input[type="submit"], [onclick], [role="button"]',
8+
);
9+
}
10+
11+
export default function findNearestClickableElement(position: {
12+
x: number;
13+
y: number;
14+
}): Element | undefined {
15+
const elements = findNearestElements(position);
16+
17+
return [...(elements || [])].find(clickable);
18+
}

0 commit comments

Comments
 (0)