Skip to content

Commit 99db1c5

Browse files
committed
Refactor Joystick component to improve axis value extraction and enhance readability
1 parent 324415b commit 99db1c5

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

packages/leva/src/components/UI/Joystick.tsx

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type JoystickProps = { value: Vector2d | Vector3d } & Pick<Vector2dProps, 'onUpd
1313
}
1414

1515
const AXIS_KEYS = ['x', 'y', 'z'] as const
16+
const AXIS_INDEX: Record<string, number> = { x: 0, y: 1, z: 2 }
1617

1718
/**
1819
* Type-safe helper to extract axis values from Vector2d/Vector3d
@@ -44,9 +45,12 @@ export function Joystick({ value, settings, onUpdate, children }: JoystickProps)
4445

4546
useLayoutEffect(() => {
4647
if (joystickShown) {
47-
const { top, left, width, height } = joystickRef.current!.getBoundingClientRect()
48-
playgroundRef.current!.style.left = left + width / 2 + 'px'
49-
playgroundRef.current!.style.top = top + height / 2 + 'px'
48+
const rect = joystickRef.current?.getBoundingClientRect()
49+
const playground = playgroundRef.current
50+
if (rect && playground) {
51+
playground.style.left = rect.left + rect.width / 2 + 'px'
52+
playground.style.top = rect.top + rect.height / 2 + 'px'
53+
}
5054
}
5155
}, [joystickShown])
5256

@@ -74,15 +78,10 @@ export function Joystick({ value, settings, onUpdate, children }: JoystickProps)
7478
const incX = stepV1 * outOfBoundsX.current * stepMultiplier.current
7579
const incY = yFactor * stepV2 * outOfBoundsY.current * stepMultiplier.current
7680

77-
return Array.isArray(v)
78-
? {
79-
[v1]: v[AXIS_KEYS.indexOf(v1 as 'x' | 'y' | 'z')] + incX,
80-
[v2]: v[AXIS_KEYS.indexOf(v2 as 'x' | 'y' | 'z')] + incY,
81-
}
82-
: {
83-
[v1]: v[v1] + incX,
84-
[v2]: v[v2] + incY,
85-
}
81+
return {
82+
[v1]: getAxisValue(v, v1) + incX,
83+
[v2]: getAxisValue(v, v2) + incY,
84+
}
8685
})
8786
}, 16)
8887
}, [w, h, onUpdate, set, stepV1, stepV2, v1, v2, yFactor])
@@ -145,7 +144,7 @@ export function Joystick({ value, settings, onUpdate, children }: JoystickProps)
145144
{joystickShown && (
146145
<Portal>
147146
<JoystickPlayground ref={playgroundRef} isOutOfBounds={isOutOfBounds}>
148-
{children ? children : <JoystickGrid />}
147+
{children || <JoystickGrid />}
149148
<span ref={spanRef} />
150149
</JoystickPlayground>
151150
</Portal>

0 commit comments

Comments
 (0)