2022-04-24 23:12:11 +02:00
|
|
|
import { NextPage } from 'next'
|
|
|
|
import HomeLayout from '../../components/layout/home/HomeLayout'
|
2022-04-25 22:32:24 +02:00
|
|
|
import CreateWish, {
|
|
|
|
BasePrompt,
|
|
|
|
} from '../../components/domain/wishes/createWish/CreateWish'
|
|
|
|
import { useEffect, useMemo, useState } from 'react'
|
|
|
|
import { createWish, Wish } from '../../components/domain/wishes/models'
|
|
|
|
import { v4 } from 'uuid'
|
|
|
|
import { result } from '../../components/common/result'
|
|
|
|
|
|
|
|
interface WishItem {
|
|
|
|
value: Wish
|
|
|
|
dirty: boolean
|
|
|
|
focus: boolean
|
|
|
|
}
|
2022-04-24 23:12:11 +02:00
|
|
|
|
|
|
|
const HomePage: NextPage = (props) => {
|
2022-04-25 22:32:24 +02:00
|
|
|
const stableId = useMemo(() => v4(), [])
|
|
|
|
|
|
|
|
const [wishes, setWishes] = useState<{ [key: string]: WishItem }>({
|
|
|
|
[stableId]: {
|
|
|
|
value: result.getValue(createWish(stableId, '')),
|
|
|
|
dirty: false,
|
|
|
|
focus: false,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
const wishArr = useMemo(() => Array.from(Object.values(wishes)), [wishes])
|
|
|
|
const allDirty = useMemo(
|
|
|
|
() => wishArr.map((w) => w.dirty).reduce((prev, curr) => prev && curr),
|
|
|
|
[wishArr]
|
|
|
|
)
|
|
|
|
useMemo(() => {
|
|
|
|
if (!allDirty) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const id = v4()
|
|
|
|
setWishes((wishes) => ({
|
|
|
|
...wishes,
|
|
|
|
[id]: {
|
|
|
|
value: result.getValue(createWish(id, '')),
|
|
|
|
dirty: false,
|
|
|
|
focus: false,
|
|
|
|
},
|
|
|
|
}))
|
|
|
|
}, [allDirty])
|
|
|
|
|
|
|
|
const submit = (wishes: Wish[]) => {
|
|
|
|
console.log(wishes)
|
|
|
|
}
|
|
|
|
|
2022-04-24 23:12:11 +02:00
|
|
|
return (
|
|
|
|
<HomeLayout page="home">
|
2022-04-25 22:32:24 +02:00
|
|
|
<BasePrompt>
|
|
|
|
{wishArr.map((wish) => (
|
|
|
|
<CreateWish
|
|
|
|
key={wish.value.id}
|
|
|
|
hasFocus={wish.focus}
|
|
|
|
onFocus={() => {
|
|
|
|
setWishes((wishes) => ({
|
|
|
|
...Array.from(Object.values(wishes)) // Get array
|
|
|
|
.map((w) => ({ ...w, focus: false })) // Reset focus for all
|
|
|
|
.reduce((obj, cur) => ({ ...obj, [cur.value.id]: cur }), {}), // Translate to object
|
|
|
|
[wish.value.id]: { ...wish, focus: true },
|
|
|
|
}))
|
|
|
|
}}
|
|
|
|
onSubmit={(wish) => {
|
|
|
|
setWishes((ws) => ({
|
|
|
|
...ws,
|
|
|
|
[wish.id]: { value: wish, dirty: true, focus: true },
|
|
|
|
}))
|
|
|
|
}}
|
|
|
|
wish={wish.value}
|
|
|
|
/>
|
|
|
|
))}
|
|
|
|
|
|
|
|
<button
|
|
|
|
type="button"
|
|
|
|
className="rounded bg-pink-400 py-2 px-4 text-white"
|
|
|
|
onClick={() =>
|
|
|
|
submit(wishArr.filter((w) => w.dirty).map((w) => w.value))
|
|
|
|
}
|
|
|
|
>
|
|
|
|
Submit
|
|
|
|
</button>
|
|
|
|
</BasePrompt>
|
2022-04-24 23:12:11 +02:00
|
|
|
</HomeLayout>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export default HomePage
|