@startlibs/form 1.0.11 → 1.1.0

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.
Files changed (92) hide show
  1. package/lib/AutoComplete.mjs +550 -0
  2. package/lib/AutoComplete.mjs.map +1 -0
  3. package/lib/Checkbox.mjs +76 -0
  4. package/lib/Checkbox.mjs.map +1 -0
  5. package/lib/Combobox.mjs +544 -0
  6. package/lib/Combobox.mjs.map +1 -0
  7. package/lib/ComboboxWithCustom.mjs +77 -0
  8. package/lib/ComboboxWithCustom.mjs.map +1 -0
  9. package/lib/DatePicker.mjs +625 -0
  10. package/lib/DatePicker.mjs.map +1 -0
  11. package/lib/EditableBox.mjs +496 -0
  12. package/lib/EditableBox.mjs.map +1 -0
  13. package/lib/Errors.mjs +176 -0
  14. package/lib/Errors.mjs.map +1 -0
  15. package/lib/ExpandableBox.mjs +209 -0
  16. package/lib/ExpandableBox.mjs.map +1 -0
  17. package/lib/Field.mjs +65 -0
  18. package/lib/Field.mjs.map +1 -0
  19. package/lib/FieldBox.mjs +80 -0
  20. package/lib/FieldBox.mjs.map +1 -0
  21. package/lib/Form.mjs +322 -0
  22. package/lib/Form.mjs.map +1 -0
  23. package/lib/FormValue.mjs +111 -0
  24. package/lib/FormValue.mjs.map +1 -0
  25. package/lib/InputboxGroup.mjs +104 -0
  26. package/lib/InputboxGroup.mjs.map +1 -0
  27. package/lib/Radiobox.mjs +67 -0
  28. package/lib/Radiobox.mjs.map +1 -0
  29. package/lib/RichText.mjs +634 -0
  30. package/lib/RichText.mjs.map +1 -0
  31. package/lib/TextInput.mjs +359 -0
  32. package/lib/TextInput.mjs.map +1 -0
  33. package/lib/alt/checkbox/SimpleCheckbox.mjs +82 -0
  34. package/lib/alt/checkbox/SimpleCheckbox.mjs.map +1 -0
  35. package/lib/alt/checkbox/ToggleCheckbox.mjs +68 -0
  36. package/lib/alt/checkbox/ToggleCheckbox.mjs.map +1 -0
  37. package/lib/alt/radiobox/CleanTabRadiobox.mjs +44 -0
  38. package/lib/alt/radiobox/CleanTabRadiobox.mjs.map +1 -0
  39. package/lib/alt/radiobox/IconRadioBox.mjs +52 -0
  40. package/lib/alt/radiobox/IconRadioBox.mjs.map +1 -0
  41. package/lib/alt/radiobox/SimpleRadiobox.mjs +61 -0
  42. package/lib/alt/radiobox/SimpleRadiobox.mjs.map +1 -0
  43. package/lib/alt/radiobox/TabRadiobox.mjs +54 -0
  44. package/lib/alt/radiobox/TabRadiobox.mjs.map +1 -0
  45. package/lib/enhanceInput.mjs +131 -0
  46. package/lib/enhanceInput.mjs.map +1 -0
  47. package/lib/index.cjs +5345 -0
  48. package/lib/index.cjs.map +1 -0
  49. package/lib/index.mjs +28 -0
  50. package/lib/index.mjs.map +1 -0
  51. package/lib/useConfirmDialog.mjs +117 -0
  52. package/lib/useConfirmDialog.mjs.map +1 -0
  53. package/lib/useDraftConfirmation.mjs +56 -0
  54. package/lib/useDraftConfirmation.mjs.map +1 -0
  55. package/lib/validation.mjs +91 -0
  56. package/lib/validation.mjs.map +1 -0
  57. package/lib/withFormImageInput.mjs +281 -0
  58. package/lib/withFormImageInput.mjs.map +1 -0
  59. package/package.json +44 -25
  60. package/src/AutoComplete.jsx +642 -0
  61. package/src/Checkbox.jsx +45 -0
  62. package/src/Combobox.jsx +606 -0
  63. package/src/ComboboxWithCustom.jsx +68 -0
  64. package/src/DatePicker.jsx +733 -0
  65. package/src/EditableBox.jsx +502 -0
  66. package/src/Errors.jsx +174 -0
  67. package/src/ExpandableBox.jsx +207 -0
  68. package/src/Field.jsx +76 -0
  69. package/src/FieldBox.jsx +136 -0
  70. package/src/Form.jsx +291 -0
  71. package/src/FormValue.jsx +67 -0
  72. package/src/IconRadioBoxOldHubt.jsx +93 -0
  73. package/src/InputboxGroup.jsx +121 -0
  74. package/src/Radiobox.jsx +33 -0
  75. package/src/RichText.jsx +812 -0
  76. package/src/TextInput.jsx +519 -0
  77. package/src/alt/checkbox/SimpleCheckbox.jsx +162 -0
  78. package/src/alt/checkbox/ToggleCheckbox.jsx +143 -0
  79. package/src/alt/radiobox/CleanTabRadiobox.jsx +46 -0
  80. package/src/alt/radiobox/IconRadioBox.jsx +93 -0
  81. package/src/alt/radiobox/SimpleRadiobox.jsx +153 -0
  82. package/src/alt/radiobox/TabRadiobox.jsx +73 -0
  83. package/src/enhanceInput.jsx +107 -0
  84. package/src/index.js +27 -0
  85. package/src/useConfirmDialog.jsx +105 -0
  86. package/src/useDraftConfirmation.jsx +60 -0
  87. package/src/validation.js +92 -0
  88. package/src/withFormImageInput.jsx +297 -0
  89. package/.babelrc +0 -28
  90. package/lib/index.js +0 -6255
  91. package/rollup.config.js +0 -43
  92. package/yarn-error.log +0 -1607
