Skip to content

Instantly share code, notes, and snippets.

@hckhanh
Created September 26, 2019 16:01
Show Gist options
  • Save hckhanh/d479971d5bde2d0d5f7d20e5e1e145d2 to your computer and use it in GitHub Desktop.
Save hckhanh/d479971d5bde2d0d5f7d20e5e1e145d2 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const todoMachine = Machine({
id: "todo",
initial: "reading",
context: {
id: undefined,
title: "",
prevTitle: ""
},
on: {
TOGGLE_COMPLETE: {
target: ".reading.completed",
actions: [assign({ completed: true }), "notifyChanged"]
},
DELETE: "deleted"
},
states: {
reading: {
initial: "unknown",
states: {
unknown: {
on: {
"": [
{ target: "completed", cond: ctx => ctx.completed },
{ target: "pending" }
]
}
},
pending: {},
completed: {
on: {
TOGGLE_COMPLETE: {
target: "pending",
actions: [assign({ completed: false }), "notifyChanged"]
}
}
},
hist: {
type: "history"
}
},
on: {
EDIT: {
target: "editing",
actions: "focusInput"
}
}
},
editing: {
onEntry: assign({ prevTitle: ctx => ctx.title }),
on: {
CHANGE: {
actions: assign({
title: (ctx, e) => e.value
})
},
COMMIT: [
{
target: "reading.hist",
actions: "notifyChanged",
cond: ctx => ctx.title.trim().length > 0
},
{ target: "deleted" }
],
BLUR: {
target: "reading",
actions: "notifyChanged"
},
CANCEL: {
target: "reading",
actions: assign({ title: ctx => ctx.prevTitle })
}
}
},
deleted: {
onEntry: "notifyDeleted"
}
}
});
const fetchMachine = Machine({
id: "todos",
context: {
todo: "", // new todo
todos: []
},
initial: "all",
states: {
all: {},
active: {},
completed: {}
},
on: {
"NEWTODO.CHANGE": {
actions: assign({
todo: (ctx, e) => e.value
})
},
"NEWTODO.COMMIT": {
actions: [
assign({
todo: "", // clear todo
todos: (ctx, e) => ctx.todos.concat(createTodo(e.value.trim()))
}),
"persist"
],
cond: (ctx, e) => e.value.trim().length
},
"TODO.COMMIT": {
actions: [
assign({
todos: (ctx, e) =>
ctx.todos.map(todo => (todo.id === e.todo.id ? e.todo : todo))
}),
"persist"
]
},
"TODO.DELETE": {
actions: assign({
todos: (ctx, e) => {
return ctx.todos.filter(todo => todo.id !== e.id);
}
})
},
"SHOW.all": ".all",
"SHOW.active": ".active",
"SHOW.completed": ".completed",
"MARK.completed": {
actions: assign({
todos: ctx => ctx.todos.map(todo => ({ ...todo, completed: true }))
})
},
"MARK.active": {
actions: assign({
todos: ctx => ctx.todos.map(todo => ({ ...todo, completed: false }))
})
},
CLEAR_COMPLETED: {
actions: assign({
todos: ctx => ctx.todos.filter(todo => !todo.completed)
})
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment