This repository was archived by the owner on Mar 19, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmodel.js
61 lines (52 loc) · 1.85 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// @flow
import { createEffect, createEvent, createStore } from "effector"
import type { Effect, Store } from "effector"
import { type Fetching, createFetching } from "@lib/fetching"
import { history } from "@lib/routing"
import { type Card, cardsApi } from "@api/cards"
export const pageUnloaded = createEvent<void>()
export const titleChanged = createEvent<SyntheticEvent<HTMLInputElement>>()
export const contentChanged = createEvent<mixed>()
export const savePressed = createEvent<void>()
export const cardLoading: Effect<number, { card: Card }, void> = createEffect()
export const cardFetching: Fetching<*, void> = createFetching(
cardLoading,
"loading",
{
reset: pageUnloaded,
},
)
type SaveCard = { id: number, title: string, content: mixed }
export const cardSaving: Effect<SaveCard, { card: Card }, void> = createEffect()
export const cardSaveFetching: Fetching<*, void> = createFetching(
cardSaving,
"initial",
{
reset: pageUnloaded,
},
)
export const $card: Store<?Card> = createStore(null)
export const $cardId: Store<?number> = $card.map((card) => card && card.id)
export const $title: Store<?string> = $card.map((card) => card && card.title)
export const $content: Store<?mixed> = $card.map((card) => card && card.content)
cardLoading.use((cardId) => cardsApi.getById(cardId))
$card.on(cardLoading.done, (_, { result }) => result.card)
$card.on(titleChanged, (card, event) => ({
...card,
title: event.currentTarget.value,
}))
$card.on(contentChanged, (card, content) => ({ ...card, content }))
cardSaving.use(({ id, title, content }) =>
cardsApi.edit({ id, title, content }),
)
cardSaving.done.watch(({ params }) => {
history.push(`/open/${params.id}`)
})
savePressed.watch(() => {
const card = $card.getState()
if (card) {
const { id, title, content } = card
cardSaving({ id, title, content })
}
})
$card.reset(pageUnloaded)