import { h, withState3, Html } from 'lib/rx' import * as request from 'request' import * as route from 'route' import * as form from 'lib/form' import * as L from 'lib/loadable' import { User } from 'models/user' interface Params { updateUser: (user: User) => void } export function view({ updateUser }: Params): Html { return withState3>( ['', '', L.init], (emailVar, passwordVar, requestVar) => { return h('main', h('form', { className: 'g-Login', onsubmit: emailVar.flatMap(email => passwordVar.map(password => (event: Event) => { event.preventDefault() const payload = { email, password } requestVar.update(_ => L.loading) request .post('/api/login', JSON.stringify(payload)) .then(user => { requestVar.update(_ => L.loaded(undefined)) updateUser(user) route.push(route.maps) }) .catch(({ message }) => { requestVar.update(_ => L.failure(message)) const passwordInput = document.querySelector('input[type=password]') as HTMLInputElement passwordInput.select() }) })) }, h('h1', { className: 'g-Login__Title' }, 'Maps'), form.input({ label: 'Identifiant', required: true, select: true, onUpdate: value => { emailVar.update(_ => value) requestVar.update(_ => L.init) } }), form.input({ label: 'Mot de passe', type: 'password', required: true, onUpdate: value => { passwordVar.update(_ => value) requestVar.update(_ => L.init) } }), form.error(requestVar), form.submit({ className: 'g-Button--FullWidth', label: 'Connexion', requestVar }) ) ) } ) }