Skip to content

Commit

Permalink
useTransform
Browse files Browse the repository at this point in the history
  • Loading branch information
luludotdev committed Feb 2, 2024
1 parent daf5340 commit e04e42a
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 5 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"url": "git+https://github.com/WorldQL/dreamlab-ui.git"
},
"devDependencies": {
"@dreamlab.gg/core": "^0.0.71",
"@dreamlab.gg/core": "0.0.72-dev-81d3412",
"@luludev/eslint-config": "^0.5.3",
"@types/react": "^18.2.48",
"@types/react-dom": "^18.2.18",
Expand Down
1 change: 1 addition & 0 deletions src/react/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from './useCamera.ts'
export * from './useForceUpdate.ts'
export * from './useGame.ts'
export * from './usePlayer.ts'
export * from './useTransform.ts'
60 changes: 60 additions & 0 deletions src/react/hooks/useTransform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { isTrackedTransform } from '@dreamlab.gg/core/math'
import type {
PositionListener,
RotationListener,
Transform,
ZIndexListener,
} from '@dreamlab.gg/core/math'
import {
useCallback,
useEffect,
useState,
} from 'https://esm.sh/v136/react@18.2.0'

/**
* Return a reference to a {@link Transform} that will automatically trigger React re-renders
*
* @param transform - Transform
*/
export const useTransform = (transform: Transform): Transform => {
const [_x, setX] = useState<number>()
const [_y, setY] = useState<number>()
const [_r, setRotation] = useState<number>()
const [_z, setZIndex] = useState<number>()

const onPositionChanged = useCallback<PositionListener>(
(component, value, _delta) => {
if (component === 'x') setX(value)
else if (component === 'y') setY(value)
},
[setX, setY],
)

const onRotationChanged = useCallback<RotationListener>(
(value, _delta) => setRotation(value),
[setRotation],
)

const onZIndexChanged = useCallback<ZIndexListener>(
value => setZIndex(value),
[setZIndex],
)

useEffect(() => {
if (!isTrackedTransform(transform)) {
throw new Error('`useTransform` only works with tracked transforms')
}

transform.addPositionListener(onPositionChanged)
transform.addRotationListener(onRotationChanged)
transform.addZIndexListener(onZIndexChanged)

return () => {
transform.removeListener(onPositionChanged)
transform.removeListener(onRotationChanged)
transform.removeListener(onZIndexChanged)
}
})

return transform
}

0 comments on commit e04e42a

Please sign in to comment.