@itcase/forms 1.1.11 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3108 @@
1
+ 'use strict';
2
+
3
+ var libphonenumberJs = require('libphonenumber-js');
4
+ var React$1 = require('react');
5
+ var finalForm = require('final-form');
6
+ var reactFinalForm = require('react-final-form');
7
+ var clsx = require('clsx');
8
+ var Checkbox = require('@itcase/ui/components/Checkbox');
9
+ var Divider = require('@itcase/ui/components/Divider');
10
+ var Text = require('@itcase/ui/components/Text');
11
+ var useDeviceTargetClass = require('@itcase/ui/hooks/useDeviceTargetClass');
12
+ var useStyles = require('@itcase/ui/hooks/useStyles');
13
+ var camelCase = require('lodash/camelCase');
14
+ var snakeCase = require('lodash/snakeCase');
15
+ var Choice = require('@itcase/ui/components/Choice');
16
+ var Icon = require('@itcase/ui/components/Icon');
17
+ var Code = require('@itcase/ui/components/Code');
18
+ var DatePicker = require('@itcase/ui/components/DatePicker');
19
+ var useDevicePropsGenerator = require('@itcase/ui/hooks/useDevicePropsGenerator');
20
+ var axios = require('axios');
21
+ var fileSelector = require('file-selector');
22
+ var castArray = require('lodash/castArray');
23
+ var reactDropzone = require('react-dropzone');
24
+ var common = require('@itcase/common');
25
+ var Button = require('@itcase/ui/components/Button');
26
+ var Group$1 = require('@itcase/ui/components/Group');
27
+ var Loader = require('@itcase/ui/components/Loader');
28
+ var Title = require('@itcase/ui/components/Title');
29
+ var Input = require('@itcase/ui/components/Input');
30
+ var Radio = require('@itcase/ui/components/Radio');
31
+ var Segmented = require('@itcase/ui/components/Segmented');
32
+ var Select = require('@itcase/ui/components/Select');
33
+ var Switch = require('@itcase/ui/components/Switch');
34
+ var Textarea = require('@itcase/ui/components/Textarea');
35
+ var reactImask = require('react-imask');
36
+ var Chips = require('@itcase/ui/components/Chips');
37
+ var Notification = require('@itcase/ui/components/Notification');
38
+ var createDecorator = require('final-form-focus');
39
+
40
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
41
+
42
+ var React__default = /*#__PURE__*/_interopDefault(React$1);
43
+ var clsx__default = /*#__PURE__*/_interopDefault(clsx);
44
+ var camelCase__default = /*#__PURE__*/_interopDefault(camelCase);
45
+ var snakeCase__default = /*#__PURE__*/_interopDefault(snakeCase);
46
+ var axios__default = /*#__PURE__*/_interopDefault(axios);
47
+ var castArray__default = /*#__PURE__*/_interopDefault(castArray);
48
+ var createDecorator__default = /*#__PURE__*/_interopDefault(createDecorator);
49
+
50
+ const phoneValidation = value => {
51
+ if (!value) {
52
+ return true;
53
+ }
54
+ return libphonenumberJs.isPossiblePhoneNumber(value, 'RU');
55
+ };
56
+ const emailValidation = value => {
57
+ // from https://emailregex.com/
58
+ if (!value) {
59
+ return true;
60
+ }
61
+
62
+ // from https://www.regular-expressions.info/email.html
63
+ const regexp = /^[a-za-яёЁ0-9_-]+(?:\.[a-za-яёЁ0-9_-]+)*@(?:[a-za-яёЁ0-9](?:[a-za-яёЁ0-9-]*[a-za-яёЁ0-9])?\.)+[a-za-яёЁ0-9]+$/;
64
+ return regexp.test(String(value).toLowerCase());
65
+ };
66
+ const dateValidation = value => {
67
+ const valueDate = value instanceof Date ? value : new Date(value);
68
+ const isDateValid = !isNaN(valueDate.getTime());
69
+ return isDateValid;
70
+ };
71
+ const addRequiredFieldsParamToSchema = schema => {
72
+ const fields = Object.entries(schema.fields);
73
+ schema.requiredFields = fields.reduce((list, [fieldName, validationProps]) => {
74
+ if (validationProps.exclusiveTests?.required) {
75
+ list.push(fieldName);
76
+ }
77
+ return list;
78
+ }, []);
79
+ return schema;
80
+ };
81
+
82
+ /**
83
+ * Sets the `innerError.message` in an `errors` object at the key
84
+ * defined by `innerError.path`.
85
+ * @param {Object} errors The object to set the error in.
86
+ * @param {{ path: string, message: string }} innerError A `yup` field error.
87
+ * @returns {Object} The result of setting the new error message onto `errors`.
88
+ */
89
+ const setInError = (errors, innerError) => {
90
+ return finalForm.setIn(errors, innerError.path, innerError.message);
91
+ };
92
+
93
+ /**
94
+ * Empty object map with no prototype. Used as default
95
+ * value for reducing the `err.inner` array of errors
96
+ * from a `yup~ValidationError`.
97
+ */
98
+ const emptyObj = Object.create(null);
99
+
100
+ /**
101
+ * Takes a `yup` validation schema and returns a function that expects
102
+ * a map of values to validate. If the validation passes, the function resolves to `undefined`
103
+ * (signalling that the values are valid). If the validation doesn't pass, it resolves
104
+ * to a map of invalid field names to errors.
105
+ * @param {import('yup').ObjectSchema} schema `yup` schema definition.
106
+ * @returns {(values: Object) => Promise<?Object>} An async function that expects some `values`
107
+ * and resolves to either `undefined` or a map of field names to error messages.
108
+ */
109
+
110
+ const makeValidate = schema => {
111
+ return async function validate(values) {
112
+ try {
113
+ await schema.validate(values, {
114
+ abortEarly: false
115
+ });
116
+ } catch (error) {
117
+ if (error.inner) {
118
+ return error.inner.reduce(setInError, emptyObj);
119
+ } else {
120
+ console.warn('itcase-forms schema.validate error: An error not related to the form occurred during validation. Validation ignored.');
121
+ }
122
+ }
123
+ };
124
+ };
125
+ function useYupValidationSchema(schema, language) {
126
+ const validate = React$1.useMemo(() => schema && makeValidate(schema), [schema, language]);
127
+ return validate;
128
+ }
129
+
130
+ const defaultFieldProps = {
131
+ width: 'fill',
132
+ direction: 'vertical',
133
+ labelTextColor: 'surfaceTextPrimary',
134
+ labelTextSize: 'm',
135
+ errorMessageTextColor: 'errorTextSecondary',
136
+ errorMessageTextSize: 's',
137
+ dividerFill: 'errorPrimary',
138
+ helpTextColor: 'surfaceTextQuaternary',
139
+ helpTextSize: 's',
140
+ messageTextColor: 'surfaceTextSecondary',
141
+ messageTextSize: 's',
142
+ requiredMessageTextColor: 'warningTextSecondary',
143
+ requiredMessageTextSize: 's',
144
+ showMessage: true
145
+ };
146
+
147
+ function FieldWrapperBase(props) {
148
+ const {
149
+ id,
150
+ className,
151
+ type = 'normal',
152
+ label,
153
+ labelHidden,
154
+ labelTextColor,
155
+ labelTextSize,
156
+ labelTextSizeMobile,
157
+ labelTextSizeTablet,
158
+ labelTextWeight,
159
+ desc,
160
+ descTextColor,
161
+ descTextSize,
162
+ descTextWeight,
163
+ errorKey,
164
+ errorMessage,
165
+ isErrorState,
166
+ metaError,
167
+ helpTextColorSuccess,
168
+ isDisabled,
169
+ afterItem,
170
+ beforeItem,
171
+ dataTour,
172
+ dividerDirection,
173
+ dividerFill,
174
+ dividerSize,
175
+ dividerWidth,
176
+ fieldClassName,
177
+ helpText,
178
+ helpTextColor,
179
+ helpTextSize,
180
+ helpTextSizeMobile,
181
+ helpTextWeight,
182
+ inputName,
183
+ inputValue,
184
+ messageTextSize,
185
+ metaActive,
186
+ showDivider,
187
+ showMessage,
188
+ tag: Tag = 'div',
189
+ before,
190
+ after,
191
+ isHidden,
192
+ isRequired,
193
+ isValidState,
194
+ children
195
+ } = props;
196
+ const formFieldClass = React$1.useMemo(() => clsx__default.default(className, isValidState && 'form__item_state_success', isRequired && 'form__item_state_required', isDisabled && 'form__item_state_disabled', metaActive && 'form__item_state_focus', inputValue && 'form__item_state_filled', isErrorState && `form__item_state_${errorKey}`), [className, isErrorState, isValidState, isRequired, metaActive, inputValue, isDisabled, metaError]);
197
+ const fieldClass = React$1.useMemo(() => clsx__default.default(fieldClassName, isValidState && `${fieldClassName}_state_success`, metaActive && `${fieldClassName}_state_focus`, inputValue && `${fieldClassName}_state_filled`, isDisabled && `${fieldClassName}_state_disabled`, isErrorState && `${fieldClassName}_state_${errorKey}`), [fieldClassName, isErrorState, isValidState, metaActive, inputValue, isDisabled, metaError]);
198
+ const sizeClass = useDeviceTargetClass.useDeviceTargetClass(props, {
199
+ prefix: 'form-field_size_',
200
+ propsKey: 'size'
201
+ });
202
+ const fillClass = useDeviceTargetClass.useDeviceTargetClass(props, {
203
+ prefix: 'fill_',
204
+ propsKey: 'fill'
205
+ });
206
+ const inputFillClass = useDeviceTargetClass.useDeviceTargetClass(props, {
207
+ prefix: 'fill_',
208
+ propsKey: 'inputFill'
209
+ });
210
+ const shapeClass = useDeviceTargetClass.useDeviceTargetClass(props, {
211
+ prefix: 'form-field_shape_',
212
+ propsKey: 'shape'
213
+ });
214
+ const inputShapeClass = useDeviceTargetClass.useDeviceTargetClass(props, {
215
+ prefix: 'form-field__item-value_shape_',
216
+ propsKey: 'inputShape'
217
+ });
218
+ const directionClass = useDeviceTargetClass.useDeviceTargetClass(props, {
219
+ prefix: 'direction_',
220
+ propsKey: 'direction'
221
+ });
222
+ const widthClass = useDeviceTargetClass.useDeviceTargetClass(props, {
223
+ prefix: 'width_',
224
+ propsKey: 'width'
225
+ });
226
+ const {
227
+ styles: formFieldStyles
228
+ } = useStyles.useStyles(props);
229
+ const errorTextSize = props[`${errorKey}MessageTextSize`];
230
+ const errorTextColor = props[`${errorKey}MessageTextColor`];
231
+ const errorTextWeight = props[`${errorKey}MessageTextWeight`];
232
+ return /*#__PURE__*/React__default.default.createElement(Tag, {
233
+ className: clsx__default.default(formFieldClass, 'form__item', 'form-field', type && `form-field_type_${type}`, sizeClass, fillClass, shapeClass, isDisabled && `form-field_state_disabled`, isHidden && `form-field_state_hidden`, directionClass, widthClass),
234
+ "data-test-id": `${inputName}Field`,
235
+ "data-tour": dataTour,
236
+ style: formFieldStyles
237
+ }, before, (label || labelHidden) && /*#__PURE__*/React__default.default.createElement("div", {
238
+ className: clsx__default.default('form-field__label'),
239
+ "data-test-id": `${inputName}FieldLabel`,
240
+ htmlFor: id
241
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
242
+ size: labelTextSize,
243
+ textColor: labelTextColor,
244
+ textWeight: labelTextWeight,
245
+ sizeMobile: labelTextSizeMobile,
246
+ sizeTablet: labelTextSizeTablet
247
+ }, label, labelHidden && '\u00A0')), desc && /*#__PURE__*/React__default.default.createElement("div", {
248
+ className: "form-field__desc",
249
+ "data-test-id": `${inputName}FieldDesc`
250
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
251
+ size: descTextSize,
252
+ textColor: descTextColor,
253
+ textWeight: descTextWeight
254
+ }, desc)), /*#__PURE__*/React__default.default.createElement("div", {
255
+ className: clsx__default.default('form-field__content', inputFillClass, inputShapeClass)
256
+ }, /*#__PURE__*/React__default.default.createElement("div", {
257
+ className: clsx__default.default('form-field__content-inner', fieldClass)
258
+ }, beforeItem, children, afterItem), showDivider && /*#__PURE__*/React__default.default.createElement(Divider.Divider, {
259
+ className: "form-field__item-divider",
260
+ width: dividerWidth,
261
+ direction: dividerDirection,
262
+ size: dividerSize,
263
+ fill: dividerFill
264
+ })), showMessage && /*#__PURE__*/React__default.default.createElement("div", {
265
+ className: "form-field__message",
266
+ "data-test-id": `${inputName}FieldMessage`
267
+ }, isErrorState && errorMessage && /*#__PURE__*/React__default.default.createElement(Text.Text, {
268
+ id: `${inputName}-error`,
269
+ className: "form-field__message-item form-field__message-item_type-error",
270
+ size: errorTextSize,
271
+ textColor: errorTextColor,
272
+ textWeight: errorTextWeight,
273
+ dataTestId: `${inputName}FieldMessageError`
274
+ }, errorMessage), Boolean(helpText) && (!isErrorState || !errorMessage) && /*#__PURE__*/React__default.default.createElement(Text.Text, {
275
+ className: "form-field__message-item form-field__message-item_type_help-text",
276
+ size: helpTextSize,
277
+ textColor: isValidState ? helpTextColorSuccess : helpTextColor,
278
+ textWeight: helpTextWeight,
279
+ dataTestId: `${inputName}FieldMessageHelpText`,
280
+ sizeMobile: helpTextSizeMobile
281
+ }, helpText), (!isErrorState && !helpText || isErrorState && !helpText && !errorMessage) && /*#__PURE__*/React__default.default.createElement(Text.Text, {
282
+ className: "form-field__message-item form-field__message-item_type_help-text",
283
+ size: messageTextSize,
284
+ dataTestId: `${inputName}FieldMessageHelpText`
285
+ }, '\u00A0')), after);
286
+ }
287
+ function FieldWrapper(props) {
288
+ const {
289
+ inputName
290
+ } = props;
291
+ const {
292
+ change
293
+ } = reactFinalForm.useForm(); // , mutators
294
+
295
+ React$1.useEffect(() => {
296
+ return () => {
297
+ change(inputName, undefined);
298
+ };
299
+ }, []);
300
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapperBase, props);
301
+ }
302
+
303
+ // Whether to display an error message based on "fieldProps" and meta-objects
304
+ function useFieldValidationState(props) {
305
+ const {
306
+ fieldProps = {},
307
+ meta = {},
308
+ input = {}
309
+ } = props;
310
+ // Determines if there's a submission error that hasn't been rectified since the last submission.
311
+ const submitError = !meta.modifiedSinceLastSubmit && meta.submitError;
312
+
313
+ // Determines a key for the error, defaulting to 'error' if no specific key is found.
314
+ const errorKey = meta.error?.key || 'error';
315
+ const successKey = 'success';
316
+
317
+ // Determines if the field is in an error state based on various conditions.
318
+ const isErrorState = React$1.useMemo(() => {
319
+ if (fieldProps.showErrorsOnSubmit) {
320
+ return Boolean(meta.submitFailed && meta.touched && (meta.error || submitError));
321
+ } else {
322
+ return Boolean(meta.touched && (meta.error || submitError));
323
+ }
324
+ }, [fieldProps.showErrorsOnSubmit, meta.submitFailed, meta.touched, meta.error, submitError]);
325
+
326
+ // Determines if the field's input state is valid
327
+ const isValidState = React$1.useMemo(() => {
328
+ const hasValue = Array.isArray(input?.value) ? input?.value.length : input?.value;
329
+ const isModifiedAfterSubmit = meta.modifiedSinceLastSubmit && !meta.error && submitError;
330
+ return Boolean(hasValue && (meta.valid || isModifiedAfterSubmit));
331
+ }, [input?.value, meta.valid, meta.error, submitError, meta.modifiedSinceLastSubmit]);
332
+ const errorMessage = React$1.useMemo(() => {
333
+ // If final-form field has error in "meta" render-property.
334
+ // If field not modified after last form submit - use submit error
335
+ const error = meta.error || submitError || false;
336
+ if (error) {
337
+ // And error in "meta" is string
338
+ if (typeof error === 'string') {
339
+ // Return error as message
340
+ return error;
341
+ }
342
+ // Or if error in "meta" has "message" property(is object of error)
343
+ if (error.message) {
344
+ // Return message from error
345
+ return error.message;
346
+ }
347
+ }
348
+
349
+ // Field doesn't have error message
350
+ return '';
351
+ }, [meta.error, submitError]);
352
+ return {
353
+ errorKey,
354
+ successKey,
355
+ isErrorState,
356
+ isValidState,
357
+ errorMessage
358
+ };
359
+ }
360
+
361
+ // This hook changes the props of the child component depending on the type of error,
362
+ // looks at what props were in initialProps, if they are there then changes
363
+ function useValidationAppearanceInputProps(props) {
364
+ const {
365
+ validationStateKey,
366
+ inputProps
367
+ } = props;
368
+
369
+ // TODO: need to add props that can change during errors in this field
370
+ const validationAppearanceInputProps = React$1.useMemo(() => {
371
+ // const resultAppearanceProps = {
372
+ // messageTextColor: props.errorMessageTextColor,
373
+ // messageTextSize: props.errorMessageTextSize,
374
+ // messageTextWeight: props.errorMessageTextWeight,
375
+ // // Override appearance(styled) props for child input
376
+ // inputProps: {},
377
+ // }
378
+ const updatedInputProps = {};
379
+ if (validationStateKey) {
380
+ Object.entries(inputProps).forEach(([propKey, propValue]) => {
381
+ // Convert the input property key to "snake_case" format.
382
+ // e.g. "requiredBorderColor" -> "required_border_color".
383
+ const propKeySnake = snakeCase__default.default(propKey);
384
+ // Check if this property is for appearance.
385
+ // Key maybe starts with: "error", "required", "success", etc from validation config.
386
+ const isPropForValidationState = propKeySnake.startsWith(`${validationStateKey}_`);
387
+
388
+ // If property is for appearance
389
+ if (isPropForValidationState) {
390
+ // Remove validation state part from begin of property key, to make clean appearance property.
391
+ // e.g. "required_border_color" -> "border_color".
392
+ const stateTargetKeySnake = propKeySnake.replace(`${validationStateKey}_`, '');
393
+ // Convert clean appearance property key to "camelCase" format.
394
+ // e.g. "border_color" -> "borderColor"
395
+ const stateTargetKey = camelCase__default.default(stateTargetKeySnake);
396
+ // And save the value with a new clean property key
397
+ updatedInputProps[stateTargetKey] = propValue;
398
+ // Else if not already added earlier
399
+ } else if (!updatedInputProps[propKey]) {
400
+ // Just save original property
401
+ updatedInputProps[propKey] = propValue;
402
+ }
403
+ });
404
+ }
405
+ return updatedInputProps;
406
+ }, [validationStateKey, inputProps]);
407
+ return validationAppearanceInputProps;
408
+ }
409
+
410
+ const defaultCheckboxProps = {
411
+ appearance: 'defaultPrimary',
412
+ width: 'fill',
413
+ errorBorderColor: 'errorBorderSecondary',
414
+ requiredBorderColor: 'warningBorderSecondary'
415
+ };
416
+
417
+ const CheckboxField = /*#__PURE__*/React__default.default.memo(function CheckboxField(props) {
418
+ const {
419
+ name,
420
+ initialValue,
421
+ isDisabled,
422
+ classNameGroupItem,
423
+ fieldProps = {},
424
+ inputProps = {},
425
+ showMessage,
426
+ isRequired,
427
+ onChange
428
+ } = props;
429
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
430
+ type: "checkbox",
431
+ name: name,
432
+ initialValue: initialValue
433
+ }, function Render({
434
+ input,
435
+ meta
436
+ }) {
437
+ /** Note:
438
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
439
+ * React Hooks cannot be called inside a callback.
440
+ * React Hooks must be called in a React function component or a
441
+ * custom React Hook function.
442
+ */
443
+
444
+ const onChangeField = React$1.useCallback(event => {
445
+ input.onChange(event);
446
+ if (onChange) {
447
+ onChange(event.target.checked, input.name);
448
+ }
449
+ }, [onChange, input.onChange]);
450
+ const {
451
+ errorKey,
452
+ errorMessage,
453
+ isErrorState,
454
+ isValidState
455
+ } = useFieldValidationState({
456
+ fieldProps: fieldProps,
457
+ input: input,
458
+ meta: meta
459
+ });
460
+ const updatedInputProps = useValidationAppearanceInputProps({
461
+ inputProps: inputProps,
462
+ validationStateKey: isErrorState ? errorKey : 'success'
463
+ });
464
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
465
+ className: clsx__default.default('form-field_type_checkbox', 'form__item_type_checkbox', classNameGroupItem),
466
+ errorKey: errorKey,
467
+ errorMessage: errorMessage,
468
+ isErrorState: isErrorState,
469
+ metaError: meta.error,
470
+ isDisabled: isDisabled,
471
+ fieldClassName: "form-checkbox",
472
+ inputName: input.name,
473
+ inputValue: input.checked,
474
+ metaActive: meta.active,
475
+ showMessage: showMessage,
476
+ tag: "label",
477
+ isRequired: isRequired,
478
+ isValidState: isValidState
479
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Checkbox.Checkbox, Object.assign({
480
+ type: "checkbox",
481
+ name: input.name,
482
+ isDisabled: isDisabled,
483
+ autoComplete: "nope",
484
+ checked: input.checked,
485
+ onBlur: input.onBlur,
486
+ onChange: onChangeField,
487
+ onFocus: input.onFocus
488
+ }, updatedInputProps)));
489
+ });
490
+ });
491
+
492
+ const defaultChoiceProps = {
493
+ width: 'fill',
494
+ borderColor: 'surfaceBorderTertiary',
495
+ // error
496
+ errorBorderColor: 'errorBorderPrimary',
497
+ fill: 'surfaceSecondary',
498
+ fillActive: 'accentPrimary',
499
+ fillActiveDisabled: 'surfaceTertiary',
500
+ fillHover: 'surfacePrimaryHover',
501
+ indicatorFill: 'accentPrimary',
502
+ labelTextActiveColor: 'accentTextPrimary',
503
+ labelTextActiveColorDisabled: 'surfaceTextDisabled',
504
+ labelTextColor: 'surfaceTextPrimary',
505
+ labelTextColorDisabled: 'surfaceTextDisabled',
506
+ labelTextSize: 'm',
507
+ requiredBorderColor: 'warningBorderPrimary',
508
+ shape: 'rounded'
509
+ };
510
+
511
+ const ChoiceField = /*#__PURE__*/React__default.default.memo(function ChoiceField(props) {
512
+ const {
513
+ name,
514
+ initialValue,
515
+ label,
516
+ isDisabled,
517
+ classNameGroupItem,
518
+ fieldProps,
519
+ inputProps,
520
+ messageType,
521
+ options,
522
+ placeholder,
523
+ showMessage,
524
+ isCheckbox,
525
+ isRequired,
526
+ onChange
527
+ } = props;
528
+ const {
529
+ change
530
+ } = reactFinalForm.useForm();
531
+ const setActiveSegment = React$1.useCallback((option, isChecked) => {
532
+ change(name, isChecked && option.value);
533
+ if (onChange) {
534
+ onChange(option.value, name, isChecked);
535
+ }
536
+ }, [change, onChange]);
537
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
538
+ initialValue: initialValue,
539
+ name: name
540
+ }, function Render({
541
+ input,
542
+ meta
543
+ }) {
544
+ /** Note:
545
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
546
+ * React Hooks cannot be called inside a callback.
547
+ * React Hooks must be called in a React function component or a
548
+ * custom React Hook function.
549
+ */
550
+ const activeOption = React$1.useMemo(() => {
551
+ const emptyOption = {
552
+ value: null,
553
+ label: null
554
+ };
555
+ if (input.value) {
556
+ const currentOption = options.find(option => option.value === input.value);
557
+ return currentOption || emptyOption;
558
+ }
559
+ return emptyOption;
560
+ }, [input.value]);
561
+ const {
562
+ isErrorState,
563
+ isValidState,
564
+ errorKey,
565
+ errorMessage
566
+ } = useFieldValidationState({
567
+ fieldProps: fieldProps,
568
+ input: input,
569
+ meta: meta
570
+ });
571
+ const updatedInputProps = useValidationAppearanceInputProps({
572
+ inputProps: inputProps,
573
+ validationStateKey: isErrorState ? errorKey : 'success'
574
+ });
575
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
576
+ className: clsx__default.default('form-field_type_choice', 'form__item_type_choice', classNameGroupItem),
577
+ label: label,
578
+ errorKey: errorKey,
579
+ errorMessage: errorMessage,
580
+ isErrorState: isErrorState,
581
+ metaError: meta.error,
582
+ isDisabled: isDisabled,
583
+ fieldClassName: "form-choice",
584
+ inputName: input.name,
585
+ inputValue: input.value || [],
586
+ messageType: messageType,
587
+ metaActive: meta.active,
588
+ showMessage: showMessage,
589
+ isRequired: isRequired,
590
+ isValidState: isValidState
591
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Choice.Choice, Object.assign({
592
+ className: clsx__default.default(meta.active && 'form-choice_state_focus', meta.error && meta.touched && `form-choice_state_${errorKey}`),
593
+ name: input.name,
594
+ isDisabled: isDisabled,
595
+ active: activeOption,
596
+ inputValue: input.value || [],
597
+ options: options,
598
+ placeholder: placeholder,
599
+ isCheckbox: isCheckbox,
600
+ isRequired: isRequired,
601
+ setActiveSegment: setActiveSegment
602
+ }, updatedInputProps)));
603
+ });
604
+ });
605
+
606
+ const CustomField = /*#__PURE__*/React__default.default.memo(function CustomField(props) {
607
+ const {
608
+ Component,
609
+ isDisabled,
610
+ isRequired,
611
+ name,
612
+ initialValue,
613
+ fieldProps = {},
614
+ classNameGroupItem,
615
+ showMessage,
616
+ clearIcon,
617
+ clearIconFill,
618
+ clearIconFillHover,
619
+ clearIconShape,
620
+ clearIconSize,
621
+ onClickClearIcon
622
+ } = props;
623
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
624
+ initialValue: initialValue,
625
+ name: name
626
+ }, function Render({
627
+ input,
628
+ meta
629
+ }) {
630
+ /** Note:
631
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
632
+ * React Hooks cannot be called inside a callback.
633
+ * React Hooks must be called in a React function component or a
634
+ * custom React Hook function.
635
+ */
636
+
637
+ const {
638
+ isErrorState,
639
+ isValidState,
640
+ errorKey,
641
+ errorMessage
642
+ } = useFieldValidationState({
643
+ fieldProps: fieldProps,
644
+ input: input,
645
+ meta: meta
646
+ });
647
+ const updatedInputProps = useValidationAppearanceInputProps({
648
+ validationStateKey: isErrorState ? errorKey : 'success',
649
+ // For "Custom" field we pass all props. Can contain some special props, we don't known.
650
+ inputProps: props
651
+ });
652
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
653
+ className: clsx__default.default('form-field_type_custom', 'form__item_type_custom', classNameGroupItem),
654
+ errorKey: errorKey,
655
+ errorMessage: errorMessage,
656
+ fieldClassName: 'form-custom',
657
+ inputName: input.name,
658
+ inputValue: input.value,
659
+ isDisabled: isDisabled,
660
+ isErrorState: isErrorState,
661
+ isRequired: isRequired,
662
+ isValidState: isValidState,
663
+ metaActive: meta.active,
664
+ metaError: meta.error,
665
+ showMessage: showMessage
666
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Component, Object.assign({}, updatedInputProps, {
667
+ input: input,
668
+ isDisabled: isDisabled,
669
+ meta: meta
670
+ })), clearIcon && /*#__PURE__*/React__default.default.createElement(Icon.Icon, {
671
+ className: "form-field__icon",
672
+ iconFill: clearIconFill,
673
+ iconFillHover: clearIconFillHover,
674
+ imageSrc: clearIcon,
675
+ shape: clearIconShape,
676
+ size: clearIconSize,
677
+ SvgImage: clearIcon,
678
+ onClick: onClickClearIcon
679
+ }));
680
+ });
681
+ });
682
+
683
+ const defaultCodeProps = {
684
+ fieldProps: {
685
+ size: 'l',
686
+ labelTextColor: 'surfaceTextPrimary',
687
+ labelTextSize: 's',
688
+ labelTextWeight: 'normal',
689
+ helpText: 'Supporting text',
690
+ helpTextColor: 'surfaceTextPrimary',
691
+ helpTextSize: 's',
692
+ helpTextWeight: 'normal',
693
+ showMessage: true
694
+ },
695
+ inputProps: {
696
+ width: 'fill',
697
+ size: 'l',
698
+ fill: 'surfaceSecondary',
699
+ inputBorderColor: 'surfaceBorderTertiary',
700
+ inputBorderColorHover: 'surfaceBorderQuaternary',
701
+ inputBorderFocusColor: 'surfaceBorderAccent',
702
+ inputCaretColor: 'surfaceItemAccent',
703
+ inputFill: 'surfacePrimary',
704
+ inputFillHover: 'surfaceSecondary',
705
+ inputPlaceholderTextColor: 'surfaceSecondary',
706
+ inputSize: 'l',
707
+ inputTextColor: 'surfaceSecondary',
708
+ inputTextSize: 'xxl',
709
+ inputTextWeight: 'normal'
710
+ }
711
+ };
712
+
713
+ const CodeField = /*#__PURE__*/React__default.default.memo(function CodeField(props) {
714
+ const {
715
+ name,
716
+ initialValue,
717
+ isDisabled,
718
+ classNameGroupItem,
719
+ fieldProps = {},
720
+ inputProps = {},
721
+ showMessage,
722
+ isRequired
723
+ } = props;
724
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
725
+ name: name,
726
+ initialValue: initialValue
727
+ }, function Render({
728
+ input,
729
+ meta
730
+ }) {
731
+ /** Note:
732
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
733
+ * React Hooks cannot be called inside a callback.
734
+ * React Hooks must be called in a React function component or a
735
+ * custom React Hook function.
736
+ */
737
+
738
+ const {
739
+ isErrorState,
740
+ isValidState,
741
+ errorKey} = useFieldValidationState({
742
+ fieldProps: fieldProps,
743
+ input: input,
744
+ meta: meta
745
+ });
746
+ const updatedInputProps = useValidationAppearanceInputProps({
747
+ inputProps: inputProps,
748
+ validationStateKey: isErrorState ? errorKey : 'success'
749
+ });
750
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
751
+ className: clsx__default.default('form-field_type_code', 'form__item_type_code', classNameGroupItem),
752
+ fieldClassName: 'form-code',
753
+ inputName: input.name,
754
+ inputValue: input.value,
755
+ metaActive: meta.active,
756
+ showMessage: showMessage,
757
+ isRequired: isRequired,
758
+ isValidState: isValidState
759
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Code.Code, Object.assign({
760
+ name: input.name,
761
+ isDisabled: isDisabled,
762
+ autoComplete: "nope",
763
+ value: input.value,
764
+ onBlur: input.onBlur,
765
+ onChange: input.onChange,
766
+ onFocus: input.onFocus
767
+ }, updatedInputProps)));
768
+ });
769
+ });
770
+
771
+ const defaultDatepickerProps = {
772
+ dateFormat: 'dd/MM/yyyy - HH:mm',
773
+ readOnly: false,
774
+ selectsRange: false,
775
+ showTimeSelect: true,
776
+ timeCaption: 'Время',
777
+ timeFormat: 'p',
778
+ timeIntervals: 60,
779
+ isClearable: true,
780
+ isStartDefaultNull: true
781
+ };
782
+
783
+ function DatePickerField(props) {
784
+ const {
785
+ name,
786
+ isDisabled,
787
+ classNameGroupItem,
788
+ datePickerProps,
789
+ fieldProps = {},
790
+ inputProps = {},
791
+ showMessage,
792
+ isRequired,
793
+ onChange
794
+ } = props;
795
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
796
+ name: name
797
+ }, function Render({
798
+ input,
799
+ meta
800
+ }) {
801
+ /** Note:
802
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
803
+ * React Hooks cannot be called inside a callback.
804
+ * React Hooks must be called in a React function component or a
805
+ * custom React Hook function.
806
+ */
807
+
808
+ const onChangeField = React$1.useCallback((startDate, endDate) => {
809
+ if (!datePickerProps.selectsRange) {
810
+ // When we need to save single date, value is date
811
+ // TODO: make object with one date? need to check all forms with DatePickerField
812
+ input.onChange(startDate);
813
+ } else {
814
+ // When we need to save range, value is object with two date
815
+ input.onChange({
816
+ endDate,
817
+ startDate
818
+ });
819
+ }
820
+ if (onChange) {
821
+ onChange(startDate, endDate);
822
+ }
823
+ }, [input.onChange, onChange]);
824
+ const {
825
+ errorKey,
826
+ errorMessage,
827
+ isErrorState,
828
+ isValidState
829
+ } = useFieldValidationState({
830
+ fieldProps: fieldProps,
831
+ input: input,
832
+ meta: meta
833
+ });
834
+ const updatedInputProps = useValidationAppearanceInputProps({
835
+ inputProps: inputProps,
836
+ validationStateKey: isErrorState ? errorKey : 'success'
837
+ });
838
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
839
+ className: clsx__default.default('form-field_type_datepicker', 'form__item_type_datepicker', classNameGroupItem),
840
+ errorKey: errorKey,
841
+ errorMessage: errorMessage,
842
+ isErrorState: isErrorState,
843
+ metaError: meta.error,
844
+ isDisabled: isDisabled,
845
+ fieldClassName: "form-datepicker",
846
+ inputName: input.name,
847
+ inputValue: input.value || '',
848
+ metaActive: meta.active,
849
+ showMessage: showMessage,
850
+ isRequired: isRequired,
851
+ isValidState: isValidState
852
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(DatePicker.DatePickerInput, {
853
+ name: input.name,
854
+ isDisabled: isDisabled,
855
+ datePickerProps: datePickerProps,
856
+ endValue: datePickerProps.selectsRange ? input.value.endDate : null,
857
+ inputProps: updatedInputProps,
858
+ value: datePickerProps.selectsRange ? input.value.startDate : input.value,
859
+ onBlur: input.onBlur,
860
+ onChange: onChangeField,
861
+ onFocus: input.onFocus
862
+ }));
863
+ });
864
+ }
865
+
866
+ const defaultDropzoneProps = {
867
+ fill: 'surfacePrimary',
868
+ borderColor: 'surfaceBorderTertiary',
869
+ borderColorHover: 'surfaceBorderQuaternary',
870
+ hintTitle: 'Перетащите изображение или выберите файл с компьютера',
871
+ hintTitleTextColor: 'surfaceTextPrimary',
872
+ hintTitleTextSize: 'm',
873
+ removeThumbAppearance: 'dangerPrimary sizeM',
874
+ removeThumbShape: 'rounded',
875
+ shape: 'rounded',
876
+ showFilename: true,
877
+ thumbBorderColor: 'surfaceBorderTertiary',
878
+ thumbBorderColorHover: 'surfaceBorderQuaternary',
879
+ thumbBorderWidth: 1,
880
+ thumbNameTextColor: 'surfaceTextPrimary',
881
+ thumbNameTextSize: 's',
882
+ isPreviews: true
883
+ };
884
+
885
+ const FileInputDropzone = /*#__PURE__*/React__default.default.memo(function FileInputDropzone(props) {
886
+ const {
887
+ className,
888
+ maxFiles,
889
+ maxSize,
890
+ size,
891
+ fileErrorText,
892
+ dropzoneProps = {},
893
+ hintDescription,
894
+ hintTitle,
895
+ inputName,
896
+ inputValue,
897
+ showFilename,
898
+ thumbColumn,
899
+ isPreviews,
900
+ onAddFiles,
901
+ onDeleteFile
902
+ } = props;
903
+
904
+ // TODO: delete react-final-form things out of here?
905
+ const {
906
+ change
907
+ } = reactFinalForm.useForm();
908
+ const [fileError, setFileError] = React$1.useState('');
909
+ const [fileIsLoading, setFileIsLoading] = React$1.useState(false);
910
+ const filesList = React$1.useMemo(() => inputValue ? castArray__default.default(inputValue) : [], [inputValue]);
911
+ const changeFormState = React$1.useCallback(newFiles => {
912
+ // If max files in dropzone is 1 - return file as it self, else as array of files
913
+ // ps: for old projects compatibility
914
+ const toSave = dropzoneProps.maxFiles == 1 ? newFiles[0] : newFiles;
915
+ change(inputName, toSave);
916
+ return toSave;
917
+ },
918
+ // If "inputName" will be changes, then it should be a different field
919
+ // eslint-disable-next-line react-hooks/exhaustive-deps
920
+ [dropzoneProps, change]);
921
+
922
+ //
923
+ const convertFiledValueAndSaveAsFiles = React$1.useCallback(async currentFilesList => {
924
+ setFileIsLoading(true);
925
+ const newFiles = [];
926
+ for (const fileItem of currentFilesList) {
927
+ if (typeof fileItem === 'string') {
928
+ const newFile = await convertToFile(fileItem, isPreviews);
929
+ if (newFile) {
930
+ newFiles.push(newFile);
931
+ }
932
+ } else {
933
+ newFiles.push(fileItem);
934
+ }
935
+ }
936
+ changeFormState(newFiles);
937
+ setFileIsLoading(false);
938
+ }, [isPreviews, changeFormState]);
939
+
940
+ // Delete file from dropzone
941
+ const removeFile = React$1.useCallback((event, index) => {
942
+ event.stopPropagation();
943
+ event.preventDefault();
944
+ const newFiles = [...filesList];
945
+ newFiles.splice(index, 1);
946
+ if (onDeleteFile) {
947
+ onDeleteFile(filesList[index], inputName);
948
+ }
949
+ changeFormState(newFiles);
950
+ },
951
+ // If "inputName" will be changes, then it should be a different field
952
+ // eslint-disable-next-line react-hooks/exhaustive-deps
953
+ [filesList, changeFormState, onDeleteFile]);
954
+
955
+ // Create dropzone options
956
+ const {
957
+ getInputProps,
958
+ getRootProps
959
+ } = reactDropzone.useDropzone({
960
+ maxFiles: maxFiles || 5,
961
+ maxSize: maxSize || 10485760,
962
+ // 10mb
963
+ // accept: { 'image/*': [] },
964
+ ...dropzoneProps,
965
+ getFilesFromEvent: async event => {
966
+ const result = await fileSelector.fromEvent(event);
967
+ const newFiles = result.filter(item => item instanceof File);
968
+ // Add exists and new files to accepted(or rejected)
969
+ return [...filesList, ...newFiles];
970
+ },
971
+ onDropAccepted: acceptedFiles => {
972
+ // If dropped files has accepted and we need a previews
973
+ if (isPreviews) {
974
+ // Add preview to every file
975
+ acceptedFiles.forEach(file => {
976
+ if (!file.error) {
977
+ file.preview = URL.createObjectURL(file);
978
+ }
979
+ });
980
+ }
981
+ // Save to form data (including empty when files are not valid)
982
+ const filesToSave = changeFormState(acceptedFiles);
983
+ setFileError('');
984
+
985
+ // Save DataURL for all files
986
+ const readerPromisesList = acceptedFiles.map(file => {
987
+ return new Promise(resolve => setFileDataURL(file, resolve));
988
+ });
989
+ // Save files to form values
990
+ Promise.all(readerPromisesList).then(() => {
991
+ if (onAddFiles) {
992
+ onAddFiles(filesToSave, inputName);
993
+ }
994
+ });
995
+ },
996
+ onDropRejected: rejectedFiles => {
997
+ // If dropped files has rejected
998
+ if (rejectedFiles.length) {
999
+ let fileErrorMessage = 'Ошибка при добавлении файла';
1000
+ const firstFileErrorItem = rejectedFiles[0].errors[0];
1001
+ if (firstFileErrorItem) {
1002
+ if (firstFileErrorItem.code === reactDropzone.ErrorCode.TooManyFiles) {
1003
+ fileErrorMessage = `Максимальное количество файлов: ${maxFiles}`;
1004
+ } else {
1005
+ fileErrorMessage = firstFileErrorItem.message;
1006
+ }
1007
+ }
1008
+ // Show error
1009
+ setFileError(fileErrorMessage);
1010
+ } else {
1011
+ // Else clean error
1012
+ setFileError('');
1013
+ }
1014
+ }
1015
+ });
1016
+ React$1.useEffect(() => {
1017
+ const currentFilesList = castArray__default.default(inputValue);
1018
+ const isNeedToConvert = currentFilesList.some(fileItem => typeof fileItem === 'string');
1019
+ if (isNeedToConvert) {
1020
+ // First time convert value to Files and save to local and form state
1021
+ convertFiledValueAndSaveAsFiles(currentFilesList);
1022
+ }
1023
+
1024
+ // Make sure to revoke the data uris to avoid memory leaks, will run on unmount
1025
+ return () => {
1026
+ filesList.forEach(file => {
1027
+ if (file?.preview) {
1028
+ URL.revokeObjectURL(file.preview);
1029
+ }
1030
+ });
1031
+ };
1032
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1033
+ }, [inputValue]);
1034
+ const propsGenerator = useDevicePropsGenerator.useDevicePropsGenerator(props);
1035
+ const {
1036
+ fillClass,
1037
+ fillHoverClass,
1038
+ borderColorClass,
1039
+ borderColorHoverClass,
1040
+ borderTypeClass,
1041
+ borderWidthClass,
1042
+ errorMessageTextColor,
1043
+ errorMessageTextSize,
1044
+ errorMessageTextWeight,
1045
+ hintDescriptionTextColor,
1046
+ hintDescriptionTextSize,
1047
+ hintDescriptionTextWeight,
1048
+ hintDescriptionTextWrap,
1049
+ hintTitleTextColor,
1050
+ hintTitleTextSize,
1051
+ hintTitleTextWeight,
1052
+ hintTitleTextWrap,
1053
+ removeThumbAppearance,
1054
+ removeThumbShape,
1055
+ removeThumbText,
1056
+ removeThumbTextWeight,
1057
+ shapeClass,
1058
+ thumbBorderColorClass,
1059
+ thumbBorderColorHoverClass,
1060
+ thumbBorderTypeClass,
1061
+ thumbBorderWidthClass,
1062
+ thumbDirectionClass,
1063
+ thumbNameTextColor,
1064
+ thumbNameTextSize,
1065
+ thumbNameTextWeight,
1066
+ thumbNameTextWrap
1067
+ } = propsGenerator;
1068
+ return /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement("div", getRootProps({
1069
+ className: `form-dropzone__dropzone dropzone ${className} form-dropzone__dropzone_size_${size} ${shapeClass}`
1070
+ }), /*#__PURE__*/React__default.default.createElement("input", Object.assign({}, getInputProps(), {
1071
+ name: inputName
1072
+ })), /*#__PURE__*/React__default.default.createElement("div", {
1073
+ className: clsx__default.default('form-dropzone__dropzone-wrapper', thumbColumn && `form-dropzone__dropzone-wrapper_column_${thumbColumn}`, fillClass && `fill_${fillClass}`, fillHoverClass && `fill_hover_${fillHoverClass}`, borderColorClass && `border-color_${borderColorClass}`, borderColorHoverClass && `border-color_hover_${borderColorHoverClass}`, borderWidthClass && `border-width_${borderWidthClass}`, borderTypeClass)
1074
+ }, filesList.map((file, index) => /*#__PURE__*/React__default.default.createElement("aside", {
1075
+ className: clsx__default.default('form-dropzone__thumb', fillClass, thumbDirectionClass, thumbBorderWidthClass, thumbBorderColorClass, thumbBorderColorHoverClass, thumbBorderTypeClass),
1076
+ key: file.id || `${file.name}_${index}`
1077
+ }, isPreviews && !file.error && /*#__PURE__*/React__default.default.createElement("div", {
1078
+ className: "form-dropzone__thumb-image"
1079
+ }, /*#__PURE__*/React__default.default.createElement("img", {
1080
+ className: "form-dropzone__thumb-image-inner",
1081
+ src: file.preview || file.image,
1082
+ onLoad: () => {
1083
+ // Revoke data uri after image is loaded
1084
+ URL.revokeObjectURL(file.preview);
1085
+ }
1086
+ })), file.error && /*#__PURE__*/React__default.default.createElement("div", null, /*#__PURE__*/React__default.default.createElement(Text.Text, {
1087
+ size: thumbNameTextSize,
1088
+ textColor: thumbNameTextColor,
1089
+ textWeight: thumbNameTextWeight,
1090
+ textWrap: thumbNameTextWrap
1091
+ }, fileErrorText || file.error)), showFilename && /*#__PURE__*/React__default.default.createElement("div", {
1092
+ className: "form-dropzone__thumb-name"
1093
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
1094
+ className: "form-dropzone__thumb-name-inner",
1095
+ size: thumbNameTextSize,
1096
+ textColor: thumbNameTextColor,
1097
+ textWeight: thumbNameTextWeight,
1098
+ textWrap: thumbNameTextWrap
1099
+ }, file.name)), fileIsLoading && /*#__PURE__*/React__default.default.createElement("div", {
1100
+ className: "form-dropzone__thumb-loader"
1101
+ }, /*#__PURE__*/React__default.default.createElement(Loader.Loader, {
1102
+ width: "fill",
1103
+ height: "fill",
1104
+ fill: "surfacePrimary",
1105
+ itemFill: "surfaceItemAccent",
1106
+ set: "simple"
1107
+ })), /*#__PURE__*/React__default.default.createElement("div", {
1108
+ className: clsx__default.default('form-dropzone__thumb-remove')
1109
+ }, /*#__PURE__*/React__default.default.createElement(Button.Button, {
1110
+ className: "form-dropzone__thumb-remove-text",
1111
+ appearance: removeThumbAppearance,
1112
+ label: removeThumbText || 'Удалить',
1113
+ labelTextWeight: removeThumbTextWeight,
1114
+ shape: removeThumbShape,
1115
+ onClick: event => removeFile(event, index)
1116
+ })))), !filesList.length ? /*#__PURE__*/React__default.default.createElement("div", {
1117
+ className: "form-dropzone__hint"
1118
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
1119
+ className: "form-dropzone__hint-title",
1120
+ size: hintTitleTextSize,
1121
+ textColor: hintTitleTextColor,
1122
+ textWeight: hintTitleTextWeight,
1123
+ textWrap: hintTitleTextWrap
1124
+ }, hintTitle || 'Select a file or drag in form'), hintDescription && /*#__PURE__*/React__default.default.createElement(Text.Text, {
1125
+ className: "form-dropzone__hint-text",
1126
+ size: hintDescriptionTextSize,
1127
+ textColor: hintDescriptionTextColor,
1128
+ textWeight: hintDescriptionTextWeight,
1129
+ textWrap: hintDescriptionTextWrap
1130
+ }, hintDescription)) : /*#__PURE__*/React__default.default.createElement("div", {
1131
+ className: "form-dropzone__hint form-dropzone__hint_type_add-more"
1132
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
1133
+ className: "form-dropzone__hint-title",
1134
+ size: hintTitleTextSize,
1135
+ textColor: hintTitleTextColor,
1136
+ textWeight: hintTitleTextWeight,
1137
+ textWrap: hintTitleTextWrap
1138
+ }, hintTitle || 'Select a file or drag in form'), hintDescription && /*#__PURE__*/React__default.default.createElement(Text.Text, {
1139
+ className: "form-dropzone__hint-text",
1140
+ size: hintDescriptionTextSize,
1141
+ textColor: hintDescriptionTextColor,
1142
+ textWeight: hintDescriptionTextWeight,
1143
+ textWrap: hintDescriptionTextWrap
1144
+ }, hintDescription)))), fileError && /*#__PURE__*/React__default.default.createElement("div", {
1145
+ className: "form-field__message"
1146
+ }, /*#__PURE__*/React__default.default.createElement(Text.Text, {
1147
+ className: "form-field__message-item form-field__message-item_type_message",
1148
+ size: errorMessageTextSize,
1149
+ textColor: errorMessageTextColor,
1150
+ textWeight: errorMessageTextWeight
1151
+ }, fileError)));
1152
+ });
1153
+ async function getFileByURL(url) {
1154
+ try {
1155
+ const response = await axios__default.default({
1156
+ url: url,
1157
+ responseType: 'blob'
1158
+ });
1159
+ const blobObject = response.data;
1160
+ const dirtyFilename = response.headers['content-disposition']?.split('filename=')[1];
1161
+ // Remove double quotes
1162
+ let filename = dirtyFilename?.substring(1).slice(0, -1);
1163
+ if (!filename) {
1164
+ filename = url.split('/').at(-1);
1165
+ // const typeParts = blobObject.type.split('/')
1166
+ // const fileType = typeParts[typeParts.length - 1]
1167
+ // filename = `${new Date().getTime()}.${fileType}`
1168
+ }
1169
+ return new File([blobObject], filename, {
1170
+ type: blobObject.type
1171
+ });
1172
+ } catch (error) {
1173
+ console.log('error: ', error);
1174
+ return null;
1175
+ }
1176
+ }
1177
+ async function convertToFile(inputValue, isPreviews) {
1178
+ let newFile = null;
1179
+
1180
+ // Download image by url and save as File instance
1181
+ const isURL = typeof inputValue === 'string' && inputValue.includes('/');
1182
+ if (inputValue.image || isURL) {
1183
+ newFile = await getFileByURL(inputValue.image || inputValue);
1184
+ if (newFile) {
1185
+ setFileDataURL(newFile);
1186
+ }
1187
+ }
1188
+
1189
+ // Convert dataURL to File instance
1190
+ if (inputValue.dataURL) {
1191
+ newFile = common.createFileFromDataURL(inputValue.name || inputValue.path, inputValue.dataURL);
1192
+ newFile.dataURL = inputValue.dataURL;
1193
+ }
1194
+
1195
+ // Save new File to state
1196
+ if (newFile) {
1197
+ newFile.id = inputValue.id;
1198
+ if (isPreviews) {
1199
+ newFile.preview = URL.createObjectURL(newFile);
1200
+ }
1201
+ }
1202
+ return newFile;
1203
+ }
1204
+ function setFileDataURL(file, resolve) {
1205
+ resolve = resolve || (() => {});
1206
+ // Init reader and save his file
1207
+ const reader = new FileReader();
1208
+ reader._readedFile = file;
1209
+
1210
+ // Set handlers
1211
+ reader.onabort = () => resolve();
1212
+ reader.onerror = () => resolve();
1213
+ reader.onload = event => {
1214
+ event.target._readedFile.dataURL = reader.result;
1215
+ resolve();
1216
+ };
1217
+ // Run reader
1218
+ if (file instanceof File) {
1219
+ reader.readAsDataURL(file);
1220
+ } else {
1221
+ resolve();
1222
+ }
1223
+ }
1224
+
1225
+ const FileInput = /*#__PURE__*/React__default.default.memo(function FileInput(props) {
1226
+ const {
1227
+ className,
1228
+ name,
1229
+ width,
1230
+ maxFiles,
1231
+ maxSize,
1232
+ label,
1233
+ fileErrorText,
1234
+ classNameGroupItem,
1235
+ dropzoneProps,
1236
+ fieldProps,
1237
+ hintDescription,
1238
+ hintTitle,
1239
+ showFilename,
1240
+ showMessage,
1241
+ isPreviews,
1242
+ isRequired,
1243
+ onAddFiles,
1244
+ onDeleteFile
1245
+ } = props;
1246
+ const propsGenerator = useDevicePropsGenerator.useDevicePropsGenerator(props);
1247
+ const {
1248
+ size,
1249
+ fill,
1250
+ fillHover,
1251
+ labelTextColor,
1252
+ borderColorHover,
1253
+ borderType,
1254
+ borderWidth,
1255
+ errorMessageTextColor,
1256
+ errorMessageTextSize,
1257
+ errorMessageTextWeight,
1258
+ hintDescriptionTextColor,
1259
+ hintDescriptionTextSize,
1260
+ hintDescriptionTextWeight,
1261
+ hintDescriptionTextWrap,
1262
+ hintTitleTextColor,
1263
+ hintTitleTextSize,
1264
+ hintTitleTextWeight,
1265
+ hintTitleTextWrap,
1266
+ removeThumbAppearance,
1267
+ removeThumbText,
1268
+ removeThumbTextWeight,
1269
+ removeThumbShape,
1270
+ shape,
1271
+ thumbBorderColor,
1272
+ thumbBorderColorHover,
1273
+ thumbBorderType,
1274
+ thumbBorderWidth,
1275
+ thumbColumn = 1,
1276
+ thumbDirection = 'vertical',
1277
+ thumbNameTextColor,
1278
+ thumbNameTextSize,
1279
+ thumbNameTextWeight,
1280
+ thumbNameTextWrap
1281
+ } = propsGenerator;
1282
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1283
+ name: name
1284
+ }, function Render({
1285
+ input,
1286
+ meta
1287
+ }) {
1288
+ /** Note:
1289
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1290
+ * React Hooks cannot be called inside a callback.
1291
+ * React Hooks must be called in a React function component or a
1292
+ * custom React Hook function.
1293
+ */
1294
+
1295
+ const {
1296
+ errorKey,
1297
+ errorMessage,
1298
+ isErrorState,
1299
+ isValidState
1300
+ } = useFieldValidationState({
1301
+ fieldProps: fieldProps,
1302
+ input: input,
1303
+ meta: meta
1304
+ });
1305
+ const updatedInputProps = useValidationAppearanceInputProps({
1306
+ inputProps: props,
1307
+ validationStateKey: isErrorState ? errorKey : 'success'
1308
+ });
1309
+
1310
+ /** TODO:
1311
+ * REFACTOR PROPERTIES
1312
+ */
1313
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
1314
+ className: clsx__default.default('form-field_type_dropzone', 'form__item_type_dropzone', classNameGroupItem),
1315
+ width: width,
1316
+ label: label,
1317
+ labelTextColor: labelTextColor,
1318
+ errorKey: errorKey,
1319
+ errorMessage: errorMessage,
1320
+ isErrorState: isErrorState,
1321
+ metaError: meta.error,
1322
+ fieldClassName: "form-dropzone",
1323
+ inputName: input.name,
1324
+ inputValue: input.value,
1325
+ metaActive: meta.active,
1326
+ metaTouched: meta.touched,
1327
+ showMessage: showMessage,
1328
+ isRequired: isRequired,
1329
+ isValidState: isValidState
1330
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(FileInputDropzone, {
1331
+ className: className,
1332
+ maxFiles: maxFiles,
1333
+ maxSize: maxSize,
1334
+ size: size,
1335
+ fill: fill,
1336
+ fillHover: fillHover,
1337
+ borderColor: updatedInputProps.borderColor,
1338
+ borderColorHover: borderColorHover,
1339
+ borderType: borderType,
1340
+ borderWidth: borderWidth,
1341
+ errorMessageTextColor: errorMessageTextColor,
1342
+ errorMessageTextSize: errorMessageTextSize,
1343
+ errorMessageWeight: errorMessageTextWeight,
1344
+ fileErrorText: fileErrorText,
1345
+ metaError: meta.error,
1346
+ dropzoneProps: dropzoneProps,
1347
+ hintDescription: hintDescription,
1348
+ hintDescriptionTextColor: hintDescriptionTextColor,
1349
+ hintDescriptionTextSize: hintDescriptionTextSize,
1350
+ hintDescriptionTextWeight: hintDescriptionTextWeight,
1351
+ hintDescriptionTextWrap: hintDescriptionTextWrap,
1352
+ hintTitle: hintTitle,
1353
+ hintTitleTextColor: hintTitleTextColor,
1354
+ hintTitleTextSize: hintTitleTextSize,
1355
+ hintTitleTextWeight: hintTitleTextWeight,
1356
+ hintTitleTextWrap: hintTitleTextWrap,
1357
+ inputName: input.name,
1358
+ inputValue: input.value,
1359
+ metaTouched: meta.touched,
1360
+ removeThumbAppearance: removeThumbAppearance,
1361
+ removeThumbText: removeThumbText,
1362
+ removeThumbTextWeight: removeThumbTextWeight,
1363
+ removeThumbShape: removeThumbShape,
1364
+ shape: shape,
1365
+ showFilename: showFilename,
1366
+ thumbBorderColor: thumbBorderColor,
1367
+ thumbBorderColorHover: thumbBorderColorHover,
1368
+ thumbBorderType: thumbBorderType,
1369
+ thumbBorderWidth: thumbBorderWidth,
1370
+ thumbColumn: thumbColumn,
1371
+ thumbDirection: thumbDirection,
1372
+ thumbNameTextColor: thumbNameTextColor,
1373
+ thumbNameTextSize: thumbNameTextSize,
1374
+ thumbNameTextWeight: thumbNameTextWeight,
1375
+ thumbNameTextWrap: thumbNameTextWrap,
1376
+ isPreviews: isPreviews,
1377
+ onAddFiles: onAddFiles,
1378
+ onDeleteFile: onDeleteFile
1379
+ }));
1380
+ });
1381
+ });
1382
+
1383
+ const Group = /*#__PURE__*/React__default.default.memo(function Group(props) {
1384
+ const {
1385
+ className,
1386
+ name,
1387
+ label,
1388
+ labelTextColor,
1389
+ labelTextSize,
1390
+ labelTextWeight,
1391
+ message,
1392
+ dataTour,
1393
+ messageTextColor = 'surfaceTextTertiary',
1394
+ messageTextSize = 's',
1395
+ messageTextWeight,
1396
+ showGroupMessage,
1397
+ before,
1398
+ after,
1399
+ isHidden,
1400
+ children
1401
+ } = props;
1402
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1403
+ name: name
1404
+ }, function Render({
1405
+ input,
1406
+ meta
1407
+ }) {
1408
+ /** Note:
1409
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1410
+ * React Hooks cannot be called inside a callback.
1411
+ * React Hooks must be called in a React function component or a
1412
+ * custom React Hook function.
1413
+ */
1414
+ const {
1415
+ isErrorState,
1416
+ errorKey,
1417
+ errorMessage
1418
+ } = useFieldValidationState({
1419
+ fieldProps: props,
1420
+ // or fieldProps?
1421
+ input: input,
1422
+ meta: meta
1423
+ });
1424
+ const updatedProps = useValidationAppearanceInputProps({
1425
+ inputProps: props,
1426
+ validationStateKey: isErrorState ? errorKey : 'success'
1427
+ });
1428
+ return /*#__PURE__*/React__default.default.createElement("div", {
1429
+ className: clsx__default.default('form__group', className, isHidden && 'form__group_hidden'),
1430
+ "data-tour": dataTour
1431
+ }, /*#__PURE__*/React__default.default.createElement("div", {
1432
+ className: "form__group-wrapper"
1433
+ }, before, label && /*#__PURE__*/React__default.default.createElement("div", {
1434
+ className: "form__group-label"
1435
+ }, /*#__PURE__*/React__default.default.createElement(Title.Title, {
1436
+ size: labelTextSize,
1437
+ textColor: labelTextColor,
1438
+ textWeight: labelTextWeight
1439
+ }, label)), /*#__PURE__*/React__default.default.createElement("div", {
1440
+ className: "form__group-items"
1441
+ }, children), after), showGroupMessage && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, isErrorState && errorMessage && /*#__PURE__*/React__default.default.createElement(Text.Text, {
1442
+ className: `form__group-message form__group-message_type-${errorKey}`,
1443
+ id: `${name}-error`,
1444
+ size: updatedProps.messageTextSize,
1445
+ textColor: updatedProps.messageTextColor,
1446
+ textWeight: updatedProps.messageTextWeight
1447
+ }, errorMessage), Boolean(message) && (!isErrorState || !errorMessage) && /*#__PURE__*/React__default.default.createElement(Text.Text, {
1448
+ className: "form__group-message",
1449
+ size: messageTextSize,
1450
+ textColor: messageTextColor,
1451
+ textWeight: messageTextWeight
1452
+ }, message), !isErrorState && !message && /*#__PURE__*/React__default.default.createElement(Text.Text, {
1453
+ className: "form__group-message",
1454
+ size: messageTextSize
1455
+ }, '\u00A0')));
1456
+ });
1457
+ });
1458
+
1459
+ const defaultInputProps = {
1460
+ appearance: 'sizeM defaultSecondary',
1461
+ width: 'fill',
1462
+ errorBorderColor: 'errorBorderSecondary',
1463
+ requiredBorderColor: 'warningBorderSecondary',
1464
+ shape: 'rounded'
1465
+ };
1466
+
1467
+ const InputField = /*#__PURE__*/React__default.default.memo(function InputField(props) {
1468
+ const {
1469
+ name,
1470
+ initialValue,
1471
+ isDisabled,
1472
+ classNameGroupItem,
1473
+ // dataTestId,
1474
+ // iconBorder,
1475
+ // iconBorderHover,
1476
+ clearIcon,
1477
+ clearIconFill,
1478
+ clearIconFillHover,
1479
+ clearIconShape,
1480
+ clearIconSize,
1481
+ fieldProps = {},
1482
+ iconFill,
1483
+ iconFillHover,
1484
+ iconRevealableHide,
1485
+ iconRevealableShow,
1486
+ iconShape,
1487
+ iconSize,
1488
+ inputProps = {},
1489
+ parse,
1490
+ showMessage,
1491
+ isPassword,
1492
+ isRequired,
1493
+ isRevealable,
1494
+ onChange,
1495
+ onClickClearIcon
1496
+ } = props;
1497
+ const [isRevealed, setIsRevealed] = React$1.useState(false);
1498
+ const inputType = React$1.useMemo(() => {
1499
+ if (isPassword) {
1500
+ return isRevealed ? 'text' : 'password';
1501
+ } else {
1502
+ return 'text';
1503
+ }
1504
+ }, [isRevealed, isPassword]);
1505
+ const onClickIconReveal = React$1.useCallback(event => {
1506
+ event.preventDefault();
1507
+ setIsRevealed(prev => !prev);
1508
+ }, []);
1509
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1510
+ name: name,
1511
+ initialValue: initialValue,
1512
+ parse: parse
1513
+ }, function Render({
1514
+ input,
1515
+ meta
1516
+ }) {
1517
+ /** Note:
1518
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1519
+ * React Hooks cannot be called inside a callback.
1520
+ * React Hooks must be called in a React function component or a
1521
+ * custom React Hook function.
1522
+ */
1523
+
1524
+ const onChangeField = React$1.useCallback(event => {
1525
+ input.onChange(event);
1526
+ if (onChange) {
1527
+ onChange(event.target.value, input.name);
1528
+ }
1529
+ }, [onChange, input.onChange]);
1530
+ const {
1531
+ isErrorState,
1532
+ isValidState,
1533
+ errorKey,
1534
+ errorMessage
1535
+ } = useFieldValidationState({
1536
+ fieldProps: fieldProps,
1537
+ input: input,
1538
+ meta: meta
1539
+ });
1540
+ const updatedInputProps = useValidationAppearanceInputProps({
1541
+ inputProps: inputProps,
1542
+ validationStateKey: isErrorState ? errorKey : 'success'
1543
+ });
1544
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
1545
+ className: clsx__default.default('form-field_type_input', 'form__item_type_input', classNameGroupItem),
1546
+ errorKey: errorKey,
1547
+ errorMessage: errorMessage,
1548
+ isErrorState: isErrorState,
1549
+ metaError: meta.error,
1550
+ isDisabled: isDisabled,
1551
+ fieldClassName: isRevealable ? 'form-password' : 'form-input',
1552
+ inputName: input.name,
1553
+ inputValue: input.value || '',
1554
+ metaActive: meta.active,
1555
+ showMessage: showMessage,
1556
+ isRequired: isRequired,
1557
+ isValidState: isValidState
1558
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Input.Input, Object.assign({
1559
+ className: clsx__default.default(meta.active && 'input_state_focus', meta.error && meta.touched && `input_state_${errorKey}`),
1560
+ type: inputType,
1561
+ name: input.name,
1562
+ isDisabled: isDisabled,
1563
+ autoComplete: "nope",
1564
+ dataTestId: `${input.name}FieldInput`,
1565
+ value: input.value || '',
1566
+ onBlur: input.onBlur,
1567
+ onChange: onChangeField,
1568
+ onFocus: input.onFocus
1569
+ }, updatedInputProps)), isRevealable && /*#__PURE__*/React__default.default.createElement(Icon.Icon, {
1570
+ className: "form-field__icon",
1571
+ size: iconSize,
1572
+ iconFill: iconFill,
1573
+ iconFillHover: iconFillHover,
1574
+ imageSrc: isRevealed ? iconRevealableHide : iconRevealableShow,
1575
+ shape: iconShape,
1576
+ SvgImage: isRevealed ? iconRevealableHide : iconRevealableShow,
1577
+ onClick: onClickIconReveal
1578
+ }), clearIcon && /*#__PURE__*/React__default.default.createElement(Icon.Icon, {
1579
+ className: "form-field__icon",
1580
+ size: clearIconSize,
1581
+ iconFill: clearIconFill,
1582
+ iconFillHover: clearIconFillHover,
1583
+ imageSrc: clearIcon,
1584
+ shape: clearIconShape,
1585
+ SvgImage: clearIcon,
1586
+ onClick: onClickClearIcon
1587
+ }));
1588
+ });
1589
+ });
1590
+
1591
+ const defaultRadioProps = {
1592
+ fieldProps: {
1593
+ width: 'fill',
1594
+ size: 'm',
1595
+ labelTextColor: 'surfaceTextPrimary',
1596
+ labelTextSize: 's',
1597
+ labelTextWeight: 'normal',
1598
+ textColor: 'surfaceTextPrimary',
1599
+ helpText: 'Supporting text',
1600
+ helpTextColor: 'surfaceTextPrimary',
1601
+ helpTextSize: 's',
1602
+ helpTextWeight: 'normal',
1603
+ showMessage: true
1604
+ },
1605
+ inputProps: {
1606
+ width: 'fill',
1607
+ size: 'm',
1608
+ labelTextColor: 'surfaceTextPrimary',
1609
+ labelTextSize: 's',
1610
+ descTextColor: 'surfaceTextPrimary',
1611
+ descTextSize: 's'
1612
+ }
1613
+ };
1614
+
1615
+ function RadioGroupInput(props) {
1616
+ const {
1617
+ input,
1618
+ value,
1619
+ onChange
1620
+ } = props;
1621
+ const onChangeField = React$1.useCallback(event => onChange(event.target.value), [onChange]);
1622
+ return /*#__PURE__*/React.createElement(Input.Input, Object.assign({
1623
+ name: input.name,
1624
+ autoComplete: "nope",
1625
+ value: value,
1626
+ onBlur: input.onBlur,
1627
+ onChange: onChangeField,
1628
+ onFocus: input.onFocus
1629
+ }, props));
1630
+ }
1631
+
1632
+ function RadioGroupItem(props) {
1633
+ const {
1634
+ input,
1635
+ inputProps,
1636
+ option,
1637
+ onChange
1638
+ } = props;
1639
+ const onChangeField = React$1.useCallback(event => {
1640
+ if (event.target.checked) {
1641
+ onChange(option.value);
1642
+ }
1643
+ }, [onChange]);
1644
+ return /*#__PURE__*/React.createElement(Radio.Radio, Object.assign({
1645
+ className: "form-radio__item",
1646
+ type: "radio",
1647
+ name: input.name,
1648
+ label: option.label,
1649
+ checked: option.value === input.value,
1650
+ value: option.value,
1651
+ onBlur: input.onBlur,
1652
+ onChange: onChangeField,
1653
+ onFocus: input.onFocus
1654
+ }, inputProps));
1655
+ }
1656
+
1657
+ function RadioGroupList(props) {
1658
+ const {
1659
+ editableProps,
1660
+ input,
1661
+ inputProps,
1662
+ options,
1663
+ onChange
1664
+ } = props;
1665
+ const [editableValue, setEditableValue] = React$1.useState(() => {
1666
+ const isRadioValue = options.find(option => option.value === input.value);
1667
+ if (!isRadioValue) {
1668
+ return input.value;
1669
+ }
1670
+ return '';
1671
+ });
1672
+ React$1.useEffect(() => {
1673
+ // When a new value from outside enters the form
1674
+ if (input.value) {
1675
+ // Check value for radio type
1676
+ const isRadioValue = options.find(option => option.value === input.value && !option.editable);
1677
+ // If new value not in radio list - set to editable input
1678
+ setEditableValue(isRadioValue ? '' : input.value);
1679
+ } else {
1680
+ // If new value is empty - clear editable input
1681
+ setEditableValue('');
1682
+ }
1683
+ }, [input.value]);
1684
+
1685
+ // Callback for value changes
1686
+ const onChangeSomeInput = React$1.useCallback(value => {
1687
+ // Save to form values
1688
+ input.onChange(value);
1689
+ if (onChange) {
1690
+ // Pass to custom event
1691
+ onChange(value, input.name);
1692
+ }
1693
+ }, [input, onChange]);
1694
+
1695
+ // Handle for radio inputs
1696
+ const onChangeRadio = React$1.useCallback(value => {
1697
+ setEditableValue('');
1698
+ onChangeSomeInput(value);
1699
+ }, [onChangeSomeInput]);
1700
+
1701
+ // Handle for text input
1702
+ const onChangeEditable = React$1.useCallback(value => {
1703
+ setEditableValue(value);
1704
+ onChangeSomeInput(value);
1705
+ }, [onChangeSomeInput]);
1706
+ return /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, options.map(option => option.editable ? /*#__PURE__*/React__default.default.createElement(RadioGroupInput, {
1707
+ key: option.label,
1708
+ editableProps: editableProps,
1709
+ input: input,
1710
+ inputProps: inputProps,
1711
+ option: option,
1712
+ value: editableValue,
1713
+ onChange: onChangeEditable
1714
+ }) : /*#__PURE__*/React__default.default.createElement(RadioGroupItem, {
1715
+ key: option.value,
1716
+ input: input,
1717
+ inputProps: inputProps,
1718
+ option: option,
1719
+ onChange: onChangeRadio
1720
+ })));
1721
+ }
1722
+
1723
+ const RadioGroup = /*#__PURE__*/React__default.default.memo(function RadioGroup(props) {
1724
+ const {
1725
+ name,
1726
+ isDisabled,
1727
+ editableProps = {},
1728
+ fieldProps = {},
1729
+ inputProps = {},
1730
+ options = [],
1731
+ showMessage,
1732
+ isRequired,
1733
+ onChange
1734
+ } = props;
1735
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1736
+ name: name
1737
+ }, function Render({
1738
+ input,
1739
+ meta
1740
+ }) {
1741
+ /** Note:
1742
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1743
+ * React Hooks cannot be called inside a callback.
1744
+ * React Hooks must be called in a React function component or a
1745
+ * custom React Hook function.
1746
+ */
1747
+
1748
+ const {
1749
+ errorKey,
1750
+ errorMessage,
1751
+ isErrorState,
1752
+ isValidState
1753
+ } = useFieldValidationState({
1754
+ fieldProps: fieldProps,
1755
+ input: input,
1756
+ meta: meta
1757
+ });
1758
+ const updatedInputProps = useValidationAppearanceInputProps({
1759
+ inputProps: inputProps,
1760
+ validationStateKey: isErrorState ? errorKey : 'success'
1761
+ });
1762
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
1763
+ className: clsx__default.default('form-field_type_radio', 'form__item_type_radio"', classNameGroupItem),
1764
+ errorKey: errorKey,
1765
+ errorMessage: errorMessage,
1766
+ isErrorState: isErrorState,
1767
+ metaError: meta.error,
1768
+ isDisabled: isDisabled,
1769
+ fieldClassName: 'form-radio',
1770
+ inputName: input.name,
1771
+ inputValue: input.value || '',
1772
+ metaActive: meta.active,
1773
+ showMessage: showMessage,
1774
+ isRequired: isRequired,
1775
+ isValidState: isValidState
1776
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(RadioGroupList, {
1777
+ isDisabled: isDisabled,
1778
+ editableProps: editableProps,
1779
+ input: input,
1780
+ inputProps: updatedInputProps,
1781
+ options: options,
1782
+ onChange: onChange
1783
+ }));
1784
+ });
1785
+ });
1786
+
1787
+ const defaultSegmentedProps = {
1788
+ appearance: 'sizeM surfacePrimary',
1789
+ width: 'fill',
1790
+ errorLabelTextColor: 'errorTextPrimary',
1791
+ requiredLabelTextColor: 'warningTextPrimary',
1792
+ shape: 'rounded'
1793
+ };
1794
+
1795
+ function SegmentedField(props) {
1796
+ const {
1797
+ name,
1798
+ isDisabled,
1799
+ fieldProps,
1800
+ inputProps,
1801
+ options,
1802
+ showMessage,
1803
+ isRequired
1804
+ } = props;
1805
+ const {
1806
+ change
1807
+ } = reactFinalForm.useForm();
1808
+ const setActiveSegment = React$1.useCallback(option => {
1809
+ change(name, option.value);
1810
+ }, [change]);
1811
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1812
+ name: name
1813
+ }, function Render({
1814
+ input,
1815
+ meta
1816
+ }) {
1817
+ /** Note:
1818
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1819
+ * React Hooks cannot be called inside a callback.
1820
+ * React Hooks must be called in a React function component or a
1821
+ * custom React Hook function.
1822
+ */
1823
+
1824
+ const activeOption = React$1.useMemo(() => {
1825
+ const emptyOption = {
1826
+ label: null,
1827
+ value: null
1828
+ };
1829
+ if (input.value) {
1830
+ const currentOption = options.find(option => option.value === input.value);
1831
+ return currentOption || emptyOption;
1832
+ }
1833
+ return emptyOption;
1834
+ }, [input.value]);
1835
+ const {
1836
+ errorKey,
1837
+ errorMessage,
1838
+ isErrorState,
1839
+ isValidState
1840
+ } = useFieldValidationState({
1841
+ fieldProps: fieldProps,
1842
+ input: input,
1843
+ meta: meta
1844
+ });
1845
+ const updatedInputProps = useValidationAppearanceInputProps({
1846
+ inputProps: inputProps,
1847
+ validationStateKey: isErrorState ? errorKey : 'success'
1848
+ });
1849
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
1850
+ className: clsx__default.default('form-field_type_segmented', 'form__item_type_segmented'),
1851
+ errorKey: errorKey,
1852
+ errorMessage: errorMessage,
1853
+ isErrorState: isErrorState,
1854
+ metaError: meta.error,
1855
+ isDisabled: isDisabled,
1856
+ fieldClassName: "form-segmented",
1857
+ inputName: input.name,
1858
+ inputValue: input.value || [],
1859
+ metaActive: meta.active,
1860
+ showMessage: showMessage,
1861
+ isRequired: isRequired,
1862
+ isValidState: isValidState
1863
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Segmented.Segmented, Object.assign({
1864
+ isDisabled: isDisabled,
1865
+ activeSegment: activeOption,
1866
+ segments: options,
1867
+ setActiveSegment: setActiveSegment
1868
+ }, updatedInputProps)));
1869
+ });
1870
+ }
1871
+
1872
+ const defaultSelectProps = {
1873
+ elevation: 8,
1874
+ isClearable: true,
1875
+ isSearchable: true,
1876
+ badgeAppearance: 'accent',
1877
+ badgeSize: 'm',
1878
+ badgeTextSize: 'm',
1879
+ // clearIcon: icon24.Clear,
1880
+ clearIconFill: 'surfaceItemPrimary',
1881
+ closeMenuOnSelect: true,
1882
+ // optionSelected: <Icon iconFill="surfaceItemAccent" SvgImage={icon24.Check} />,
1883
+
1884
+ dividerDirection: 'horizontal',
1885
+ dividerFill: 'surfaceTertiary',
1886
+ dividerSize: 'xxs',
1887
+ // dropdownIcon: icon24.ChevronDownSmall,
1888
+ dropdownIconFill: 'surfaceItemPrimary',
1889
+ // error
1890
+ errorInputBorderColor: 'errorBorderPrimary',
1891
+ headingFill: 'surfaceSecondary',
1892
+ loadingMessage: /*#__PURE__*/React__default.default.createElement(Loader.Loader, {
1893
+ width: "fill",
1894
+ height: "fill",
1895
+ fill: "surfacePrimary",
1896
+ position: "absolute",
1897
+ left: "0px",
1898
+ right: "0px",
1899
+ zIndex: "1",
1900
+ itemFill: "surfaceItemAccent",
1901
+ set: "simple"
1902
+ })
1903
+ };
1904
+
1905
+ function getDefaultValue(options, selectValue) {
1906
+ const selectValues = Array.isArray(selectValue) ? selectValue : [selectValue];
1907
+ let result = [];
1908
+ options.forEach(item => {
1909
+ const isValue = selectValues.includes(item.value);
1910
+ const isLabel = selectValues.includes(item.label);
1911
+ let childOptions = [];
1912
+ if (item.options) {
1913
+ childOptions = getDefaultValue(item.options, selectValue);
1914
+ }
1915
+ if (isValue || isLabel) {
1916
+ result.push(item);
1917
+ } else if (childOptions.length) {
1918
+ result = result.concat(childOptions);
1919
+ }
1920
+ });
1921
+ return result;
1922
+ }
1923
+ const SelectField = /*#__PURE__*/React__default.default.memo(function SelectField(props) {
1924
+ const {
1925
+ isDisabled,
1926
+ isRequired,
1927
+ classNameGroupItem,
1928
+ fieldProps,
1929
+ initialValue,
1930
+ name,
1931
+ options = [],
1932
+ selectProps,
1933
+ selectRef,
1934
+ showMessage,
1935
+ onChange,
1936
+ onInputChange
1937
+ } = props;
1938
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
1939
+ name: name,
1940
+ initialValue: initialValue
1941
+ }, function Render({
1942
+ input,
1943
+ meta
1944
+ }) {
1945
+ /** Note:
1946
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
1947
+ * React Hooks cannot be called inside a callback.
1948
+ * React Hooks must be called in a React function component or a
1949
+ * custom React Hook function.
1950
+ */
1951
+ const [selectedOptions, setSelectedOptions] = React$1.useState(null);
1952
+ const defaultValue = React$1.useMemo(() => {
1953
+ const optionsValues = getDefaultValue(options, input.value);
1954
+ if (!optionsValues.length && input.value?.length) {
1955
+ optionsValues.push({
1956
+ label: input.value,
1957
+ value: input.value
1958
+ });
1959
+ }
1960
+ return optionsValues;
1961
+ }, [input.value]);
1962
+ const onChangeField = React$1.useCallback(value => {
1963
+ input.onChange(value);
1964
+ if (onChange) {
1965
+ onChange(value, input.name);
1966
+ }
1967
+ }, [onChange, input.onChange]);
1968
+ const onChangeValue = React$1.useCallback((option, actionMeta) => {
1969
+ const value = Array.isArray(option) ? option.map(o => o.value) : option?.value || null;
1970
+ setSelectedOptions(option);
1971
+ onChangeField(value);
1972
+ }, [onChangeField]);
1973
+ React$1.useEffect(() => {
1974
+ setSelectedOptions(defaultValue);
1975
+ }, [defaultValue]);
1976
+ const {
1977
+ isErrorState,
1978
+ isValidState,
1979
+ errorKey,
1980
+ errorMessage
1981
+ } = useFieldValidationState({
1982
+ fieldProps: fieldProps,
1983
+ input: input,
1984
+ meta: meta
1985
+ });
1986
+ const updatedSelectProps = useValidationAppearanceInputProps({
1987
+ inputProps: selectProps,
1988
+ validationStateKey: isErrorState ? errorKey : 'success'
1989
+ });
1990
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
1991
+ className: clsx__default.default('form-field_type_select', 'form__item_type_select', classNameGroupItem),
1992
+ errorKey: errorKey,
1993
+ errorMessage: errorMessage,
1994
+ isErrorState: isErrorState,
1995
+ metaError: meta.error,
1996
+ isDisabled: isDisabled,
1997
+ fieldClassName: 'form-select',
1998
+ inputName: input.name,
1999
+ inputValue: input.value,
2000
+ metaActive: meta.active,
2001
+ showMessage: showMessage,
2002
+ isRequired: isRequired,
2003
+ isValidState: isValidState
2004
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Select.Select, Object.assign({
2005
+ className: "form-select-item",
2006
+ isDisabled: isDisabled,
2007
+ instanceId: `id_${input.name}`,
2008
+ options: options,
2009
+ ref: selectRef,
2010
+ value: selectedOptions,
2011
+ onChange: onChangeValue,
2012
+ onInputChange: onInputChange
2013
+ }, updatedSelectProps)));
2014
+ });
2015
+ });
2016
+
2017
+ const defaultSwitchProps = {
2018
+ fieldProps: {
2019
+ width: 'fill',
2020
+ size: 'xl',
2021
+ labelTextColor: 'surfaceTextPrimary',
2022
+ labelTextSize: 's',
2023
+ labelTextWeight: 'normal',
2024
+ textColor: 'surfaceTextPrimary',
2025
+ helpText: 'Supporting text',
2026
+ helpTextColor: 'surfaceTextPrimary',
2027
+ helpTextSize: 's',
2028
+ helpTextWeight: 'normal',
2029
+ showMessage: true
2030
+ },
2031
+ inputProps: {
2032
+ size: 'm',
2033
+ fill: 'surfaceSecondary',
2034
+ title: 'Switch',
2035
+ titleTextColor: 'surfaceTextPrimary',
2036
+ titleTextSize: 's',
2037
+ desc: 'Description',
2038
+ descTextColor: 'surfaceTextPrimary',
2039
+ descTextSize: 'xs'
2040
+ }
2041
+ };
2042
+
2043
+ const SwitchField = /*#__PURE__*/React__default.default.memo(function SwitchField(props) {
2044
+ const {
2045
+ name,
2046
+ isDisabled,
2047
+ classNameGroupItem,
2048
+ fieldProps = {},
2049
+ inputProps = {},
2050
+ showMessage,
2051
+ isRequired,
2052
+ onChange
2053
+ } = props;
2054
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
2055
+ type: "checkbox",
2056
+ name: name
2057
+ }, function Render({
2058
+ input,
2059
+ meta
2060
+ }) {
2061
+ /** Note:
2062
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
2063
+ * React Hooks cannot be called inside a callback.
2064
+ * React Hooks must be called in a React function component or a
2065
+ * custom React Hook function.
2066
+ */
2067
+
2068
+ const onChangeField = React$1.useCallback(event => {
2069
+ input.onChange(event);
2070
+ if (onChange) {
2071
+ onChange(event.target.checked, input.name);
2072
+ }
2073
+ }, [onChange, input.onChange]);
2074
+ const {
2075
+ errorKey,
2076
+ errorMessage,
2077
+ isErrorState,
2078
+ isValidState
2079
+ } = useFieldValidationState({
2080
+ fieldProps: fieldProps,
2081
+ input: input,
2082
+ meta: meta
2083
+ });
2084
+ const updatedInputProps = useValidationAppearanceInputProps({
2085
+ inputProps: inputProps,
2086
+ validationStateKey: isErrorState ? errorKey : 'success'
2087
+ });
2088
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
2089
+ className: clsx__default.default('form-field_type_switch', 'form__item_type_switch', classNameGroupItem),
2090
+ errorKey: errorKey,
2091
+ errorMessage: errorMessage,
2092
+ isErrorState: isErrorState,
2093
+ metaError: meta.error,
2094
+ isDisabled: isDisabled,
2095
+ fieldClassName: "form-switch",
2096
+ inputName: input.name,
2097
+ inputValue: input.checked,
2098
+ metaActive: meta.active,
2099
+ showMessage: showMessage,
2100
+ tag: "label",
2101
+ isRequired: isRequired,
2102
+ isValidState: isValidState
2103
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Switch.Switch, Object.assign({
2104
+ type: "checkbox",
2105
+ name: input.name,
2106
+ isDisabled: isDisabled,
2107
+ autoComplete: "nope",
2108
+ checked: input.checked,
2109
+ onBlur: input.onBlur,
2110
+ onChange: onChangeField,
2111
+ onFocus: input.onFocus
2112
+ }, updatedInputProps)));
2113
+ });
2114
+ });
2115
+
2116
+ const defaultTextareaProps = {
2117
+ appearance: 'sizeM defaultSecondary',
2118
+ width: 'fill',
2119
+ errorBorderColor: 'errorBorderSecondary',
2120
+ requiredBorderColor: 'warningBorderSecondary',
2121
+ shape: 'rounded'
2122
+ };
2123
+
2124
+ const TextareaField = /*#__PURE__*/React__default.default.memo(function TextareaField(props) {
2125
+ const {
2126
+ name,
2127
+ isDisabled,
2128
+ classNameGroupItem,
2129
+ fieldProps = {},
2130
+ inputProps = {},
2131
+ showMessage,
2132
+ isRequired
2133
+ } = props;
2134
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
2135
+ name: name
2136
+ }, function Render({
2137
+ input,
2138
+ meta
2139
+ }) {
2140
+ /** Note:
2141
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
2142
+ * React Hooks cannot be called inside a callback.
2143
+ * React Hooks must be called in a React function component or a
2144
+ * custom React Hook function.
2145
+ */
2146
+
2147
+ const {
2148
+ errorKey,
2149
+ errorMessage,
2150
+ isErrorState,
2151
+ isValidState
2152
+ } = useFieldValidationState({
2153
+ fieldProps: fieldProps,
2154
+ input: input,
2155
+ meta: meta
2156
+ });
2157
+ const updatedInputProps = useValidationAppearanceInputProps({
2158
+ inputProps: inputProps,
2159
+ validationStateKey: isErrorState ? errorKey : 'success'
2160
+ });
2161
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
2162
+ className: clsx__default.default('form-field_type_textarea', 'form__item_type_textarea', classNameGroupItem),
2163
+ errorKey: errorKey,
2164
+ errorMessage: errorMessage,
2165
+ isErrorState: isErrorState,
2166
+ metaError: meta.error,
2167
+ isDisabled: isDisabled,
2168
+ fieldClassName: 'form-textarea',
2169
+ inputName: input.name,
2170
+ inputValue: input.value,
2171
+ metaActive: meta.active,
2172
+ showMessage: showMessage,
2173
+ isRequired: isRequired,
2174
+ isValidState: isValidState
2175
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Textarea.Textarea, Object.assign({
2176
+ name: input.name,
2177
+ isDisabled: isDisabled,
2178
+ autoComplete: "nope",
2179
+ value: input.value,
2180
+ onBlur: input.onBlur,
2181
+ onChange: input.onChange,
2182
+ onFocus: input.onFocus
2183
+ }, updatedInputProps)));
2184
+ });
2185
+ });
2186
+
2187
+ const MaskedInputField = /*#__PURE__*/React__default.default.memo(function MaskedInputField(props) {
2188
+ const {
2189
+ name,
2190
+ initialValue,
2191
+ isDisabled,
2192
+ classNameGroupItem,
2193
+ clearIcon,
2194
+ clearIconFill,
2195
+ clearIconFillHover,
2196
+ clearIconShape,
2197
+ clearIconSize,
2198
+ fieldProps = {},
2199
+ inputProps = {},
2200
+ optionsMask,
2201
+ showMessage,
2202
+ unmasked,
2203
+ isRequired,
2204
+ onClickClearIcon
2205
+ } = props;
2206
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
2207
+ name: name,
2208
+ initialValue: initialValue
2209
+ }, function Render({
2210
+ input,
2211
+ meta
2212
+ }) {
2213
+ /** Note:
2214
+ * Create "Render" function by "eslint-react-hooks/rules-of-hooks":
2215
+ * React Hooks cannot be called inside a callback.
2216
+ * React Hooks must be called in a React function component or a
2217
+ * custom React Hook function.
2218
+ */
2219
+
2220
+ const {
2221
+ ref,
2222
+ unmaskedValue,
2223
+ value,
2224
+ setUnmaskedValue
2225
+ } = reactImask.useIMask(optionsMask, {
2226
+ onAccept: (newValue, event, element) => {
2227
+ if (element) {
2228
+ input.onChange(event._unmaskedValue);
2229
+ }
2230
+ }
2231
+ });
2232
+ React$1.useEffect(() => {
2233
+ if (input.value !== unmaskedValue) {
2234
+ setUnmaskedValue(input.value.replace(unmasked, ''));
2235
+ }
2236
+ }, [input.value]);
2237
+ const {
2238
+ errorKey,
2239
+ errorMessage,
2240
+ isErrorState,
2241
+ isValidState
2242
+ } = useFieldValidationState({
2243
+ fieldProps: fieldProps,
2244
+ input: input,
2245
+ meta: meta
2246
+ });
2247
+ const updatedInputProps = useValidationAppearanceInputProps({
2248
+ inputProps: inputProps,
2249
+ validationStateKey: isErrorState ? errorKey : 'success'
2250
+ });
2251
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
2252
+ className: clsx__default.default('form-field_type_maskedInput', 'form__item_type_maskedInput', classNameGroupItem),
2253
+ errorKey: errorKey,
2254
+ errorMessage: errorMessage,
2255
+ isErrorState: isErrorState,
2256
+ metaError: meta.error,
2257
+ isDisabled: isDisabled,
2258
+ fieldClassName: 'form-maskedInput',
2259
+ inputName: input.name,
2260
+ inputValue: input.value,
2261
+ metaActive: meta.active,
2262
+ showMessage: showMessage,
2263
+ isRequired: isRequired,
2264
+ isValidState: isValidState
2265
+ }, fieldProps), /*#__PURE__*/React__default.default.createElement(Input.Input, Object.assign({
2266
+ className: clsx__default.default(meta.active && 'input_state_focus', meta.error && meta.touched && `input_state_${errorKey}`),
2267
+ ref: ref,
2268
+ value: value,
2269
+ onBlur: input.onBlur,
2270
+ onFocus: input.onFocus
2271
+ }, updatedInputProps)), clearIcon && /*#__PURE__*/React__default.default.createElement(Icon.Icon, {
2272
+ className: "form-field__icon",
2273
+ size: clearIconSize,
2274
+ iconFill: clearIconFill,
2275
+ iconFillHover: clearIconFillHover,
2276
+ imageSrc: clearIcon,
2277
+ shape: clearIconShape,
2278
+ SvgImage: clearIcon,
2279
+ onClick: onClickClearIcon
2280
+ }));
2281
+ });
2282
+ });
2283
+
2284
+ const defaultChipsProps = {
2285
+ appearance: 'surfacePrimary',
2286
+ width: 'fill',
2287
+ errorBorderColor: 'errorBorderSecondary',
2288
+ requiredBorderColor: 'warningBorderSecondary'
2289
+ };
2290
+
2291
+ function ChipsField(props) {
2292
+ const {
2293
+ name,
2294
+ initialValue,
2295
+ isDisabled,
2296
+ classNameGroupItem,
2297
+ emptyMessage,
2298
+ emptyMessageTextColor,
2299
+ emptyMessageTextSize,
2300
+ fieldProps,
2301
+ inputProps,
2302
+ options,
2303
+ showMessage,
2304
+ isRequired,
2305
+ onChange
2306
+ } = props;
2307
+ const {
2308
+ change
2309
+ } = reactFinalForm.useForm();
2310
+
2311
+ // Callback for value changes
2312
+ const onChangeSomeInput = React$1.useCallback((inputValue, newOptionValue) => {
2313
+ const updatedValues = inputValue.includes(newOptionValue) ? inputValue.filter(selectedValue => selectedValue !== newOptionValue) : [...inputValue, newOptionValue];
2314
+ change(name, updatedValues);
2315
+ onChange && onChange(updatedValues);
2316
+ }, [change, name, onChange]);
2317
+ React$1.useEffect(() => {
2318
+ initialValue && change(name, initialValue);
2319
+ // update the form value only when the initialValue changes, so use disable eslint to ignore the warning
2320
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2321
+ }, [initialValue]);
2322
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Field, {
2323
+ name: name,
2324
+ initialValue: initialValue
2325
+ }, function Render({
2326
+ input,
2327
+ meta
2328
+ }) {
2329
+ const {
2330
+ errorKey,
2331
+ errorMessage,
2332
+ isErrorState,
2333
+ isValidState
2334
+ } = useFieldValidationState({
2335
+ fieldProps: fieldProps,
2336
+ input: input,
2337
+ meta: meta
2338
+ });
2339
+ const updatedInputProps = useValidationAppearanceInputProps({
2340
+ inputProps: inputProps,
2341
+ validationStateKey: isErrorState ? errorKey : 'success'
2342
+ });
2343
+ const activeOptionsList = React$1.useMemo(() => {
2344
+ const emptyOptionsList = [{
2345
+ label: null,
2346
+ value: null
2347
+ }];
2348
+ if (input?.value) {
2349
+ const currentOptions = options.filter(option => input.value?.includes(option.value));
2350
+ return currentOptions || emptyOptionsList;
2351
+ }
2352
+ return emptyOptionsList;
2353
+ }, [input.value]);
2354
+ return /*#__PURE__*/React__default.default.createElement(FieldWrapper, Object.assign({
2355
+ className: clsx__default.default('form-field_type_chips', 'form__item_type_chips', classNameGroupItem),
2356
+ errorKey: errorKey,
2357
+ errorMessage: errorMessage,
2358
+ isErrorState: isErrorState,
2359
+ metaError: meta.error,
2360
+ isDisabled: isDisabled,
2361
+ fieldClassName: "form-chips",
2362
+ inputName: input.name,
2363
+ inputValue: input.value,
2364
+ metaActive: meta.active,
2365
+ showMessage: showMessage,
2366
+ isRequired: isRequired,
2367
+ isValidState: isValidState
2368
+ }, fieldProps), options.length ? options.map(option => /*#__PURE__*/React__default.default.createElement(Chips.Chips, Object.assign({
2369
+ className: clsx__default.default(meta.active && 'form-chips_state_focus', meta.error && meta.touched && `form-chips_state_${errorKey}`),
2370
+ key: option.value,
2371
+ label: option.label,
2372
+ isDisabled: option.isDisabled,
2373
+ value: option.value,
2374
+ isActive: activeOptionsList.some(activeOption => activeOption.value === option.value),
2375
+ onClick: () => onChangeSomeInput(input.value, option.value)
2376
+ }, updatedInputProps))) : /*#__PURE__*/React__default.default.createElement(Text.Text, {
2377
+ size: emptyMessageTextSize,
2378
+ textColor: emptyMessageTextColor
2379
+ }, emptyMessage));
2380
+ });
2381
+ }
2382
+
2383
+ const formTypes = {
2384
+ code: 'code',
2385
+ text: 'text',
2386
+ textarea: 'textarea',
2387
+ custom: 'custom',
2388
+ checkbox: 'checkbox',
2389
+ chips: 'chips',
2390
+ choice: 'choice',
2391
+ datePicker: 'datePicker',
2392
+ dateRangePicker: 'dateRangePicker',
2393
+ fileInput: 'fileInput',
2394
+ group: 'group',
2395
+ maskedInput: 'maskedInput',
2396
+ radioGroup: 'radioGroup',
2397
+ segmented: 'segmented',
2398
+ select: 'select',
2399
+ switch: 'switch'
2400
+ };
2401
+ function generateField(field, config, props) {
2402
+ switch (field.type) {
2403
+ case formTypes.checkbox:
2404
+ {
2405
+ return /*#__PURE__*/React__default.default.createElement(CheckboxField, Object.assign({
2406
+ key: config.key
2407
+ }, field, props));
2408
+ }
2409
+ case formTypes.choice:
2410
+ {
2411
+ return /*#__PURE__*/React__default.default.createElement(ChoiceField, Object.assign({
2412
+ key: config.key
2413
+ }, field, props));
2414
+ }
2415
+ case formTypes.chips:
2416
+ {
2417
+ return /*#__PURE__*/React__default.default.createElement(ChipsField, Object.assign({
2418
+ key: config.key
2419
+ }, field, props));
2420
+ }
2421
+ case formTypes.code:
2422
+ {
2423
+ return /*#__PURE__*/React__default.default.createElement(CodeField, Object.assign({
2424
+ key: config.key
2425
+ }, field, props));
2426
+ }
2427
+ case formTypes.switch:
2428
+ {
2429
+ return /*#__PURE__*/React__default.default.createElement(SwitchField, Object.assign({
2430
+ key: config.key
2431
+ }, field, props));
2432
+ }
2433
+ case formTypes.segmented:
2434
+ {
2435
+ return /*#__PURE__*/React__default.default.createElement(SegmentedField, Object.assign({
2436
+ key: config.key
2437
+ }, field, props));
2438
+ }
2439
+ case formTypes.datePicker:
2440
+ {
2441
+ return /*#__PURE__*/React__default.default.createElement(DatePickerField, Object.assign({
2442
+ key: config.key
2443
+ }, field, props));
2444
+ }
2445
+ case formTypes.fileInput:
2446
+ {
2447
+ return /*#__PURE__*/React__default.default.createElement(FileInput, Object.assign({
2448
+ key: config.key
2449
+ }, field, props));
2450
+ }
2451
+ case formTypes.radioGroup:
2452
+ {
2453
+ return /*#__PURE__*/React__default.default.createElement(RadioGroup, Object.assign({
2454
+ key: config.key
2455
+ }, field, props));
2456
+ }
2457
+ case formTypes.select:
2458
+ {
2459
+ return /*#__PURE__*/React__default.default.createElement(SelectField, Object.assign({
2460
+ key: config.key
2461
+ }, field, props));
2462
+ }
2463
+ case formTypes.text:
2464
+ {
2465
+ return /*#__PURE__*/React__default.default.createElement(InputField, Object.assign({
2466
+ key: config.key
2467
+ }, field, props));
2468
+ }
2469
+ case formTypes.textarea:
2470
+ {
2471
+ return /*#__PURE__*/React__default.default.createElement(TextareaField, Object.assign({
2472
+ key: config.key
2473
+ }, field, props));
2474
+ }
2475
+ case formTypes.maskedInput:
2476
+ {
2477
+ return /*#__PURE__*/React__default.default.createElement(MaskedInputField, Object.assign({
2478
+ key: config.key
2479
+ }, field, props));
2480
+ }
2481
+ case formTypes.custom:
2482
+ {
2483
+ return /*#__PURE__*/React__default.default.createElement(CustomField, Object.assign({
2484
+ key: config.key
2485
+ }, field, props));
2486
+ }
2487
+ case formTypes.group:
2488
+ {
2489
+ return /*#__PURE__*/React__default.default.createElement(Group, Object.assign({
2490
+ key: config.key
2491
+ }, field, props), Object.entries(field.group).map(([key, value]) => {
2492
+ const groupProps = {
2493
+ ...value,
2494
+ classNameGroupItem: value.classNameGroupItem || 'form__group-item',
2495
+ showMessage: field.showMessage
2496
+ };
2497
+ return generateField(groupProps, {
2498
+ key: key + '_form_group'
2499
+ }, props);
2500
+ }));
2501
+ }
2502
+ }
2503
+ }
2504
+
2505
+ const focusOnError = (formElementsList, errors) => {
2506
+ const selectsIds = Object.keys(errors).map(fieldName => {
2507
+ if (fieldName === finalForm.FORM_ERROR) {
2508
+ // TODO: get from somewhere
2509
+ return 'notification__item_status_error';
2510
+ }
2511
+ return `react-select-id_${fieldName}-input`;
2512
+ });
2513
+ const errorFieldElement = formElementsList.find(element => {
2514
+ if (element.name) {
2515
+ return finalForm.getIn(errors, element.name);
2516
+ } else {
2517
+ return selectsIds.includes(element.id);
2518
+ }
2519
+ });
2520
+ const errorsList = Object.keys(errors);
2521
+ if (!errorFieldElement && errorsList.length) {
2522
+ let errorElement;
2523
+ try {
2524
+ const fieldName = errorsList[0];
2525
+ if (fieldName === finalForm.FORM_ERROR) {
2526
+ errorElement = document.querySelector('notification__item_status_error');
2527
+ } else {
2528
+ errorElement = document.querySelector(`#${fieldName}-error`);
2529
+ if (!errorElement) {
2530
+ errorElement = document.querySelector(`#id_${fieldName}`);
2531
+ }
2532
+ }
2533
+ } catch (err) {
2534
+ console.warn(err);
2535
+ }
2536
+ if (errorElement) {
2537
+ errorElement.scrollIntoView({
2538
+ block: 'center'
2539
+ }); // , behavior: 'smooth'
2540
+ }
2541
+ }
2542
+
2543
+ // The field is covered by the header because header is "sticky",
2544
+ // that's we scroll manually so that the field falls into the center of the visible area
2545
+ if (errorFieldElement) {
2546
+ errorFieldElement.scrollIntoView({
2547
+ block: 'center'
2548
+ });
2549
+ }
2550
+ return null;
2551
+ };
2552
+ const focusOnErrorDecorator = createDecorator__default.default(null, focusOnError);
2553
+ const setErrorsMutator = (args, state) => {
2554
+ const [fieldName, data] = args;
2555
+ const submitError = data.submitError;
2556
+ const fieldError = data.error;
2557
+ if (fieldName === 'non_field_errors') {
2558
+ // state.formState.invalid = true
2559
+ // state.formState.valid = false
2560
+ state.formState.error = fieldError;
2561
+ state.formState.submitError = submitError;
2562
+ } else if (fieldName in state.fields) {
2563
+ if (fieldError) {
2564
+ const errorsState = Object.assign({}, state.formState.errors, {
2565
+ [fieldName]: fieldError
2566
+ });
2567
+ state.fields[fieldName].touched = true;
2568
+ state.fields[fieldName].error = fieldError;
2569
+ state.formState.errors = errorsState;
2570
+ }
2571
+ if (submitError) {
2572
+ const submitErrorsState = Object.assign({}, state.formState.submitErrors, {
2573
+ [fieldName]: submitError
2574
+ });
2575
+
2576
+ // state.fields[fieldName].submitFailed = true
2577
+ // state.fields[fieldName].submitSucceeded = false
2578
+ state.fields[fieldName].submitError = submitError;
2579
+ state.formState.submitErrors = submitErrorsState;
2580
+ state.formState.submitFailed = true;
2581
+ state.formState.submitSucceeded = false;
2582
+ state.formState.lastSubmittedValues = state.formState.values;
2583
+ }
2584
+ }
2585
+ };
2586
+ const sendFormDataToServer = async (url, data) => {
2587
+ try {
2588
+ const response = await axios__default.default({
2589
+ url: url,
2590
+ method: 'POST',
2591
+ data: data
2592
+ });
2593
+ return {
2594
+ success: true,
2595
+ response
2596
+ };
2597
+ } catch (error) {
2598
+ const formErrors = {};
2599
+ if (typeof error.response?.data === 'string') {
2600
+ formErrors[finalForm.FORM_ERROR] = 'Something went wrong';
2601
+ }
2602
+ if (typeof error.response?.data === 'object') {
2603
+ Object.entries(error.response.data).forEach(([fieldName, errorsList]) => {
2604
+ formErrors[fieldName] = errorsList[0];
2605
+ });
2606
+ }
2607
+ return {
2608
+ success: false,
2609
+ formErrors,
2610
+ error
2611
+ };
2612
+ }
2613
+ };
2614
+
2615
+ const FinalForm = /*#__PURE__*/React__default.default.forwardRef(function FinalForm(props, ref) {
2616
+ const {
2617
+ className,
2618
+ type,
2619
+ initialValues,
2620
+ initialValuesEqual,
2621
+ config,
2622
+ title,
2623
+ titleFill,
2624
+ titleTextColor,
2625
+ titleTextSize,
2626
+ titleTextWeight,
2627
+ desc,
2628
+ descSize,
2629
+ descTextColor,
2630
+ descTextWeight,
2631
+ primaryButton,
2632
+ primaryButtonFill,
2633
+ primaryButtonFillHover,
2634
+ primaryButtonLabel,
2635
+ primaryButtonLabelSize,
2636
+ primaryButtonLabelTextColor,
2637
+ primaryButtonLabelTextWeight,
2638
+ primaryButtonSize,
2639
+ secondaryButton,
2640
+ secondaryButtonFill,
2641
+ secondaryButtonFillHover,
2642
+ secondaryButtonLabel,
2643
+ secondaryButtonLabelSize,
2644
+ secondaryButtonLabelTextColor,
2645
+ secondaryButtonLabelTextWeight,
2646
+ secondaryButtonSize,
2647
+ tertiaryButton,
2648
+ tertiaryButtonFill,
2649
+ tertiaryButtonFillHover,
2650
+ tertiaryButtonLabel,
2651
+ tertiaryButtonLabelSize,
2652
+ tertiaryButtonLabelTextColor,
2653
+ tertiaryButtonLabelTextWeight,
2654
+ tertiaryButtonSize,
2655
+ dataTestIdPrimaryButton,
2656
+ dataTourPrimaryButton,
2657
+ dataTestIdSecondaryButton,
2658
+ dataTourSecondaryButton,
2659
+ onClickSecondaryButton,
2660
+ dataTestIdTertiaryButton,
2661
+ dataTourTertiaryButton,
2662
+ onClickTertiaryButton,
2663
+ additionalProps = {},
2664
+ buttonDirection = 'vertical',
2665
+ buttonFill,
2666
+ buttonGap,
2667
+ buttonJustifyContent,
2668
+ buttonPadding,
2669
+ buttonPosition,
2670
+ dataTestId,
2671
+ dataTestIdButtons,
2672
+ dataTour,
2673
+ dataTourButtons,
2674
+ disableFieldsAutoComplete = false,
2675
+ fieldsGap,
2676
+ formName,
2677
+ groupGap,
2678
+ language,
2679
+ loader,
2680
+ loaderFill,
2681
+ loaderItemFill,
2682
+ loaderShape,
2683
+ loaderSize,
2684
+ loaderText,
2685
+ loaderType,
2686
+ mutators,
2687
+ notificationCloseButton,
2688
+ notificationType,
2689
+ renderFieldsWrapper = wrapperChildren => wrapperChildren,
2690
+ validationSchema,
2691
+ before,
2692
+ after,
2693
+ isLoading,
2694
+ onChangeFormValues,
2695
+ onSubmit
2696
+ } = props;
2697
+ const validate = useYupValidationSchema(validationSchema, language);
2698
+ const onRefFormInstance = React$1.useCallback(formInstance => {
2699
+ if (ref) {
2700
+ ref.current = formInstance;
2701
+ }
2702
+ }, [ref]);
2703
+ const propsGenerator = useDevicePropsGenerator.useDevicePropsGenerator(props);
2704
+ const {
2705
+ directionClass,
2706
+ fillClass,
2707
+ elevationClass,
2708
+ shapeClass
2709
+ } = propsGenerator;
2710
+ const {
2711
+ styles: formStyles,
2712
+ wrapper: wrapperStyles
2713
+ } = useStyles.useStyles(props);
2714
+ return /*#__PURE__*/React__default.default.createElement(reactFinalForm.Form, {
2715
+ initialValues: initialValues,
2716
+ initialValuesEqual: initialValuesEqual,
2717
+ render: ({
2718
+ submitError,
2719
+ form,
2720
+ handleSubmit,
2721
+ modifiedSinceLastSubmit
2722
+ }) => {
2723
+ return /*#__PURE__*/React__default.default.createElement("form", {
2724
+ className: clsx__default.default(className, 'form', type && `form_type_${type}`, buttonPosition && `form_button-position_${buttonPosition}`, directionClass, fillClass, shapeClass, elevationClass),
2725
+ name: formName,
2726
+ autoCapitalize: disableFieldsAutoComplete ? 'off' : undefined,
2727
+ autoComplete: disableFieldsAutoComplete ? 'off' : undefined,
2728
+ autoCorrect: disableFieldsAutoComplete ? 'off' : undefined,
2729
+ "data-test-id": dataTestId,
2730
+ "data-tour": dataTour
2731
+ // We no need set reference to html element, we need reference to "final-form" instance
2732
+ ,
2733
+ ref: () => onRefFormInstance(form),
2734
+ spellCheck: disableFieldsAutoComplete ? 'false' : undefined,
2735
+ style: formStyles,
2736
+ onSubmit: handleSubmit
2737
+ }, before, title && /*#__PURE__*/React__default.default.createElement(Title.Title, {
2738
+ className: "form__title",
2739
+ size: titleTextSize,
2740
+ fill: titleFill,
2741
+ textColor: titleTextColor,
2742
+ textWeight: titleTextWeight
2743
+ }, title), desc && /*#__PURE__*/React__default.default.createElement(Text.Text, {
2744
+ className: "form__desc",
2745
+ size: descSize,
2746
+ textColor: descTextColor,
2747
+ textWeight: descTextWeight
2748
+ }, desc), submitError && !modifiedSinceLastSubmit && /*#__PURE__*/React__default.default.createElement("div", {
2749
+ className: clsx__default.default('notification', 'form-notification', notificationType ? `form-notification_type_${notificationType}` : 'form-notification_type_global')
2750
+ }, /*#__PURE__*/React__default.default.createElement(Notification.NotificationItem, {
2751
+ className: "form-notification__item",
2752
+ title: form.getState().submitError,
2753
+ titleTextSize: "h6",
2754
+ status: "error",
2755
+ closeButton: notificationCloseButton,
2756
+ set: "form"
2757
+ })), onChangeFormValues && /*#__PURE__*/React__default.default.createElement(reactFinalForm.FormSpy, {
2758
+ subscription: {
2759
+ values: true
2760
+ },
2761
+ onChange: onChangeFormValues
2762
+ }), Boolean(Object.keys(config).length) && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, renderFieldsWrapper(/*#__PURE__*/React__default.default.createElement(Group$1.Group, {
2763
+ className: "form__wrapper",
2764
+ direction: "vertical",
2765
+ gap: fieldsGap || groupGap,
2766
+ style: wrapperStyles
2767
+ }, Object.keys(config).map(key => generateField(config[key], {
2768
+ key
2769
+ }, additionalProps[config[key].name])), isLoading && (loader || /*#__PURE__*/React__default.default.createElement(Loader.Loader, {
2770
+ className: "form__loader",
2771
+ type: loaderType,
2772
+ size: loaderSize,
2773
+ fill: loaderFill,
2774
+ text: loaderText,
2775
+ itemFill: loaderItemFill,
2776
+ shape: loaderShape
2777
+ }))))), (primaryButtonLabel || primaryButton || secondaryButtonLabel || secondaryButton || tertiaryButton || tertiaryButtonLabel) && /*#__PURE__*/React__default.default.createElement(Group$1.Group, {
2778
+ className: "form__button",
2779
+ direction: buttonDirection,
2780
+ justifyContent: buttonJustifyContent,
2781
+ fill: buttonFill,
2782
+ padding: buttonPadding,
2783
+ gap: buttonGap,
2784
+ dataTestId: dataTestIdButtons,
2785
+ dataTour: dataTourButtons
2786
+ }, primaryButtonLabel ? /*#__PURE__*/React__default.default.createElement(Button.Button, {
2787
+ className: "form__button-item",
2788
+ width: "fill",
2789
+ size: primaryButtonSize,
2790
+ fill: primaryButtonFill,
2791
+ fillHover: primaryButtonFillHover,
2792
+ label: primaryButtonLabel,
2793
+ labelTextColor: primaryButtonLabelTextColor,
2794
+ labelTextSize: primaryButtonLabelSize,
2795
+ labelTextWeight: primaryButtonLabelTextWeight,
2796
+ dataTestId: dataTestIdPrimaryButton,
2797
+ dataTour: dataTourPrimaryButton
2798
+ }) : primaryButton, secondaryButtonLabel ? /*#__PURE__*/React__default.default.createElement(Button.Button, {
2799
+ className: "form__button-item",
2800
+ width: "fill",
2801
+ size: secondaryButtonSize,
2802
+ fill: secondaryButtonFill,
2803
+ fillHover: secondaryButtonFillHover,
2804
+ label: secondaryButtonLabel,
2805
+ labelTextColor: secondaryButtonLabelTextColor,
2806
+ labelTextSize: secondaryButtonLabelSize,
2807
+ labelTextWeight: secondaryButtonLabelTextWeight,
2808
+ dataTestId: dataTestIdSecondaryButton,
2809
+ dataTour: dataTourSecondaryButton,
2810
+ onClick: onClickSecondaryButton
2811
+ }) : secondaryButton, tertiaryButtonLabel ? /*#__PURE__*/React__default.default.createElement(Button.Button, {
2812
+ className: "form__button-item",
2813
+ width: "fill",
2814
+ size: tertiaryButtonSize,
2815
+ fill: tertiaryButtonFill,
2816
+ fillHover: tertiaryButtonFillHover,
2817
+ label: tertiaryButtonLabel,
2818
+ labelTextColor: tertiaryButtonLabelTextColor,
2819
+ labelTextSize: tertiaryButtonLabelSize,
2820
+ labelTextWeight: tertiaryButtonLabelTextWeight,
2821
+ dataTestId: dataTestIdTertiaryButton,
2822
+ dataTour: dataTourTertiaryButton,
2823
+ onClick: onClickTertiaryButton
2824
+ }) : tertiaryButton), after);
2825
+ },
2826
+ decorators: [focusOnErrorDecorator],
2827
+ mutators: mutators,
2828
+ subscription: {
2829
+ submitError: true,
2830
+ modifiedSinceLastSubmit: true,
2831
+ pristine: true,
2832
+ submitting: true
2833
+ },
2834
+ validate: validate,
2835
+ onSubmit: onSubmit
2836
+ });
2837
+ });
2838
+ FinalForm.defaultProps = {
2839
+ direction: 'vertical'
2840
+ };
2841
+
2842
+ const DEFAULT_MESSAGES_FIELDS = {
2843
+ /*
2844
+ !!! it also works without props simply based on the class and key as before `input_state_${meta.error.key}`
2845
+ the KEY is needed for example for border color
2846
+ the name of the key is anything you want, the main thing is that there is a props with the same KEY and color in FieldProps
2847
+ ...example
2848
+ required - KEY for yellow color
2849
+ error - KEY for red color
2850
+ custom or blue - KEY blue or other color
2851
+ requiredBorderColor: 'warningBorderPrimary',
2852
+ errorBorderColor: 'errorBorderPrimary',
2853
+ customBorderColor: 'customBorderPrimary',
2854
+ blueBorderColor: 'blueBorderPrimary',
2855
+ const defaultFieldProps = {
2856
+ messageTextSize: 's',
2857
+ messageTextColor: 'surfaceTextSecondary',
2858
+ requiredMessageTextSize: 's',
2859
+ requiredMessageTextColor: 'warningTextPrimary',
2860
+ errorMessageTextSize: 's',
2861
+ errorMessageTextColor: 'errorTextPrimary',
2862
+ }
2863
+ // INPUT
2864
+ const defaultInputProps = {
2865
+ ... other
2866
+ stateBorderColor: 'surfaceBorderTertiary',
2867
+ requiredStateBorderColor: 'warningBorderPrimary',
2868
+ errorStateBorderColor: 'errorBorderPrimary',
2869
+ }
2870
+ // RADIO
2871
+ const defaultRadioProps = {
2872
+ ... other
2873
+ stateBorderColor: 'surfaceBorderTertiary',
2874
+ requiredStateBorderColor: 'warningBorderPrimary',
2875
+ errorStateBorderColor: 'errorBorderPrimary',
2876
+ }
2877
+ // SELECT
2878
+ const defaultSelectProps = {
2879
+ ... other
2880
+ borderColor: 'surfaceBorderTertiary',
2881
+ requiredBorderColor: 'warningBorderPrimary',
2882
+ errorBorderColor: 'errorBorderPrimary',
2883
+ inputBorderColor: 'surfaceBorderTertiary',
2884
+ requiredInputBorderColor: 'warningBorderPrimary',
2885
+ errorInputBorderColor: 'errorBorderPrimary',
2886
+ }
2887
+ ... etc
2888
+ */
2889
+
2890
+ // DEFAULT
2891
+ // required - KEY for yellow color
2892
+ // error - KEY for red color
2893
+
2894
+ // key: 'required'
2895
+ required: {
2896
+ key: 'required',
2897
+ message: 'Обязательное поле'
2898
+ },
2899
+ phone_required: {
2900
+ key: 'required',
2901
+ message: 'Укажите номер телефона'
2902
+ },
2903
+ email_required: {
2904
+ key: 'required',
2905
+ message: 'Укажите адрес электронной почты'
2906
+ },
2907
+ password_required: {
2908
+ key: 'required',
2909
+ message: 'Введите пароль'
2910
+ },
2911
+ phone_or_email_required: {
2912
+ key: 'required',
2913
+ message: 'Введите телефон или адрес эл. почты'
2914
+ },
2915
+ // key: 'error'
2916
+ matches: {
2917
+ key: 'error',
2918
+ message: 'Допускается ввод только цифр от 0 до 9'
2919
+ },
2920
+ min: {
2921
+ key: 'error',
2922
+ message: ({
2923
+ min
2924
+ }) => `Значение должно быть не менее ${min} символов`
2925
+ },
2926
+ max: {
2927
+ key: 'error',
2928
+ message: ({
2929
+ max
2930
+ }) => `Значение должно быть не менее ${max} символов`
2931
+ },
2932
+ url: {
2933
+ key: 'error',
2934
+ message: 'Введите корректный URL-адрес'
2935
+ },
2936
+ invalid_value: {
2937
+ key: 'error',
2938
+ message: 'Некорректное значение'
2939
+ },
2940
+ numeric_value: {
2941
+ key: 'error',
2942
+ message: 'Только числовое значение'
2943
+ },
2944
+ phone_error: {
2945
+ key: 'error',
2946
+ message: 'Введите корректный номер телефона'
2947
+ },
2948
+ email_error: {
2949
+ key: 'error',
2950
+ message: 'Введите корректный адрес электронной почты'
2951
+ }
2952
+ };
2953
+
2954
+ const parseNumericField = value => {
2955
+ const numberValue = value.slice(0, 10).replace(/,/g, '.').replace(/[^\d.]/g, '');
2956
+ const parsedValue = parseFloat(numberValue);
2957
+ if (parsedValue || parsedValue === 0) {
2958
+ if (numberValue.endsWith('.')) {
2959
+ if ((numberValue.match(/\./g) || []).length > 1) {
2960
+ return numberValue.slice(0, -1);
2961
+ }
2962
+ return numberValue;
2963
+ }
2964
+ return numberValue;
2965
+ }
2966
+ return '';
2967
+ };
2968
+
2969
+ // const getErrorsForFinalForm = (errorData) => {
2970
+ // /*
2971
+ // * errorData - its an "axios" error
2972
+ // */
2973
+
2974
+ // const formErrors = {}
2975
+
2976
+ // const responseErrorMessage = errorData.toJSON ? errorData.toJSON().message : errorData.message
2977
+
2978
+ // // const status = (errorData.response && errorData.response.status) || null
2979
+ // const problemError = getProblemFromError(errorData)
2980
+ // // const problemStatus = getProblemFromStatus(status)
2981
+
2982
+ // if (problemError === NETWORK_ERROR || problemError === CONNECTION_ERROR) {
2983
+ // // Say to "react-final-form" that we have general error
2984
+ // formErrors[FORM_ERROR] = 'Проблемы с подключением к сервису'
2985
+ // } else if (errorData.response?.data) {
2986
+ // // Collect errors for some fields, which in the response from server
2987
+ // const serverErrors = errorData.response.data
2988
+ // if (typeof serverErrors === 'string') {
2989
+ // if (errorData.response.status === 500) {
2990
+ // formErrors[FORM_ERROR] =
2991
+ // 'Во время обработки запроса произошла ошибка, попробуйте повторить запрос'
2992
+ // }
2993
+ // // formErrors[FORM_ERROR] = responseErrorMessage
2994
+ // } else {
2995
+ // if (errorData.response.status === 500) {
2996
+ // formErrors[FORM_ERROR] =
2997
+ // 'Во время обработки запроса произошла ошибка, попробуйте повторить запрос'
2998
+ // }
2999
+ // for (const key in serverErrors) {
3000
+ // // TODO: what is forms has "detail" field? show as form error is well?
3001
+ // const errorFieldKey = key === 'non_field_errors' || key === 'detail' ? FORM_ERROR : key
3002
+ // // Say to "react-final-form" that we have some fields errors
3003
+ // formErrors[errorFieldKey] = castArray(serverErrors[key])[0]
3004
+ // }
3005
+ // }
3006
+ // } else if (typeof errorData === 'object' && Object.keys(errorData).length) {
3007
+ // for (const key in errorData) {
3008
+ // const errorFieldKey = key === 'non_field_errors' || key === 'detail' ? FORM_ERROR : key
3009
+ // // Say to "react-final-form" that we have some fields errors
3010
+ // formErrors[errorFieldKey] = castArray(errorData[key])[0]
3011
+ // }
3012
+ // } else {
3013
+ // // Say to "react-final-form" that we have general error
3014
+ // formErrors[FORM_ERROR] = responseErrorMessage || 'Произошла ошибка'
3015
+ // }
3016
+
3017
+ // return formErrors
3018
+ // }
3019
+
3020
+ const getErrorsForFinalForm = error => {
3021
+ /*
3022
+ * error - its an "axios" error in many cases
3023
+ */
3024
+
3025
+ const formErrors = {};
3026
+ const serverErrors = error.response?.data;
3027
+ if (serverErrors) {
3028
+ // Collect errors for some fields, which in the response from server
3029
+ if (typeof serverErrors === 'string') {
3030
+ // Server may send an html page as error data
3031
+ formErrors[finalForm.FORM_ERROR] = 'Во время обработки запроса произошла ошибка, попробуйте повторить запрос';
3032
+ } else {
3033
+ for (const key in serverErrors) {
3034
+ // "non_field_errors" and "detail" is special keys in django to mark errors not for fields
3035
+ const errorFieldKey = key === 'non_field_errors' || key === 'detail' ? finalForm.FORM_ERROR : key;
3036
+
3037
+ // Say to "react-final-form" that we have some fields errors
3038
+ formErrors[errorFieldKey] = castArray__default.default(serverErrors[key])[0];
3039
+ }
3040
+ }
3041
+ } else {
3042
+ // const responseErrorMessage = error.toJSON
3043
+ // ? error.toJSON().message
3044
+ // : error.message
3045
+
3046
+ // Say to "react-final-form" that we have general error
3047
+ formErrors[finalForm.FORM_ERROR] = error.message || 'Произошла ошибка';
3048
+ }
3049
+ return formErrors;
3050
+ };
3051
+
3052
+ Object.defineProperty(exports, "Field", {
3053
+ enumerable: true,
3054
+ get: function () { return reactFinalForm.Field; }
3055
+ });
3056
+ Object.defineProperty(exports, "useForm", {
3057
+ enumerable: true,
3058
+ get: function () { return reactFinalForm.useForm; }
3059
+ });
3060
+ Object.defineProperty(exports, "useFormState", {
3061
+ enumerable: true,
3062
+ get: function () { return reactFinalForm.useFormState; }
3063
+ });
3064
+ exports.CheckboxField = CheckboxField;
3065
+ exports.ChipsField = ChipsField;
3066
+ exports.ChoiceField = ChoiceField;
3067
+ exports.CodeField = CodeField;
3068
+ exports.CustomField = CustomField;
3069
+ exports.DEFAULT_MESSAGES_FIELDS = DEFAULT_MESSAGES_FIELDS;
3070
+ exports.DatePickerField = DatePickerField;
3071
+ exports.FieldWrapper = FieldWrapper;
3072
+ exports.FieldWrapperBase = FieldWrapperBase;
3073
+ exports.FileInput = FileInput;
3074
+ exports.FinalForm = FinalForm;
3075
+ exports.Group = Group;
3076
+ exports.InputField = InputField;
3077
+ exports.MaskedInputField = MaskedInputField;
3078
+ exports.RadioGroup = RadioGroup;
3079
+ exports.SegmentedField = SegmentedField;
3080
+ exports.SelectField = SelectField;
3081
+ exports.SwitchField = SwitchField;
3082
+ exports.TextareaField = TextareaField;
3083
+ exports.addRequiredFieldsParamToSchema = addRequiredFieldsParamToSchema;
3084
+ exports.dateValidation = dateValidation;
3085
+ exports.defaultCheckboxProps = defaultCheckboxProps;
3086
+ exports.defaultChipsProps = defaultChipsProps;
3087
+ exports.defaultChoiceProps = defaultChoiceProps;
3088
+ exports.defaultCodeProps = defaultCodeProps;
3089
+ exports.defaultDatepickerProps = defaultDatepickerProps;
3090
+ exports.defaultDropzoneProps = defaultDropzoneProps;
3091
+ exports.defaultFieldProps = defaultFieldProps;
3092
+ exports.defaultInputProps = defaultInputProps;
3093
+ exports.defaultRadioProps = defaultRadioProps;
3094
+ exports.defaultSegmentedProps = defaultSegmentedProps;
3095
+ exports.defaultSelectProps = defaultSelectProps;
3096
+ exports.defaultSwitchProps = defaultSwitchProps;
3097
+ exports.defaultTextareaProps = defaultTextareaProps;
3098
+ exports.emailValidation = emailValidation;
3099
+ exports.focusOnError = focusOnError;
3100
+ exports.focusOnErrorDecorator = focusOnErrorDecorator;
3101
+ exports.formTypes = formTypes;
3102
+ exports.generateField = generateField;
3103
+ exports.getErrorsForFinalForm = getErrorsForFinalForm;
3104
+ exports.parseNumericField = parseNumericField;
3105
+ exports.phoneValidation = phoneValidation;
3106
+ exports.sendFormDataToServer = sendFormDataToServer;
3107
+ exports.setErrorsMutator = setErrorsMutator;
3108
+ exports.useYupValidationSchema = useYupValidationSchema;