Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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)
- })
- }
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement