-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathstate.ts
More file actions
338 lines (302 loc) · 10.7 KB
/
Copy pathstate.ts
File metadata and controls
338 lines (302 loc) · 10.7 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import type { Middleware, MiddlewareHandlerParams } from '../../../middleware';
import { generateUUIDv4 } from '../../../utils';
import type {
PollComposerFieldErrors,
PollComposerState,
PollComposerStateChangeMiddlewareValue,
TargetedPollOptionTextUpdate,
} from './types';
export const VALID_MAX_VOTES_VALUE_REGEX = /^([2-9]|10)$/;
export const MAX_POLL_OPTIONS = 100 as const;
const textFieldIsEmpty = (text: string) => !text.trim();
export type PollStateValidationOutput = Partial<
Omit<Record<keyof PollComposerState['data'], string>, 'options'> & {
options?: Record<string, string>;
}
>;
export type PollStateChangeValidator = (params: {
data: PollComposerState['data'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
currentError?: PollComposerFieldErrors[keyof PollComposerFieldErrors];
}) => PollStateValidationOutput;
export const pollStateChangeValidators: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
> = {
enforce_unique_vote: () => ({ max_votes_allowed: undefined }),
max_votes_allowed: ({ data, value }) => {
if (data.enforce_unique_vote && value)
return { max_votes_allowed: 'Enforce unique vote is enabled' };
const numericMatch = value.match(/^[0-9]+$/);
if (!numericMatch && value) {
return { max_votes_allowed: 'Only numbers are allowed' };
}
if (value?.length > 1 && !value.match(VALID_MAX_VOTES_VALUE_REGEX))
return { max_votes_allowed: 'Type a number from 2 to 10' };
return { max_votes_allowed: undefined };
},
options: ({ value: options }) => {
const errors: Record<string, string> = {};
const seenOptions = new Set<string>();
options.forEach((option: { id: string; text: string }) => {
if (seenOptions.has(option.text) && option.text.length) {
errors[option.id] = 'Option already exists';
} else {
seenOptions.add(option.text);
}
});
return Object.keys(errors).length > 0 ? { options: errors } : { options: undefined };
},
};
export const defaultPollFieldChangeEventValidators: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
> = {
name: ({ currentError, value }) =>
value && currentError
? { name: undefined }
: { name: typeof currentError === 'string' ? currentError : undefined },
};
export const defaultPollFieldBlurEventValidators: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
> = {
max_votes_allowed: ({ value }) => {
if (value && !value.match(VALID_MAX_VOTES_VALUE_REGEX))
return { max_votes_allowed: 'Type a number from 2 to 10' };
return { max_votes_allowed: undefined };
},
name: ({ value }) => {
if (textFieldIsEmpty(value)) return { name: 'Question is required' };
return { name: undefined };
},
options: (params) => {
const defaultResult = pollStateChangeValidators.options?.(params);
const errors = defaultResult?.options ?? {};
params.value.forEach((option: { id: string; text: string }, index: number) => {
const isTheLastOption = index === params.value.length - 1;
if (textFieldIsEmpty(option.text) && !isTheLastOption) {
errors[option.id] = 'Option is empty';
}
});
return Object.keys(errors).length > 0 ? { options: errors } : { options: undefined };
},
};
export type PollCompositionStateProcessorOutput = Partial<PollComposerState['data']>;
export type PollCompositionStateProcessor = (params: {
data: PollComposerState['data'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
}) => PollCompositionStateProcessorOutput;
export const isTargetedOptionTextUpdate = (
value: unknown,
): value is TargetedPollOptionTextUpdate =>
!Array.isArray(value) &&
typeof (value as TargetedPollOptionTextUpdate)?.index === 'number' &&
typeof (value as TargetedPollOptionTextUpdate)?.text === 'string';
const clampMaxVotesAllowed = (value: unknown): string => {
if (value === '' || value == null) return '';
const num = typeof value === 'string' ? parseInt(value, 10) : Number(value);
if (!Number.isInteger(num) || Number.isNaN(num)) return '';
return String(Math.min(10, Math.max(2, num)));
};
export const pollCompositionStateProcessors: Partial<
Record<keyof PollComposerState['data'], PollCompositionStateProcessor>
> = {
enforce_unique_vote: ({ value }) => ({
enforce_unique_vote: value,
max_votes_allowed: '',
}),
max_votes_allowed: ({ value }) => ({
max_votes_allowed: clampMaxVotesAllowed(value),
}),
options: ({ value, data }) => {
// If it's a direct array update (like drag-drop reordering)
if (Array.isArray(value)) {
return {
options: value.map((option) => ({
id: option.id,
text: option.text.trim(),
})),
};
}
// For single option updates
const { index, text } = value;
const prevOptions = data.options || [];
const targetOption = prevOptions[index];
if (!targetOption) {
return { options: prevOptions };
}
const nextOptionsAfterTarget = prevOptions.slice(index + 1);
const shouldPreserveClearedOption =
!text &&
nextOptionsAfterTarget.length > 0 &&
nextOptionsAfterTarget.every((option) => !option.text);
if (shouldPreserveClearedOption) {
return {
options: [
...prevOptions.slice(0, index),
{ ...targetOption, text },
...nextOptionsAfterTarget,
],
};
}
const shouldRemoveOption =
prevOptions && prevOptions.slice(index + 1).length > 0 && !text;
const optionListHead = prevOptions.slice(0, index);
const optionListTail = prevOptions.slice(index + 1);
const newOptions = [
...optionListHead,
...(shouldRemoveOption ? [] : [{ ...targetOption, text }]),
...optionListTail,
];
const shouldAddNewOption =
prevOptions.length < MAX_POLL_OPTIONS &&
!newOptions.some((option) => !option.text.trim());
if (shouldAddNewOption) {
newOptions.push({ id: generateUUIDv4(), text: '' });
}
return { options: newOptions };
},
};
export type PollComposerStateMiddlewareFactoryOptions = {
processors?: {
handleFieldChange?: Partial<
Record<keyof PollComposerState['data'], PollCompositionStateProcessor>
>;
handleFieldBlur?: Partial<
Record<keyof PollComposerState['data'], PollCompositionStateProcessor>
>;
};
validators?: {
handleFieldChange?: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
>;
handleFieldBlur?: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
>;
};
};
export type PollComposerStateMiddleware = Middleware<
PollComposerStateChangeMiddlewareValue,
'handleFieldChange' | 'handleFieldBlur'
>;
export const createPollComposerStateMiddleware = ({
processors: customProcessors,
validators: customValidators,
}: PollComposerStateMiddlewareFactoryOptions = {}): PollComposerStateMiddleware => {
const universalHandler = ({
state,
validators,
processors,
}: {
state: PollComposerStateChangeMiddlewareValue;
validators: Partial<
Record<keyof PollComposerState['data'], PollStateChangeValidator>
>;
processors?: Partial<
Record<keyof PollComposerState['data'], PollCompositionStateProcessor>
>;
}) => {
const { previousState, targetFields } = state;
let newData: Partial<PollComposerState['data']>;
if (!processors && isTargetedOptionTextUpdate(targetFields.options)) {
const options = [...previousState.data.options];
const targetOption = previousState.data.options[targetFields.options.index];
if (targetOption) {
targetOption.text = targetFields.options.text;
options.splice(targetFields.options.index, 1, targetOption);
}
newData = { ...targetFields, options };
} else if (!processors) {
newData = targetFields as PollComposerState['data'];
} else {
newData = Object.entries(targetFields).reduce(
(acc, [key, value]) => {
const processor = processors[key as keyof PollComposerState['data']];
acc = {
...acc,
...(processor
? processor({ data: previousState.data, value })
: { [key]: value }),
};
return acc;
},
{} as PollComposerState['data'],
);
}
const newErrors = Object.keys(targetFields).reduce((acc, key) => {
const validator = validators[key as keyof PollComposerState['data']];
if (validator) {
const error = validator({
currentError: previousState.errors[key as keyof PollComposerState['data']],
data: previousState.data,
value: newData[key as keyof PollComposerState['data']],
});
acc = { ...acc, ...error };
}
return acc;
}, {} as PollComposerFieldErrors);
return { newData, newErrors };
};
return {
id: 'stream-io/poll-composer-state-processing',
handlers: {
handleFieldChange: ({
state,
next,
forward,
}: MiddlewareHandlerParams<PollComposerStateChangeMiddlewareValue>) => {
if (!state.targetFields) return forward();
const { previousState, injectedFieldErrors } = state;
const { newData, newErrors } = universalHandler({
processors: {
...pollCompositionStateProcessors,
...customProcessors?.handleFieldChange,
},
state,
validators: {
...pollStateChangeValidators,
...defaultPollFieldChangeEventValidators,
...customValidators?.handleFieldChange,
},
});
return next({
...state,
nextState: {
...previousState,
data: { ...previousState.data, ...newData },
errors: { ...previousState.errors, ...newErrors, ...injectedFieldErrors },
},
});
},
handleFieldBlur: ({
state,
next,
forward,
}: MiddlewareHandlerParams<PollComposerStateChangeMiddlewareValue>) => {
if (!state.targetFields) return forward();
const { previousState } = state;
const { newData, newErrors } = universalHandler({
processors: customProcessors?.handleFieldBlur,
state,
validators: {
...pollStateChangeValidators,
...defaultPollFieldBlurEventValidators,
...customValidators?.handleFieldBlur,
},
});
return next({
...state,
nextState: {
...previousState,
data: { ...previousState.data, ...newData },
errors: {
...previousState.errors,
...newErrors,
...state.injectedFieldErrors,
},
},
});
},
},
};
};