Skip to content

Instantly share code, notes, and snippets.

@tmlangley
Last active April 23, 2020 19:17
Show Gist options
  • Save tmlangley/ab82d035006d5b1b0753f7c56ffd7602 to your computer and use it in GitHub Desktop.
Save tmlangley/ab82d035006d5b1b0753f7c56ffd7602 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const defaultComparison = (context, event) => context.filterData !== event.value;
const createFilterMachine = (id, applyTransformer, compareFn = defaultComparison) => Machine({
id,
context: {
filterData: null,
valueChanged: false,
},
initial: 'idle',
states: {
idle: {
id: 'idle',
on: {
OPEN: {
target: 'editing',
actions: 'resetValueChanged'
},
FETCHING: 'loading',
RESET: {
target: 'idle',
actions: 'clearFilterData'
}
}
},
editing: {
on: {
CLOSE: [{
target: 'idle',
cond: ({valueChanged}) => !valueChanged
}, {
target: '#applyingFilter',
cond: ({valueChanged}) => valueChanged
}],
UPDATE: {
target: 'editing',
actions: 'filterChanged'
},
RESET: {
target: '#idle',
actions: 'clearFilterData'
}
}
},
loading: {
initial: 'default',
on: {
SUCCESS: '#idle',
SET_LAST_APPLIED_FILTER: '.lastApplied',
},
states: {
default: {},
lastApplied: {}
},
},
applyingFilter: {
id: 'applyingFilter',
on: {
'': {
target: 'idle',
actions: 'applyFilter'
}
}
}
},
}, {
actions: {
resetValueChanged: assign({
valueChanged: (_context, _event) => false
}),
filterChanged: assign({
filterData: (context, event) => applyTransformer(event.value),
valueChanged: (context, event) => compareFn(context, event)
}),
applyFilter: sendParent((context) => ({
type: 'FILTER_APPLIED',
payload: {
id,
value: context.filterData
}
})),
clearFilterData: assign({
filterData: (_context, _event) => null
}),
}
});
const myMachine = createFilterMachine('exampleFilter', i => i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment