import { h, withState, withState2, Html } from 'lib/rx'
import * as request from 'request'
import * as modal from 'ui/modal'
import * as route from 'route'
import { Map } from 'models/map'
import * as form from 'lib/form'
import * as L from 'lib/loadable'
import * as layout from 'ui/layout'
export function view(): Html {
return withState>>(L.loading, mapsVar => {
request
.get>('/api/maps')
.then(res => {
res.sort((a, b) => a.name.localeCompare(b.name))
mapsVar.update(_ => L.loaded(res))
})
.catch(({ message }) => L.failure(message))
return h('div',
{ className: 'g-Maps' },
withState(false, showVar => [
h('button',
{ className: 'g-Button g-Button--Primary',
onclick: (event: Event) => showVar.update(_ => true)
},
'Nouvelle carte'
),
showVar.map(show => {
if (show) {
return createModal({
onClose: () => showVar.update(_ => false)
})
}
})
]),
mapsVar.map(loadable => layout.loadable(loadable, maps => h('ul', maps.map(viewMap))))
)
})
}
function viewMap(m: Map): Html {
const url = route.toString(route.map({ id: m.id }))
return h('li',
h('a', { href: url }, m.name)
)
}
// Create map
interface CreateParams {
onClose: () => void,
}
function createModal({ onClose }: CreateParams): Html {
return modal.view({
header: 'Nouvelle carte',
body: withState2>(['', L.init], (nameVar, requestVar) =>
h('form',
{
onsubmit: nameVar.map(name => (event: Event) => {
event.preventDefault()
requestVar.update(_ => L.loading)
request
.post