package/lib/index.mjs ADDED
@@ -0,0 +1,28 @@
1
+ export { ComponentMetaContext, Form, FormContext, WithForm, getFormResponse, getFormValues, useForm, useFormMeta, useFormValue, useFormValueRef, withForm, withForm2 } from './Form.mjs';
2
+ export { EnhanceInput, PathContext, enhanceInput, enhancedInputDisplayName, useInput } from './enhanceInput.mjs';
3
+ export { BellowFieldDescription, Field, FieldDescription, HelpText } from './Field.mjs';
4
+ export { FieldBox, FieldBoxAction, FieldBoxHelpText, FieldBoxIcon } from './FieldBox.mjs';
5
+ export { ConfirmDialog, FormDialog, useConfirmDialog, useConfirmDialogWithProps } from './useConfirmDialog.mjs';
6
+ export { FloatLabelTextInput, TextInput, useTextInput } from './TextInput.mjs';
7
+ export { ErrorFilterProvider, Errors, ErrorsContext, useErrors, useErrorsUtils, useHasError, useProvideErrors, useTransientErrorHelper } from './Errors.mjs';
8
+ export { FileInput, WithFileInput, WithImageInput } from './withFormImageInput.mjs';
9
+ export { Checkbox } from './Checkbox.mjs';
10
+ export { Combobox, ComboboxInput, ComboboxMenu, NO_DIGITABLE_FOUND, Option, SEPARATOR } from './Combobox.mjs';
11
+ export { ComboboxWithCustom } from './ComboboxWithCustom.mjs';
12
+ export { AutoComplete, AutoCompleteTextbox } from './AutoComplete.mjs';
13
+ export { ConfirmEditableBoxes, EditableBox } from './EditableBox.mjs';
14
+ export { FormMeta, FormValue, IfFormMeta, IfFormValue, IfFormValueUpdate, LazyFormValues, SwitchOnFormValue } from './FormValue.mjs';
15
+ export { Radiobox } from './Radiobox.mjs';
16
+ export { CheckboxGroup, InputboxGroup, RadioboxGroup } from './InputboxGroup.mjs';
17
+ export { CALENDAR_LEVEL_DAY, CALENDAR_LEVEL_MONTH, CALENDAR_LEVEL_YEAR, DatePicker } from './DatePicker.mjs';
18
+ export { ExpandableBox, PseudoExpandableBox, checkErrors } from './ExpandableBox.mjs';
19
+ export { RichText, RichTextContainer, RichTextInput } from './RichText.mjs';
20
+ export { IconRadioBox, IconRadioBoxIconContainer, IconRadioBoxText } from './alt/radiobox/IconRadioBox.mjs';
21
+ export { SimpleCheckbox } from './alt/checkbox/SimpleCheckbox.mjs';
22
+ export { ToggleCheckbox } from './alt/checkbox/ToggleCheckbox.mjs';
23
+ export { TabButton, TabRadiobox } from './alt/radiobox/TabRadiobox.mjs';
24
+ export { CleanTabRadiobox, Tab } from './alt/radiobox/CleanTabRadiobox.mjs';
25
+ export { SimpleRadiobox } from './alt/radiobox/SimpleRadiobox.mjs';
26
+ export { useDraftConfirmation } from './useDraftConfirmation.mjs';
27
+ export { validation } from './validation.mjs';
28
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,117 @@
1
+ import _identity from 'lodash/fp/identity';
2
+ import React from 'react';
3
+ import { Errors } from './Errors.mjs';
4
+ import { WithForm } from './Form.mjs';
5
+ import { addExtraProp, callIfFunction, using } from '@startlibs/utils';
6
+ import { useDialog, useDialogWithToggle, setNotification, Dialog, Button } from '@startlibs/components';
7
+
8
+ const useConfirmDialog = (dialog, args, toggleCallback) => {
9
+ return useDialog(closeDialog => addExtraProp(callIfFunction(dialog, closeDialog), {
10
+ closeDialog
11
+ }), args, toggleCallback);
12
+ };
13
+ const useConfirmDialogWithProps = function (dialog, args) {
14
+ let {
15
+ overrideClose = true
16
+ } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
17
+ return useDialogWithToggle(toggle => addExtraProp(callIfFunction(dialog, toggle.isOpen, toggle.close), {
18
+ closeDialog: toggle.close
19
+ }, overrideClose), args);
20
+ };
21
+ const ConfirmDialog = _ref => {
22
+ let {
23
+ action = _identity,
24
+ onSuccess,
25
+ skipDom,
26
+ className,
27
+ closeDialog,
28
+ onClose,
29
+ skipCloseIcon,
30
+ cancelLabel = "Cancelar",
31
+ cancelButton = cancelLabel && /*#__PURE__*/React.createElement(Button, {
32
+ tabIndex: 2
33
+ }, cancelLabel),
34
+ onFailure,
35
+ title,
36
+ keepOnSuccess,
37
+ confirm,
38
+ formRef,
39
+ children,
40
+ preValidation,
41
+ onNonPreValidation,
42
+ values,
43
+ meta,
44
+ onChange,
45
+ alternativeButton,
46
+ notify,
47
+ confirmChanges,
48
+ auxiliarActions,
49
+ transform,
50
+ isLoading,
51
+ stickyFooter,
52
+ fullscreen,
53
+ fullscreenOnMobile,
54
+ alwaysSave = true,
55
+ skipErrors,
56
+ hidden,
57
+ skipCheckFocus
58
+ } = _ref;
59
+ const handleClose = React.useCallback(async () => {
60
+ if (onClose) await onClose().catch(console.error);
61
+ if (closeDialog) closeDialog();
62
+ }, [onClose, closeDialog]);
63
+ return /*#__PURE__*/React.createElement(WithForm, {
64
+ alwaysSave: alwaysSave,
65
+ ref: formRef,
66
+ preValidation: preValidation,
67
+ onNonPreValidation: onNonPreValidation,
68
+ values: values,
69
+ meta: meta,
70
+ action: action,
71
+ transform: transform,
72
+ onFailure: onFailure,
73
+ onChange: onChange,
74
+ onSuccess: function () {
75
+ for (var _len = arguments.length, props = new Array(_len), _key = 0; _key < _len; _key++) {
76
+ props[_key] = arguments[_key];
77
+ }
78
+ return Promise.resolve(callIfFunction(onSuccess, ...props)).then(v => {
79
+ if (!keepOnSuccess) {
80
+ handleClose();
81
+ }
82
+ if (notify) {
83
+ setNotification(notify);
84
+ }
85
+ return v;
86
+ });
87
+ }
88
+ }, form => !hidden && /*#__PURE__*/React.createElement(Dialog, {
89
+ className: className,
90
+ title: title,
91
+ skipCheckFocus: skipCheckFocus,
92
+ skipCloseIcon: skipCloseIcon,
93
+ confirmChanges: confirmChanges,
94
+ isLoading: isLoading,
95
+ closeDialog: handleClose,
96
+ form: form,
97
+ stickyFooter: stickyFooter,
98
+ auxiliarActions: auxiliarActions,
99
+ fullscreen: fullscreen,
100
+ fullscreenOnMobile: fullscreenOnMobile,
101
+ footer: (cancelButton || alternativeButton || confirm) && /*#__PURE__*/React.createElement(React.Fragment, null, cancelButton && addExtraProp(callIfFunction(cancelButton, handleClose), {
102
+ onClick: handleClose
103
+ }, false), callIfFunction(alternativeButton, handleClose), confirm && using(callIfFunction(confirm, {
104
+ form,
105
+ isLoading
106
+ }))(c => c && addExtraProp(c, {
107
+ isLoading: form.isLoading,
108
+ type: "submit"
109
+ })))
110
+ }, callIfFunction(children, form), !skipErrors && /*#__PURE__*/React.createElement(Errors, {
111
+ autoScroll: true
112
+ })));
113
+ };
114
+ const FormDialog = ConfirmDialog;
115
+
116
+ export { ConfirmDialog, FormDialog, useConfirmDialog, useConfirmDialogWithProps };
117
+ //# sourceMappingURL=useConfirmDialog.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useConfirmDialog.mjs","sources":["../src/useConfirmDialog.jsx"],"sourcesContent":["import React from 'react'\nimport _ from 'lodash/fp'\nimport {Errors} from './Errors'\nimport {WithForm} from './Form'\nimport {callIfFunction, addExtraProp, using} from '@startlibs/utils'\nimport {setNotification, Button, Dialog} from '@startlibs/components'\nimport {useDialogWithToggle, useDialog} from '@startlibs/components'\n\nexport const useConfirmDialog = (dialog, args, toggleCallback) => {\n return useDialog((closeDialog) => addExtraProp(callIfFunction(dialog, closeDialog), {closeDialog}), args, toggleCallback)\n}\n\nexport const useConfirmDialogWithProps = (dialog, args, {overrideClose = true} = {}) => {\n return useDialogWithToggle((toggle) => addExtraProp(callIfFunction(dialog, toggle.isOpen, toggle.close), {closeDialog: toggle.close}, overrideClose), args)\n}\n\nexport const ConfirmDialog = ({\n action = _.identity,\n onSuccess,\n skipDom,\n className,\n closeDialog,\n onClose,\n skipCloseIcon,\n cancelLabel = \"Cancelar\",\n cancelButton = cancelLabel && <Button tabIndex={2}>{cancelLabel}</Button>,\n onFailure,\n title,\n keepOnSuccess,\n confirm,\n formRef,\n children,\n preValidation,\n onNonPreValidation,\n values,meta,\n onChange,\n alternativeButton,\n notify,\n confirmChanges,\n auxiliarActions,\n transform,\n isLoading,\n stickyFooter,\n fullscreen,\n fullscreenOnMobile,\n alwaysSave = true,skipErrors,\n hidden,\n skipCheckFocus\n }) => {\n const handleClose = React.useCallback(async () => {\n if (onClose) await onClose().catch(console.error)\n if (closeDialog) closeDialog()\n }, [onClose, closeDialog])\n\n return <WithForm\n alwaysSave={alwaysSave}\n ref={formRef}\n preValidation={preValidation}\n onNonPreValidation={onNonPreValidation}\n values={values}\n meta={meta}\n action={action}\n transform={transform}\n onFailure={onFailure}\n onChange={onChange}\n onSuccess={(...props) =>\n Promise.resolve(callIfFunction(onSuccess, ...props))\n .then((v) => {\n if (!keepOnSuccess) {\n handleClose()\n }\n if (notify) {\n setNotification(notify)\n }\n return v\n })\n }\n >{form => !hidden &&\n <Dialog\n className={className}\n title={title}\n skipCheckFocus={skipCheckFocus}\n skipCloseIcon={skipCloseIcon}\n confirmChanges={confirmChanges}\n isLoading={isLoading}\n closeDialog={handleClose}\n form={form}\n stickyFooter={stickyFooter}\n auxiliarActions={auxiliarActions}\n fullscreen={fullscreen}\n fullscreenOnMobile={fullscreenOnMobile}\n footer={(cancelButton || alternativeButton || confirm) && <>\n {cancelButton && addExtraProp(callIfFunction(cancelButton,handleClose),{onClick:handleClose},false)}\n {callIfFunction(alternativeButton, handleClose)}\n {confirm && using(callIfFunction(confirm,{form,isLoading}))( c => c && addExtraProp(c, {isLoading: form.isLoading, type: \"submit\"}))}\n </>}\n >\n {callIfFunction(children,form)}\n {!skipErrors && <Errors autoScroll/>}\n </Dialog>\n }</WithForm>\n}\n\n\nexport const FormDialog = ConfirmDialog"],"names":["useConfirmDialog","dialog","args","toggleCallback","useDialog","closeDialog","addExtraProp","callIfFunction","useConfirmDialogWithProps","overrideClose","arguments","length","undefined","useDialogWithToggle","toggle","isOpen","close","ConfirmDialog","_ref","action","_identity","onSuccess","skipDom","className","onClose","skipCloseIcon","cancelLabel","cancelButton","React","createElement","Button","tabIndex","onFailure","title","keepOnSuccess","confirm","formRef","children","preValidation","onNonPreValidation","values","meta","onChange","alternativeButton","notify","confirmChanges","auxiliarActions","transform","isLoading","stickyFooter","fullscreen","fullscreenOnMobile","alwaysSave","skipErrors","hidden","skipCheckFocus","handleClose","useCallback","catch","console","error","WithForm","ref","_len","props","Array","_key","Promise","resolve","then","v","setNotification","form","Dialog","footer","Fragment","onClick","using","c","type","Errors","autoScroll","FormDialog"],"mappings":";;;;;;;AAQO,MAAMA,gBAAgB,GAAGA,CAACC,MAAM,EAAEC,IAAI,EAAEC,cAAc,KAAK;AAChE,EAAA,OAAOC,SAAS,CAAEC,WAAW,IAAKC,YAAY,CAACC,cAAc,CAACN,MAAM,EAAEI,WAAW,CAAC,EAAE;AAACA,IAAAA,WAAAA;AAAW,GAAC,CAAC,EAAEH,IAAI,EAAEC,cAAc,CAAC,CAAA;AAC3H,EAAC;AAEM,MAAMK,yBAAyB,GAAG,UAACP,MAAM,EAAEC,IAAI,EAAkC;EAAA,IAAhC;AAACO,IAAAA,aAAa,GAAG,IAAA;AAAI,GAAC,GAAAC,SAAA,CAAAC,MAAA,GAAAD,CAAAA,IAAAA,SAAA,CAAAE,CAAAA,CAAAA,KAAAA,SAAA,GAAAF,SAAA,CAAG,CAAA,CAAA,GAAA,EAAE,CAAA;AACjF,EAAA,OAAOG,mBAAmB,CAAEC,MAAM,IAAK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RefToggle, useRefState, StartlibsContext } from '@startlibs/core';
4
+ import { callIfFunction } from '@startlibs/utils';
5
+
6
+ const useDraftConfirmation = (submit, discard, meta) => {
7
+ const loading = useToggle();
8
+ const dialog = useToggle();
9
+ const draft = useRefToggle();
10
+ const promiseResolver = useRefState();
11
+ const startlibs = useContext(StartlibsContext);
12
+ const confirmation = function () {
13
+ let dialogType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'submit-draft';
14
+ let callback = arguments.length > 1 ? arguments[1] : undefined;
15
+ if (callIfFunction(draft.isOpen)) {
16
+ dialog.openWith(dialogType);
17
+ return new Promise(res => promiseResolver.set(() => r => {
18
+ dialog.close();
19
+ callIfFunction(callback, r);
20
+ res(r);
21
+ }));
22
+ } else {
23
+ return Promise.resolve();
24
+ }
25
+ };
26
+ const submitAndResolve = async () => {
27
+ loading.open();
28
+ try {
29
+ await submit();
30
+ callIfFunction(promiseResolver.get());
31
+ } catch (e) {} finally {
32
+ dialog.close();
33
+ loading.close();
34
+ }
35
+ };
36
+ const discardAndResolve = () => {
37
+ callIfFunction(discard);
38
+ callIfFunction(promiseResolver.get());
39
+ };
40
+ const Dialog = startlibs.dialogs[dialog.isOpen];
41
+ if (process.env.NODE_ENV !== 'production') {
42
+ if (dialog.isOpen && !Dialog) {
43
+ console.log("Dialog [".concat(dialogType, "] not registered in startlibs.dialogs"));
44
+ }
45
+ }
46
+ const feedback = dialog.isOpen ? /*#__PURE__*/React.createElement(Dialog, _extends({
47
+ submit: submitAndResolve,
48
+ discard: discardAndResolve,
49
+ isLoading: loading.isOpen,
50
+ cancel: dialog.close
51
+ }, meta)) : null;
52
+ return [feedback, draft, confirmation];
53
+ };
54
+
55
+ export { useDraftConfirmation };
56
+ //# sourceMappingURL=useDraftConfirmation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDraftConfirmation.mjs","sources":["../src/useDraftConfirmation.jsx"],"sourcesContent":["import React, {useContext} from 'react'\nimport {useToggle, useRefToggle, StartlibsContext, useRefState} from '@startlibs/core'\nimport {callIfFunction} from '@startlibs/utils'\n\nexport const useDraftConfirmation = (submit, discard, meta) => {\n const loading = useToggle()\n const dialog = useToggle()\n const draft = useRefToggle()\n const promiseResolver = useRefState()\n const startlibs = useContext(StartlibsContext)\n\n const confirmation = (dialogType = 'submit-draft', callback) => {\n if (callIfFunction(draft.isOpen)) {\n dialog.openWith(dialogType)\n return new Promise((res) =>\n promiseResolver.set(() => (r) => {\n dialog.close()\n callIfFunction(callback,r)\n res(r)\n }))\n } else {\n return Promise.resolve()\n }\n }\n\n\n const submitAndResolve = async () => {\n loading.open()\n try {\n await submit()\n callIfFunction(promiseResolver.get())\n } catch (e) { } finally {\n dialog.close()\n loading.close()\n }\n }\n\n const discardAndResolve = () => {\n callIfFunction(discard)\n callIfFunction(promiseResolver.get())\n }\n\n const Dialog = startlibs.dialogs[dialog.isOpen]\n if (process.env.NODE_ENV !== 'production') {\n if (dialog.isOpen && !Dialog) { console.log(`Dialog [${dialogType}] not registered in startlibs.dialogs`) }\n }\n\n const feedback =\n dialog.isOpen\n ? <Dialog\n submit={submitAndResolve}\n discard={discardAndResolve}\n isLoading={loading.isOpen}\n cancel={dialog.close}\n {...meta}\n />\n : null\n\n return [feedback, draft, confirmation]\n}"],"names":["useDraftConfirmation","submit","discard","meta","loading","useToggle","dialog","draft","useRefToggle","promiseResolver","useRefState","startlibs","useContext","StartlibsContext","confirmation","dialogType","arguments","length","undefined","callback","callIfFunction","isOpen","openWith","Promise","res","set","r","close","resolve","submitAndResolve","open","get","e","discardAndResolve","Dialog","dialogs","process","env","NODE_ENV","console","log","concat","feedback","React","createElement","_extends","isLoading","cancel"],"mappings":";;;;;AAIO,MAAMA,oBAAoB,GAAGA,CAACC,MAAM,EAAEC,OAAO,EAAEC,IAAI,KAAK;AAC7D,EAAA,MAAMC,OAAO,GAAGC,SAAS,EAAE,CAAA;AAC3B,EAAA,MAAMC,MAAM,GAAGD,SAAS,EAAE,CAAA;AAC1B,EAAA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B,KAAA;GACD,CAAA;EAED,MAAMM,iBAAiB,GAAGA,MAAM;IAC9Bb,cAAc,CAAClB,OAAO,CAAC,CAAA;AACvBkB,IAAAA,cAAc,CAACX,eAAe,CAACsB,GAAG,EAAE,CAAC,CAAA;GACtC,CAAA;EAED,MAAMG,MAAM,GAAGvB,SAAS,CAACwB,OAAO,CAAC7B,MAAM,CAACe,MAAM,CAAC,CAAA;AAC/C,EAAA,IAAIe,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;AACzC,IAAA,IAAIhC,MAAM,CAACe,MAAM,IAAI,CAACa,MAAM,EAAE;AAAEK,MAAAA,OAAO,CAACC,GAAG,CAAA,UAAA,CAAAC,MAAA,CAAY1B,UAAU,0CAAuC,CAAC,CAAA;AAAC,KAAA;AAC5G,GAAA;AAEA,EAAA,MAAM2B,QAAQ,GACZpC,MAAM,CAACe,MAAM,gBACXsB,KAAA,CAAAC,aAAA,CAACV,MAAM,EAAAW,QAAA,CAAA;AACP5C,IAAAA,MAAM,EAAE4B,gBAAiB;AACzB3B,IAAAA,OAAO,EAAE+B,iBAAkB;IAC3Ba,SAAS,EAAE1C,OAAO,CAACiB,MAAO;IAC1B0B,MAAM,EAAEzC,MAAM,CAACqB,KAAAA;AAAM,GAAA,EACjBxB,IAAI,CACT,CAAC,GACA,IAAI,CAAA;AAER,EAAA,OAAO,CAACuC,QAAQ,EAAEnC,KAAK,EAAEO,YAAY,CAAC,CAAA;AACxC;;;;"}
@@ -0,0 +1,91 @@
1
+ import _defineProperty from '@babel/runtime/helpers/defineProperty';
2
+ import _fromPairs from 'lodash/fp/fromPairs';
3
+ import _filter from 'lodash/fp/filter';
4
+ import _get from 'lodash/fp/get';
5
+ import _map from 'lodash/fp/map';
6
+ import _entries from 'lodash/fp/entries';
7
+ import _flow from 'lodash/fp/flow';
8
+ import { callIfFunction } from '@startlibs/utils';
9
+
10
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
11
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
12
+ const error = 'Error';
13
+ let messages = {
14
+ required: error,
15
+ minLength: n => error,
16
+ confirmPassword: error,
17
+ confirmEmails: error,
18
+ emailValidation: error,
19
+ SERVER_ERROR: error
20
+ };
21
+ let SERVER_ERROR = messages.SERVER_ERROR;
22
+ const setErrorMessages = newMessages => messages = newMessages;
23
+ const onEmpty = (success, errors) => Object.keys(errors).length ? errors : success;
24
+ const required = (s, k) => !s && messages.required;
25
+ const minLength = n => (s, k) => s && s.length < n && messages.minLength(n);
26
+ const confirmPasswords = passwordKey => (confirm, k, props) => (props[passwordKey] || confirm) && props[passwordKey] !== confirm && messages.confirmPassword;
27
+ const confirmEmails = emailKey => (confirm, k, props) => (props[emailKey] || confirm) && props[emailKey] !== confirm && messages.confirmEmails;
28
+ const confirm = function (sourceKey, messageKey) {
29
+ let isEqual = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (a, b) => a === b;
30
+ return (confirm, k, props) => (props[sourceKey] || confirm) && !isEqual(props[sourceKey], confirm) && (messages[messageKey] || messageKey);
31
+ };
32
+ const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;
33
+ const emailValidation = (s, k) => !emailRegex.test(s) && messages.emailValidation;
34
+ const optional = cb => function (v) {
35
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
36
+ args[_key - 1] = arguments[_key];
37
+ }
38
+ return v ? cb(v, ...args) : false;
39
+ };
40
+ const buildValidation = function (validations) {
41
+ let custom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : () => {};
42
+ return values => onEmpty(false, _objectSpread(_objectSpread({}, _flow(_entries, _map(_ref => {
43
+ let [k, v] = _ref;
44
+ return [k, [].concat(v).map(fn => fn(_get(k, values), k, values)).filter(_ => _)];
45
+ }), _filter(_ref2 => {
46
+ let [k, v] = _ref2;
47
+ return v.length;
48
+ }), _fromPairs)(callIfFunction(validations))), callIfFunction(custom, values)));
49
+ };
50
+ const buildAsyncValidation = function (validations) {
51
+ let custom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : async () => {};
52
+ return async props => onEmpty(false, _objectSpread(_objectSpread({}, await _flow(_entries, _map(_ref3 => {
53
+ let [k, v] = _ref3;
54
+ return Promise.all([].concat(v).map(fn => fn(_get(k, props), k, props))).then(v => [k, v.filter(Boolean)]);
55
+ }), promiseArray => Promise.all(promiseArray).then(v => _flow(_filter(_ref4 => {
56
+ let [k, v] = _ref4;
57
+ return v.length;
58
+ }), _fromPairs)(v)))(await callIfFunction(validations))), await callIfFunction(custom, props)));
59
+ };
60
+ const responseFailure = fn => (v, response, _ref5) => {
61
+ let {
62
+ setErrors
63
+ } = _ref5;
64
+ const errorSetter = setErrors;
65
+ const r = [].concat(response, v);
66
+ const error = fn(...r);
67
+ if (error === true) ; else if (error) {
68
+ errorSetter(error);
69
+ } else if (!_get('[0].errors', response)) {
70
+ errorSetter({
71
+ "": [messages.SERVER_ERROR]
72
+ });
73
+ }
74
+ };
75
+ const validation = {
76
+ SERVER_ERROR,
77
+ setErrorMessages,
78
+ required,
79
+ minLength,
80
+ confirmPasswords,
81
+ confirmEmails,
82
+ confirm,
83
+ emailValidation,
84
+ optional,
85
+ buildValidation,
86
+ buildAsyncValidation,
87
+ responseFailure
88
+ };
89
+
90
+ export { SERVER_ERROR, buildAsyncValidation, buildValidation, confirm, confirmEmails, confirmPasswords, emailValidation, minLength, optional, required, responseFailure, setErrorMessages, validation };
91
+ //# sourceMappingURL=validation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.mjs","sources":["../src/validation.js"],"sourcesContent":["import _ from 'lodash/fp'\nimport {callIfFunction} from '@startlibs/utils'\n\nconst error = 'Error'\n\nlet messages = {\n required: error,\n minLength: (n) => error,\n confirmPassword: error,\n confirmEmails: error,\n emailValidation: error,\n SERVER_ERROR: error\n}\n\nexport let SERVER_ERROR = messages.SERVER_ERROR\n\nexport const setErrorMessages = (newMessages) => messages = newMessages\n\nconst onEmpty = (success, errors) => Object.keys(errors).length ? errors : success\n\nexport const required = (s, k) => !s && messages.required\n\nexport const minLength = (n) => (s, k) => s && s.length < n && messages.minLength(n)\n\nexport const confirmPasswords = (passwordKey) => (confirm, k, props) => (props[passwordKey] || confirm) && props[passwordKey] !== confirm && messages.confirmPassword\nexport const confirmEmails = (emailKey) => (confirm, k, props) => (props[emailKey] || confirm) && props[emailKey] !== confirm && messages.confirmEmails\nexport const confirm = (sourceKey,messageKey,isEqual = (a,b) => a === b) => (confirm, k, props) => (props[sourceKey] || confirm) && !isEqual(props[sourceKey],confirm) && (messages[messageKey] || messageKey)\n\nconst emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@(([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{2,})$/i\nexport const emailValidation = (s, k) => !emailRegex.test(s) && messages.emailValidation\n\nexport const optional = (cb) => (v, ...args) => v ? cb(v, ...args) : false\n\nexport const buildValidation = (validations, custom = () => {\n}) => (values) =>\n onEmpty(false,\n {\n ..._.flow(\n _.entries,\n _.map(([k, v]) => [k, [].concat(v).map(fn => fn(_.get(k, values), k, values)).filter(_ => _)]),\n _.filter(([k, v]) => v.length),\n _.fromPairs\n )(callIfFunction(validations)),\n ...callIfFunction(custom, values)\n }\n )\n\nexport const buildAsyncValidation = (validations, custom = async () => {\n}) => async (props) =>\n onEmpty(false,\n {\n ... await _.flow(\n _.entries,\n _.map(([k, v]) => Promise.all([].concat(v).map(fn => fn(_.get(k, props), k, props))).then(v => [k,v.filter(Boolean)])),\n promiseArray => Promise.all(promiseArray).then((v) =>\n _.flow(\n _.filter(([k, v]) => v.length),\n _.fromPairs\n )(v)\n )\n )(await callIfFunction(validations)),\n ... await callIfFunction(custom, props)\n }\n )\n\n\nexport const responseFailure = (fn) => (v, response, {setErrors}) => {\n const errorSetter = setErrors\n const r = [].concat(response, v)\n const error = fn(...r)\n if (error === true) {\n } else if (error) {\n errorSetter(error)\n } else if (!_.get('[0].errors',response)) {\n errorSetter({\"\": [messages.SERVER_ERROR]})\n }\n}\n\nexport const validation = {\n SERVER_ERROR,\n setErrorMessages,\n required,\n minLength,\n confirmPasswords,\n confirmEmails,\n confirm,\n emailValidation,\n optional,\n buildValidation,\n buildAsyncValidation,\n responseFailure\n}"],"names":["error","messages","required","minLength","n","confirmPassword","confirmEmails","emailValidation","SERVER_ERROR","setErrorMessages","newMessages","onEmpty","success","errors","Object","keys","length","s","k","confirmPasswords","passwordKey","confirm","props","emailKey","sourceKey","messageKey","isEqual","arguments","undefined","a","b","emailRegex","test","optional","cb","v","_len","args","Array","_key","buildValidation","validations","custom","values","_objectSpread","_flow","_entries","_map","_ref","concat","map","fn","_get","filter","_","_filter","_ref2","_fromPairs","callIfFunction","buildAsyncValidation","_ref3","Promise","all","then","Boolean","promiseArray","_ref4","responseFailure","response","_ref5","setErrors","errorSetter","r","validation"],"mappings":";;;;;;;;;;;AAGA,MAAMA,KAAK,GAAG,OAAO,CAAA;AAErB,IAAIC,QAAQ,GAAG;AACbC,EAAAA,QAAQ,EAAEF,KAAK;EACfG,SAAS,EAAGC,CAAC,IAAKJ,KAAK;AACvBK,EAAAA,eAAe,EAAEL,KAAK;AACtBM,EAAAA,aAAa,EAAEN,K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;AAAC,MAAA,EAAE,EAAE,CAACtE,QAAQ,CAACO,YAAY,CAAA;AAAC,KAAC,CAAC,CAAA;AAC5C,GAAA;AACF,EAAC;AAEM,MAAMiE,UAAU,GAAG;EACxBjE,YAAY;EACZC,gBAAgB;EAChBP,QAAQ;EACRC,SAAS;EACTgB,gBAAgB;EAChBb,aAAa;EACbe,OAAO;EACPd,eAAe;EACf0B,QAAQ;EACRO,eAAe;EACfmB,oBAAoB;AACpBQ,EAAAA,eAAAA;AACF;;;;"}
@@ -0,0 +1,281 @@
1
+ import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
2
+ import _filter from 'lodash/fp/filter';
3
+ import _get from 'lodash/fp/get';
4
+ import _difference from 'lodash/fp/difference';
5
+ import _union from 'lodash/fp/union';
6
+ import _update from 'lodash/fp/update';
7
+ import _set from 'lodash/fp/set';
8
+ import _flow from 'lodash/fp/flow';
9
+ import _stubFalse from 'lodash/fp/stubFalse';
10
+ import React, { useContext, useState } from 'react';
11
+ import styled from 'styled-components';
12
+ import { FormContext, useFormValue } from './Form.mjs';
13
+ import { useToggle } from '@startlibs/core';
14
+ import { callIfFunction, getUID } from '@startlibs/utils';
15
+
16
+ const _excluded = ["children", "multiple", "path", "preValidation", "onChangeFile", "onClose", "onClick", "uploadFetcher", "onSuccess", "onFailure", "ajaxError", "onTouchEnd"],
17
+ _excluded2 = ["children", "multiple", "path", "preValidation", "onChangeFile", "onClose", "onClick", "uploadFetcher", "onSuccess", "onFailure", "ajaxError", "onTouchEnd", "maxFiles"];
18
+ const FileInput = /*#__PURE__*/styled.input.attrs({
19
+ type: 'file'
20
+ }).withConfig({
21
+ displayName: "withFormImageInput__FileInput",
22
+ componentId: "sc-o7trbb-0"
23
+ })(["z-index:1;cursor:pointer;opacity:0;position:absolute;top:0;right:0;left:0;bottom:0;width:100%;height:100%;overflow:hidden;::-webkit-file-upload-button{visibility:hidden;}::file-upload-button{visibility:hidden;}"]);
24
+ const WithImageInput = _ref => {
25
+ let {
26
+ children,
27
+ multiple,
28
+ path = ["image"],
29
+ preValidation = _stubFalse,
30
+ onChangeFile,
31
+ onClose,
32
+ onClick,
33
+ uploadFetcher,
34
+ onSuccess,
35
+ onFailure,
36
+ ajaxError,
37
+ onTouchEnd
38
+ } = _ref;
39
+ _objectWithoutProperties(_ref, _excluded);
40
+ const form = useContext(FormContext);
41
+ const loading = useToggle();
42
+ const [tempImage, setTempImage] = useState();
43
+ const getPath = function (str) {
44
+ let fileIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
45
+ return typeof path === 'function' ? [].concat(path(str, fileIndex)) : str !== 'image' ? [].concat(path).slice(0, -1).concat(str) : path;
46
+ };
47
+ const imagePath = getPath('image');
48
+ const [formImage] = useFormValue(imagePath);
49
+ const image = tempImage || formImage;
50
+ const validate = files => {
51
+ const validations = files.map(preValidation).filter(Boolean);
52
+ if (validations.length) {
53
+ validations.forEach(v => form.setError(getPath('image').join('.'), v));
54
+ return files.filter(file => !preValidation(file));
55
+ }
56
+ return files;
57
+ };
58
+ const handleFileEvent = e => {
59
+ e.preventDefault();
60
+ callIfFunction(onClose);
61
+ const files = Array.from((e.nativeEvent.dataTransfer || e.nativeEvent.target).files);
62
+ if (files.length > 0) {
63
+ validate(files.slice(0, multiple ? undefined : 1)).forEach((file, i) => handleFile(file, e, i));
64
+ }
65
+ };
66
+ const handleFile = function (file, eventTarget) {
67
+ let fileIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
68
+ const getIndexedPath = str => getPath(str, fileIndex);
69
+ const path = getIndexedPath();
70
+ const oldUploadStatus = form.getMeta(getIndexedPath('uploadStatus'));
71
+ const oldImage = form.getValue(getIndexedPath('image'));
72
+ const oldImageHeight = form.getValue(getIndexedPath('imageHeight'));
73
+ const oldImageWidth = form.getValue(getIndexedPath('imageWidth'));
74
+ const oldFilename = form.getValue(getIndexedPath('fileName'));
75
+ const objectUrl = URL.createObjectURL(file);
76
+ const image = document.createElement('img');
77
+ image.onload = () => {
78
+ const {
79
+ naturalWidth: imageWidth,
80
+ naturalHeight: imageHeight
81
+ } = image;
82
+ const newValues = {
83
+ image: file,
84
+ filename: file.name,
85
+ imageWidth,
86
+ imageHeight
87
+ };
88
+ form.setValues(_flow(_set(getIndexedPath('filename'), file.name), _set(getIndexedPath('image'), file), _set(getIndexedPath('imageWidth'), imageWidth), _set(getIndexedPath('imageHeight'), imageHeight)));
89
+ form.setMeta(_flow(_update('submittingFiles', v => v ? v + 1 : 1), _update('uploadingPaths', _union([path.join(".")])), _set(getIndexedPath('uploadStatus'), 'loading')));
90
+ setTempImage(objectUrl);
91
+ callIfFunction(onChangeFile, file);
92
+ loading.open();
93
+ uploadFetcher(file, newValues).then(_ref2 => {
94
+ let {
95
+ image,
96
+ uploadStatus
97
+ } = _ref2;
98
+ loading.close();
99
+ if (form.getValue(getIndexedPath('image')) !== file) {
100
+ form.setMeta(_update(['submittingFiles'], v => v - 1));
101
+ return;
102
+ }
103
+ form.clearErrors();
104
+ form.setValue(getIndexedPath('image'), image, false);
105
+ form.setMeta(_flow(_update('uploadingPaths', _difference(_difference.placeholder, [path.join(".")])), _update(['submittingFiles'], v => v - 1), _update(['submittedFiles'], v => (v || []).concat([{
106
+ path,
107
+ file,
108
+ image
109
+ }])), _set(getIndexedPath('uploadStatus'), uploadStatus)));
110
+ setTempImage(null);
111
+ callIfFunction(onSuccess, {
112
+ image,
113
+ uploadStatus,
114
+ imageWidth,
115
+ imageHeight
116
+ });
117
+ }).catch(e => {
118
+ loading.close();
119
+ if (form.getValue(getIndexedPath('image')) !== file) {
120
+ form.setMeta(_update(['submittingFiles'], v => v - 1));
121
+ return;
122
+ }
123
+ form.setError(getIndexedPath('image').join('.'), callIfFunction(ajaxError, _get('[1].status', e)));
124
+ form.setValues(_flow(_set(getIndexedPath('filename'), oldFilename), _set(getIndexedPath('image'), oldImage), _set(getIndexedPath('imageWidth'), oldImageWidth), _set(getIndexedPath('imageHeight'), oldImageHeight)), false);
125
+ form.setMeta(_flow(_update('uploadingPaths', _difference(_difference.placeholder, [path.join(".")])), _update(['submittingFiles'], v => v - 1), _update(['submittedFiles'], v => (v || []).concat([{
126
+ path,
127
+ file,
128
+ image
129
+ }])), _set(getIndexedPath('uploadStatus'), oldUploadStatus)));
130
+ setTempImage(null);
131
+ callIfFunction(onFailure);
132
+ });
133
+ if (eventTarget && eventTarget.parentNode && typeof eventTarget.parentNode.click === 'function') eventTarget.parentNode.click();
134
+ };
135
+ image.src = objectUrl;
136
+ };
137
+ const handleClick = e => {
138
+ callIfFunction(onClick, e);
139
+ };
140
+ const handleTouchEnd = e => {
141
+ callIfFunction(onTouchEnd, e);
142
+ };
143
+ return children(/*#__PURE__*/React.createElement(FileInput, {
144
+ multiple: multiple,
145
+ onChange: handleFileEvent,
146
+ onClick: handleClick,
147
+ tabIndex: -1,
148
+ onTouchEnd: handleTouchEnd
149
+ }), {
150
+ image,
151
+ isLoading: loading.isOpen,
152
+ handleFile,
153
+ handleFileEvent,
154
+ Input: FileInput
155
+ });
156
+ };
157
+ const WithFileInput = _ref3 => {
158
+ let {
159
+ children,
160
+ multiple,
161
+ path = ["file"],
162
+ preValidation = _stubFalse,
163
+ onChangeFile,
164
+ onClose,
165
+ onClick,
166
+ uploadFetcher,
167
+ onSuccess,
168
+ onFailure,
169
+ ajaxError,
170
+ onTouchEnd,
171
+ maxFiles
172
+ } = _ref3;
173
+ _objectWithoutProperties(_ref3, _excluded2);
174
+ const form = useContext(FormContext);
175
+ const loading = useToggle();
176
+ useState();
177
+ const getPath = (str, fileIndex) => typeof path === 'function' ? [].concat(path(str, fileIndex)) : str !== 'file' ? [].concat(path).slice(0, -1).concat(str) : path;
178
+ const validate = files => {
179
+ const validations = files.map(preValidation).filter(Boolean);
180
+ if (validations.length) {
181
+ validations.forEach(v => form.setError(getPath('file', 0).join('.'), v));
182
+ return files.filter(file => !preValidation(file));
183
+ }
184
+ return files;
185
+ };
186
+ const handleFileEvent = e => {
187
+ e.preventDefault();
188
+ callIfFunction(onClose);
189
+ const files = Array.from((e.nativeEvent.dataTransfer || e.nativeEvent.target).files);
190
+ if (files.length > 0) {
191
+ validate(files.slice(0, multiple ? undefined : 1)).forEach((file, i) => handleFile(file, e));
192
+ }
193
+ };
194
+ const handleFile = (file, eventTarget) => {
195
+ const currentFileIndex = (form.getValue(getPath()) || []).length;
196
+ if (currentFileIndex >= maxFiles) {
197
+ form.setErrors({
198
+ '': 'Número máximo de arquivos atingido'
199
+ });
200
+ return;
201
+ }
202
+ const createGetIndexedPath = index => str => getPath(str, index);
203
+ const getIndexedPath = createGetIndexedPath(currentFileIndex);
204
+ const path = getIndexedPath();
205
+ const oldUploadStatus = form.getMeta(getIndexedPath('uploadStatus'));
206
+ const oldFile = form.getValue(getIndexedPath('file'));
207
+ const oldFilename = form.getValue(getIndexedPath('fileName'));
208
+ const uid = getUID();
209
+ form.setValues(_flow(_set(getIndexedPath('filename'), file.name), _set(getIndexedPath('file'), file), _set(getIndexedPath('uid'), uid)));
210
+ form.setMeta(_flow(_update('submittingFiles', v => v ? v + 1 : 1), _update('uploadingPaths', _union([path.join(".")])), _set(getIndexedPath('uploadStatus'), 'loading')));
211
+ callIfFunction(onChangeFile, file);
212
+ loading.open();
213
+ uploadFetcher(file).then(_ref4 => {
214
+ let {
215
+ file,
216
+ uploadStatus,
217
+ response
218
+ } = _ref4;
219
+ loading.close();
220
+ const list = form.getValue(getPath()) || [];
221
+ const index = list.findIndex(f => f.uid === uid);
222
+ if (index < 0) {
223
+ form.setMeta(_update(['submittingFiles'], v => v - 1));
224
+ return;
225
+ }
226
+ const getIndexedPath = createGetIndexedPath(index);
227
+ form.clearErrors();
228
+ form.setValue(getIndexedPath('file'), response, false);
229
+ form.setMeta(_flow(_update('uploadingPaths', _difference(_difference.placeholder, [path.join(".")])), _update(['submittingFiles'], v => v - 1), _update(['submittedFiles'], v => (v || []).concat([{
230
+ path,
231
+ file
232
+ }])), _set(getIndexedPath('uploadStatus'), uploadStatus)));
233
+ callIfFunction(onSuccess, {
234
+ file,
235
+ uploadStatus
236
+ });
237
+ }).catch(e => {
238
+ loading.close();
239
+ const list = form.getValue(getPath()) || [];
240
+ const index = list.findIndex(f => f.uid === uid);
241
+ if (index < 0) {
242
+ form.setMeta(_update(['submittingFiles'], v => v - 1));
243
+ return;
244
+ }
245
+ const getIndexedPath = createGetIndexedPath(index);
246
+ form.setError(getIndexedPath('file').join('.'), callIfFunction(ajaxError, _get('[1].status', e)));
247
+ if (oldFile) {
248
+ form.setValues(_flow(_set(getIndexedPath('filename'), oldFilename), _set(getIndexedPath('file'), oldFile)), false);
249
+ } else {
250
+ form.setValues(_update(getPath(), _filter(f => f.uid !== uid)), false);
251
+ }
252
+ form.setMeta(_flow(_update('uploadingPaths', _difference(_difference.placeholder, [path.join(".")])), _update(['submittingFiles'], v => v - 1), _update(['submittedFiles'], v => (v || []).concat([{
253
+ path,
254
+ file
255
+ }])), _set(getIndexedPath('uploadStatus'), oldUploadStatus)));
256
+ callIfFunction(onFailure);
257
+ });
258
+ if (eventTarget && eventTarget.parentNode && typeof eventTarget.parentNode.click === 'function') eventTarget.parentNode.click();
259
+ };
260
+ const handleClick = e => {
261
+ callIfFunction(onClick, e);
262
+ };
263
+ const handleTouchEnd = e => {
264
+ callIfFunction(onTouchEnd, e);
265
+ };
266
+ return children(/*#__PURE__*/React.createElement(FileInput, {
267
+ multiple: multiple,
268
+ onChange: handleFileEvent,
269
+ onClick: handleClick,
270
+ tabIndex: -1,
271
+ onTouchEnd: handleTouchEnd
272
+ }), {
273
+ isLoading: loading.isOpen,
274
+ handleFile,
275
+ handleFileEvent,
276
+ Input: FileInput
277
+ });
278
+ };
279
+
280
+ export { FileInput, WithFileInput, WithImageInput };
281
+ //# sourceMappingURL=withFormImageInput.mjs.map