Skip to content

Instantly share code, notes, and snippets.

@mpj
Last active July 20, 2022 19:04
Show Gist options
  • Save mpj/6969ecff1d5b8e5ccb559ca525ee2632 to your computer and use it in GitHub Desktop.
Save mpj/6969ecff1d5b8e5ccb559ca525ee2632 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Intro to XState</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="box"></div>
<script src="https://unpkg.com/[email protected]/dist/xstate.js"></script>
<script src="index.js"></script>
</body>
</html>
const { createMachine, interpret, assign } = XState;
const dragDropMachine = createMachine({
initial: 'idle',
context: {
// the position of the box
x: 0,
y: 0,
// where you clicked
pointerx: 0,
pointery: 0,
// how far from where you clicked
dx: 0, // how far: x
dy: 0, // how far: y
},
states: {
idle: {
on: {
// event: nextstate
mousedown: {
target: 'dragging',
actions: assign((context, mouseEvent) => {
return {
...context,
pointerx: mouseEvent.clientX,
pointery: mouseEvent.clientY
}
})
}
}
},
dragging: {
on: {
mousemove: {
target: 'dragging',
actions: assign((context, mouseEvent) => {
return {
...context,
dx: mouseEvent.clientX - context.pointerx,
dy: mouseEvent.clientY - context.pointery
}
})
},
mouseup: {
target: 'idle',
actions: assign((context) => {
return {
...context,
x: context.x + context.dx,
y: context.y + context.dy,
dx: 0,
dy: 0
}
})
// change context.x and context.y
}
}
}
}
})
const body = document.body;
const box = document.getElementById('box')
const dragDropService = interpret(dragDropMachine)
.onTransition(state => {
if (state.changed) {
console.log(state.context)
box.style.setProperty('left',
// where the box is + how far the box moved
state.context.x + state.context.dx + 'px')
box.style.setProperty('top',
state.context.y + state.context.dy + 'px')
body.dataset.state = state.toStrings().join(' ')
}
})
.start();
body.addEventListener('mousedown', event => {
// event.clientX
// event.clientY
dragDropService.send(event)
})
body.addEventListener('mouseup', event => {
dragDropService.send(event)
})
body.addEventListener('mousemove', event => {
dragDropService.send(event)
})
@bwaidelich
Copy link

a simpler version (less math :) and more logic in the state machine) that also works if the box doesn't start at position 0,0: https://gist.github.com/bwaidelich/aa5f33c4937e070dd3c53c6345623167

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment