Skip to content

Instantly share code, notes, and snippets.

@carlosmoran97
Forked from mpj/index.html
Created June 25, 2021 01:30
Show Gist options
  • Save carlosmoran97/718c7cdd9a1b67bbe9e3d62091db4649 to your computer and use it in GitHub Desktop.
Save carlosmoran97/718c7cdd9a1b67bbe9e3d62091db4649 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)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment