Created
August 1, 2016 14:08
-
-
Save tlaitinen/4b8a9f7b59c29a74d40d0804384e3e14 to your computer and use it in GitHub Desktop.
This file contains 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
import xs from 'xstream'; | |
import isolate from '@cycle/isolate'; | |
import {div, button, input} from '@cycle/dom'; | |
function intent(domSource, httpSource) { | |
const errorObj = { httpError: true } | |
const username$ = domSource.select('.username').events('input') | |
.map(ev => ev.target.value).startWith('') | |
const password$ = domSource.select('.password').events('input') | |
.map(ev => ev.target.value).startWith('') | |
return { | |
username$, | |
password$, | |
loginRequest$: domSource | |
.select('.login') | |
.events('click') | |
.map(() => xs.combine(username$, password$) | |
.map(([username, password]) => ({username, password}))) | |
.flatten(), | |
loginSuccess$: httpSource | |
.select('login') | |
.map((response$) => response$.replaceError(err => { console.log (err); return xs.of(errorObj) } )) | |
.flatten() | |
.startWith(null) | |
} | |
} | |
function model(actions) { | |
return xs.combine( | |
actions.username$, | |
actions.password$, | |
actions.loginSuccess$ | |
).map(([username, password, res]) => { | |
return { | |
username, | |
password, | |
loginResult: res ? res.status == 200 : null | |
} | |
}) | |
} | |
function view(state$) { | |
return state$.map(({username, password, loginResult}) => | |
div('.login-form', [ | |
input('.username', { | |
attrs: { | |
type: 'text' | |
} | |
}), | |
input('.password', { | |
attrs: { | |
type: 'password' | |
} | |
}), | |
button('.login', ['Login']), | |
'Login result: ' + loginResult | |
])) | |
} | |
function createLoginComponent() { | |
function Login(sources) { | |
const actions = intent(sources.DOM, sources.HTTP); | |
const state$ = model(actions); | |
const vdom$ = view(state$); | |
return { | |
DOM: vdom$, | |
HTTP: actions.loginRequest$.map((p) => ({ | |
url: "backend/login", | |
method: "POST", | |
category: "login", | |
send: p, | |
type: 'application/json' | |
})), | |
router: xs.empty() | |
} | |
} | |
return isolate(Login) | |
} | |
export {createLoginComponent} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment