Created
November 25, 2020 04:56
-
-
Save faisalarbain/9f24b3cb12e32526f380e46d6f1e534b 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 passwordRegex = /^[^\s]{1,}$/; | |
const usernameRegex = /^[a-zA-Z0-9]{6,}$/; | |
const validateUsername = (_, { | |
username = "" | |
}) => { | |
return usernameRegex.test(username) | |
} | |
const validatePassword = (_, { | |
password = "" | |
}) => { | |
return passwordRegex.test(password) | |
} | |
const isEmpty = (key) => (_, ev) => !(ev[key] || '') | |
const updateContext = (key) => assign({ | |
[key]: (ctx, ev) => ev[key] || '' | |
}) | |
const inputSM = (cond, key) => ({ | |
initial: 'normal', | |
states: { | |
normal: {}, | |
invalid: {}, | |
valid: { | |
on: { | |
SUBMIT: [{ | |
target: 'submitted', | |
cond, | |
}] | |
} | |
}, | |
submitted: { | |
type: 'final' | |
}, | |
}, | |
on: { | |
INPUT: [{ | |
target: '.normal', | |
cond: isEmpty(key), | |
actions: updateContext(key) | |
}, | |
{ | |
target: '.valid', | |
cond, | |
actions: updateContext(key) | |
}, | |
{ | |
target: '.invalid', | |
actions: updateContext(key) | |
} | |
] | |
}, | |
onDone: 'checking' | |
}) | |
const LoginMachine = Machine({ | |
id: 'login', | |
context: { | |
username: '', | |
password: '', | |
}, | |
initial: 'initialize', | |
states: { | |
initialize: { | |
invoke: { | |
src: 'initialize', | |
onDone: 'checkUsername', | |
onError: { | |
target: 'error' | |
} | |
} | |
}, | |
checkUsername: { | |
initial: 'input', | |
states: { | |
input: inputSM(validateUsername, 'username'), | |
checking: { | |
invoke: { | |
src: 'checkUsername', | |
onDone: 'success', | |
onError: { | |
target: '#login.checkUsername.input.valid', | |
actions: ['error'] | |
} | |
} | |
}, | |
success: { | |
type: 'final' | |
} | |
}, | |
onDone: 'checkPhrase' | |
}, | |
checkPhrase: { | |
on: { | |
CONFIRM: 'checkPassword', | |
REJECT: '#login.checkUsername.input.valid' | |
} | |
}, | |
checkPassword: { | |
initial: 'input', | |
states: { | |
input: inputSM(validatePassword, 'password'), | |
checking: { | |
invoke: { | |
src: 'authenticate', | |
onDone: 'success', | |
onError: { | |
target: '#login.checkPassword.input.valid', | |
actions: ['error'] | |
} | |
}, | |
on: { | |
REJECT: undefined | |
} | |
}, | |
success: { | |
type: 'final' | |
}, | |
}, | |
on: { | |
REJECT: '#login.checkUsername.input.valid' | |
}, | |
onDone: 'loggedIn', | |
}, | |
loggedIn: { | |
entry: ['onLoggedIn'], | |
type: 'final' | |
}, | |
error: {}, | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment