-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDetailContext.tsx
More file actions
executable file
·229 lines (199 loc) · 6.69 KB
/
DetailContext.tsx
File metadata and controls
executable file
·229 lines (199 loc) · 6.69 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/* eslint-disable react-refresh/only-export-components */
import { ReactNode, createContext, useState, JSX, useEffect, Context, useContext } from 'react'
import { DropdownOption } from '../common/editingComponents'
import { ValidationObject } from '@/shared/validators/validator'
import { EditDataType } from '@/shared/types'
import {
TextFieldOptions,
OptionalRadioSelectionProps,
FieldsWithErrorsType,
SetFieldsWithErrorsType,
} from '../DetailView'
const cloneDeep = <T,>(value: T): T => {
if (typeof structuredClone === 'function') {
return structuredClone(value)
}
return JSON.parse(JSON.stringify(value)) as T
}
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value)
const normalizeForDirtyCheck = (value: unknown): unknown => {
if (Array.isArray(value)) {
return value.map(item => normalizeForDirtyCheck(item))
}
if (isPlainObject(value)) {
const normalizedEntries = Object.entries(value).flatMap(([key, nestedValue]) => {
if (key === 'rowState' && nestedValue === 'clean') return []
return [[key, normalizeForDirtyCheck(nestedValue)]]
})
return Object.fromEntries(normalizedEntries)
}
return value
}
const isEqualWith = (
value: unknown,
other: unknown,
customizer?: (value: unknown, other: unknown) => boolean | undefined
): boolean => {
const customizedResult = customizer?.(value, other)
if (customizedResult !== undefined) return customizedResult
if (Object.is(value, other)) return true
if (Array.isArray(value) && Array.isArray(other)) {
if (value.length !== other.length) return false
return value.every((item, index) => isEqualWith(item, other[index], customizer))
}
if (isPlainObject(value) && isPlainObject(other)) {
const valueKeys = Object.keys(value)
const otherKeys = Object.keys(other)
if (valueKeys.length !== otherKeys.length) return false
return valueKeys.every(key => isEqualWith(value[key], other[key], customizer))
}
return false
}
export type ModeOptions = 'read' | 'new' | 'edit' | 'staging-edit' | 'staging-new'
export type ModeType = {
read: boolean
staging: boolean
new: boolean
option: ModeOptions
}
export const modeOptionToMode: Record<ModeOptions, ModeType> = {
new: {
read: false,
staging: false,
new: true,
option: 'new',
},
read: {
read: true,
staging: false,
new: false,
option: 'read',
},
edit: {
read: false,
staging: false,
new: false,
option: 'edit',
},
'staging-edit': {
read: false,
staging: true,
new: false,
option: 'staging-edit',
},
'staging-new': {
read: false,
staging: true,
new: true,
option: 'staging-new',
},
}
export type DetailContextType<T> = {
data: T
mode: ModeType
setMode: (newMode: ModeOptions) => void
editData: EditDataType<T>
setEditData: SetEditDataType<T>
textField: (field: keyof EditDataType<T>, options?: TextFieldOptions) => JSX.Element
bigTextField: (field: keyof EditDataType<T>) => JSX.Element
dropdown: (
field: keyof EditDataType<T>,
options: Array<DropdownOption | string>,
name: string,
disabled?: boolean
) => JSX.Element
dropdownWithSearch: (
field: keyof EditDataType<T>,
options: Array<DropdownOption | string>,
name: string,
disabled?: boolean,
label?: string
) => JSX.Element
radioSelection: (
field: keyof EditDataType<T>,
options: Array<DropdownOption | string>,
name: string,
optionalRadioSelectionProps?: OptionalRadioSelectionProps
) => JSX.Element
validator: (editData: EditDataType<T>, field: keyof EditDataType<T>) => ValidationObject
validateFields?: (editData: EditDataType<T>) => ValidationObject[]
fieldsWithErrors: FieldsWithErrorsType
setFieldsWithErrors: SetFieldsWithErrorsType
isDirty: boolean
resetEditData: () => void
markEditDataClean?: (editData?: unknown) => void
}
export type SetEditDataType<T> = (editData: EditDataType<T>) => void
export const DetailContext = createContext<DetailContextType<unknown>>(null!)
export const makeEditData = <T,>(data: T): EditDataType<T> => ({
...(cloneDeep(data) as EditDataType<T>),
references: [],
comment: '',
})
export const DetailContextProvider = <T extends object>({
children,
contextState,
}: {
children: ReactNode | ReactNode[]
contextState: Omit<DetailContextType<T>, 'setEditData' | 'isDirty' | 'resetEditData'>
}) => {
const [initialEditData, setInitialEditData] = useState<EditDataType<T>>(makeEditData(contextState.data))
const [editData, setEditData] = useState<EditDataType<T>>(makeEditData(contextState.data))
const [isDirty, setIsDirty] = useState(false)
const compareValues = (value: unknown, other: unknown) => {
const isEmpty = (input: unknown) => input === '' || input === null || input === undefined
if (isEmpty(value) && isEmpty(other)) return true
return undefined
}
useEffect(() => {
const nextEditData = makeEditData(contextState.data)
setInitialEditData(nextEditData)
setEditData(cloneDeep(nextEditData))
setIsDirty(false)
}, [contextState.data])
useEffect(() => {
setIsDirty(!isEqualWith(normalizeForDirtyCheck(editData), normalizeForDirtyCheck(initialEditData), compareValues))
}, [editData, initialEditData])
const handleSetEditData = (data: unknown) => {
const newEditData = data as EditDataType<T>
setEditData(newEditData)
setIsDirty(
!isEqualWith(normalizeForDirtyCheck(newEditData), normalizeForDirtyCheck(initialEditData), compareValues)
)
}
const resetEditData = () => {
setEditData(cloneDeep(initialEditData))
setIsDirty(false)
}
const markEditDataClean = (nextEditData?: unknown) => {
const cleanEditData = cloneDeep((nextEditData as EditDataType<T> | undefined) ?? editData)
setInitialEditData(cleanEditData)
setEditData(cloneDeep(cleanEditData))
setIsDirty(false)
}
return (
<DetailContext.Provider
value={{
...contextState,
editData,
setEditData: handleSetEditData,
isDirty,
resetEditData,
markEditDataClean,
validator: (editData: unknown, fieldName: keyof EditDataType<T>) =>
contextState.validator(editData as EditDataType<T>, fieldName),
validateFields: contextState.validateFields
? (editData: unknown) => contextState.validateFields?.(editData as EditDataType<T>) ?? []
: undefined,
}}
>
{children}
</DetailContext.Provider>
)
}
export const useDetailContext = <T,>() => {
const detailContext = useContext<DetailContextType<T>>(DetailContext as unknown as Context<DetailContextType<T>>)
if (!detailContext) throw new Error('detailContext lacking provider')
return detailContext
}