@lodashventure/medusa-campaign 0.0.8 → 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.
@@ -4,13 +4,14 @@ const adminSdk = require("@medusajs/admin-sdk");
4
4
  const icons = require("@medusajs/icons");
5
5
  const ui = require("@medusajs/ui");
6
6
  const dayjs = require("dayjs");
7
- const react = require("react");
7
+ const React = require("react");
8
8
  const reactRouterDom = require("react-router-dom");
9
9
  const reactQuery = require("@tanstack/react-query");
10
10
  const lodash = require("lodash");
11
11
  const Medusa = require("@medusajs/js-sdk");
12
- const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
12
+ const _interopDefault = (e2) => e2 && e2.__esModule ? e2 : { default: e2 };
13
13
  const dayjs__default = /* @__PURE__ */ _interopDefault(dayjs);
14
+ const React__default = /* @__PURE__ */ _interopDefault(React);
14
15
  const Medusa__default = /* @__PURE__ */ _interopDefault(Medusa);
15
16
  function getDefaultExportFromCjs(x) {
16
17
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
@@ -19,8 +20,8 @@ var axios$3 = { exports: {} };
19
20
  var bind$2 = function bind(fn, thisArg) {
20
21
  return function wrap() {
21
22
  var args = new Array(arguments.length);
22
- for (var i = 0; i < args.length; i++) {
23
- args[i] = arguments[i];
23
+ for (var i2 = 0; i2 < args.length; i2++) {
24
+ args[i2] = arguments[i2];
24
25
  }
25
26
  return fn.apply(thisArg, args);
26
27
  };
@@ -30,11 +31,11 @@ var toString = Object.prototype.toString;
30
31
  function isArray(val) {
31
32
  return toString.call(val) === "[object Array]";
32
33
  }
33
- function isUndefined(val) {
34
+ function isUndefined$1(val) {
34
35
  return typeof val === "undefined";
35
36
  }
36
37
  function isBuffer(val) {
37
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
38
+ return val !== null && !isUndefined$1(val) && val.constructor !== null && !isUndefined$1(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
38
39
  }
39
40
  function isArrayBuffer(val) {
40
41
  return toString.call(val) === "[object ArrayBuffer]";
@@ -51,16 +52,16 @@ function isArrayBufferView(val) {
51
52
  }
52
53
  return result;
53
54
  }
54
- function isString(val) {
55
+ function isString$1(val) {
55
56
  return typeof val === "string";
56
57
  }
57
58
  function isNumber(val) {
58
59
  return typeof val === "number";
59
60
  }
60
- function isObject(val) {
61
+ function isObject$1(val) {
61
62
  return val !== null && typeof val === "object";
62
63
  }
63
- function isPlainObject(val) {
64
+ function isPlainObject$1(val) {
64
65
  if (toString.call(val) !== "[object Object]") {
65
66
  return false;
66
67
  }
@@ -76,11 +77,11 @@ function isFile(val) {
76
77
  function isBlob(val) {
77
78
  return toString.call(val) === "[object Blob]";
78
79
  }
79
- function isFunction(val) {
80
+ function isFunction$1(val) {
80
81
  return toString.call(val) === "[object Function]";
81
82
  }
82
83
  function isStream(val) {
83
- return isObject(val) && isFunction(val.pipe);
84
+ return isObject$1(val) && isFunction$1(val.pipe);
84
85
  }
85
86
  function isURLSearchParams(val) {
86
87
  return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
@@ -102,8 +103,8 @@ function forEach(obj, fn) {
102
103
  obj = [obj];
103
104
  }
104
105
  if (isArray(obj)) {
105
- for (var i = 0, l = obj.length; i < l; i++) {
106
- fn.call(null, obj[i], i, obj);
106
+ for (var i2 = 0, l = obj.length; i2 < l; i2++) {
107
+ fn.call(null, obj[i2], i2, obj);
107
108
  }
108
109
  } else {
109
110
  for (var key in obj) {
@@ -116,9 +117,9 @@ function forEach(obj, fn) {
116
117
  function merge() {
117
118
  var result = {};
118
119
  function assignValue(val, key) {
119
- if (isPlainObject(result[key]) && isPlainObject(val)) {
120
+ if (isPlainObject$1(result[key]) && isPlainObject$1(val)) {
120
121
  result[key] = merge(result[key], val);
121
- } else if (isPlainObject(val)) {
122
+ } else if (isPlainObject$1(val)) {
122
123
  result[key] = merge({}, val);
123
124
  } else if (isArray(val)) {
124
125
  result[key] = val.slice();
@@ -126,20 +127,20 @@ function merge() {
126
127
  result[key] = val;
127
128
  }
128
129
  }
129
- for (var i = 0, l = arguments.length; i < l; i++) {
130
- forEach(arguments[i], assignValue);
130
+ for (var i2 = 0, l = arguments.length; i2 < l; i2++) {
131
+ forEach(arguments[i2], assignValue);
131
132
  }
132
133
  return result;
133
134
  }
134
- function extend(a, b, thisArg) {
135
+ function extend(a2, b, thisArg) {
135
136
  forEach(b, function assignValue(val, key) {
136
137
  if (thisArg && typeof val === "function") {
137
- a[key] = bind$1(val, thisArg);
138
+ a2[key] = bind$1(val, thisArg);
138
139
  } else {
139
- a[key] = val;
140
+ a2[key] = val;
140
141
  }
141
142
  });
142
- return a;
143
+ return a2;
143
144
  }
144
145
  function stripBOM(content) {
145
146
  if (content.charCodeAt(0) === 65279) {
@@ -153,15 +154,15 @@ var utils$9 = {
153
154
  isBuffer,
154
155
  isFormData,
155
156
  isArrayBufferView,
156
- isString,
157
+ isString: isString$1,
157
158
  isNumber,
158
- isObject,
159
- isPlainObject,
160
- isUndefined,
159
+ isObject: isObject$1,
160
+ isPlainObject: isPlainObject$1,
161
+ isUndefined: isUndefined$1,
161
162
  isDate,
162
163
  isFile,
163
164
  isBlob,
164
- isFunction,
165
+ isFunction: isFunction$1,
165
166
  isStream,
166
167
  isURLSearchParams,
167
168
  isStandardBrowserEnv,
@@ -428,14 +429,14 @@ function requireParseHeaders() {
428
429
  var parsed = {};
429
430
  var key;
430
431
  var val;
431
- var i;
432
+ var i2;
432
433
  if (!headers) {
433
434
  return parsed;
434
435
  }
435
436
  utils2.forEach(headers.split("\n"), function parser(line) {
436
- i = line.indexOf(":");
437
- key = utils2.trim(line.substr(0, i)).toLowerCase();
438
- val = utils2.trim(line.substr(i + 1));
437
+ i2 = line.indexOf(":");
438
+ key = utils2.trim(line.substr(0, i2)).toLowerCase();
439
+ val = utils2.trim(line.substr(i2 + 1));
439
440
  if (key) {
440
441
  if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
441
442
  return;
@@ -652,9 +653,9 @@ function stringifySafely(rawValue, parser, encoder) {
652
653
  try {
653
654
  (parser || JSON.parse)(rawValue);
654
655
  return utils$5.trim(rawValue);
655
- } catch (e) {
656
- if (e.name !== "SyntaxError") {
657
- throw e;
656
+ } catch (e2) {
657
+ if (e2.name !== "SyntaxError") {
658
+ throw e2;
658
659
  }
659
660
  }
660
661
  }
@@ -694,12 +695,12 @@ var defaults$3 = {
694
695
  if (strictJSONParsing || forcedJSONParsing && utils$5.isString(data) && data.length) {
695
696
  try {
696
697
  return JSON.parse(data);
697
- } catch (e) {
698
+ } catch (e2) {
698
699
  if (strictJSONParsing) {
699
- if (e.name === "SyntaxError") {
700
- throw enhanceError2(e, this, "E_JSON_PARSE");
700
+ if (e2.name === "SyntaxError") {
701
+ throw enhanceError2(e2, this, "E_JSON_PARSE");
701
702
  }
702
- throw e;
703
+ throw e2;
703
704
  }
704
705
  }
705
706
  }
@@ -885,9 +886,9 @@ const require$$0 = {
885
886
  };
886
887
  var pkg = require$$0;
887
888
  var validators$1 = {};
888
- ["object", "boolean", "number", "function", "string", "symbol"].forEach(function(type, i) {
889
+ ["object", "boolean", "number", "function", "string", "symbol"].forEach(function(type, i2) {
889
890
  validators$1[type] = function validator2(thing) {
890
- return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
891
+ return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type;
891
892
  };
892
893
  });
893
894
  var deprecatedWarnings = {};
@@ -895,10 +896,10 @@ var currentVerArr = pkg.version.split(".");
895
896
  function isOlderVersion(version2, thanVersion) {
896
897
  var pkgVersionArr = thanVersion ? thanVersion.split(".") : currentVerArr;
897
898
  var destVer = version2.split(".");
898
- for (var i = 0; i < 3; i++) {
899
- if (pkgVersionArr[i] > destVer[i]) {
899
+ for (var i2 = 0; i2 < 3; i2++) {
900
+ if (pkgVersionArr[i2] > destVer[i2]) {
900
901
  return true;
901
- } else if (pkgVersionArr[i] < destVer[i]) {
902
+ } else if (pkgVersionArr[i2] < destVer[i2]) {
902
903
  return false;
903
904
  }
904
905
  }
@@ -930,9 +931,9 @@ function assertOptions(options, schema, allowUnknown) {
930
931
  throw new TypeError("options must be an object");
931
932
  }
932
933
  var keys = Object.keys(options);
933
- var i = keys.length;
934
- while (i-- > 0) {
935
- var opt = keys[i];
934
+ var i2 = keys.length;
935
+ while (i2-- > 0) {
936
+ var opt = keys[i2];
936
937
  var validator2 = schema[opt];
937
938
  if (validator2) {
938
939
  var value = options[opt];
@@ -1102,8 +1103,8 @@ function requireCancelToken() {
1102
1103
  };
1103
1104
  CancelToken.source = function source() {
1104
1105
  var cancel;
1105
- var token = new CancelToken(function executor(c) {
1106
- cancel = c;
1106
+ var token = new CancelToken(function executor(c2) {
1107
+ cancel = c2;
1107
1108
  });
1108
1109
  return {
1109
1110
  token,
@@ -1180,11 +1181,11 @@ const useFlashSales = (pagination) => {
1180
1181
  const FlashSalePage = () => {
1181
1182
  const navigate = reactRouterDom.useNavigate();
1182
1183
  const limit = 20;
1183
- const [pagination, setPagination] = react.useState({
1184
+ const [pagination, setPagination] = React.useState({
1184
1185
  pageSize: limit,
1185
1186
  pageIndex: 0
1186
1187
  });
1187
- const offset = react.useMemo(() => {
1188
+ const offset = React.useMemo(() => {
1188
1189
  return pagination.pageIndex * limit;
1189
1190
  }, [pagination]);
1190
1191
  const columnHelper2 = ui.createDataTableColumnHelper();
@@ -1229,7 +1230,7 @@ const FlashSalePage = () => {
1229
1230
  const table = ui.useDataTable({
1230
1231
  data: (data == null ? void 0 : data.campaigns) || [],
1231
1232
  columns: columns2,
1232
- getRowId: (campaign) => campaign.id,
1233
+ getRowId: (campaign2) => campaign2.id,
1233
1234
  pagination: {
1234
1235
  state: pagination,
1235
1236
  onPaginationChange: setPagination
@@ -1257,6 +1258,1887 @@ const config$1 = adminSdk.defineRouteConfig({
1257
1258
  label: "Flash Sale",
1258
1259
  icon: icons.Sparkles
1259
1260
  });
1261
+ var isCheckBoxInput = (element) => element.type === "checkbox";
1262
+ var isDateObject = (value) => value instanceof Date;
1263
+ var isNullOrUndefined = (value) => value == null;
1264
+ const isObjectType = (value) => typeof value === "object";
1265
+ var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
1266
+ var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
1267
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
1268
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
1269
+ var isPlainObject = (tempObject) => {
1270
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
1271
+ return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
1272
+ };
1273
+ var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
1274
+ function cloneObject(data) {
1275
+ let copy;
1276
+ const isArray2 = Array.isArray(data);
1277
+ if (data instanceof Date) {
1278
+ copy = new Date(data);
1279
+ } else if (data instanceof Set) {
1280
+ copy = new Set(data);
1281
+ } else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) && (isArray2 || isObject(data))) {
1282
+ copy = isArray2 ? [] : {};
1283
+ if (!isArray2 && !isPlainObject(data)) {
1284
+ copy = data;
1285
+ } else {
1286
+ for (const key in data) {
1287
+ if (data.hasOwnProperty(key)) {
1288
+ copy[key] = cloneObject(data[key]);
1289
+ }
1290
+ }
1291
+ }
1292
+ } else {
1293
+ return data;
1294
+ }
1295
+ return copy;
1296
+ }
1297
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
1298
+ var isUndefined = (val) => val === void 0;
1299
+ var get = (object, path, defaultValue) => {
1300
+ if (!path || !isObject(object)) {
1301
+ return defaultValue;
1302
+ }
1303
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result2, key) => isNullOrUndefined(result2) ? result2 : result2[key], object);
1304
+ return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
1305
+ };
1306
+ var isBoolean = (value) => typeof value === "boolean";
1307
+ const EVENTS = {
1308
+ BLUR: "blur",
1309
+ FOCUS_OUT: "focusout",
1310
+ CHANGE: "change"
1311
+ };
1312
+ const VALIDATION_MODE = {
1313
+ onBlur: "onBlur",
1314
+ onChange: "onChange",
1315
+ onSubmit: "onSubmit",
1316
+ onTouched: "onTouched",
1317
+ all: "all"
1318
+ };
1319
+ const INPUT_VALIDATION_RULES = {
1320
+ max: "max",
1321
+ min: "min",
1322
+ maxLength: "maxLength",
1323
+ minLength: "minLength",
1324
+ pattern: "pattern",
1325
+ required: "required",
1326
+ validate: "validate"
1327
+ };
1328
+ const HookFormContext = React__default.default.createContext(null);
1329
+ const useFormContext = () => React__default.default.useContext(HookFormContext);
1330
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
1331
+ const result = {
1332
+ defaultValues: control._defaultValues
1333
+ };
1334
+ for (const key in formState) {
1335
+ Object.defineProperty(result, key, {
1336
+ get: () => {
1337
+ const _key = key;
1338
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
1339
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
1340
+ }
1341
+ localProxyFormState && (localProxyFormState[_key] = true);
1342
+ return formState[_key];
1343
+ }
1344
+ });
1345
+ }
1346
+ return result;
1347
+ };
1348
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
1349
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
1350
+ updateFormState(formStateData);
1351
+ const { name, ...formState } = formStateData;
1352
+ return isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
1353
+ };
1354
+ var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
1355
+ var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
1356
+ function useSubscribe(props) {
1357
+ const _props = React__default.default.useRef(props);
1358
+ _props.current = props;
1359
+ React__default.default.useEffect(() => {
1360
+ const subscription = !props.disabled && _props.current.subject && _props.current.subject.subscribe({
1361
+ next: _props.current.next
1362
+ });
1363
+ return () => {
1364
+ subscription && subscription.unsubscribe();
1365
+ };
1366
+ }, [props.disabled]);
1367
+ }
1368
+ function useFormState(props) {
1369
+ const methods = useFormContext();
1370
+ const { control = methods.control, disabled, name, exact } = props || {};
1371
+ const [formState, updateFormState] = React__default.default.useState(control._formState);
1372
+ const _mounted = React__default.default.useRef(true);
1373
+ const _localProxyFormState = React__default.default.useRef({
1374
+ isDirty: false,
1375
+ isLoading: false,
1376
+ dirtyFields: false,
1377
+ touchedFields: false,
1378
+ isValidating: false,
1379
+ isValid: false,
1380
+ errors: false
1381
+ });
1382
+ const _name = React__default.default.useRef(name);
1383
+ _name.current = name;
1384
+ useSubscribe({
1385
+ disabled,
1386
+ next: (value) => _mounted.current && shouldSubscribeByName(_name.current, value.name, exact) && shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) && updateFormState({
1387
+ ...control._formState,
1388
+ ...value
1389
+ }),
1390
+ subject: control._subjects.state
1391
+ });
1392
+ React__default.default.useEffect(() => {
1393
+ _mounted.current = true;
1394
+ _localProxyFormState.current.isValid && control._updateValid(true);
1395
+ return () => {
1396
+ _mounted.current = false;
1397
+ };
1398
+ }, [control]);
1399
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
1400
+ }
1401
+ var isString = (value) => typeof value === "string";
1402
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
1403
+ if (isString(names)) {
1404
+ isGlobal && _names.watch.add(names);
1405
+ return get(formValues, names, defaultValue);
1406
+ }
1407
+ if (Array.isArray(names)) {
1408
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
1409
+ }
1410
+ isGlobal && (_names.watchAll = true);
1411
+ return formValues;
1412
+ };
1413
+ function useWatch(props) {
1414
+ const methods = useFormContext();
1415
+ const { control = methods.control, name, defaultValue, disabled, exact } = props || {};
1416
+ const _name = React__default.default.useRef(name);
1417
+ _name.current = name;
1418
+ useSubscribe({
1419
+ disabled,
1420
+ subject: control._subjects.values,
1421
+ next: (formState) => {
1422
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
1423
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
1424
+ }
1425
+ }
1426
+ });
1427
+ const [value, updateValue] = React__default.default.useState(control._getWatch(name, defaultValue));
1428
+ React__default.default.useEffect(() => control._removeUnmounted());
1429
+ return value;
1430
+ }
1431
+ var isKey = (value) => /^\w*$/.test(value);
1432
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
1433
+ var set = (object, path, value) => {
1434
+ let index = -1;
1435
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
1436
+ const length = tempPath.length;
1437
+ const lastIndex = length - 1;
1438
+ while (++index < length) {
1439
+ const key = tempPath[index];
1440
+ let newValue = value;
1441
+ if (index !== lastIndex) {
1442
+ const objValue = object[key];
1443
+ newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
1444
+ }
1445
+ object[key] = newValue;
1446
+ object = object[key];
1447
+ }
1448
+ return object;
1449
+ };
1450
+ function useController(props) {
1451
+ const methods = useFormContext();
1452
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
1453
+ const isArrayField = isNameInFieldArray(control._names.array, name);
1454
+ const value = useWatch({
1455
+ control,
1456
+ name,
1457
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
1458
+ exact: true
1459
+ });
1460
+ const formState = useFormState({
1461
+ control,
1462
+ name
1463
+ });
1464
+ const _registerProps = React__default.default.useRef(control.register(name, {
1465
+ ...props.rules,
1466
+ value,
1467
+ ...isBoolean(props.disabled) ? { disabled: props.disabled } : {}
1468
+ }));
1469
+ React__default.default.useEffect(() => {
1470
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
1471
+ const updateMounted = (name2, value2) => {
1472
+ const field = get(control._fields, name2);
1473
+ if (field) {
1474
+ field._f.mount = value2;
1475
+ }
1476
+ };
1477
+ updateMounted(name, true);
1478
+ if (_shouldUnregisterField) {
1479
+ const value2 = cloneObject(get(control._options.defaultValues, name));
1480
+ set(control._defaultValues, name, value2);
1481
+ if (isUndefined(get(control._formValues, name))) {
1482
+ set(control._formValues, name, value2);
1483
+ }
1484
+ }
1485
+ return () => {
1486
+ (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false);
1487
+ };
1488
+ }, [name, control, isArrayField, shouldUnregister]);
1489
+ React__default.default.useEffect(() => {
1490
+ if (get(control._fields, name)) {
1491
+ control._updateDisabledField({
1492
+ disabled,
1493
+ fields: control._fields,
1494
+ name,
1495
+ value: get(control._fields, name)._f.value
1496
+ });
1497
+ }
1498
+ }, [disabled, name, control]);
1499
+ return {
1500
+ field: {
1501
+ name,
1502
+ value,
1503
+ ...isBoolean(disabled) || isBoolean(formState.disabled) ? { disabled: formState.disabled || disabled } : {},
1504
+ onChange: React__default.default.useCallback((event) => _registerProps.current.onChange({
1505
+ target: {
1506
+ value: getEventValue(event),
1507
+ name
1508
+ },
1509
+ type: EVENTS.CHANGE
1510
+ }), [name]),
1511
+ onBlur: React__default.default.useCallback(() => _registerProps.current.onBlur({
1512
+ target: {
1513
+ value: get(control._formValues, name),
1514
+ name
1515
+ },
1516
+ type: EVENTS.BLUR
1517
+ }), [name, control]),
1518
+ ref: (elm) => {
1519
+ const field = get(control._fields, name);
1520
+ if (field && elm) {
1521
+ field._f.ref = {
1522
+ focus: () => elm.focus(),
1523
+ select: () => elm.select(),
1524
+ setCustomValidity: (message) => elm.setCustomValidity(message),
1525
+ reportValidity: () => elm.reportValidity()
1526
+ };
1527
+ }
1528
+ }
1529
+ },
1530
+ formState,
1531
+ fieldState: Object.defineProperties({}, {
1532
+ invalid: {
1533
+ enumerable: true,
1534
+ get: () => !!get(formState.errors, name)
1535
+ },
1536
+ isDirty: {
1537
+ enumerable: true,
1538
+ get: () => !!get(formState.dirtyFields, name)
1539
+ },
1540
+ isTouched: {
1541
+ enumerable: true,
1542
+ get: () => !!get(formState.touchedFields, name)
1543
+ },
1544
+ error: {
1545
+ enumerable: true,
1546
+ get: () => get(formState.errors, name)
1547
+ }
1548
+ })
1549
+ };
1550
+ }
1551
+ const Controller = (props) => props.render(useController(props));
1552
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
1553
+ ...errors[name],
1554
+ types: {
1555
+ ...errors[name] && errors[name].types ? errors[name].types : {},
1556
+ [type]: message || true
1557
+ }
1558
+ } : {};
1559
+ var generateId = () => {
1560
+ const d = typeof performance === "undefined" ? Date.now() : performance.now() * 1e3;
1561
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c2) => {
1562
+ const r = (Math.random() * 16 + d) % 16 | 0;
1563
+ return (c2 == "x" ? r : r & 3 | 8).toString(16);
1564
+ });
1565
+ };
1566
+ var getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus) ? options.focusName || `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.` : "";
1567
+ var getValidationModes = (mode) => ({
1568
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
1569
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
1570
+ isOnChange: mode === VALIDATION_MODE.onChange,
1571
+ isOnAll: mode === VALIDATION_MODE.all,
1572
+ isOnTouch: mode === VALIDATION_MODE.onTouched
1573
+ });
1574
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (_names.watchAll || _names.watch.has(name) || [..._names.watch].some((watchName) => name.startsWith(watchName) && /^\.\w+/.test(name.slice(watchName.length))));
1575
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
1576
+ for (const key of fieldsNames || Object.keys(fields)) {
1577
+ const field = get(fields, key);
1578
+ if (field) {
1579
+ const { _f, ...currentField } = field;
1580
+ if (_f) {
1581
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
1582
+ break;
1583
+ } else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
1584
+ break;
1585
+ } else {
1586
+ iterateFieldsByAction(currentField, action);
1587
+ }
1588
+ } else if (isObject(currentField)) {
1589
+ iterateFieldsByAction(currentField, action);
1590
+ }
1591
+ }
1592
+ }
1593
+ };
1594
+ var updateFieldArrayRootError = (errors, error, name) => {
1595
+ const fieldArrayErrors = compact(get(errors, name));
1596
+ set(fieldArrayErrors, "root", error[name]);
1597
+ set(errors, name, fieldArrayErrors);
1598
+ return errors;
1599
+ };
1600
+ var isFileInput = (element) => element.type === "file";
1601
+ var isFunction = (value) => typeof value === "function";
1602
+ var isHTMLElement = (value) => {
1603
+ if (!isWeb) {
1604
+ return false;
1605
+ }
1606
+ const owner = value ? value.ownerDocument : 0;
1607
+ return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
1608
+ };
1609
+ var isMessage = (value) => isString(value);
1610
+ var isRadioInput = (element) => element.type === "radio";
1611
+ var isRegex = (value) => value instanceof RegExp;
1612
+ const defaultResult = {
1613
+ value: false,
1614
+ isValid: false
1615
+ };
1616
+ const validResult = { value: true, isValid: true };
1617
+ var getCheckboxValue = (options) => {
1618
+ if (Array.isArray(options)) {
1619
+ if (options.length > 1) {
1620
+ const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
1621
+ return { value: values, isValid: !!values.length };
1622
+ }
1623
+ return options[0].checked && !options[0].disabled ? (
1624
+ // @ts-expect-error expected to work in the browser
1625
+ options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : { value: options[0].value, isValid: true } : validResult
1626
+ ) : defaultResult;
1627
+ }
1628
+ return defaultResult;
1629
+ };
1630
+ const defaultReturn = {
1631
+ isValid: false,
1632
+ value: null
1633
+ };
1634
+ var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
1635
+ isValid: true,
1636
+ value: option.value
1637
+ } : previous, defaultReturn) : defaultReturn;
1638
+ function getValidateError(result, ref, type = "validate") {
1639
+ if (isMessage(result) || Array.isArray(result) && result.every(isMessage) || isBoolean(result) && !result) {
1640
+ return {
1641
+ type,
1642
+ message: isMessage(result) ? result : "",
1643
+ ref
1644
+ };
1645
+ }
1646
+ }
1647
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
1648
+ value: validationData,
1649
+ message: ""
1650
+ };
1651
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
1652
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled } = field._f;
1653
+ const inputValue = get(formValues, name);
1654
+ if (!mount || disabled) {
1655
+ return {};
1656
+ }
1657
+ const inputRef = refs ? refs[0] : ref;
1658
+ const setCustomValidity = (message) => {
1659
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
1660
+ inputRef.setCustomValidity(isBoolean(message) ? "" : message || "");
1661
+ inputRef.reportValidity();
1662
+ }
1663
+ };
1664
+ const error = {};
1665
+ const isRadio = isRadioInput(ref);
1666
+ const isCheckBox = isCheckBoxInput(ref);
1667
+ const isRadioOrCheckbox2 = isRadio || isCheckBox;
1668
+ const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
1669
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
1670
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
1671
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
1672
+ error[name] = {
1673
+ type: exceedMax ? maxType : minType,
1674
+ message,
1675
+ ref,
1676
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message)
1677
+ };
1678
+ };
1679
+ if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox2 && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
1680
+ const { value, message } = isMessage(required) ? { value: !!required, message: required } : getValueAndMessage(required);
1681
+ if (value) {
1682
+ error[name] = {
1683
+ type: INPUT_VALIDATION_RULES.required,
1684
+ message,
1685
+ ref: inputRef,
1686
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
1687
+ };
1688
+ if (!validateAllFieldCriteria) {
1689
+ setCustomValidity(message);
1690
+ return error;
1691
+ }
1692
+ }
1693
+ }
1694
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
1695
+ let exceedMax;
1696
+ let exceedMin;
1697
+ const maxOutput = getValueAndMessage(max);
1698
+ const minOutput = getValueAndMessage(min);
1699
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
1700
+ const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
1701
+ if (!isNullOrUndefined(maxOutput.value)) {
1702
+ exceedMax = valueNumber > maxOutput.value;
1703
+ }
1704
+ if (!isNullOrUndefined(minOutput.value)) {
1705
+ exceedMin = valueNumber < minOutput.value;
1706
+ }
1707
+ } else {
1708
+ const valueDate = ref.valueAsDate || new Date(inputValue);
1709
+ const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
1710
+ const isTime = ref.type == "time";
1711
+ const isWeek = ref.type == "week";
1712
+ if (isString(maxOutput.value) && inputValue) {
1713
+ exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
1714
+ }
1715
+ if (isString(minOutput.value) && inputValue) {
1716
+ exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
1717
+ }
1718
+ }
1719
+ if (exceedMax || exceedMin) {
1720
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
1721
+ if (!validateAllFieldCriteria) {
1722
+ setCustomValidity(error[name].message);
1723
+ return error;
1724
+ }
1725
+ }
1726
+ }
1727
+ if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
1728
+ const maxLengthOutput = getValueAndMessage(maxLength);
1729
+ const minLengthOutput = getValueAndMessage(minLength);
1730
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
1731
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
1732
+ if (exceedMax || exceedMin) {
1733
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
1734
+ if (!validateAllFieldCriteria) {
1735
+ setCustomValidity(error[name].message);
1736
+ return error;
1737
+ }
1738
+ }
1739
+ }
1740
+ if (pattern && !isEmpty && isString(inputValue)) {
1741
+ const { value: patternValue, message } = getValueAndMessage(pattern);
1742
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
1743
+ error[name] = {
1744
+ type: INPUT_VALIDATION_RULES.pattern,
1745
+ message,
1746
+ ref,
1747
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
1748
+ };
1749
+ if (!validateAllFieldCriteria) {
1750
+ setCustomValidity(message);
1751
+ return error;
1752
+ }
1753
+ }
1754
+ }
1755
+ if (validate) {
1756
+ if (isFunction(validate)) {
1757
+ const result = await validate(inputValue, formValues);
1758
+ const validateError = getValidateError(result, inputRef);
1759
+ if (validateError) {
1760
+ error[name] = {
1761
+ ...validateError,
1762
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
1763
+ };
1764
+ if (!validateAllFieldCriteria) {
1765
+ setCustomValidity(validateError.message);
1766
+ return error;
1767
+ }
1768
+ }
1769
+ } else if (isObject(validate)) {
1770
+ let validationResult = {};
1771
+ for (const key in validate) {
1772
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
1773
+ break;
1774
+ }
1775
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
1776
+ if (validateError) {
1777
+ validationResult = {
1778
+ ...validateError,
1779
+ ...appendErrorsCurry(key, validateError.message)
1780
+ };
1781
+ setCustomValidity(validateError.message);
1782
+ if (validateAllFieldCriteria) {
1783
+ error[name] = validationResult;
1784
+ }
1785
+ }
1786
+ }
1787
+ if (!isEmptyObject(validationResult)) {
1788
+ error[name] = {
1789
+ ref: inputRef,
1790
+ ...validationResult
1791
+ };
1792
+ if (!validateAllFieldCriteria) {
1793
+ return error;
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+ setCustomValidity(true);
1799
+ return error;
1800
+ };
1801
+ var appendAt = (data, value) => [
1802
+ ...data,
1803
+ ...convertToArrayPayload(value)
1804
+ ];
1805
+ var fillEmptyArray = (value) => Array.isArray(value) ? value.map(() => void 0) : void 0;
1806
+ function insert(data, index, value) {
1807
+ return [
1808
+ ...data.slice(0, index),
1809
+ ...convertToArrayPayload(value),
1810
+ ...data.slice(index)
1811
+ ];
1812
+ }
1813
+ var moveArrayAt = (data, from, to) => {
1814
+ if (!Array.isArray(data)) {
1815
+ return [];
1816
+ }
1817
+ if (isUndefined(data[to])) {
1818
+ data[to] = void 0;
1819
+ }
1820
+ data.splice(to, 0, data.splice(from, 1)[0]);
1821
+ return data;
1822
+ };
1823
+ var prependAt = (data, value) => [
1824
+ ...convertToArrayPayload(value),
1825
+ ...convertToArrayPayload(data)
1826
+ ];
1827
+ function removeAtIndexes(data, indexes) {
1828
+ let i2 = 0;
1829
+ const temp = [...data];
1830
+ for (const index of indexes) {
1831
+ temp.splice(index - i2, 1);
1832
+ i2++;
1833
+ }
1834
+ return compact(temp).length ? temp : [];
1835
+ }
1836
+ var removeArrayAt = (data, index) => isUndefined(index) ? [] : removeAtIndexes(data, convertToArrayPayload(index).sort((a2, b) => a2 - b));
1837
+ var swapArrayAt = (data, indexA, indexB) => {
1838
+ [data[indexA], data[indexB]] = [data[indexB], data[indexA]];
1839
+ };
1840
+ function baseGet(object, updatePath) {
1841
+ const length = updatePath.slice(0, -1).length;
1842
+ let index = 0;
1843
+ while (index < length) {
1844
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
1845
+ }
1846
+ return object;
1847
+ }
1848
+ function isEmptyArray(obj) {
1849
+ for (const key in obj) {
1850
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
1851
+ return false;
1852
+ }
1853
+ }
1854
+ return true;
1855
+ }
1856
+ function unset(object, path) {
1857
+ const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
1858
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
1859
+ const index = paths.length - 1;
1860
+ const key = paths[index];
1861
+ if (childObject) {
1862
+ delete childObject[key];
1863
+ }
1864
+ if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) {
1865
+ unset(object, paths.slice(0, -1));
1866
+ }
1867
+ return object;
1868
+ }
1869
+ var updateAt = (fieldValues, index, value) => {
1870
+ fieldValues[index] = value;
1871
+ return fieldValues;
1872
+ };
1873
+ function useFieldArray(props) {
1874
+ const methods = useFormContext();
1875
+ const { control = methods.control, name, keyName = "id", shouldUnregister } = props;
1876
+ const [fields, setFields] = React__default.default.useState(control._getFieldArray(name));
1877
+ const ids = React__default.default.useRef(control._getFieldArray(name).map(generateId));
1878
+ const _fieldIds = React__default.default.useRef(fields);
1879
+ const _name = React__default.default.useRef(name);
1880
+ const _actioned = React__default.default.useRef(false);
1881
+ _name.current = name;
1882
+ _fieldIds.current = fields;
1883
+ control._names.array.add(name);
1884
+ props.rules && control.register(name, props.rules);
1885
+ useSubscribe({
1886
+ next: ({ values, name: fieldArrayName }) => {
1887
+ if (fieldArrayName === _name.current || !fieldArrayName) {
1888
+ const fieldValues = get(values, _name.current);
1889
+ if (Array.isArray(fieldValues)) {
1890
+ setFields(fieldValues);
1891
+ ids.current = fieldValues.map(generateId);
1892
+ }
1893
+ }
1894
+ },
1895
+ subject: control._subjects.array
1896
+ });
1897
+ const updateValues = React__default.default.useCallback((updatedFieldArrayValues) => {
1898
+ _actioned.current = true;
1899
+ control._updateFieldArray(name, updatedFieldArrayValues);
1900
+ }, [control, name]);
1901
+ const append = (value, options) => {
1902
+ const appendValue = convertToArrayPayload(cloneObject(value));
1903
+ const updatedFieldArrayValues = appendAt(control._getFieldArray(name), appendValue);
1904
+ control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);
1905
+ ids.current = appendAt(ids.current, appendValue.map(generateId));
1906
+ updateValues(updatedFieldArrayValues);
1907
+ setFields(updatedFieldArrayValues);
1908
+ control._updateFieldArray(name, updatedFieldArrayValues, appendAt, {
1909
+ argA: fillEmptyArray(value)
1910
+ });
1911
+ };
1912
+ const prepend = (value, options) => {
1913
+ const prependValue = convertToArrayPayload(cloneObject(value));
1914
+ const updatedFieldArrayValues = prependAt(control._getFieldArray(name), prependValue);
1915
+ control._names.focus = getFocusFieldName(name, 0, options);
1916
+ ids.current = prependAt(ids.current, prependValue.map(generateId));
1917
+ updateValues(updatedFieldArrayValues);
1918
+ setFields(updatedFieldArrayValues);
1919
+ control._updateFieldArray(name, updatedFieldArrayValues, prependAt, {
1920
+ argA: fillEmptyArray(value)
1921
+ });
1922
+ };
1923
+ const remove = (index) => {
1924
+ const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);
1925
+ ids.current = removeArrayAt(ids.current, index);
1926
+ updateValues(updatedFieldArrayValues);
1927
+ setFields(updatedFieldArrayValues);
1928
+ control._updateFieldArray(name, updatedFieldArrayValues, removeArrayAt, {
1929
+ argA: index
1930
+ });
1931
+ };
1932
+ const insert$1 = (index, value, options) => {
1933
+ const insertValue = convertToArrayPayload(cloneObject(value));
1934
+ const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);
1935
+ control._names.focus = getFocusFieldName(name, index, options);
1936
+ ids.current = insert(ids.current, index, insertValue.map(generateId));
1937
+ updateValues(updatedFieldArrayValues);
1938
+ setFields(updatedFieldArrayValues);
1939
+ control._updateFieldArray(name, updatedFieldArrayValues, insert, {
1940
+ argA: index,
1941
+ argB: fillEmptyArray(value)
1942
+ });
1943
+ };
1944
+ const swap = (indexA, indexB) => {
1945
+ const updatedFieldArrayValues = control._getFieldArray(name);
1946
+ swapArrayAt(updatedFieldArrayValues, indexA, indexB);
1947
+ swapArrayAt(ids.current, indexA, indexB);
1948
+ updateValues(updatedFieldArrayValues);
1949
+ setFields(updatedFieldArrayValues);
1950
+ control._updateFieldArray(name, updatedFieldArrayValues, swapArrayAt, {
1951
+ argA: indexA,
1952
+ argB: indexB
1953
+ }, false);
1954
+ };
1955
+ const move = (from, to) => {
1956
+ const updatedFieldArrayValues = control._getFieldArray(name);
1957
+ moveArrayAt(updatedFieldArrayValues, from, to);
1958
+ moveArrayAt(ids.current, from, to);
1959
+ updateValues(updatedFieldArrayValues);
1960
+ setFields(updatedFieldArrayValues);
1961
+ control._updateFieldArray(name, updatedFieldArrayValues, moveArrayAt, {
1962
+ argA: from,
1963
+ argB: to
1964
+ }, false);
1965
+ };
1966
+ const update = (index, value) => {
1967
+ const updateValue = cloneObject(value);
1968
+ const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);
1969
+ ids.current = [...updatedFieldArrayValues].map((item, i2) => !item || i2 === index ? generateId() : ids.current[i2]);
1970
+ updateValues(updatedFieldArrayValues);
1971
+ setFields([...updatedFieldArrayValues]);
1972
+ control._updateFieldArray(name, updatedFieldArrayValues, updateAt, {
1973
+ argA: index,
1974
+ argB: updateValue
1975
+ }, true, false);
1976
+ };
1977
+ const replace = (value) => {
1978
+ const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));
1979
+ ids.current = updatedFieldArrayValues.map(generateId);
1980
+ updateValues([...updatedFieldArrayValues]);
1981
+ setFields([...updatedFieldArrayValues]);
1982
+ control._updateFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);
1983
+ };
1984
+ React__default.default.useEffect(() => {
1985
+ control._state.action = false;
1986
+ isWatched(name, control._names) && control._subjects.state.next({
1987
+ ...control._formState
1988
+ });
1989
+ if (_actioned.current && (!getValidationModes(control._options.mode).isOnSubmit || control._formState.isSubmitted)) {
1990
+ if (control._options.resolver) {
1991
+ control._executeSchema([name]).then((result) => {
1992
+ const error = get(result.errors, name);
1993
+ const existingError = get(control._formState.errors, name);
1994
+ if (existingError ? !error && existingError.type || error && (existingError.type !== error.type || existingError.message !== error.message) : error && error.type) {
1995
+ error ? set(control._formState.errors, name, error) : unset(control._formState.errors, name);
1996
+ control._subjects.state.next({
1997
+ errors: control._formState.errors
1998
+ });
1999
+ }
2000
+ });
2001
+ } else {
2002
+ const field = get(control._fields, name);
2003
+ if (field && field._f) {
2004
+ validateField(field, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) && control._subjects.state.next({
2005
+ errors: updateFieldArrayRootError(control._formState.errors, error, name)
2006
+ }));
2007
+ }
2008
+ }
2009
+ }
2010
+ control._subjects.values.next({
2011
+ name,
2012
+ values: { ...control._formValues }
2013
+ });
2014
+ control._names.focus && iterateFieldsByAction(control._fields, (ref, key) => {
2015
+ if (control._names.focus && key.startsWith(control._names.focus) && ref.focus) {
2016
+ ref.focus();
2017
+ return 1;
2018
+ }
2019
+ return;
2020
+ });
2021
+ control._names.focus = "";
2022
+ control._updateValid();
2023
+ _actioned.current = false;
2024
+ }, [fields, name, control]);
2025
+ React__default.default.useEffect(() => {
2026
+ !get(control._formValues, name) && control._updateFieldArray(name);
2027
+ return () => {
2028
+ (control._options.shouldUnregister || shouldUnregister) && control.unregister(name);
2029
+ };
2030
+ }, [name, control, keyName, shouldUnregister]);
2031
+ return {
2032
+ swap: React__default.default.useCallback(swap, [updateValues, name, control]),
2033
+ move: React__default.default.useCallback(move, [updateValues, name, control]),
2034
+ prepend: React__default.default.useCallback(prepend, [updateValues, name, control]),
2035
+ append: React__default.default.useCallback(append, [updateValues, name, control]),
2036
+ remove: React__default.default.useCallback(remove, [updateValues, name, control]),
2037
+ insert: React__default.default.useCallback(insert$1, [updateValues, name, control]),
2038
+ update: React__default.default.useCallback(update, [updateValues, name, control]),
2039
+ replace: React__default.default.useCallback(replace, [updateValues, name, control]),
2040
+ fields: React__default.default.useMemo(() => fields.map((field, index) => ({
2041
+ ...field,
2042
+ [keyName]: ids.current[index] || generateId()
2043
+ })), [fields, keyName])
2044
+ };
2045
+ }
2046
+ var createSubject = () => {
2047
+ let _observers = [];
2048
+ const next = (value) => {
2049
+ for (const observer of _observers) {
2050
+ observer.next && observer.next(value);
2051
+ }
2052
+ };
2053
+ const subscribe = (observer) => {
2054
+ _observers.push(observer);
2055
+ return {
2056
+ unsubscribe: () => {
2057
+ _observers = _observers.filter((o2) => o2 !== observer);
2058
+ }
2059
+ };
2060
+ };
2061
+ const unsubscribe = () => {
2062
+ _observers = [];
2063
+ };
2064
+ return {
2065
+ get observers() {
2066
+ return _observers;
2067
+ },
2068
+ next,
2069
+ subscribe,
2070
+ unsubscribe
2071
+ };
2072
+ };
2073
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
2074
+ function deepEqual(object1, object2) {
2075
+ if (isPrimitive(object1) || isPrimitive(object2)) {
2076
+ return object1 === object2;
2077
+ }
2078
+ if (isDateObject(object1) && isDateObject(object2)) {
2079
+ return object1.getTime() === object2.getTime();
2080
+ }
2081
+ const keys1 = Object.keys(object1);
2082
+ const keys2 = Object.keys(object2);
2083
+ if (keys1.length !== keys2.length) {
2084
+ return false;
2085
+ }
2086
+ for (const key of keys1) {
2087
+ const val1 = object1[key];
2088
+ if (!keys2.includes(key)) {
2089
+ return false;
2090
+ }
2091
+ if (key !== "ref") {
2092
+ const val2 = object2[key];
2093
+ if (isDateObject(val1) && isDateObject(val2) || isObject(val1) && isObject(val2) || Array.isArray(val1) && Array.isArray(val2) ? !deepEqual(val1, val2) : val1 !== val2) {
2094
+ return false;
2095
+ }
2096
+ }
2097
+ }
2098
+ return true;
2099
+ }
2100
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
2101
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
2102
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
2103
+ var objectHasFunction = (data) => {
2104
+ for (const key in data) {
2105
+ if (isFunction(data[key])) {
2106
+ return true;
2107
+ }
2108
+ }
2109
+ return false;
2110
+ };
2111
+ function markFieldsDirty(data, fields = {}) {
2112
+ const isParentNodeArray = Array.isArray(data);
2113
+ if (isObject(data) || isParentNodeArray) {
2114
+ for (const key in data) {
2115
+ if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
2116
+ fields[key] = Array.isArray(data[key]) ? [] : {};
2117
+ markFieldsDirty(data[key], fields[key]);
2118
+ } else if (!isNullOrUndefined(data[key])) {
2119
+ fields[key] = true;
2120
+ }
2121
+ }
2122
+ }
2123
+ return fields;
2124
+ }
2125
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
2126
+ const isParentNodeArray = Array.isArray(data);
2127
+ if (isObject(data) || isParentNodeArray) {
2128
+ for (const key in data) {
2129
+ if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
2130
+ if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {
2131
+ dirtyFieldsFromValues[key] = Array.isArray(data[key]) ? markFieldsDirty(data[key], []) : { ...markFieldsDirty(data[key]) };
2132
+ } else {
2133
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
2134
+ }
2135
+ } else {
2136
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
2137
+ }
2138
+ }
2139
+ }
2140
+ return dirtyFieldsFromValues;
2141
+ }
2142
+ var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
2143
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ? value : valueAsNumber ? value === "" ? NaN : value ? +value : value : valueAsDate && isString(value) ? new Date(value) : setValueAs ? setValueAs(value) : value;
2144
+ function getFieldValue(_f) {
2145
+ const ref = _f.ref;
2146
+ if (_f.refs ? _f.refs.every((ref2) => ref2.disabled) : ref.disabled) {
2147
+ return;
2148
+ }
2149
+ if (isFileInput(ref)) {
2150
+ return ref.files;
2151
+ }
2152
+ if (isRadioInput(ref)) {
2153
+ return getRadioValue(_f.refs).value;
2154
+ }
2155
+ if (isMultipleSelect(ref)) {
2156
+ return [...ref.selectedOptions].map(({ value }) => value);
2157
+ }
2158
+ if (isCheckBoxInput(ref)) {
2159
+ return getCheckboxValue(_f.refs).value;
2160
+ }
2161
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
2162
+ }
2163
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
2164
+ const fields = {};
2165
+ for (const name of fieldsNames) {
2166
+ const field = get(_fields, name);
2167
+ field && set(fields, name, field._f);
2168
+ }
2169
+ return {
2170
+ criteriaMode,
2171
+ names: [...fieldsNames],
2172
+ fields,
2173
+ shouldUseNativeValidation
2174
+ };
2175
+ };
2176
+ var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
2177
+ var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
2178
+ function schemaErrorLookup(errors, _fields, name) {
2179
+ const error = get(errors, name);
2180
+ if (error || isKey(name)) {
2181
+ return {
2182
+ error,
2183
+ name
2184
+ };
2185
+ }
2186
+ const names = name.split(".");
2187
+ while (names.length) {
2188
+ const fieldName = names.join(".");
2189
+ const field = get(_fields, fieldName);
2190
+ const foundError = get(errors, fieldName);
2191
+ if (field && !Array.isArray(field) && name !== fieldName) {
2192
+ return { name };
2193
+ }
2194
+ if (foundError && foundError.type) {
2195
+ return {
2196
+ name: fieldName,
2197
+ error: foundError
2198
+ };
2199
+ }
2200
+ names.pop();
2201
+ }
2202
+ return {
2203
+ name
2204
+ };
2205
+ }
2206
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
2207
+ if (mode.isOnAll) {
2208
+ return false;
2209
+ } else if (!isSubmitted && mode.isOnTouch) {
2210
+ return !(isTouched || isBlurEvent);
2211
+ } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
2212
+ return !isBlurEvent;
2213
+ } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
2214
+ return isBlurEvent;
2215
+ }
2216
+ return true;
2217
+ };
2218
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
2219
+ const defaultOptions = {
2220
+ mode: VALIDATION_MODE.onSubmit,
2221
+ reValidateMode: VALIDATION_MODE.onChange,
2222
+ shouldFocusError: true
2223
+ };
2224
+ function createFormControl(props = {}, flushRootRender) {
2225
+ let _options = {
2226
+ ...defaultOptions,
2227
+ ...props
2228
+ };
2229
+ let _formState = {
2230
+ submitCount: 0,
2231
+ isDirty: false,
2232
+ isLoading: isFunction(_options.defaultValues),
2233
+ isValidating: false,
2234
+ isSubmitted: false,
2235
+ isSubmitting: false,
2236
+ isSubmitSuccessful: false,
2237
+ isValid: false,
2238
+ touchedFields: {},
2239
+ dirtyFields: {},
2240
+ errors: _options.errors || {},
2241
+ disabled: false
2242
+ };
2243
+ let _fields = {};
2244
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
2245
+ let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
2246
+ let _state = {
2247
+ action: false,
2248
+ mount: false,
2249
+ watch: false
2250
+ };
2251
+ let _names = {
2252
+ mount: /* @__PURE__ */ new Set(),
2253
+ unMount: /* @__PURE__ */ new Set(),
2254
+ array: /* @__PURE__ */ new Set(),
2255
+ watch: /* @__PURE__ */ new Set()
2256
+ };
2257
+ let delayErrorCallback;
2258
+ let timer = 0;
2259
+ const _proxyFormState = {
2260
+ isDirty: false,
2261
+ dirtyFields: false,
2262
+ touchedFields: false,
2263
+ isValidating: false,
2264
+ isValid: false,
2265
+ errors: false
2266
+ };
2267
+ const _subjects = {
2268
+ values: createSubject(),
2269
+ array: createSubject(),
2270
+ state: createSubject()
2271
+ };
2272
+ const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
2273
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
2274
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
2275
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
2276
+ const debounce = (callback) => (wait) => {
2277
+ clearTimeout(timer);
2278
+ timer = setTimeout(callback, wait);
2279
+ };
2280
+ const _updateValid = async (shouldUpdateValid) => {
2281
+ if (_proxyFormState.isValid || shouldUpdateValid) {
2282
+ const isValid2 = _options.resolver ? isEmptyObject((await _executeSchema()).errors) : await executeBuiltInValidation(_fields, true);
2283
+ if (isValid2 !== _formState.isValid) {
2284
+ _subjects.state.next({
2285
+ isValid: isValid2
2286
+ });
2287
+ }
2288
+ }
2289
+ };
2290
+ const _updateIsValidating = (value) => _proxyFormState.isValidating && _subjects.state.next({
2291
+ isValidating: value
2292
+ });
2293
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
2294
+ if (args && method) {
2295
+ _state.action = true;
2296
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
2297
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
2298
+ shouldSetValues && set(_fields, name, fieldValues);
2299
+ }
2300
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
2301
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
2302
+ shouldSetValues && set(_formState.errors, name, errors);
2303
+ unsetEmptyArray(_formState.errors, name);
2304
+ }
2305
+ if (_proxyFormState.touchedFields && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
2306
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
2307
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
2308
+ }
2309
+ if (_proxyFormState.dirtyFields) {
2310
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
2311
+ }
2312
+ _subjects.state.next({
2313
+ name,
2314
+ isDirty: _getDirty(name, values),
2315
+ dirtyFields: _formState.dirtyFields,
2316
+ errors: _formState.errors,
2317
+ isValid: _formState.isValid
2318
+ });
2319
+ } else {
2320
+ set(_formValues, name, values);
2321
+ }
2322
+ };
2323
+ const updateErrors = (name, error) => {
2324
+ set(_formState.errors, name, error);
2325
+ _subjects.state.next({
2326
+ errors: _formState.errors
2327
+ });
2328
+ };
2329
+ const _setErrors = (errors) => {
2330
+ _formState.errors = errors;
2331
+ _subjects.state.next({
2332
+ errors: _formState.errors,
2333
+ isValid: false
2334
+ });
2335
+ };
2336
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
2337
+ const field = get(_fields, name);
2338
+ if (field) {
2339
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
2340
+ isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
2341
+ _state.mount && _updateValid();
2342
+ }
2343
+ };
2344
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
2345
+ let shouldUpdateField = false;
2346
+ let isPreviousDirty = false;
2347
+ const output = {
2348
+ name
2349
+ };
2350
+ const disabledField = get(_fields, name) && get(_fields, name)._f.disabled;
2351
+ if (!isBlurEvent || shouldDirty) {
2352
+ if (_proxyFormState.isDirty) {
2353
+ isPreviousDirty = _formState.isDirty;
2354
+ _formState.isDirty = output.isDirty = _getDirty();
2355
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
2356
+ }
2357
+ const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
2358
+ isPreviousDirty = !disabledField && get(_formState.dirtyFields, name);
2359
+ isCurrentFieldPristine || disabledField ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
2360
+ output.dirtyFields = _formState.dirtyFields;
2361
+ shouldUpdateField = shouldUpdateField || _proxyFormState.dirtyFields && isPreviousDirty !== !isCurrentFieldPristine;
2362
+ }
2363
+ if (isBlurEvent) {
2364
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
2365
+ if (!isPreviousFieldTouched) {
2366
+ set(_formState.touchedFields, name, isBlurEvent);
2367
+ output.touchedFields = _formState.touchedFields;
2368
+ shouldUpdateField = shouldUpdateField || _proxyFormState.touchedFields && isPreviousFieldTouched !== isBlurEvent;
2369
+ }
2370
+ }
2371
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
2372
+ return shouldUpdateField ? output : {};
2373
+ };
2374
+ const shouldRenderByError = (name, isValid2, error, fieldState) => {
2375
+ const previousFieldError = get(_formState.errors, name);
2376
+ const shouldUpdateValid = _proxyFormState.isValid && isBoolean(isValid2) && _formState.isValid !== isValid2;
2377
+ if (props.delayError && error) {
2378
+ delayErrorCallback = debounce(() => updateErrors(name, error));
2379
+ delayErrorCallback(props.delayError);
2380
+ } else {
2381
+ clearTimeout(timer);
2382
+ delayErrorCallback = null;
2383
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
2384
+ }
2385
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
2386
+ const updatedFormState = {
2387
+ ...fieldState,
2388
+ ...shouldUpdateValid && isBoolean(isValid2) ? { isValid: isValid2 } : {},
2389
+ errors: _formState.errors,
2390
+ name
2391
+ };
2392
+ _formState = {
2393
+ ..._formState,
2394
+ ...updatedFormState
2395
+ };
2396
+ _subjects.state.next(updatedFormState);
2397
+ }
2398
+ _updateIsValidating(false);
2399
+ };
2400
+ const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
2401
+ const executeSchemaAndUpdateState = async (names) => {
2402
+ const { errors } = await _executeSchema(names);
2403
+ if (names) {
2404
+ for (const name of names) {
2405
+ const error = get(errors, name);
2406
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
2407
+ }
2408
+ } else {
2409
+ _formState.errors = errors;
2410
+ }
2411
+ return errors;
2412
+ };
2413
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
2414
+ valid: true
2415
+ }) => {
2416
+ for (const name in fields) {
2417
+ const field = fields[name];
2418
+ if (field) {
2419
+ const { _f, ...fieldValue } = field;
2420
+ if (_f) {
2421
+ const isFieldArrayRoot = _names.array.has(_f.name);
2422
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
2423
+ if (fieldError[_f.name]) {
2424
+ context.valid = false;
2425
+ if (shouldOnlyCheckValid) {
2426
+ break;
2427
+ }
2428
+ }
2429
+ !shouldOnlyCheckValid && (get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name));
2430
+ }
2431
+ fieldValue && await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context);
2432
+ }
2433
+ }
2434
+ return context.valid;
2435
+ };
2436
+ const _removeUnmounted = () => {
2437
+ for (const name of _names.unMount) {
2438
+ const field = get(_fields, name);
2439
+ field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
2440
+ }
2441
+ _names.unMount = /* @__PURE__ */ new Set();
2442
+ };
2443
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data), !deepEqual(getValues(), _defaultValues));
2444
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
2445
+ ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue
2446
+ }, isGlobal, defaultValue);
2447
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
2448
+ const setFieldValue = (name, value, options = {}) => {
2449
+ const field = get(_fields, name);
2450
+ let fieldValue = value;
2451
+ if (field) {
2452
+ const fieldReference = field._f;
2453
+ if (fieldReference) {
2454
+ !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
2455
+ fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
2456
+ if (isMultipleSelect(fieldReference.ref)) {
2457
+ [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
2458
+ } else if (fieldReference.refs) {
2459
+ if (isCheckBoxInput(fieldReference.ref)) {
2460
+ fieldReference.refs.length > 1 ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) && (checkboxRef.checked = Array.isArray(fieldValue) ? !!fieldValue.find((data) => data === checkboxRef.value) : fieldValue === checkboxRef.value)) : fieldReference.refs[0] && (fieldReference.refs[0].checked = !!fieldValue);
2461
+ } else {
2462
+ fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
2463
+ }
2464
+ } else if (isFileInput(fieldReference.ref)) {
2465
+ fieldReference.ref.value = "";
2466
+ } else {
2467
+ fieldReference.ref.value = fieldValue;
2468
+ if (!fieldReference.ref.type) {
2469
+ _subjects.values.next({
2470
+ name,
2471
+ values: { ..._formValues }
2472
+ });
2473
+ }
2474
+ }
2475
+ }
2476
+ }
2477
+ (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
2478
+ options.shouldValidate && trigger(name);
2479
+ };
2480
+ const setValues = (name, value, options) => {
2481
+ for (const fieldKey in value) {
2482
+ const fieldValue = value[fieldKey];
2483
+ const fieldName = `${name}.${fieldKey}`;
2484
+ const field = get(_fields, fieldName);
2485
+ (_names.array.has(name) || !isPrimitive(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options);
2486
+ }
2487
+ };
2488
+ const setValue = (name, value, options = {}) => {
2489
+ const field = get(_fields, name);
2490
+ const isFieldArray = _names.array.has(name);
2491
+ const cloneValue = cloneObject(value);
2492
+ set(_formValues, name, cloneValue);
2493
+ if (isFieldArray) {
2494
+ _subjects.array.next({
2495
+ name,
2496
+ values: { ..._formValues }
2497
+ });
2498
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) && options.shouldDirty) {
2499
+ _subjects.state.next({
2500
+ name,
2501
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
2502
+ isDirty: _getDirty(name, cloneValue)
2503
+ });
2504
+ }
2505
+ } else {
2506
+ field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options);
2507
+ }
2508
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
2509
+ _subjects.values.next({
2510
+ name,
2511
+ values: { ..._formValues }
2512
+ });
2513
+ !_state.mount && flushRootRender();
2514
+ };
2515
+ const onChange = async (event) => {
2516
+ const target = event.target;
2517
+ let name = target.name;
2518
+ let isFieldValueUpdated = true;
2519
+ const field = get(_fields, name);
2520
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
2521
+ const _updateIsFieldValueUpdated = (fieldValue) => {
2522
+ isFieldValueUpdated = Number.isNaN(fieldValue) || fieldValue === get(_formValues, name, fieldValue);
2523
+ };
2524
+ if (field) {
2525
+ let error;
2526
+ let isValid2;
2527
+ const fieldValue = getCurrentFieldValue();
2528
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
2529
+ const shouldSkipValidation = !hasValidation(field._f) && !_options.resolver && !get(_formState.errors, name) && !field._f.deps || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
2530
+ const watched = isWatched(name, _names, isBlurEvent);
2531
+ set(_formValues, name, fieldValue);
2532
+ if (isBlurEvent) {
2533
+ field._f.onBlur && field._f.onBlur(event);
2534
+ delayErrorCallback && delayErrorCallback(0);
2535
+ } else if (field._f.onChange) {
2536
+ field._f.onChange(event);
2537
+ }
2538
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
2539
+ const shouldRender = !isEmptyObject(fieldState) || watched;
2540
+ !isBlurEvent && _subjects.values.next({
2541
+ name,
2542
+ type: event.type,
2543
+ values: { ..._formValues }
2544
+ });
2545
+ if (shouldSkipValidation) {
2546
+ _proxyFormState.isValid && _updateValid();
2547
+ return shouldRender && _subjects.state.next({ name, ...watched ? {} : fieldState });
2548
+ }
2549
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
2550
+ _updateIsValidating(true);
2551
+ if (_options.resolver) {
2552
+ const { errors } = await _executeSchema([name]);
2553
+ _updateIsFieldValueUpdated(fieldValue);
2554
+ if (isFieldValueUpdated) {
2555
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
2556
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
2557
+ error = errorLookupResult.error;
2558
+ name = errorLookupResult.name;
2559
+ isValid2 = isEmptyObject(errors);
2560
+ }
2561
+ } else {
2562
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
2563
+ _updateIsFieldValueUpdated(fieldValue);
2564
+ if (isFieldValueUpdated) {
2565
+ if (error) {
2566
+ isValid2 = false;
2567
+ } else if (_proxyFormState.isValid) {
2568
+ isValid2 = await executeBuiltInValidation(_fields, true);
2569
+ }
2570
+ }
2571
+ }
2572
+ if (isFieldValueUpdated) {
2573
+ field._f.deps && trigger(field._f.deps);
2574
+ shouldRenderByError(name, isValid2, error, fieldState);
2575
+ }
2576
+ }
2577
+ };
2578
+ const _focusInput = (ref, key) => {
2579
+ if (get(_formState.errors, key) && ref.focus) {
2580
+ ref.focus();
2581
+ return 1;
2582
+ }
2583
+ return;
2584
+ };
2585
+ const trigger = async (name, options = {}) => {
2586
+ let isValid2;
2587
+ let validationResult;
2588
+ const fieldNames = convertToArrayPayload(name);
2589
+ _updateIsValidating(true);
2590
+ if (_options.resolver) {
2591
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
2592
+ isValid2 = isEmptyObject(errors);
2593
+ validationResult = name ? !fieldNames.some((name2) => get(errors, name2)) : isValid2;
2594
+ } else if (name) {
2595
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
2596
+ const field = get(_fields, fieldName);
2597
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
2598
+ }))).every(Boolean);
2599
+ !(!validationResult && !_formState.isValid) && _updateValid();
2600
+ } else {
2601
+ validationResult = isValid2 = await executeBuiltInValidation(_fields);
2602
+ }
2603
+ _subjects.state.next({
2604
+ ...!isString(name) || _proxyFormState.isValid && isValid2 !== _formState.isValid ? {} : { name },
2605
+ ..._options.resolver || !name ? { isValid: isValid2 } : {},
2606
+ errors: _formState.errors,
2607
+ isValidating: false
2608
+ });
2609
+ options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
2610
+ return validationResult;
2611
+ };
2612
+ const getValues = (fieldNames) => {
2613
+ const values = {
2614
+ ..._defaultValues,
2615
+ ..._state.mount ? _formValues : {}
2616
+ };
2617
+ return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
2618
+ };
2619
+ const getFieldState = (name, formState) => ({
2620
+ invalid: !!get((formState || _formState).errors, name),
2621
+ isDirty: !!get((formState || _formState).dirtyFields, name),
2622
+ isTouched: !!get((formState || _formState).touchedFields, name),
2623
+ error: get((formState || _formState).errors, name)
2624
+ });
2625
+ const clearErrors = (name) => {
2626
+ name && convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
2627
+ _subjects.state.next({
2628
+ errors: name ? _formState.errors : {}
2629
+ });
2630
+ };
2631
+ const setError = (name, error, options) => {
2632
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
2633
+ set(_formState.errors, name, {
2634
+ ...error,
2635
+ ref
2636
+ });
2637
+ _subjects.state.next({
2638
+ name,
2639
+ errors: _formState.errors,
2640
+ isValid: false
2641
+ });
2642
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
2643
+ };
2644
+ const watch = (name, defaultValue) => isFunction(name) ? _subjects.values.subscribe({
2645
+ next: (payload) => name(_getWatch(void 0, defaultValue), payload)
2646
+ }) : _getWatch(name, defaultValue, true);
2647
+ const unregister = (name, options = {}) => {
2648
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
2649
+ _names.mount.delete(fieldName);
2650
+ _names.array.delete(fieldName);
2651
+ if (!options.keepValue) {
2652
+ unset(_fields, fieldName);
2653
+ unset(_formValues, fieldName);
2654
+ }
2655
+ !options.keepError && unset(_formState.errors, fieldName);
2656
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
2657
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
2658
+ !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
2659
+ }
2660
+ _subjects.values.next({
2661
+ values: { ..._formValues }
2662
+ });
2663
+ _subjects.state.next({
2664
+ ..._formState,
2665
+ ...!options.keepDirty ? {} : { isDirty: _getDirty() }
2666
+ });
2667
+ !options.keepIsValid && _updateValid();
2668
+ };
2669
+ const _updateDisabledField = ({ disabled, name, field, fields, value }) => {
2670
+ if (isBoolean(disabled)) {
2671
+ const inputValue = disabled ? void 0 : isUndefined(value) ? getFieldValue(field ? field._f : get(fields, name)._f) : value;
2672
+ set(_formValues, name, inputValue);
2673
+ updateTouchAndDirty(name, inputValue, false, false, true);
2674
+ }
2675
+ };
2676
+ const register = (name, options = {}) => {
2677
+ let field = get(_fields, name);
2678
+ const disabledIsDefined = isBoolean(options.disabled);
2679
+ set(_fields, name, {
2680
+ ...field || {},
2681
+ _f: {
2682
+ ...field && field._f ? field._f : { ref: { name } },
2683
+ name,
2684
+ mount: true,
2685
+ ...options
2686
+ }
2687
+ });
2688
+ _names.mount.add(name);
2689
+ if (field) {
2690
+ _updateDisabledField({
2691
+ field,
2692
+ disabled: options.disabled,
2693
+ name
2694
+ });
2695
+ } else {
2696
+ updateValidAndValue(name, true, options.value);
2697
+ }
2698
+ return {
2699
+ ...disabledIsDefined ? { disabled: options.disabled } : {},
2700
+ ..._options.progressive ? {
2701
+ required: !!options.required,
2702
+ min: getRuleValue(options.min),
2703
+ max: getRuleValue(options.max),
2704
+ minLength: getRuleValue(options.minLength),
2705
+ maxLength: getRuleValue(options.maxLength),
2706
+ pattern: getRuleValue(options.pattern)
2707
+ } : {},
2708
+ name,
2709
+ onChange,
2710
+ onBlur: onChange,
2711
+ ref: (ref) => {
2712
+ if (ref) {
2713
+ register(name, options);
2714
+ field = get(_fields, name);
2715
+ const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
2716
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
2717
+ const refs = field._f.refs || [];
2718
+ if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) {
2719
+ return;
2720
+ }
2721
+ set(_fields, name, {
2722
+ _f: {
2723
+ ...field._f,
2724
+ ...radioOrCheckbox ? {
2725
+ refs: [
2726
+ ...refs.filter(live),
2727
+ fieldRef,
2728
+ ...Array.isArray(get(_defaultValues, name)) ? [{}] : []
2729
+ ],
2730
+ ref: { type: fieldRef.type, name }
2731
+ } : { ref: fieldRef }
2732
+ }
2733
+ });
2734
+ updateValidAndValue(name, false, void 0, fieldRef);
2735
+ } else {
2736
+ field = get(_fields, name, {});
2737
+ if (field._f) {
2738
+ field._f.mount = false;
2739
+ }
2740
+ (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
2741
+ }
2742
+ }
2743
+ };
2744
+ };
2745
+ const _focusError = () => _options.shouldFocusError && iterateFieldsByAction(_fields, _focusInput, _names.mount);
2746
+ const _disableForm = (disabled) => {
2747
+ if (isBoolean(disabled)) {
2748
+ _subjects.state.next({ disabled });
2749
+ iterateFieldsByAction(_fields, (ref, name) => {
2750
+ let requiredDisabledState = disabled;
2751
+ const currentField = get(_fields, name);
2752
+ if (currentField && isBoolean(currentField._f.disabled)) {
2753
+ requiredDisabledState || (requiredDisabledState = currentField._f.disabled);
2754
+ }
2755
+ ref.disabled = requiredDisabledState;
2756
+ }, 0, false);
2757
+ }
2758
+ };
2759
+ const handleSubmit = (onValid, onInvalid) => async (e2) => {
2760
+ if (e2) {
2761
+ e2.preventDefault && e2.preventDefault();
2762
+ e2.persist && e2.persist();
2763
+ }
2764
+ let fieldValues = cloneObject(_formValues);
2765
+ _subjects.state.next({
2766
+ isSubmitting: true
2767
+ });
2768
+ if (_options.resolver) {
2769
+ const { errors, values } = await _executeSchema();
2770
+ _formState.errors = errors;
2771
+ fieldValues = values;
2772
+ } else {
2773
+ await executeBuiltInValidation(_fields);
2774
+ }
2775
+ unset(_formState.errors, "root");
2776
+ if (isEmptyObject(_formState.errors)) {
2777
+ _subjects.state.next({
2778
+ errors: {}
2779
+ });
2780
+ await onValid(fieldValues, e2);
2781
+ } else {
2782
+ if (onInvalid) {
2783
+ await onInvalid({ ..._formState.errors }, e2);
2784
+ }
2785
+ _focusError();
2786
+ setTimeout(_focusError);
2787
+ }
2788
+ _subjects.state.next({
2789
+ isSubmitted: true,
2790
+ isSubmitting: false,
2791
+ isSubmitSuccessful: isEmptyObject(_formState.errors),
2792
+ submitCount: _formState.submitCount + 1,
2793
+ errors: _formState.errors
2794
+ });
2795
+ };
2796
+ const resetField = (name, options = {}) => {
2797
+ if (get(_fields, name)) {
2798
+ if (isUndefined(options.defaultValue)) {
2799
+ setValue(name, get(_defaultValues, name));
2800
+ } else {
2801
+ setValue(name, options.defaultValue);
2802
+ set(_defaultValues, name, options.defaultValue);
2803
+ }
2804
+ if (!options.keepTouched) {
2805
+ unset(_formState.touchedFields, name);
2806
+ }
2807
+ if (!options.keepDirty) {
2808
+ unset(_formState.dirtyFields, name);
2809
+ _formState.isDirty = options.defaultValue ? _getDirty(name, get(_defaultValues, name)) : _getDirty();
2810
+ }
2811
+ if (!options.keepError) {
2812
+ unset(_formState.errors, name);
2813
+ _proxyFormState.isValid && _updateValid();
2814
+ }
2815
+ _subjects.state.next({ ..._formState });
2816
+ }
2817
+ };
2818
+ const _reset = (formValues, keepStateOptions = {}) => {
2819
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2820
+ const cloneUpdatedValues = cloneObject(updatedValues);
2821
+ const values = formValues && !isEmptyObject(formValues) ? cloneUpdatedValues : _defaultValues;
2822
+ if (!keepStateOptions.keepDefaultValues) {
2823
+ _defaultValues = updatedValues;
2824
+ }
2825
+ if (!keepStateOptions.keepValues) {
2826
+ if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
2827
+ for (const fieldName of _names.mount) {
2828
+ get(_formState.dirtyFields, fieldName) ? set(values, fieldName, get(_formValues, fieldName)) : setValue(fieldName, get(values, fieldName));
2829
+ }
2830
+ } else {
2831
+ if (isWeb && isUndefined(formValues)) {
2832
+ for (const name of _names.mount) {
2833
+ const field = get(_fields, name);
2834
+ if (field && field._f) {
2835
+ const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
2836
+ if (isHTMLElement(fieldReference)) {
2837
+ const form = fieldReference.closest("form");
2838
+ if (form) {
2839
+ form.reset();
2840
+ break;
2841
+ }
2842
+ }
2843
+ }
2844
+ }
2845
+ }
2846
+ _fields = {};
2847
+ }
2848
+ _formValues = props.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneObject(values);
2849
+ _subjects.array.next({
2850
+ values: { ...values }
2851
+ });
2852
+ _subjects.values.next({
2853
+ values: { ...values }
2854
+ });
2855
+ }
2856
+ _names = {
2857
+ mount: /* @__PURE__ */ new Set(),
2858
+ unMount: /* @__PURE__ */ new Set(),
2859
+ array: /* @__PURE__ */ new Set(),
2860
+ watch: /* @__PURE__ */ new Set(),
2861
+ watchAll: false,
2862
+ focus: ""
2863
+ };
2864
+ !_state.mount && flushRootRender();
2865
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
2866
+ _state.watch = !!props.shouldUnregister;
2867
+ _subjects.state.next({
2868
+ submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
2869
+ isDirty: keepStateOptions.keepDirty ? _formState.isDirty : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
2870
+ isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
2871
+ dirtyFields: keepStateOptions.keepDirtyValues ? _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : {},
2872
+ touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
2873
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2874
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
2875
+ isSubmitting: false
2876
+ });
2877
+ };
2878
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, keepStateOptions);
2879
+ const setFocus = (name, options = {}) => {
2880
+ const field = get(_fields, name);
2881
+ const fieldReference = field && field._f;
2882
+ if (fieldReference) {
2883
+ const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
2884
+ if (fieldRef.focus) {
2885
+ fieldRef.focus();
2886
+ options.shouldSelect && fieldRef.select();
2887
+ }
2888
+ }
2889
+ };
2890
+ const _updateFormState = (updatedFormState) => {
2891
+ _formState = {
2892
+ ..._formState,
2893
+ ...updatedFormState
2894
+ };
2895
+ };
2896
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
2897
+ reset(values, _options.resetOptions);
2898
+ _subjects.state.next({
2899
+ isLoading: false
2900
+ });
2901
+ });
2902
+ return {
2903
+ control: {
2904
+ register,
2905
+ unregister,
2906
+ getFieldState,
2907
+ handleSubmit,
2908
+ setError,
2909
+ _executeSchema,
2910
+ _getWatch,
2911
+ _getDirty,
2912
+ _updateValid,
2913
+ _removeUnmounted,
2914
+ _updateFieldArray,
2915
+ _updateDisabledField,
2916
+ _getFieldArray,
2917
+ _reset,
2918
+ _resetDefaultValues,
2919
+ _updateFormState,
2920
+ _disableForm,
2921
+ _subjects,
2922
+ _proxyFormState,
2923
+ _setErrors,
2924
+ get _fields() {
2925
+ return _fields;
2926
+ },
2927
+ get _formValues() {
2928
+ return _formValues;
2929
+ },
2930
+ get _state() {
2931
+ return _state;
2932
+ },
2933
+ set _state(value) {
2934
+ _state = value;
2935
+ },
2936
+ get _defaultValues() {
2937
+ return _defaultValues;
2938
+ },
2939
+ get _names() {
2940
+ return _names;
2941
+ },
2942
+ set _names(value) {
2943
+ _names = value;
2944
+ },
2945
+ get _formState() {
2946
+ return _formState;
2947
+ },
2948
+ set _formState(value) {
2949
+ _formState = value;
2950
+ },
2951
+ get _options() {
2952
+ return _options;
2953
+ },
2954
+ set _options(value) {
2955
+ _options = {
2956
+ ..._options,
2957
+ ...value
2958
+ };
2959
+ }
2960
+ },
2961
+ trigger,
2962
+ register,
2963
+ handleSubmit,
2964
+ watch,
2965
+ setValue,
2966
+ getValues,
2967
+ reset,
2968
+ resetField,
2969
+ clearErrors,
2970
+ unregister,
2971
+ setError,
2972
+ setFocus,
2973
+ getFieldState
2974
+ };
2975
+ }
2976
+ function useForm(props = {}) {
2977
+ const _formControl = React__default.default.useRef();
2978
+ const _values = React__default.default.useRef();
2979
+ const [formState, updateFormState] = React__default.default.useState({
2980
+ isDirty: false,
2981
+ isValidating: false,
2982
+ isLoading: isFunction(props.defaultValues),
2983
+ isSubmitted: false,
2984
+ isSubmitting: false,
2985
+ isSubmitSuccessful: false,
2986
+ isValid: false,
2987
+ submitCount: 0,
2988
+ dirtyFields: {},
2989
+ touchedFields: {},
2990
+ errors: props.errors || {},
2991
+ disabled: false,
2992
+ defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
2993
+ });
2994
+ if (!_formControl.current) {
2995
+ _formControl.current = {
2996
+ ...createFormControl(props, () => updateFormState((formState2) => ({ ...formState2 }))),
2997
+ formState
2998
+ };
2999
+ }
3000
+ const control = _formControl.current.control;
3001
+ control._options = props;
3002
+ useSubscribe({
3003
+ subject: control._subjects.state,
3004
+ next: (value) => {
3005
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
3006
+ updateFormState({ ...control._formState });
3007
+ }
3008
+ }
3009
+ });
3010
+ React__default.default.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
3011
+ React__default.default.useEffect(() => {
3012
+ if (control._proxyFormState.isDirty) {
3013
+ const isDirty2 = control._getDirty();
3014
+ if (isDirty2 !== formState.isDirty) {
3015
+ control._subjects.state.next({
3016
+ isDirty: isDirty2
3017
+ });
3018
+ }
3019
+ }
3020
+ }, [control, formState.isDirty]);
3021
+ React__default.default.useEffect(() => {
3022
+ if (props.values && !deepEqual(props.values, _values.current)) {
3023
+ control._reset(props.values, control._options.resetOptions);
3024
+ _values.current = props.values;
3025
+ updateFormState((state) => ({ ...state }));
3026
+ } else {
3027
+ control._resetDefaultValues();
3028
+ }
3029
+ }, [props.values, control]);
3030
+ React__default.default.useEffect(() => {
3031
+ if (props.errors) {
3032
+ control._setErrors(props.errors);
3033
+ }
3034
+ }, [props.errors, control]);
3035
+ React__default.default.useEffect(() => {
3036
+ if (!control._state.mount) {
3037
+ control._updateValid();
3038
+ control._state.mount = true;
3039
+ }
3040
+ if (control._state.watch) {
3041
+ control._state.watch = false;
3042
+ control._subjects.state.next({ ...control._formState });
3043
+ }
3044
+ control._removeUnmounted();
3045
+ });
3046
+ _formControl.current.formState = getProxyFormState(formState, control);
3047
+ return _formControl.current;
3048
+ }
3049
+ var t$1 = function(t2, n2, e2) {
3050
+ if (t2 && "reportValidity" in t2) {
3051
+ var i2 = get(e2, n2);
3052
+ t2.setCustomValidity(i2 && i2.message || ""), t2.reportValidity();
3053
+ }
3054
+ }, n$1 = function(r, n2) {
3055
+ var e2 = function(e3) {
3056
+ var i3 = n2.fields[e3];
3057
+ i3 && i3.ref && "reportValidity" in i3.ref ? t$1(i3.ref, e3, r) : i3.refs && i3.refs.forEach(function(n3) {
3058
+ return t$1(n3, e3, r);
3059
+ });
3060
+ };
3061
+ for (var i2 in n2.fields) e2(i2);
3062
+ }, e = function(r) {
3063
+ return r instanceof Date;
3064
+ }, i = function(r) {
3065
+ return null == r;
3066
+ }, a = function(r) {
3067
+ return "object" == typeof r;
3068
+ }, o = function(r) {
3069
+ return !i(r) && !Array.isArray(r) && a(r) && !e(r);
3070
+ }, f = function(r) {
3071
+ return /^\w*$/.test(r);
3072
+ }, s = function(r, t2, n2) {
3073
+ for (var e2 = -1, i2 = f(t2) ? [t2] : function(r2) {
3074
+ return t3 = r2.replace(/["|']|\]/g, "").split(/\.|\[/), Array.isArray(t3) ? t3.filter(Boolean) : [];
3075
+ var t3;
3076
+ }(t2), a2 = i2.length, s2 = a2 - 1; ++e2 < a2; ) {
3077
+ var u2 = i2[e2], c2 = n2;
3078
+ if (e2 !== s2) {
3079
+ var l = r[u2];
3080
+ c2 = o(l) || Array.isArray(l) ? l : isNaN(+i2[e2 + 1]) ? {} : [];
3081
+ }
3082
+ r[u2] = c2, r = r[u2];
3083
+ }
3084
+ return r;
3085
+ }, u = function(t2, e2) {
3086
+ e2.shouldUseNativeValidation && n$1(t2, e2);
3087
+ var i2 = {};
3088
+ for (var a2 in t2) {
3089
+ var o2 = get(e2.fields, a2), f2 = Object.assign(t2[a2] || {}, { ref: o2 && o2.ref });
3090
+ if (c(e2.names || Object.keys(t2), a2)) {
3091
+ var u2 = Object.assign({}, get(i2, a2));
3092
+ s(u2, "root", f2), s(i2, a2, u2);
3093
+ } else s(i2, a2, f2);
3094
+ }
3095
+ return i2;
3096
+ }, c = function(r, t2) {
3097
+ return r.some(function(r2) {
3098
+ return r2.startsWith(t2 + ".");
3099
+ });
3100
+ };
3101
+ var n = function(e2, o2) {
3102
+ for (var n2 = {}; e2.length; ) {
3103
+ var t2 = e2[0], s2 = t2.code, i2 = t2.message, a2 = t2.path.join(".");
3104
+ if (!n2[a2]) if ("unionErrors" in t2) {
3105
+ var u2 = t2.unionErrors[0].errors[0];
3106
+ n2[a2] = { message: u2.message, type: u2.code };
3107
+ } else n2[a2] = { message: i2, type: s2 };
3108
+ if ("unionErrors" in t2 && t2.unionErrors.forEach(function(r) {
3109
+ return r.errors.forEach(function(r2) {
3110
+ return e2.push(r2);
3111
+ });
3112
+ }), o2) {
3113
+ var c2 = n2[a2].types, f2 = c2 && c2[t2.code];
3114
+ n2[a2] = appendErrors(a2, o2, n2, s2, f2 ? [].concat(f2, t2.message) : t2.message);
3115
+ }
3116
+ e2.shift();
3117
+ }
3118
+ return n2;
3119
+ }, t = function(r, t2, s2) {
3120
+ return void 0 === s2 && (s2 = {}), function(i2, a2, u$1) {
3121
+ try {
3122
+ return Promise.resolve(function(o2, n2) {
3123
+ try {
3124
+ var a3 = Promise.resolve(r["sync" === s2.mode ? "parse" : "parseAsync"](i2, t2)).then(function(r2) {
3125
+ return u$1.shouldUseNativeValidation && n$1({}, u$1), { errors: {}, values: s2.raw ? i2 : r2 };
3126
+ });
3127
+ } catch (r2) {
3128
+ return n2(r2);
3129
+ }
3130
+ return a3 && a3.then ? a3.then(void 0, n2) : a3;
3131
+ }(0, function(r2) {
3132
+ if (function(r3) {
3133
+ return null != r3.errors;
3134
+ }(r2)) return { values: {}, errors: u(n(r2.errors, !u$1.shouldUseNativeValidation && "all" === u$1.criteriaMode), u$1) };
3135
+ throw r2;
3136
+ }));
3137
+ } catch (r2) {
3138
+ return Promise.reject(r2);
3139
+ }
3140
+ };
3141
+ };
1260
3142
  var util;
1261
3143
  (function(util2) {
1262
3144
  util2.assertEqual = (_) => {
@@ -1284,8 +3166,8 @@ var util;
1284
3166
  return util2.objectValues(filtered);
1285
3167
  };
1286
3168
  util2.objectValues = (obj) => {
1287
- return util2.objectKeys(obj).map(function(e) {
1288
- return obj[e];
3169
+ return util2.objectKeys(obj).map(function(e2) {
3170
+ return obj[e2];
1289
3171
  });
1290
3172
  };
1291
3173
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
@@ -1349,8 +3231,8 @@ const ZodParsedType = util.arrayToEnum([
1349
3231
  "set"
1350
3232
  ]);
1351
3233
  const getParsedType = (data) => {
1352
- const t = typeof data;
1353
- switch (t) {
3234
+ const t2 = typeof data;
3235
+ switch (t2) {
1354
3236
  case "undefined":
1355
3237
  return ZodParsedType.undefined;
1356
3238
  case "string":
@@ -1450,10 +3332,10 @@ class ZodError extends Error {
1450
3332
  fieldErrors._errors.push(mapper(issue));
1451
3333
  } else {
1452
3334
  let curr = fieldErrors;
1453
- let i = 0;
1454
- while (i < issue.path.length) {
1455
- const el = issue.path[i];
1456
- const terminal = i === issue.path.length - 1;
3335
+ let i2 = 0;
3336
+ while (i2 < issue.path.length) {
3337
+ const el = issue.path[i2];
3338
+ const terminal = i2 === issue.path.length - 1;
1457
3339
  if (!terminal) {
1458
3340
  curr[el] = curr[el] || { _errors: [] };
1459
3341
  } else {
@@ -1461,7 +3343,7 @@ class ZodError extends Error {
1461
3343
  curr[el]._errors.push(mapper(issue));
1462
3344
  }
1463
3345
  curr = curr[el];
1464
- i++;
3346
+ i2++;
1465
3347
  }
1466
3348
  }
1467
3349
  }
@@ -1671,12 +3553,12 @@ class ParseStatus {
1671
3553
  }
1672
3554
  static mergeArray(status, results) {
1673
3555
  const arrayValue = [];
1674
- for (const s of results) {
1675
- if (s.status === "aborted")
3556
+ for (const s2 of results) {
3557
+ if (s2.status === "aborted")
1676
3558
  return INVALID;
1677
- if (s.status === "dirty")
3559
+ if (s2.status === "dirty")
1678
3560
  status.dirty();
1679
- arrayValue.push(s.value);
3561
+ arrayValue.push(s2.value);
1680
3562
  }
1681
3563
  return { status: status.value, value: arrayValue };
1682
3564
  }
@@ -3428,14 +5310,14 @@ class ZodArray extends ZodType {
3428
5310
  }
3429
5311
  }
3430
5312
  if (ctx.common.async) {
3431
- return Promise.all([...ctx.data].map((item, i) => {
3432
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
5313
+ return Promise.all([...ctx.data].map((item, i2) => {
5314
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
3433
5315
  })).then((result2) => {
3434
5316
  return ParseStatus.mergeArray(status, result2);
3435
5317
  });
3436
5318
  }
3437
- const result = [...ctx.data].map((item, i) => {
3438
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
5319
+ const result = [...ctx.data].map((item, i2) => {
5320
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
3439
5321
  });
3440
5322
  return ParseStatus.mergeArray(status, result);
3441
5323
  }
@@ -4037,17 +5919,17 @@ class ZodDiscriminatedUnion extends ZodType {
4037
5919
  });
4038
5920
  }
4039
5921
  }
4040
- function mergeValues(a, b) {
4041
- const aType = getParsedType(a);
5922
+ function mergeValues(a2, b) {
5923
+ const aType = getParsedType(a2);
4042
5924
  const bType = getParsedType(b);
4043
- if (a === b) {
4044
- return { valid: true, data: a };
5925
+ if (a2 === b) {
5926
+ return { valid: true, data: a2 };
4045
5927
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
4046
5928
  const bKeys = util.objectKeys(b);
4047
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
4048
- const newObj = { ...a, ...b };
5929
+ const sharedKeys = util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
5930
+ const newObj = { ...a2, ...b };
4049
5931
  for (const key of sharedKeys) {
4050
- const sharedValue = mergeValues(a[key], b[key]);
5932
+ const sharedValue = mergeValues(a2[key], b[key]);
4051
5933
  if (!sharedValue.valid) {
4052
5934
  return { valid: false };
4053
5935
  }
@@ -4055,12 +5937,12 @@ function mergeValues(a, b) {
4055
5937
  }
4056
5938
  return { valid: true, data: newObj };
4057
5939
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
4058
- if (a.length !== b.length) {
5940
+ if (a2.length !== b.length) {
4059
5941
  return { valid: false };
4060
5942
  }
4061
5943
  const newArray = [];
4062
- for (let index = 0; index < a.length; index++) {
4063
- const itemA = a[index];
5944
+ for (let index = 0; index < a2.length; index++) {
5945
+ const itemA = a2[index];
4064
5946
  const itemB = b[index];
4065
5947
  const sharedValue = mergeValues(itemA, itemB);
4066
5948
  if (!sharedValue.valid) {
@@ -4069,8 +5951,8 @@ function mergeValues(a, b) {
4069
5951
  newArray.push(sharedValue.data);
4070
5952
  }
4071
5953
  return { valid: true, data: newArray };
4072
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
4073
- return { valid: true, data: a };
5954
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a2 === +b) {
5955
+ return { valid: true, data: a2 };
4074
5956
  } else {
4075
5957
  return { valid: false };
4076
5958
  }
@@ -4364,7 +6246,7 @@ class ZodSet extends ZodType {
4364
6246
  }
4365
6247
  return { status: status.value, value: parsedSet };
4366
6248
  }
4367
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
6249
+ const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
4368
6250
  if (ctx.common.async) {
4369
6251
  return Promise.all(elements).then((elements2) => finalizeSet(elements2));
4370
6252
  } else {
@@ -4442,13 +6324,13 @@ class ZodFunction extends ZodType {
4442
6324
  const me = this;
4443
6325
  return OK(async function(...args) {
4444
6326
  const error = new ZodError([]);
4445
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
4446
- error.addIssue(makeArgsIssue(args, e));
6327
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
6328
+ error.addIssue(makeArgsIssue(args, e2));
4447
6329
  throw error;
4448
6330
  });
4449
6331
  const result = await Reflect.apply(fn, this, parsedArgs);
4450
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
4451
- error.addIssue(makeReturnsIssue(result, e));
6332
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
6333
+ error.addIssue(makeReturnsIssue(result, e2));
4452
6334
  throw error;
4453
6335
  });
4454
6336
  return parsedReturns;
@@ -5023,9 +6905,9 @@ class ZodPipeline extends ZodType {
5023
6905
  }
5024
6906
  }
5025
6907
  }
5026
- static create(a, b) {
6908
+ static create(a2, b) {
5027
6909
  return new ZodPipeline({
5028
- in: a,
6910
+ in: a2,
5029
6911
  out: b,
5030
6912
  typeName: ZodFirstPartyTypeKind.ZodPipeline
5031
6913
  });
@@ -5311,7 +7193,7 @@ const ProductSelector = ({
5311
7193
  selectedProductIds,
5312
7194
  onSelectProduct
5313
7195
  }) => {
5314
- const [search, setSearch] = react.useState("");
7196
+ const [search, setSearch] = React.useState("");
5315
7197
  const debouncedSearchHandler = lodash.debounce((value) => {
5316
7198
  setSearch(value);
5317
7199
  }, 500);
@@ -5322,7 +7204,7 @@ const ProductSelector = ({
5322
7204
  limit: 100
5323
7205
  })
5324
7206
  });
5325
- const selectableProducts = react.useMemo(() => {
7207
+ const selectableProducts = React.useMemo(() => {
5326
7208
  var _a;
5327
7209
  return (_a = products == null ? void 0 : products.products) == null ? void 0 : _a.filter(
5328
7210
  (product) => !selectedProductIds.includes(product.id)
@@ -5342,7 +7224,7 @@ const ProductSelector = ({
5342
7224
  {
5343
7225
  className: "text-lg py-2",
5344
7226
  placeholder: "Search products...",
5345
- onChange: (e) => debouncedSearchHandler(e.target.value)
7227
+ onChange: (e2) => debouncedSearchHandler(e2.target.value)
5346
7228
  }
5347
7229
  ),
5348
7230
  /* @__PURE__ */ jsxRuntime.jsx(ui.DataTable, { instance: table, children: /* @__PURE__ */ jsxRuntime.jsx(ui.DataTable.Table, {}) })
@@ -5381,207 +7263,321 @@ const FlashSaleForm = ({
5381
7263
  onCancel,
5382
7264
  disabled = false
5383
7265
  }) => {
5384
- const [campaign, setCampaign] = react.useState(
5385
- initialData || {
5386
- name: "",
5387
- description: "",
7266
+ var _a;
7267
+ const {
7268
+ control,
7269
+ register,
7270
+ handleSubmit,
7271
+ watch,
7272
+ setValue,
7273
+ formState: { errors }
7274
+ } = useForm({
7275
+ resolver: t(campaignDataSchema),
7276
+ defaultValues: {
7277
+ name: (initialData == null ? void 0 : initialData.name) || "",
7278
+ description: (initialData == null ? void 0 : initialData.description) || "",
5388
7279
  type: "flash-sale",
5389
- starts_at: "",
5390
- ends_at: ""
7280
+ starts_at: (initialData == null ? void 0 : initialData.starts_at) || "",
7281
+ ends_at: (initialData == null ? void 0 : initialData.ends_at) || "",
7282
+ products: initialProducts ? Array.from(initialProducts.values()) : []
7283
+ }
7284
+ });
7285
+ const { fields, append, remove } = useFieldArray({
7286
+ control,
7287
+ name: "products"
7288
+ });
7289
+ const [openProductModal, setOpenProductModal] = React.useState(false);
7290
+ const startsAt = watch("starts_at");
7291
+ const endsAt = watch("ends_at");
7292
+ const handleDateTimeChange = (field, type, value) => {
7293
+ const currentValue = watch(field);
7294
+ if (type === "date") {
7295
+ const time = currentValue ? dayjs__default.default(currentValue).format("HH:mm") : field === "starts_at" ? "00:00" : "23:59";
7296
+ setValue(field, `${value}T${time}`);
7297
+ } else {
7298
+ const date = currentValue ? dayjs__default.default(currentValue).format("YYYY-MM-DD") : dayjs__default.default().format("YYYY-MM-DD");
7299
+ setValue(field, `${date}T${value}`);
5391
7300
  }
5392
- );
5393
- const handleCampaignChange = (name, value) => {
5394
- setCampaign((prev) => ({ ...prev, [name]: value }));
5395
7301
  };
5396
- const [products, setProducts] = react.useState(
5397
- initialProducts || /* @__PURE__ */ new Map()
5398
- );
5399
- const handleProductChange = (product) => {
5400
- setProducts((prev) => {
5401
- const newProducts = new Map(prev);
5402
- newProducts.set(product.product.id, product);
5403
- return newProducts;
5404
- });
7302
+ const onFormSubmit = (data) => {
7303
+ onSubmit(data);
5405
7304
  };
5406
- const [openProductModal, setOpenProductModal] = react.useState(false);
5407
- const handleSave = (event) => {
5408
- event.preventDefault();
5409
- const campaignData = campaignDataSchema.safeParse({
5410
- ...campaign,
5411
- products: Array.from(products.values())
7305
+ const onFormError = () => {
7306
+ const errorMessages = Object.entries(errors).map(([key, value]) => {
7307
+ var _a2;
7308
+ if (key === "products" && Array.isArray(value)) {
7309
+ return value.map(
7310
+ (item, index) => item ? `Product ${index + 1}: ${Object.values(item).join(", ")}` : ""
7311
+ ).filter(Boolean).join(", ");
7312
+ }
7313
+ return (value == null ? void 0 : value.message) || ((_a2 = value == null ? void 0 : value.root) == null ? void 0 : _a2.message);
7314
+ }).filter(Boolean).join(", ");
7315
+ ui.toast.error("Invalid data", {
7316
+ description: errorMessages
5412
7317
  });
5413
- if (!campaignData.success) {
5414
- ui.toast.error("Invalid data", {
5415
- description: campaignData.error.issues.map((error) => error.message).join(", ")
5416
- });
5417
- return;
5418
- }
5419
- onSubmit(campaignData.data);
5420
7318
  };
5421
7319
  return /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { children: [
5422
7320
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
5423
7321
  /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-xl font-semibold", children: "Flash sale campaign" }),
5424
7322
  /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { variant: "transparent", onClick: onCancel, children: "Cancel" })
5425
7323
  ] }),
5426
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 my-8", children: [
5427
- /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Name" }),
5428
- /* @__PURE__ */ jsxRuntime.jsx(
5429
- ui.Input,
5430
- {
5431
- name: "name",
5432
- value: campaign.name,
5433
- onChange: (e) => handleCampaignChange("name", e.target.value),
5434
- disabled
5435
- }
5436
- ),
5437
- /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Description" }),
5438
- /* @__PURE__ */ jsxRuntime.jsx(
5439
- ui.Textarea,
5440
- {
5441
- name: "description",
5442
- value: campaign.description,
5443
- onChange: (e) => handleCampaignChange("description", e.target.value),
5444
- disabled
5445
- }
5446
- ),
5447
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
5448
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
5449
- /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Start Date" }),
5450
- /* @__PURE__ */ jsxRuntime.jsx(
5451
- ui.Input,
5452
- {
5453
- type: "datetime-local",
5454
- name: "start_date",
5455
- value: dayjs__default.default(campaign.starts_at).format("YYYY-MM-DDTHH:mm"),
5456
- onChange: (e) => handleCampaignChange("starts_at", e.target.value),
5457
- disabled
5458
- }
5459
- )
5460
- ] }),
5461
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
5462
- /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "End Date" }),
5463
- /* @__PURE__ */ jsxRuntime.jsx(
5464
- ui.Input,
5465
- {
5466
- type: "datetime-local",
5467
- name: "end_date",
5468
- value: dayjs__default.default(campaign.ends_at).format("YYYY-MM-DDTHH:mm"),
5469
- onChange: (e) => handleCampaignChange("ends_at", e.target.value),
5470
- disabled
5471
- }
5472
- )
5473
- ] })
5474
- ] }),
5475
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-between items-center", children: [
5476
- /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Products" }),
5477
- /* @__PURE__ */ jsxRuntime.jsx(
5478
- ui.Button,
5479
- {
5480
- variant: "secondary",
5481
- onClick: () => setOpenProductModal(true),
5482
- disabled,
5483
- children: "Add Product"
5484
- }
5485
- )
5486
- ] }),
5487
- /* @__PURE__ */ jsxRuntime.jsxs(ui.Table, { children: [
5488
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Header, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Table.Row, { children: [
5489
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Product" }),
5490
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Discount Type" }),
5491
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Discount Value" }),
5492
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Limit" }),
5493
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Max Qty per Order" }),
5494
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Actions" })
5495
- ] }) }),
5496
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Body, { children: Array.from(products.values()).map((product) => /* @__PURE__ */ jsxRuntime.jsxs(ui.Table.Row, { children: [
5497
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: product.product.title }),
5498
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsxs(
5499
- ui.Select,
5500
- {
5501
- value: product.discountType,
5502
- onValueChange: (value) => handleProductChange({
5503
- ...product,
5504
- discountType: value
5505
- }),
5506
- disabled,
5507
- children: [
5508
- /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Trigger, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Value, { placeholder: "Select discount type" }) }),
5509
- /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Content, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Item, { value: "percentage", children: "Percentage" }) })
5510
- ]
5511
- }
5512
- ) }),
5513
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
5514
- ui.Input,
5515
- {
5516
- type: "number",
5517
- value: product.discountValue,
5518
- onChange: (e) => handleProductChange({
5519
- ...product,
5520
- discountValue: Number(e.target.value)
5521
- }),
5522
- disabled
5523
- }
5524
- ) }),
5525
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
5526
- ui.Input,
5527
- {
5528
- type: "number",
5529
- value: product.limit,
5530
- onChange: (e) => handleProductChange({
5531
- ...product,
5532
- limit: Number(e.target.value)
5533
- }),
5534
- disabled
5535
- }
5536
- ) }),
5537
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
5538
- ui.Input,
5539
- {
5540
- type: "number",
5541
- value: product.maxQty,
5542
- onChange: (e) => handleProductChange({
5543
- ...product,
5544
- maxQty: Number(e.target.value)
5545
- }),
5546
- disabled
5547
- }
5548
- ) }),
5549
- /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
5550
- ui.Button,
5551
- {
5552
- variant: "danger",
5553
- onClick: () => {
5554
- setProducts((prev) => {
5555
- const newProducts = new Map(prev);
5556
- newProducts.delete(product.product.id);
5557
- return newProducts;
5558
- });
5559
- },
5560
- disabled,
5561
- children: /* @__PURE__ */ jsxRuntime.jsx(icons.Trash, {})
5562
- }
5563
- ) })
5564
- ] }, product.product.id)) })
5565
- ] }),
5566
- /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { onClick: handleSave, disabled, children: "Save" })
5567
- ] }),
7324
+ /* @__PURE__ */ jsxRuntime.jsxs(
7325
+ "form",
7326
+ {
7327
+ onSubmit: handleSubmit(onFormSubmit, onFormError),
7328
+ className: "space-y-4 my-8",
7329
+ children: [
7330
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
7331
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Name" }),
7332
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Input, { ...register("name"), disabled }),
7333
+ errors.name && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-red-500 text-sm mt-1", children: errors.name.message })
7334
+ ] }),
7335
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
7336
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Description" }),
7337
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Textarea, { ...register("description"), disabled }),
7338
+ errors.description && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-red-500 text-sm mt-1", children: errors.description.message })
7339
+ ] }),
7340
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
7341
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
7342
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Start Date" }),
7343
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
7344
+ /* @__PURE__ */ jsxRuntime.jsx(
7345
+ ui.Input,
7346
+ {
7347
+ type: "date",
7348
+ name: "start_date",
7349
+ value: campaign.starts_at ? dayjs__default.default(campaign.starts_at).format("YYYY-MM-DD") : "",
7350
+ onChange: (e2) => {
7351
+ const time = campaign.starts_at ? dayjs__default.default(campaign.starts_at).format("HH:mm") : "00:00";
7352
+ handleCampaignChange(
7353
+ "starts_at",
7354
+ `${e2.target.value}T${time}`
7355
+ );
7356
+ },
7357
+ disabled,
7358
+ className: "flex-1"
7359
+ }
7360
+ ),
7361
+ /* @__PURE__ */ jsxRuntime.jsx(
7362
+ ui.Input,
7363
+ {
7364
+ type: "time",
7365
+ name: "start_time",
7366
+ value: campaign.starts_at ? dayjs__default.default(campaign.starts_at).format("HH:mm") : "",
7367
+ onChange: (e2) => {
7368
+ const date = campaign.starts_at ? dayjs__default.default(campaign.starts_at).format("YYYY-MM-DD") : dayjs__default.default().format("YYYY-MM-DD");
7369
+ handleCampaignChange(
7370
+ "starts_at",
7371
+ `${date}T${e2.target.value}`
7372
+ );
7373
+ },
7374
+ disabled,
7375
+ className: "w-32"
7376
+ }
7377
+ )
7378
+ ] }),
7379
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
7380
+ /* @__PURE__ */ jsxRuntime.jsx(
7381
+ ui.Input,
7382
+ {
7383
+ type: "date",
7384
+ value: startsAt ? dayjs__default.default(startsAt).format("YYYY-MM-DD") : "",
7385
+ onChange: (e2) => handleDateTimeChange("starts_at", "date", e2.target.value),
7386
+ disabled,
7387
+ className: "flex-1"
7388
+ }
7389
+ ),
7390
+ /* @__PURE__ */ jsxRuntime.jsx(
7391
+ ui.Input,
7392
+ {
7393
+ type: "time",
7394
+ value: startsAt ? dayjs__default.default(startsAt).format("HH:mm") : "",
7395
+ onChange: (e2) => handleDateTimeChange("starts_at", "time", e2.target.value),
7396
+ disabled,
7397
+ className: "w-32"
7398
+ }
7399
+ )
7400
+ ] }),
7401
+ errors.starts_at && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-red-500 text-sm mt-1", children: errors.starts_at.message })
7402
+ ] }),
7403
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
7404
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "End Date" }),
7405
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
7406
+ /* @__PURE__ */ jsxRuntime.jsx(
7407
+ ui.Input,
7408
+ {
7409
+ type: "date",
7410
+ name: "end_date",
7411
+ value: campaign.ends_at ? dayjs__default.default(campaign.ends_at).format("YYYY-MM-DD") : "",
7412
+ onChange: (e2) => {
7413
+ const time = campaign.ends_at ? dayjs__default.default(campaign.ends_at).format("HH:mm") : "23:59";
7414
+ handleCampaignChange("ends_at", `${e2.target.value}T${time}`);
7415
+ },
7416
+ disabled,
7417
+ className: "flex-1"
7418
+ }
7419
+ ),
7420
+ /* @__PURE__ */ jsxRuntime.jsx(
7421
+ ui.Input,
7422
+ {
7423
+ type: "time",
7424
+ name: "end_time",
7425
+ value: campaign.ends_at ? dayjs__default.default(campaign.ends_at).format("HH:mm") : "",
7426
+ onChange: (e2) => {
7427
+ const date = campaign.ends_at ? dayjs__default.default(campaign.ends_at).format("YYYY-MM-DD") : dayjs__default.default().format("YYYY-MM-DD");
7428
+ handleCampaignChange("ends_at", `${date}T${e2.target.value}`);
7429
+ },
7430
+ disabled,
7431
+ className: "w-32"
7432
+ }
7433
+ )
7434
+ ] }),
7435
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
7436
+ /* @__PURE__ */ jsxRuntime.jsx(
7437
+ ui.Input,
7438
+ {
7439
+ type: "date",
7440
+ value: endsAt ? dayjs__default.default(endsAt).format("YYYY-MM-DD") : "",
7441
+ onChange: (e2) => handleDateTimeChange("ends_at", "date", e2.target.value),
7442
+ disabled,
7443
+ className: "flex-1"
7444
+ }
7445
+ ),
7446
+ /* @__PURE__ */ jsxRuntime.jsx(
7447
+ ui.Input,
7448
+ {
7449
+ type: "time",
7450
+ value: endsAt ? dayjs__default.default(endsAt).format("HH:mm") : "",
7451
+ onChange: (e2) => handleDateTimeChange("ends_at", "time", e2.target.value),
7452
+ disabled,
7453
+ className: "w-32"
7454
+ }
7455
+ )
7456
+ ] }),
7457
+ errors.ends_at && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-red-500 text-sm mt-1", children: errors.ends_at.message })
7458
+ ] })
7459
+ ] }),
7460
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-between items-center", children: [
7461
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Products" }),
7462
+ /* @__PURE__ */ jsxRuntime.jsx(
7463
+ ui.Button,
7464
+ {
7465
+ type: "button",
7466
+ variant: "secondary",
7467
+ onClick: () => setOpenProductModal(true),
7468
+ disabled,
7469
+ children: "Add Product"
7470
+ }
7471
+ )
7472
+ ] }),
7473
+ ((_a = errors.products) == null ? void 0 : _a.root) && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-red-500 text-sm", children: errors.products.root.message }),
7474
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.Table, { children: [
7475
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Header, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Table.Row, { children: [
7476
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Product" }),
7477
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Discount Type" }),
7478
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Discount Value" }),
7479
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Limit" }),
7480
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Max Qty per Order" }),
7481
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.HeaderCell, { children: "Actions" })
7482
+ ] }) }),
7483
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Body, { children: fields.map((field, index) => /* @__PURE__ */ jsxRuntime.jsxs(ui.Table.Row, { children: [
7484
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: field.product.title }),
7485
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
7486
+ Controller,
7487
+ {
7488
+ name: `products.${index}.discountType`,
7489
+ control,
7490
+ render: ({ field: field2 }) => /* @__PURE__ */ jsxRuntime.jsxs(
7491
+ ui.Select,
7492
+ {
7493
+ value: field2.value,
7494
+ onValueChange: field2.onChange,
7495
+ disabled,
7496
+ children: [
7497
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Trigger, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Value, { placeholder: "Select discount type" }) }),
7498
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Content, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Select.Item, { value: "percentage", children: "Percentage" }) })
7499
+ ]
7500
+ }
7501
+ )
7502
+ }
7503
+ ) }),
7504
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
7505
+ Controller,
7506
+ {
7507
+ name: `products.${index}.discountValue`,
7508
+ control,
7509
+ render: ({ field: field2 }) => /* @__PURE__ */ jsxRuntime.jsx(
7510
+ ui.Input,
7511
+ {
7512
+ type: "number",
7513
+ value: field2.value,
7514
+ onChange: (e2) => field2.onChange(Number(e2.target.value)),
7515
+ disabled
7516
+ }
7517
+ )
7518
+ }
7519
+ ) }),
7520
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
7521
+ Controller,
7522
+ {
7523
+ name: `products.${index}.limit`,
7524
+ control,
7525
+ render: ({ field: field2 }) => /* @__PURE__ */ jsxRuntime.jsx(
7526
+ ui.Input,
7527
+ {
7528
+ type: "number",
7529
+ value: field2.value,
7530
+ onChange: (e2) => field2.onChange(Number(e2.target.value)),
7531
+ disabled
7532
+ }
7533
+ )
7534
+ }
7535
+ ) }),
7536
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
7537
+ Controller,
7538
+ {
7539
+ name: `products.${index}.maxQty`,
7540
+ control,
7541
+ render: ({ field: field2 }) => /* @__PURE__ */ jsxRuntime.jsx(
7542
+ ui.Input,
7543
+ {
7544
+ type: "number",
7545
+ value: field2.value,
7546
+ onChange: (e2) => field2.onChange(Number(e2.target.value)),
7547
+ disabled
7548
+ }
7549
+ )
7550
+ }
7551
+ ) }),
7552
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
7553
+ ui.Button,
7554
+ {
7555
+ type: "button",
7556
+ variant: "danger",
7557
+ onClick: () => remove(index),
7558
+ disabled,
7559
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Trash, {})
7560
+ }
7561
+ ) })
7562
+ ] }, field.id)) })
7563
+ ] }),
7564
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { type: "submit", disabled, children: "Save" })
7565
+ ]
7566
+ }
7567
+ ),
5568
7568
  /* @__PURE__ */ jsxRuntime.jsx(ui.FocusModal, { open: openProductModal, onOpenChange: setOpenProductModal, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.FocusModal.Content, { children: [
5569
7569
  /* @__PURE__ */ jsxRuntime.jsx(ui.FocusModal.Header, { title: "Add Product" }),
5570
7570
  /* @__PURE__ */ jsxRuntime.jsx(ui.FocusModal.Body, { children: /* @__PURE__ */ jsxRuntime.jsx(
5571
7571
  ProductSelector,
5572
7572
  {
5573
- selectedProductIds: Array.from(products.keys()),
7573
+ selectedProductIds: fields.map((f2) => f2.product.id),
5574
7574
  onSelectProduct: (product) => {
5575
- setProducts((prev) => {
5576
- const newProducts = new Map(prev);
5577
- newProducts.set(product.id, {
5578
- product,
5579
- discountType: "percentage",
5580
- discountValue: 10,
5581
- limit: 10,
5582
- maxQty: 1
5583
- });
5584
- return newProducts;
7575
+ append({
7576
+ product,
7577
+ discountType: "percentage",
7578
+ discountValue: 10,
7579
+ limit: 10,
7580
+ maxQty: 1
5585
7581
  });
5586
7582
  setOpenProductModal(false);
5587
7583
  }
@@ -5606,7 +7602,7 @@ const FlashSaleDetail = () => {
5606
7602
  const navigate = reactRouterDom.useNavigate();
5607
7603
  const queryClient = reactQuery.useQueryClient();
5608
7604
  const { data, isLoading } = useFlashSaleById(id || "");
5609
- const [isEditing, setIsEditing] = react.useState(false);
7605
+ const [isEditing, setIsEditing] = React.useState(false);
5610
7606
  async function handleSubmit(campaignData2) {
5611
7607
  var _a;
5612
7608
  try {