Last active
April 23, 2020 19:17
-
-
Save tmlangley/ab82d035006d5b1b0753f7c56ffd7602 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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