Improve dom example performance (#208)

Apply animation in dom example in a performant way
This commit is contained in:
Andrew Prifer 2022-06-10 15:27:33 +02:00 committed by GitHub
parent 4215d561d0
commit 34c7b06baf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -81,16 +81,18 @@ const Box: React.FC<{
const isSelected = selection.includes(obj) const isSelected = selection.includes(obj)
const [state, setState] = useState<State>(obj.value) const boxRef = useRef<HTMLDivElement>(null!)
const preRef = useRef<HTMLPreElement>(null!)
const colorRef = useRef<HTMLDivElement>(null!)
useLayoutEffect(() => { useLayoutEffect(() => {
const unsubscribeFromChanges = onChange(obj.props, (newValues) => { const unsubscribeFromChanges = onChange(obj.props, (newValues) => {
setState(newValues) boxRef.current.style.transform = `translate(${newValues.x}px, ${newValues.y}px)`
preRef.current.innerText = JSON.stringify(newValues, null, 2)
colorRef.current.style.background = newValues.color.toString()
}) })
return unsubscribeFromChanges return unsubscribeFromChanges
}, [id]) }, [])
const [divRef, setDivRef] = useState<HTMLElement | null>(null)
const dragOpts = useMemo((): UseDragOpts => { const dragOpts = useMemo((): UseDragOpts => {
let scrub: IScrub | undefined let scrub: IScrub | undefined
@ -126,32 +128,28 @@ const Box: React.FC<{
} }
}, []) }, [])
useDrag(divRef, dragOpts) useDrag(boxRef.current, dragOpts)
return ( return (
<div <div
onClick={() => { onClick={() => {
studio.setSelection([obj]) studio.setSelection([obj])
}} }}
ref={setDivRef} ref={boxRef}
style={{ style={{
width: 300, width: 300,
height: 300, height: 300,
color: 'white', color: 'white',
position: 'absolute', position: 'absolute',
left: state.x + 'px',
top: state.y + 'px',
boxSizing: 'border-box', boxSizing: 'border-box',
border: isSelected ? '1px solid #5a92fa' : '1px solid white', border: isSelected ? '1px solid #5a92fa' : '1px solid white',
}} }}
> >
<pre style={{margin: 0, padding: '1rem'}}> <pre style={{margin: 0, padding: '1rem'}} ref={preRef}></pre>
{JSON.stringify(state, null, 4)}
</pre>
<div <div
ref={colorRef}
style={{ style={{
height: 50, height: 50,
background: state.color.toString(),
}} }}
/> />
</div> </div>
@ -179,7 +177,6 @@ export const Scene: React.FC<{project: IProject}> = ({project}) => {
useLayoutEffect(() => { useLayoutEffect(() => {
const unsubscribeFromChanges = onChange(globalObj.props, (newValues) => { const unsubscribeFromChanges = onChange(globalObj.props, (newValues) => {
console.log(newValues)
containerRef.current.style.background = containerRef.current.style.background =
newValues.background.type !== 'dynamic' newValues.background.type !== 'dynamic'
? newValues.background.type ? newValues.background.type