Skip to content

Instantly share code, notes, and snippets.

@lettertwo
Last active January 7, 2021 15:56
Show Gist options
  • Save lettertwo/ce447d39a8bb02ee8740c2c73a63f6f9 to your computer and use it in GitHub Desktop.
Save lettertwo/ce447d39a8bb02ee8740c2c73a63f6f9 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 createTicketQuantityMachine = (max = 19) => Machine({
context: {count: 0},
initial: 'idle',
states: {
idle: {
on: {
INCREMENT: {
actions: 'increment',
cond: 'canIncrement'
},
DECREMENT: {
actions: 'decrement',
cond: 'canDecrement'
}
}
}
}}, {
actions: {
increment: assign({
count: (context) => context.count + 1
}),
decrement: assign({
count: (context) => context.count - 1
}),
},
guards: {
canIncrement: (context) => context.count < max,
canDecrement: (context) => context.count > 0,
}
});
const BuyTicketsMachine = Machine({
id: 'buyTickets',
initial: 'quantitySelectable',
context: {
adult: 0,
child: 0,
senior: 0
},
states: {
quantitySelectable: {
invoke: [
{
id: 'adult',
src: 'ticketQuantityMachine',
data: {count: ({adult}) => adult},
onDone: {
actions: assign({
adult: (context, event) => event.data.count
})
}
},
{
id: 'child',
src: 'ticketQuantityMachine',
data: {count: ({child}) => child},
onDone: {
actions: assign({
child: (context, event) => event.data.count
})
}
},
{
id: 'senior',
src: 'ticketQuantityMachine',
data: {count: ({senior}) => senior},
onDone: {
actions: assign({
senior: (context, event) => event.data.count
})
}
},
],
on: {
INCREMENT: {
actions: send('INCREMENT', {to: 'adult'}),
},
NEXT: {
target: 'dateSelectable',
cond: 'hasQuantity'
}
}
},
dateSelectable: {
on: {
NEXT: {
target: 'timeSelectable',
cond: 'hasDate'
}
}
},
timeSelectable: {
on: {
NEXT: {
target: 'billingCollectable',
cond: 'hasTime'
}
}
},
billingCollectable: {
on: {
NEXT: {
target: 'billable',
cond: 'hasBillingInfo'
}
}
},
billable: {},
confirmed: {
type: 'final'
}
}
}, {
guards: {
hasQuantity: ({adult, child, senior}) =>
adult || child || senior,
},
services: {
ticketQuantityMachine: createTicketQuantityMachine
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment