-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNewSticker.tsx
More file actions
412 lines (387 loc) · 12.8 KB
/
NewSticker.tsx
File metadata and controls
412 lines (387 loc) · 12.8 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import { FC, useState, useEffect } from 'react';
import { FieldValues, useForm } from 'react-hook-form';
import cn from 'classnames';
import { registerAmount, registerSize } from '@utils/registersRHF';
import {
AMOUNT_INPUT_MAX_LENGTH,
AMOUNT_INPUT_MIN_LENGTH,
REG_STICKERS,
SIZE_INPUT_MAX_LENGTH,
SIZE_INPUT_MIN_LENGTH,
} from '@utils/constants';
import { TShape } from '@shared/types';
import { useAppDispatch } from '@shared/hooks/hooks';
import { ISticker } from '@shared/interfaces';
import {
addEmptySticker,
addSticker,
addStickers,
deleteSticker,
putStickerInCart,
updateSticker,
openMessage,
} from '@shared/store';
import {
ButtonCustom,
Input,
InputError,
InputField,
RadioButton,
TooltipCustom,
Loader,
} from '@components/UI';
import { InfoBox, Shape, StickerImage, DragAndDrop } from '@components/index';
import { messages } from '@static/popups';
import { addpage } from '@static/stickerspage';
import styles from './NewSticker.module.scss';
interface IProps {
sticker: ISticker;
stickerActiveId: string;
handleActiveSticker: (id: string) => void;
type: 'add' | 'edit';
}
export const NewSticker: FC<IProps> = ({ sticker, stickerActiveId, handleActiveSticker }) => {
const {
register,
formState: { errors, isValid },
setValue,
getValues,
watch,
} = useForm<FieldValues>({
mode: 'onBlur',
defaultValues: {
shape: sticker.shape,
amount: sticker.amount,
size: sticker.size_type,
width: sticker.optimal_width,
height: sticker.optimal_height,
},
});
const dispatch = useAppDispatch();
const [loading, setLoading] = useState(false);
const [block, setBlock] = useState(false);
const [customVisible, setCustomVisible] = useState<boolean>(sticker.size_type === 'custom');
const shapesType = {
circle: 'круг',
square: 'квадрат',
rounded_square: 'закругленный квадрат',
contour: 'по контуру',
};
const onAmountChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const number = Number(event.target.value);
if (
REG_STICKERS.test(number.toString()) &&
number <= AMOUNT_INPUT_MAX_LENGTH &&
number >= AMOUNT_INPUT_MIN_LENGTH
) {
dispatch(updateSticker({ ...sticker, amount: number }));
setBlock(false);
}
};
const onShapeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const shape = event.target.value as TShape;
if ((shape as TShape) === 'contour') {
const formData = new FormData();
formData.append('file', sticker.image);
}
dispatch(updateSticker({ ...sticker, shape }));
setBlock(false);
};
const handleDelete = () => {
dispatch(deleteSticker(sticker.id));
};
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
setLoading(true);
if (sticker.id === 'newSticker') {
dispatch(addStickers([sticker]))
.then((res) => {
const addedSticker = res.payload[0];
dispatch(addSticker({ ...addedSticker }));
dispatch(addEmptySticker());
})
.catch(() => dispatch(openMessage({ text: `${messages.somethingWrong}`, isError: true })))
.finally(() => {
setLoading(false);
setCustomVisible(false);
dispatch(
updateSticker({
...sticker,
id: 'newSticker',
image: '',
size_type: 'optimal',
shape: 'square',
amount: 1,
width: 3,
height: 3,
optimal_width: 3,
optimal_height: 3,
})
);
setValue('shape', 'square');
setValue('amount', 1);
setValue('width', 3);
setValue('height', 3);
setValue('optimal_width', 3);
setValue('optimal_height', 3);
setValue('size', 'optimal');
});
}
if (sticker.id !== 'newSticker') {
dispatch(putStickerInCart(sticker))
.then(() => setBlock(true))
.catch(() => dispatch(openMessage({ text: `${messages.somethingWrong}`, isError: true })))
.finally(() => setLoading(false));
}
};
const sizeValidate = (value: string): boolean => {
return (
REG_STICKERS.test(value) &&
Number(value) >= SIZE_INPUT_MIN_LENGTH &&
Number(value) <= SIZE_INPUT_MAX_LENGTH
);
};
const onWidthChange = () => {
const value = getValues('width').slice(0, 2);
setValue('width', value.replace(/\D/g, ''));
if (sizeValidate(value)) {
dispatch(
updateSticker({
...sticker,
width: Number(value),
height: sticker.shape === 'circle' ? Number(value) : sticker.height,
})
);
}
setBlock(false);
};
const onHeightChange = () => {
const value = getValues('height').slice(0, 2);
setValue('height', value.replace(/\D/g, ''));
if (sizeValidate(value)) {
dispatch(
updateSticker({
...sticker,
height: Number(value),
width: sticker.shape === 'circle' ? Number(value) : sticker.width,
})
);
}
setBlock(false);
};
// Проверяем, изменились ли поля формы
const image = watch('image');
const shape = watch('shape');
const amount = watch('amount');
const size = watch('size');
const width = watch('width');
const height = watch('height');
const initialSize = sticker.size_type;
const fieldsUnchanged =
initialSize === sticker.size_type &&
sticker.shape === shape &&
sticker.amount === amount &&
sticker.width === width &&
sticker.height === height;
return (
<article
className={cn(
styles.card,
sticker.id !== stickerActiveId && styles.card_unactive,
sticker.id !== stickerActiveId && sticker.id === 'newSticker' && styles.card_unactive_new
)}
onClick={sticker.id === stickerActiveId ? () => null : () => handleActiveSticker(sticker.id)}
>
{loading && <Loader loading={loading} />}
<form
className={sticker.id === stickerActiveId ? styles.info : styles.info_unactive}
onSubmit={handleSubmit}
>
<div className={styles.image}>
{/* Оставляем драгндроп с инпутом картинки, чтобы при сворачивании карточки он не размонтировался и не очищался инпут*/}
<DragAndDrop
sticker={sticker}
register={register}
name='image'
className={stickerActiveId !== sticker.id ? styles.hidden : ''}
/>
<StickerImage
sticker={sticker}
boxWidth={144}
boxHeight={144}
className={stickerActiveId === sticker.id ? styles.hidden : ''}
/>
</div>
<fieldset className={cn(styles.flex, styles.flex_shapes)}>
<label className={styles.category} htmlFor='shape'>
Форма
{sticker.id !== stickerActiveId && (
<span className={styles.shape_hidden}> {shapesType[sticker.shape]}</span>
)}
</label>
<div className={cn(styles.shapes, sticker.id !== stickerActiveId && styles.hidden)}>
<Shape
register={register}
name='shape'
sticker={sticker}
value='square'
onShapeChange={onShapeChange}
/>
<Shape
register={register}
name='shape'
sticker={sticker}
value='rounded_square'
onShapeChange={onShapeChange}
/>
<Shape
register={register}
name='shape'
sticker={sticker}
value='circle'
onShapeChange={onShapeChange}
/>
</div>
</fieldset>
<fieldset className={styles.flex}>
<label className={styles.category} htmlFor='amount'>
Количество стикеров
{sticker.id !== stickerActiveId && <span className={styles.size_hidden}>{sticker.amount}шт</span>}
</label>
{sticker.id === stickerActiveId && (
<InputField className='amount'>
<Input
className='amount'
error={errors.amount}
register={register}
name='amount'
option={{ ...registerAmount, onChange: onAmountChange }}
/>
<InputError className='amount' error={errors.amount} />
</InputField>
)}
</fieldset>
<fieldset className={styles.flex}>
<p className={styles.category}>
Размер
{sticker.id !== stickerActiveId && (
<span className={styles.size_hidden}>
{sticker.width}x{sticker.height}см
</span>
)}
</p>
<div className={cn(styles.options, sticker.id !== stickerActiveId && styles.hidden)}>
<RadioButton
register={register}
name='size'
value='optimal'
onClick={() => {
setCustomVisible(false);
setBlock(false);
dispatch(
updateSticker({
...sticker,
height: sticker.optimal_height,
width: sticker.optimal_width,
size_type: 'optimal',
})
);
}}
>
Оптимальный размер
<TooltipCustom text={addpage.tooltipOptimal} />
</RadioButton>
<div className={styles.option}>
<RadioButton
register={register}
name='size'
value='custom'
className={styles.size}
onClick={() => {
setCustomVisible(true);
setBlock(false);
dispatch(
updateSticker({
...sticker,
height: getValues('height'),
width: getValues('width'),
size_type: 'custom',
})
);
}}
>
Свой размер
</RadioButton>
<div className={cn(customVisible ? styles.visible : styles.hidden)}>
<InputField className='size'>
<Input
type='tel'
className='size'
register={register}
name='width'
placeholder='ширина'
error={errors.width}
option={{ ...registerSize, onChange: onWidthChange }}
/>
x
<Input
type='tel'
className='size'
register={register}
name='height'
placeholder='высота'
error={errors.height}
option={{ ...registerSize, onChange: onHeightChange }}
/>
см
<InputError className='size' error={errors.width || errors.height} />
</InputField>
</div>
</div>
</div>
</fieldset>
<div className={styles.flex}>
<InfoBox type='simple' description='Цвет фона'>
<div className={styles.flexible}>
белый
<div className={styles.color_sample} />
</div>
</InfoBox>
</div>
<div className={styles.flex}>
<InfoBox type='simple' description='Материал'>
винил
</InfoBox>
</div>
{sticker.id === 'newSticker' ? (
<ButtonCustom
buttonType='submit'
type='add'
label='Добавить'
title='Добавить в заказ'
disabled={!isValid || sticker.image === ''}
className={sticker.id === stickerActiveId && !loading ? styles.save : styles.hidden}
/>
) : (
<ButtonCustom
buttonType='submit'
type='save'
disabled={!isValid || fieldsUnchanged || block}
className={sticker.id === stickerActiveId && !loading ? styles.save : styles.hidden}
label='Сохранить'
title='Сохранить'
/>
)}
</form>
{sticker.id !== 'newSticker' && (
<ButtonCustom
type='delete'
className={sticker.id === stickerActiveId ? styles.delete : styles.hidden}
label='Удалить'
title='Удалить'
onClick={handleDelete}
/>
)}
</article>
);
};