|
1 | 1 | // @flow
|
| 2 | +import { |
| 3 | + createEvent, |
| 4 | + createStore, |
| 5 | + type Store, |
| 6 | + createEffect, |
| 7 | + forward, |
| 8 | + sample, |
| 9 | + combine, |
| 10 | + createStoreObject, |
| 11 | +} from "effector" |
| 12 | +import { accountApi, type Settings } from "@api/account" |
| 13 | + |
| 14 | +/** |
| 15 | + * 1. load user settings object |
| 16 | + * 2. mark page ready |
| 17 | + */ |
| 18 | + |
| 19 | +type InputEvent = SyntheticEvent<HTMLInputElement> |
| 20 | +type ButtonEvent = SyntheticEvent<HTMLButtonElement> |
| 21 | + |
| 22 | +export const pageMounted = createEvent<void>() |
| 23 | +export const pageUnmounted = createEvent<void>() |
| 24 | + |
| 25 | +export const nameChanged = createEvent<InputEvent>() |
| 26 | +export const nameSubmitted = createEvent<ButtonEvent>() |
| 27 | + |
| 28 | +export const avaChangePressed = createEvent<ButtonEvent>() |
| 29 | +export const avaEmailChanged = createEvent<InputEvent>() |
| 30 | +export const avaEmailSubmitted = createEvent<ButtonEvent>() |
| 31 | + |
| 32 | +const loadSettings = createEffect() |
| 33 | +const saveSettings = createEffect() |
| 34 | + |
| 35 | +export const $settings: Store<?Settings> = createStore(null) |
| 36 | +export const $isSettingsReady = $settings.map<boolean>(Boolean) |
| 37 | + |
| 38 | +// Stores for inputs |
| 39 | + |
| 40 | +export const $name: Store<string> = createStore("") |
| 41 | +export const $avaEmail: Store<string> = createStore("") |
| 42 | + |
| 43 | +forward({ |
| 44 | + from: pageMounted, |
| 45 | + to: loadSettings, |
| 46 | +}) |
| 47 | + |
| 48 | +loadSettings.use(accountApi.getSettings) |
| 49 | +saveSettings.use(accountApi.updateSettings) |
| 50 | + |
| 51 | +$settings |
| 52 | + .on(loadSettings.done, (_, { result }) => result.settings) |
| 53 | + .on(saveSettings.done, (_, { result }) => result.settings) |
| 54 | + .reset(pageMounted, pageUnmounted) |
| 55 | + |
| 56 | +$name |
| 57 | + .on($settings.updates, (_, settings) => settings?.displayName || "") |
| 58 | + .on(nameChanged, (_, event) => event.currentTarget.value) |
| 59 | + .reset(pageUnmounted) |
| 60 | + .watch(nameSubmitted, (displayName) => { |
| 61 | + saveSettings({ displayName }) |
| 62 | + }) |
| 63 | + |
| 64 | +$avaEmail |
| 65 | + .on($settings.updates, (_, settings) => settings?.gravatarEmail || "") |
| 66 | + .on(avaEmailChanged, (_, event) => event.currentTarget.value) |
| 67 | + .reset(pageUnmounted) |
| 68 | + .watch(avaEmailSubmitted, (_gravatarEmail) => { |
| 69 | + // HOW-62 |
| 70 | + // saveSettings({ gravatarEmail }) |
| 71 | + }) |
| 72 | + |
| 73 | +$settings.watch((settings) => console.log("SETTINGS", settings)) |
| 74 | +$isSettingsReady.watch((settingsReady) => |
| 75 | + console.log("settingsReady", settingsReady), |
| 76 | +) |
| 77 | +$name.watch((name) => console.log("name", name)) |
| 78 | +$avaEmail.watch((avaEmail) => console.log("avaEmail", avaEmail)) |
0 commit comments