-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstate.tsx
100 lines (86 loc) · 2.72 KB
/
state.tsx
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// SPDX-FileCopyrightText: 2017-2022 City of Espoo
//
// SPDX-License-Identifier: LGPL-2.1-or-later
import React, {
createContext,
useCallback,
useContext,
useMemo,
useState
} from 'react'
import { Loading, Result } from 'lib-common/api'
import { AuthorizedMessageAccount } from 'lib-common/generated/api-types/messaging'
import { constantQuery, useQueryResult } from 'lib-common/query'
import { UUID } from 'lib-common/types'
import { UserContext } from '../auth/state'
import { UnitOrGroup } from '../common/unit-or-group'
import { messagingAccountsQuery } from './queries'
export interface MessagesState {
groupAccounts: Result<AuthorizedMessageAccount[]>
groupAccount: (
groupId: UUID | null
) => Result<AuthorizedMessageAccount | undefined>
setReplyContent: (threadId: UUID, content: string) => void
getReplyContent: (threadId: UUID) => string
}
const defaultState: MessagesState = {
groupAccounts: Loading.of(),
groupAccount: () => Loading.of(),
getReplyContent: () => '',
setReplyContent: () => undefined
}
export const MessageContext = createContext<MessagesState>(defaultState)
export const MessageContextProvider = React.memo(
function MessageContextProvider({
unitOrGroup,
children
}: {
unitOrGroup: UnitOrGroup
children: React.JSX.Element
}) {
const unitId = unitOrGroup.unitId
const { user } = useContext(UserContext)
const pinLoggedEmployeeId = user
.map((u) =>
u && u.pinLoginActive ? (u.employeeId ?? undefined) : undefined
)
.getOrElse(undefined)
const shouldFetch = !!unitId && !!pinLoggedEmployeeId
const groupAccounts = useQueryResult(
shouldFetch
? messagingAccountsQuery({ unitId, employeeId: pinLoggedEmployeeId })
: constantQuery([])
)
const groupAccount = useCallback(
(groupId: UUID | null) =>
groupAccounts.map((accounts) =>
groupId
? accounts.find((account) => account.daycareGroup?.id === groupId)
: undefined
),
[groupAccounts]
)
const [replyContents, setReplyContents] = useState<Record<UUID, string>>({})
const getReplyContent = useCallback(
(threadId: UUID) => replyContents[threadId] ?? '',
[replyContents]
)
const setReplyContent = useCallback((threadId: UUID, content: string) => {
setReplyContents((state) => ({ ...state, [threadId]: content }))
}, [])
const value = useMemo(
() => ({
groupAccounts,
groupAccount,
getReplyContent,
setReplyContent
}),
[groupAccounts, groupAccount, getReplyContent, setReplyContent]
)
return (
<MessageContext.Provider value={value}>
{children}
</MessageContext.Provider>
)
}
)