Skip to content

Instantly share code, notes, and snippets.

@yerffejytnac
Last active January 27, 2020 21:21
Show Gist options
  • Save yerffejytnac/680e010426de504165abdfa055940953 to your computer and use it in GitHub Desktop.
Save yerffejytnac/680e010426de504165abdfa055940953 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const getCurrentPosition = (context, event) =>
new Promise((resolve, reject) => {
let position;
let options = null;
if (!context.position) {
return navigator.geolocation.getCurrentPosition(
p => {
const { coords, timestamp } = p;
position = { coords, timestamp };
resolve(position);
},
error => reject(error),
options
);
}
});
const setDateTime = assign((context, event) => {
if (event.type === "START") {
return {
startDateTime: Date.now()
};
}
if (event.type === "STOP") {
return {
endDateTime: Date.now()
};
}
});
const walkMachine = Machine(
{
id: "walk",
initial: "idle",
context: {
startDateTime: 0,
endDateTime: 0,
position: null
},
states: {
idle: {
invoke: {
id: "getPosition",
src: getCurrentPosition,
onDone: {
target: "idle",
actions: assign({
position: (_, event) => {
console.log("onDone", event);
const { data } = event;
return [data.coords.longitude, data.coords.latitude];
}
})
}
},
on: {
START: "walk"
}
},
walk: {
entry: "setDateTime",
on: {
TOGGLE: "pause",
STOP: "stop"
}
},
pause: {
on: {
TOGGLE: "walk"
}
},
stop: {
entry: "setDateTime",
type: "final"
}
}
},
{
actions: {
setDateTime
},
guards: {}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment