@juantroconisf/lib 7.0.0 → 8.0.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.
package/dist/index.mjs CHANGED
@@ -1,10 +1,3 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
1
  // src/utils/types.ts
9
2
  var NextUIError = class {
10
3
  isInvalid;
@@ -26,7 +19,7 @@ function handleNestedChange({
26
19
  hasNestedValues = false
27
20
  }) {
28
21
  if (!hasNestedValues) return { ...state, [id]: value };
29
- const propertyDepth = String(id).split("."), newValues = state;
22
+ const propertyDepth = String(id).split("."), newValues = { ...state };
30
23
  let current = newValues;
31
24
  for (let i = 0; i < propertyDepth.length - 1; i++) {
32
25
  const key = propertyDepth[i];
@@ -62,141 +55,131 @@ function handleArrayItemChange({
62
55
  function getNestedValue(obj, path) {
63
56
  return path.split(".").reduce((acc, key) => acc?.[key], obj);
64
57
  }
65
- function removeCompositeKeysByPrefix(map2, prefix) {
66
- const result = new Map(map2);
67
- for (const key of map2.keys()) {
58
+ function removeCompositeKeysByPrefix(map, prefix) {
59
+ const result = new Map(map);
60
+ for (const key of map.keys()) {
68
61
  if (key.startsWith(prefix)) {
69
62
  result.delete(key);
70
63
  }
71
64
  }
72
65
  return result;
73
66
  }
74
- function setNestedValue(state, dotPath, value) {
75
- const keys = dotPath.split(".");
76
- const copy = { ...state };
77
- let current = copy;
78
- for (let i = 0; i < keys.length - 1; i++) {
79
- current[keys[i]] = { ...current[keys[i]] };
80
- current = current[keys[i]];
81
- }
82
- current[keys[keys.length - 1]] = value;
83
- return copy;
84
- }
85
- var regex = {
86
- email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
87
- password: /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~`!@#$%^&*()--+={}[\]|:;"'<>,.?/_₹]).{8,24}$/
88
- };
89
- var map = {
90
- string: (val) => Boolean(val),
91
- number: (val) => String(val) !== "",
92
- object: (val) => val !== null && Object.keys(val).length > 0
93
- };
94
- var requiredValidation = (value) => Array.isArray(value) ? value.length > 0 : map[typeof value](value);
95
- var errors = {
96
- required: {
97
- validate: (val, isRequired) => !isRequired || requiredValidation(val),
98
- msg: "REQUIRED"
99
- },
100
- min: {
101
- validate: (val, min) => val >= min,
102
- msg: "VALUE_LOW"
103
- },
104
- max: {
105
- validate: (val, max) => val <= max,
106
- msg: "VALUE_HIGH"
107
- },
108
- minLength: {
109
- validate: (val = "", min) => val.length >= min,
110
- msg: "TOO_SHORT"
111
- },
112
- maxLength: {
113
- validate: (val = "", max) => val.length <= max,
114
- msg: "TOO_LONG"
115
- },
116
- pattern: {
117
- validate: (val, pattern) => new RegExp(pattern).test(val),
118
- msg: "PATTERN_INVALID"
119
- },
120
- equal: {
121
- validate: (val, comparison) => val === comparison,
122
- msg: "NOT_EQUAL"
123
- },
124
- numberIsEqual: {
125
- validate: (val, comparison) => val === comparison,
126
- msg: "NOT_EQUAL"
127
- },
128
- email: {
129
- validate: (val) => new RegExp(regex.email).test(val),
130
- msg: "INVALID_EMAIL"
131
- },
132
- password: {
133
- validate: (val) => new RegExp(regex.password).test(val),
134
- msg: "INVALID_PASSWORD"
67
+
68
+ // src/hooks/useComponentLang.tsx
69
+ import { setLocale } from "yup";
70
+ import { useEffect } from "react";
71
+
72
+ // src/assets/translations.ts
73
+ var translations = {
74
+ en: {
75
+ mixed: {
76
+ default: "Invalid value",
77
+ required: "This field is required",
78
+ oneOf: "Must be one of: ${values}",
79
+ notOneOf: "Cannot be any of: ${values}",
80
+ notType: "Incorrect data format",
81
+ defined: "Must be defined"
82
+ },
83
+ string: {
84
+ length: "Must be exactly ${length} characters",
85
+ min: "Must be at least ${min} characters",
86
+ max: "Must be at most ${max} characters",
87
+ matches: 'Must match: "${regex}"',
88
+ email: "Enter a valid email address",
89
+ url: "Enter a valid URL",
90
+ uuid: "Enter a valid UUID",
91
+ trim: "Remove leading/trailing spaces",
92
+ lowercase: "Must be in lowercase",
93
+ uppercase: "Must be in uppercase",
94
+ password: "Your password doesn't meet the security criteria."
95
+ },
96
+ number: {
97
+ min: "Value must be ${min} or greater",
98
+ max: "Value must be ${max} or less",
99
+ lessThan: "Must be less than ${less}",
100
+ moreThan: "Must be greater than ${more}",
101
+ positive: "Must be a positive number",
102
+ negative: "Must be a negative number",
103
+ integer: "Must be a whole number"
104
+ },
105
+ date: {
106
+ min: "Date must be after ${min}",
107
+ max: "Date must be before ${max}"
108
+ },
109
+ boolean: {
110
+ isValue: "Must be ${value}"
111
+ },
112
+ object: {
113
+ noUnknown: "Contains unknown properties"
114
+ },
115
+ array: {
116
+ min: "Must have at least ${min} items",
117
+ max: "Must have ${max} items or fewer",
118
+ length: "Must have exactly ${length} items"
119
+ }
135
120
  },
136
- custom: {
137
- validate: (_, bool) => bool,
138
- msg: "INVALID"
121
+ es: {
122
+ mixed: {
123
+ default: "Valor no v\xE1lido",
124
+ required: "Este campo es obligatorio",
125
+ oneOf: "Debe ser uno de: ${values}",
126
+ notOneOf: "No puede ser ninguno de: ${values}",
127
+ defined: "Debe estar definido",
128
+ notType: "Formato de dato incorrecto"
129
+ },
130
+ string: {
131
+ length: "Debe tener exactamente ${length} caracteres",
132
+ min: "Debe tener al menos ${min} caracteres",
133
+ max: "Debe tener como m\xE1ximo ${max} caracteres",
134
+ matches: 'Debe coincidir con: "${regex}"',
135
+ email: "Ingresa un correo electr\xF3nico v\xE1lido",
136
+ url: "Ingresa una URL v\xE1lida",
137
+ uuid: "Ingresa un UUID v\xE1lido",
138
+ trim: "No debe contener espacios al inicio o final",
139
+ lowercase: "Debe estar en min\xFAsculas",
140
+ uppercase: "Debe estar en may\xFAsculas",
141
+ password: "Tu contrase\xF1a no cumple con los requisitos de seguridad."
142
+ },
143
+ number: {
144
+ min: "Debe ser mayor o igual a ${min}",
145
+ max: "Debe ser menor o igual a ${max}",
146
+ lessThan: "Debe ser menor a ${less}",
147
+ moreThan: "Debe ser mayor a ${more}",
148
+ positive: "Debe ser un n\xFAmero positivo",
149
+ negative: "Debe ser un n\xFAmero negativo",
150
+ integer: "Debe ser un n\xFAmero entero"
151
+ },
152
+ date: {
153
+ min: "La fecha debe ser posterior a ${min}",
154
+ max: "La fecha debe ser anterior a ${max}"
155
+ },
156
+ boolean: {
157
+ isValue: "Debe ser ${value}"
158
+ },
159
+ object: {
160
+ noUnknown: "Contiene propiedades no permitidas"
161
+ },
162
+ array: {
163
+ min: "Debe tener al menos ${min} elementos",
164
+ max: "Debe tener como m\xE1ximo ${max} elementos",
165
+ length: "Debe tener ${length} elementos"
166
+ }
139
167
  }
140
168
  };
141
169
 
142
- // lang/en.json
143
- var en_default = { BIRTH_DATE: "Birth date", DAY: "Day", DAY_PLACEHOLDER: "Choose a day", MONTH: "Month", MONTH_PLACEHOLDER: "Choose a month", YEAR: "Year", YEAR_PLACEHOLDER: "Choose a year", PRICING: "Pricing", PRICING_TABLE: "Pricing table", OUR_PRICING_PLAN: "Our pricing plan", PRICING_DESCRIPTION: "Level up your experience. Discover the plan that unlocks the features you need.", VALUE_STORAGE: "{{value}} storage", GOOGLE_CALENDAR_SYNC: "Google Calendar Sync", INTERNAL_REMINDERS: "Internal reminders", WHATSAPP_AUTOMATED_REMINDERS: "WhatsApp Automated Reminders", PROFESSIONAL: "Professional", PROFESSIONAL_PLAN_DESCRIPTION: "For single doctors looking to level up their practice", DIGITAL_PRESCRIPTIONS: "Digital prescriptions", DICOM_VIEWER: "DICOM Viewer", VERIFIED_MEDICAL_CREDENTIALS: "Verified medical credentials", PATIENT_SELF_MANAGEMENT: "Patient self management", BUY_NOW: "Buy now", ORGANIZATION: "Organization", ORGANIZATION_PLAN_DESCRIPTION: "For organizations with multiple users looking to share information", UP_TO_VALUE_STORAGE: "Up to {{value}} storage", CONFIGURABLE_USER_PERMISSIONS: "Configurable user permissions", CALCULATE_PRICING: "Calculate pricing", DOCTORS: "Doctors", ASSISTANTS: "Assistants", BASIC: "Basic", BASIC_PLAN_DESCRIPTION: "For starters in the medical industry", USER: "User", TYPE_A_VALUE: "Type a value", STORAGE: "Storage", PASSWORD: "Password", PASSWORD_PLACEHOLDER: "Enter your password", REQUIRED: "Required", TOO_SHORT: "Too short", TOO_LONG: "Too long", VALUE_LOW: "Value is too low", VALUE_HIGH: "Value is too high", PATTERN_INVALID: "Pattern is not valid", INVALID_EMAIL: "Invalid email", SHOW_PASSWORD: "Show password", HIDE_PASSWORD: "Hide password", GROUP_PRICING_CALCULATOR: "Group Pricing Calculator", VERIFIED_ACCOUNT: "Verified account", VERIFIED_ACCOUNT_TEXT: "This account has been verified by Clinikos, as well as its affiliations with the following institutions", PHONE_NUMBER: "Phone number", PHONE_NUMBER_PLACEHOLDER: "Enter your phone number", SEND_MESSAGE: "Send message", BOOK_MEETING: "Book meeting", SIGN_UP: "Sign up", INVALID_PASSWORD: "Your password doesn't meet the security criteria.", NOT_EQUAL: "Values are not equal", GENDER: "Gender", FEMALE: "Female", MALE: "Male", CLOSE: "Close", MANDATORY_FIELDS_WARNING: "", INVALID_FIELDS_WARNING: "", COUNTRY: "Country", COUNTRY_PLACEHOLDER: "Select a country", STATE: "State", STATE_PLACEHOLDER: "Select a state", CITY: "City", CITY_PLACEHOLDER: "Select a city", TIMEZONE: "Timezone", TIMEZONE_PLACEHOLDER: "Selecte a timezone", NAME: "Name", OK: "Ok", PAGE_NOT_FOUND: "Page not found", PAGE_NOT_FOUND_DESCRIPTION: "The link you clicked may be broken or the page may have been removed or renamed", TODAY: "Today", WEEK: "Week", CALENDAR: "Calendar", EVENT: "Event", NO_INFORMATION: "No information", SYNC_GOOGLE_CALENDAR: "Sync Google Calendar", NO_RESULTS: "No results were found", GOOGLE_MEET: "Google Meet", LONG_TIME_AGO: "Long time ago", TOMORROW: "Tomorrow", CHOOSE_PLAN: "Choose a plan", CHOOSE_PLAN_DESCRIPTION: "Choose a plan that fits your needs!", PRIVACY_POLICY: "", OPTIONAL: "Optional", RESULTS: "Results", LOCATION: "Location", ADDRESS: "Address", ADDRESS_PLACEHOLDER: "Enter your address", COPY_TO_CLIPBOARD: "Copy to clipboard", ACTIONS: "Actions", MIN: "Minimum", MAX: "Maximum", DUE_DATE: "Due date", QUICK_SEARCH: "Quick search", MONTHLY: "Monthly", WEEKLY: "Weekly", GOOGLE_MAPS_LINK: "Google maps link", MINUTE: "Minute", MINUTES: "Minutes", HOUR: "Hour", HOURS: "Hours", VE_ID: "Identity card", ACCOUNT_VERIFIED_BY_CLINIKOS: "This account has been verified by Clinikos, as well as its affiliations with the following institutions", INBOX: "Inbox", ACCEPTED: "Accepted", DECLINED: "Declined", NEEDS_ACTION: "Needs action", OVERDUE: "Overdue", FILTER_BY: "Filter by", REFRESH: "Refresh", LOADING: "Loading", MINUTE_LEFT: "One minute left", VALUE_MINUTES_LEFT: "{{value}} minutes left", PLAY: "Play", PAUSE: "Pause", STOP: "Stop", LOAD_MORE: "Load more", BILLING: "Billing", DOCTOR: "Doctor", ASSISTANT: "Assistant", NUMBER_OF_DOCTORS: "Number of Doctors", NUMBER_OF_ASSISTANTS: "Number of Assistants", EACH_DOCTOR: "Each doctor", EACH_ASSISTANT: "Each assistant", ROLE: "Role", PAYMENT_METHODS: "Payment methods", UPGRADE: "Upgrade", TOTAL: "Total", BUY: "Buy", TYPE: "Type", RECURRENT: "Recurrent", ACCEPT: "Accept", DECLINE: "Decline", PREFERENCES: "Preferences", BOOKING: "Booking", PATTERN_NOT_VALID: "Pattern is not valid" };
144
-
145
- // lang/es.json
146
- var es_default = { BIRTH_DATE: "Fecha de nacimiento", DAY: "D\xEDa", DAY_PLACEHOLDER: "Elige un d\xEDa", MONTH: "Mes", MONTH_PLACEHOLDER: "Elige un mes", YEAR: "A\xF1o", YEAR_PLACEHOLDER: "Elige un a\xF1o", PRICING: "Precio", PRICING_TABLE: "Tabla de precios", OUR_PRICING_PLAN: "Nuestros precios", PRICING_DESCRIPTION: "Mejora tu experiencia. Descubre el plan que desbloquea las funciones que necesitas.", VALUE_STORAGE: "{{value}} almacenamiento", GOOGLE_CALENDAR_SYNC: "Google Calenar Sync", INTERNAL_REMINDERS: "Recordatorios internos", WHATSAPP_AUTOMATED_REMINDERS: "Recordatorios automatizados de WhatsApp", PROFESSIONAL: "Profesional", PROFESSIONAL_PLAN_DESCRIPTION: "Para doctores individuales que buscan elevar sus pr\xE1cticas", DIGITAL_PRESCRIPTIONS: "Recipes digitales", DICOM_VIEWER: "Visualizador DICOM", VERIFIED_MEDICAL_CREDENTIALS: "Credenciales m\xE9dicas verificadas", PATIENT_SELF_MANAGEMENT: "Auto gesti\xF3n para pacientes", BUY_NOW: "Comprar ahora", ORGANIZATION: "Organizaci\xF3n", ORGANIZATION_PLAN_DESCRIPTION: "Para organizaciones con m\xFAltiples usuarios que buscan compartir informaci\xF3n", UP_TO_VALUE_STORAGE: "Hasta {{value}} de almacenamiento", CONFIGURABLE_USER_PERMISSIONS: "Permisolog\xEDa configurable para usuarios", CALCULATE_PRICING: "Calcular precio", DOCTORS: "Doctores", ASSISTANTS: "Asistentes", BASIC: "B\xE1sico", BASIC_PLAN_DESCRIPTION: "Para iniciar en la industria m\xE9dica", USER: "Usuario", TYPE_A_VALUE: "Ingresa un valor", STORAGE: "Almacenamiento", PASSWORD: "Contrase\xF1a", PASSWORD_PLACEHOLDER: "Ingresa tu contrase\xF1a", REQUIRED: "Requerido", TOO_SHORT: "Demasiado corto", TOO_LONG: "Demasiado largo", VALUE_LOW: "El valor es muy bajo", VALUE_HIGH: "El valor es muy alto", PATTERN_INVALID: "El patr\xF3n no es v\xE1lido", INVALID_EMAIL: "Correo inv\xE1lido", SHOW_PASSWORD: "Mostrar contrase\xF1a", HIDE_PASSWORD: "Esconder contrase\xF1a", GROUP_PRICING_CALCULATOR: "Calculadora de precios grupal", VERIFIED_ACCOUNT: "Cuenta verificada", VERIFIED_ACCOUNT_TEXT: "Esta cuenta ha sido verificada por Clinikos, as\xED como sus afiliaciones con las siguientes instituciones", PHONE_NUMBER: "N\xFAmero de tel\xE9fono", PHONE_NUMBER_PLACEHOLDER: "Ingrese su n\xFAmero de tel\xE9fono", SEND_MESSAGE: "Enviar mensaje", BOOK_MEETING: "Agendar cita", SIGN_UP: "Reg\xEDstrate", INVALID_PASSWORD: "Tu contrase\xF1a no cumple con los requisitos de seguridad.", NOT_EQUAL: "Los valores no son iguales", GENDER: "G\xE9nero", FEMALE: "Femenino", MALE: "Masculino", CLOSE: "Cerrar", MANDATORY_FIELDS_WARNING: "", INVALID_FIELDS_WARNING: "", COUNTRY: "Pa\xEDs", COUNTRY_PLACEHOLDER: "Selecciona un pa\xEDs", STATE: "Estado", STATE_PLACEHOLDER: "Selecciona un estado", CITY: "Ciudad", CITY_PLACEHOLDER: "Selecciona una ciudad", TIMEZONE: "Zona horaria", TIMEZONE_PLACEHOLDER: "Selecciona una zora horaria", NAME: "Nombre", OK: "Ok", PAGE_NOT_FOUND: "P\xE1gina no encontrada", PAGE_NOT_FOUND_DESCRIPTION: "El enlace en el que hiciste click puede que est\xE9 roto o la p\xE1gina puede haber sido eliminada o renombrada", TODAY: "Hoy", WEEK: "Semana", CALENDAR: "Calendario", EVENT: "Evento", NO_INFORMATION: "Sin informaci\xF3n", SYNC_GOOGLE_CALENDAR: "Vincular Calendario de Google", NO_RESULTS: "No se encontraron resultados", GOOGLE_MEET: "Google Meet", LONG_TIME_AGO: "Hace mucho tiempo", TOMORROW: "Ma\xF1ana", CHOOSE_PLAN: "Elige un plan", CHOOSE_PLAN_DESCRIPTION: "\xA1Elige el plan que se ajuste a tus necesidades!", PRIVACY_POLICY: "", OPTIONAL: "Opcional", RESULTS: "Resultados", LOCATION: "Ubicaci\xF3n", ADDRESS: "Direcci\xF3n", ADDRESS_PLACEHOLDER: "Ingresa tu direcci\xF3n", COPY_TO_CLIPBOARD: "Copiar al portapapeles", ACTIONS: "Acciones", MIN: "M\xEDnimo", MAX: "M\xE1ximo", DUE_DATE: "Fecha l\xEDmite", QUICK_SEARCH: "B\xFAsqueda r\xE1pida", MONTHLY: "Mensual", WEEKLY: "Semanal", GOOGLE_MAPS_LINK: "Link de Google Maps", MINUTE: "Minuto", MINUTES: "Minutos", HOUR: "Hora", HOURS: "Horas", VE_ID: "C\xE9dula de Identidad", ACCOUNT_VERIFIED_BY_CLINIKOS: "Esta cuenta ha sido verificada por Clinikos, as\xED como sus afiliaciones con las siguientes instituciones", INBOX: "Bandeja de entrada", ACCEPTED: "Aceptado", DECLINED: "Declinado", NEEDS_ACTION: "Necesita acci\xF3n", OVERDUE: "Atrasado", FILTER_BY: "Filtrar por", REFRESH: "Refrescar", LOADING: "Cargando", MINUTE_LEFT: "Un minuto restante", VALUE_MINUTES_LEFT: "{{value}} minutos restantes", PLAY: "Reproducir", PAUSE: "Pausar", STOP: "Detener", LOAD_MORE: "Cargar m\xE1s", BILLING: "Facturaci\xF3n", DOCTOR: "Doctor", ASSISTANT: "Asistente", NUMBER_OF_DOCTORS: "N\xFAmero de Doctores", NUMBER_OF_ASSISTANTS: "N\xFAmero de Asistentes", EACH_DOCTOR: "Cada doctor", EACH_ASSISTANT: "Cada asistente", ROLE: "Rol", PAYMENT_METHODS: "M\xE9todos de pago", UPGRADE: "Mejorar", TOTAL: "Total", BUY: "Comprar", TYPE: "Tipo", RECURRENT: "Recurrente", ACCEPT: "Aceptar", DECLINE: "Declinar", PREFERENCES: "Preferencias", BOOKING: "Agendar cita", PATTERN_NOT_VALID: "El patr\xF3n no es v\xE1lido" };
147
-
148
170
  // src/hooks/useComponentLang.tsx
149
171
  var cookieName = "LOCALE";
150
- var langMap = {
151
- en: en_default,
152
- es: es_default
153
- };
154
172
  var getClientCookie = () => {
155
173
  const value = "; " + document.cookie, decodedValue = decodeURIComponent(value), parts = decodedValue.split("; " + cookieName + "=");
156
174
  if (parts.length === 2) return parts.pop()?.split(";").shift();
157
175
  };
158
- var getServerCookie = () => {
159
- try {
160
- const { cookies } = __require("next/headers");
161
- return cookies().get(cookieName)?.value;
162
- } catch {
163
- return "es";
164
- }
165
- };
166
176
  function useComponentLanguage() {
167
- const isServer = typeof window === "undefined", locale = (isServer ? getServerCookie() : getClientCookie()) || "en";
168
- return {
169
- locale,
170
- lang: langMap[locale]
171
- };
172
- }
173
-
174
- // src/hooks/useValidate.tsx
175
- var validProps = {
176
- isInvalid: false,
177
- errorMessage: ""
178
- };
179
- function useValidate() {
180
- const { lang } = useComponentLanguage();
181
- const performValidations = (value, validationTypes, errorMessages) => {
182
- if (!validationTypes) return validProps;
183
- const items = Object.entries(validationTypes), requiredExist = validationTypes?.required !== void 0, isRequired = requiredExist ? validationTypes.required : false;
184
- if (value === "" && !isRequired) return validProps;
185
- let errorFound = validProps;
186
- for (const [key, opts] of items) {
187
- if (opts === null) continue;
188
- const { validate, msg } = errors[key], isInvalid = !validate(value, opts);
189
- if (isInvalid) {
190
- errorFound = {
191
- isInvalid,
192
- errorMessage: errorMessages?.[key] || lang[msg]
193
- };
194
- break;
195
- }
177
+ useEffect(() => {
178
+ const locale = getClientCookie() || "en";
179
+ if (translations[locale]) {
180
+ setLocale(translations[locale]);
196
181
  }
197
- return errorFound;
198
- };
199
- return { performValidations };
182
+ }, []);
200
183
  }
201
184
 
202
185
  // src/hooks/useForm.utils.ts
@@ -294,19 +277,36 @@ function resolveFieldData(args, state, getIndex, getNestedValue2) {
294
277
  }
295
278
 
296
279
  // src/hooks/useForm.tsx
297
- function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
298
- const [state, setState] = useState(initialState);
299
- const [touched, setTouched] = useState(/* @__PURE__ */ new Map());
300
- const [errors2, setErrors] = useState(/* @__PURE__ */ new Map());
301
- const { performValidations } = useValidate();
302
- const stateRef = useRef(state);
303
- const touchedRef = useRef(touched);
304
- const errorsRef = useRef(errors2);
280
+ import { isSchema, object, reach } from "yup";
281
+ var DEFAULT_OPTIONS = {};
282
+ function useForm(schema, { arrayIdentifiers } = DEFAULT_OPTIONS) {
283
+ const { initialState, validationSchema } = useMemo(() => {
284
+ const state2 = {};
285
+ const extractedRules = {};
286
+ Object.entries(schema).forEach(([key, value]) => {
287
+ if (isSchema(value)) {
288
+ try {
289
+ state2[key] = value.getDefault();
290
+ } catch {
291
+ state2[key] = void 0;
292
+ }
293
+ extractedRules[key] = value;
294
+ } else {
295
+ state2[key] = value;
296
+ }
297
+ });
298
+ return {
299
+ initialState: state2,
300
+ validationSchema: object().shape(extractedRules)
301
+ };
302
+ }, [schema]);
303
+ const [state, setState] = useState(initialState), [metadata, setMetadata] = useState(/* @__PURE__ */ new Map());
304
+ useComponentLanguage();
305
+ const stateRef = useRef(state), metadataRef = useRef(metadata);
305
306
  stateRef.current = state;
306
- touchedRef.current = touched;
307
- errorsRef.current = errors2;
307
+ metadataRef.current = metadata;
308
308
  const indexMap = useMemo(() => {
309
- const map2 = /* @__PURE__ */ new Map();
309
+ const map = /* @__PURE__ */ new Map();
310
310
  const traverse = (current, path) => {
311
311
  if (!current || typeof current !== "object") return;
312
312
  if (Array.isArray(current)) {
@@ -322,7 +322,7 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
322
322
  traverse(item, `${path}.${index}`);
323
323
  }
324
324
  });
325
- map2.set(path, itemMap);
325
+ map.set(path, itemMap);
326
326
  } else {
327
327
  Object.keys(current).forEach((key) => {
328
328
  const nextPath = path ? `${path}.${key}` : key;
@@ -331,105 +331,139 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
331
331
  }
332
332
  };
333
333
  traverse(state, "");
334
- return map2;
334
+ return map;
335
335
  }, [state, arrayIdentifiers]);
336
336
  const indexMapRef = useRef(indexMap);
337
337
  indexMapRef.current = indexMap;
338
338
  const getIndex = useCallback((arrayKey, itemId) => {
339
339
  return indexMapRef.current.get(arrayKey)?.get(itemId);
340
340
  }, []);
341
- const getRule = useCallback(
342
- (path) => {
343
- if (rules?.[path]) return rules[path];
344
- const genericPath = path.replace(/\.\d+\./g, ".").replace(/\.\d+$/, "");
345
- return rules?.[genericPath];
346
- },
347
- [rules]
348
- );
349
- const getMessage = useCallback(
350
- (path) => {
351
- if (messages?.[path]) return messages[path];
341
+ const ruleCache = useRef(/* @__PURE__ */ new Map());
342
+ useMemo(() => {
343
+ ruleCache.current.clear();
344
+ }, [validationSchema]);
345
+ const getRule = useCallback((path, schema2) => {
346
+ if (ruleCache.current.has(path)) {
347
+ return ruleCache.current.get(path);
348
+ }
349
+ let rule;
350
+ try {
351
+ rule = reach(schema2, path);
352
+ } catch {
352
353
  const genericPath = path.replace(/\.\d+\./g, ".").replace(/\.\d+$/, "");
353
- return messages?.[genericPath];
354
+ try {
355
+ rule = reach(schema2, genericPath);
356
+ } catch {
357
+ rule = void 0;
358
+ }
359
+ }
360
+ ruleCache.current.set(path, rule);
361
+ return rule;
362
+ }, []);
363
+ const runValidation = useCallback(
364
+ (ruleDef, value, compositeKey) => {
365
+ if (isSchema(ruleDef)) {
366
+ try {
367
+ ruleDef.validateSync(value);
368
+ return false;
369
+ } catch (err) {
370
+ const error = {
371
+ isInvalid: true,
372
+ errorMessage: err.message || "Invalid"
373
+ };
374
+ setMetadata((prev) => {
375
+ const newMap = new Map(prev);
376
+ const currentMeta = newMap.get(compositeKey) || {
377
+ isTouched: false,
378
+ isInvalid: false,
379
+ errorMessage: ""
380
+ };
381
+ newMap.set(compositeKey, { ...currentMeta, ...error });
382
+ return newMap;
383
+ });
384
+ return true;
385
+ }
386
+ }
387
+ return false;
354
388
  },
355
- [messages]
389
+ []
356
390
  );
357
391
  const validateField = useCallback(
358
- (compositeKey, fieldPath, value, extraContext) => {
359
- let ruleDef = getRule(fieldPath);
360
- if (!ruleDef) {
361
- const stripped = fieldPath.replace(/\.@\d+/g, "").replace(/\.@\d+$/, "");
362
- if (stripped !== fieldPath) ruleDef = getRule(stripped);
392
+ (compositeKey, fieldPath, value) => {
393
+ let schemaRule = getRule(fieldPath, validationSchema);
394
+ if (schemaRule) {
395
+ if (runValidation(schemaRule, value, compositeKey)) return true;
363
396
  }
364
- const rule = typeof ruleDef === "function" ? ruleDef(
365
- value,
366
- stateRef.current,
367
- extraContext?.item,
368
- extraContext?.index
369
- ) : ruleDef;
370
- let message = getMessage(fieldPath);
371
- if (!message && fieldPath !== fieldPath.replace(/\.@\d+/, "")) {
372
- message = getMessage(fieldPath.replace(/\.@\d+/, ""));
373
- }
374
- const error = performValidations(value, rule, message);
375
- setErrors((prev) => {
397
+ setMetadata((prev) => {
376
398
  const newMap = new Map(prev);
377
- newMap.set(compositeKey, error);
399
+ const currentMeta = newMap.get(compositeKey) || {
400
+ isTouched: false,
401
+ isInvalid: false,
402
+ errorMessage: ""
403
+ };
404
+ newMap.set(compositeKey, {
405
+ ...currentMeta,
406
+ isInvalid: false,
407
+ errorMessage: ""
408
+ });
378
409
  return newMap;
379
410
  });
380
- return error.isInvalid;
411
+ return false;
381
412
  },
382
- [getRule, getMessage, performValidations]
413
+ [getRule, runValidation, validationSchema]
383
414
  );
384
415
  const validateAll = useCallback(() => {
385
- if (!rules) return false;
386
- const nextErrors = /* @__PURE__ */ new Map();
387
- let hasInvalid = false;
388
- const processRule = (ruleKey, ruleVal) => {
389
- const isGeneric = !ruleKey.match(/\.\d+\./) && !ruleKey.match(/\.@\d+/);
390
- const parts = ruleKey.split(".");
391
- let arrayKey = "";
392
- let arrayIndexInPath = -1;
393
- for (let i = 0; i < parts.length; i++) {
394
- if (indexMapRef.current.has(parts[i])) {
395
- arrayKey = parts[i];
396
- arrayIndexInPath = i;
397
- break;
398
- }
399
- }
400
- if (arrayKey && arrayIndexInPath !== -1) {
401
- const itemMap = indexMapRef.current.get(arrayKey);
402
- if (itemMap) {
403
- itemMap.forEach((idx, itemId) => {
404
- const suffix = parts.slice(arrayIndexInPath + 1).join(".");
405
- const compositeKey = `${arrayKey}.${itemId}` + (suffix ? `.${suffix}` : "");
406
- const item = stateRef.current[arrayKey][idx];
407
- const val = getNestedValue(item, suffix);
408
- const rule = typeof ruleVal === "function" ? ruleVal(val, stateRef.current, item, idx) : ruleVal;
409
- const msg = getMessage(ruleKey);
410
- const err = performValidations(val, rule, msg);
411
- nextErrors.set(compositeKey, err);
412
- if (err.isInvalid) hasInvalid = true;
416
+ if (!validationSchema) return false;
417
+ let hasError = false;
418
+ const newMetadata = new Map(metadataRef.current);
419
+ try {
420
+ validationSchema.validateSync(state, { abortEarly: false });
421
+ } catch (err) {
422
+ hasError = true;
423
+ if (err.inner) {
424
+ err.inner.forEach((validationError) => {
425
+ const yupPath = validationError.path;
426
+ const dotPath = yupPath.replace(/\[(\d+)\]/g, ".$1");
427
+ const parts = dotPath.split(".");
428
+ let current = state;
429
+ const compositeParts = [];
430
+ for (let i = 0; i < parts.length; i++) {
431
+ const part = parts[i];
432
+ if (Array.isArray(current)) {
433
+ const index = parseInt(part, 10);
434
+ const item = current[index];
435
+ if (item && typeof item === "object") {
436
+ const genericPath = compositeParts.join(".").replace(/\.\d+/g, "");
437
+ const idKey = arrayIdentifiers?.[genericPath] || "id";
438
+ const id = item[idKey];
439
+ compositeParts.push(String(id !== void 0 ? id : index));
440
+ } else {
441
+ compositeParts.push(part);
442
+ }
443
+ current = item;
444
+ } else {
445
+ compositeParts.push(part);
446
+ current = current?.[part];
447
+ }
448
+ }
449
+ const compositeKey = compositeParts.join(".");
450
+ const currentMeta = newMetadata.get(compositeKey) || {
451
+ isTouched: false,
452
+ isInvalid: false,
453
+ errorMessage: ""
454
+ };
455
+ newMetadata.set(compositeKey, {
456
+ ...currentMeta,
457
+ isTouched: true,
458
+ isInvalid: true,
459
+ errorMessage: validationError.message
413
460
  });
414
- }
415
- } else {
416
- const val = getNestedValue(stateRef.current, ruleKey);
417
- const rule = typeof ruleVal === "function" ? ruleVal(val, stateRef.current) : ruleVal;
418
- const msg = getMessage(ruleKey);
419
- const err = performValidations(val, rule, msg);
420
- nextErrors.set(ruleKey, err);
421
- if (err.isInvalid) hasInvalid = true;
461
+ });
422
462
  }
423
- };
424
- Object.entries(rules).forEach(([k, v]) => processRule(k, v));
425
- setErrors(nextErrors);
426
- setTouched((prev) => {
427
- const next = new Map(prev);
428
- nextErrors.forEach((_, k) => next.set(k, true));
429
- return next;
430
- });
431
- return hasInvalid;
432
- }, [rules, getMessage, performValidations]);
463
+ }
464
+ setMetadata(newMetadata);
465
+ return hasError;
466
+ }, [validationSchema, state, arrayIdentifiers]);
433
467
  const handleFieldChange = useCallback(
434
468
  (resolution, newValue) => {
435
469
  if (!resolution) return;
@@ -443,17 +477,29 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
443
477
  parentId,
444
478
  nestedField
445
479
  } = resolution;
480
+ let finalValue = newValue;
481
+ let rule = getRule(fieldPath, validationSchema);
482
+ if (rule && rule.type === "array" && type === "primitiveArray" /* PrimitiveArray */ && rule.innerType) {
483
+ rule = rule.innerType;
484
+ }
485
+ if (rule && rule.type === "string") {
486
+ try {
487
+ finalValue = rule.cast(newValue);
488
+ } catch {
489
+ }
490
+ }
446
491
  setState((prev) => {
447
492
  if (type === "scalar" /* Scalar */) {
448
493
  return handleNestedChange({
449
494
  state: prev,
450
495
  id: compositeKey,
451
- value: newValue
496
+ value: finalValue,
497
+ hasNestedValues: compositeKey.includes(".")
452
498
  });
453
499
  }
454
500
  if (type === "primitiveArray" /* PrimitiveArray */) {
455
501
  const arr = [...prev[arrayKey]];
456
- arr[index] = newValue;
502
+ arr[index] = finalValue;
457
503
  return { ...prev, [arrayKey]: arr };
458
504
  }
459
505
  if (type === "objectArray" /* ObjectArray */) {
@@ -462,7 +508,7 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
462
508
  arrayKey,
463
509
  index,
464
510
  field: resolution.field,
465
- value: newValue
511
+ value: finalValue
466
512
  });
467
513
  }
468
514
  if (type === "nestedPrimitiveArray" /* NestedPrimitiveArray */) {
@@ -471,41 +517,40 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
471
517
  const parentArr = [...prev[parentKey]];
472
518
  const pItem = { ...parentArr[pIndex] };
473
519
  const nestedArr = [...getNestedValue(pItem, nestedField) || []];
474
- nestedArr[index] = newValue;
520
+ nestedArr[index] = finalValue;
475
521
  pItem[nestedField] = nestedArr;
476
- const updatedItem = setNestedValue(pItem, nestedField, nestedArr);
477
- parentArr[pIndex] = updatedItem;
522
+ parentArr[pIndex] = pItem;
478
523
  return { ...prev, [parentKey]: parentArr };
479
524
  }
480
525
  return prev;
481
526
  });
482
- let extraContext = {};
483
- if (type === "objectArray" /* ObjectArray */ || type === "nestedPrimitiveArray" /* NestedPrimitiveArray */) {
484
- const idx = index;
485
- const arrKey = arrayKey || parentKey;
486
- extraContext = {
487
- index: idx,
488
- item: stateRef.current[arrKey]?.[idx]
489
- };
490
- }
491
- validateField(compositeKey, fieldPath, newValue, extraContext);
527
+ validateField(compositeKey, fieldPath, finalValue);
492
528
  },
493
- [getIndex, validateField]
529
+ [getIndex, validateField, getRule, validationSchema]
494
530
  );
495
531
  const createHandlers = useCallback(
496
532
  (resolution) => {
497
533
  if (!resolution) return {};
498
534
  const { compositeKey, fieldPath, value } = resolution;
499
- const err = errorsRef.current.get(compositeKey);
500
- const isTouched = touchedRef.current.get(compositeKey);
535
+ const meta = metadataRef.current.get(compositeKey);
536
+ const isTouched = meta?.isTouched;
501
537
  return {
502
538
  id: compositeKey,
503
- isInvalid: Boolean(isTouched && err?.isInvalid),
504
- errorMessage: isTouched ? err?.errorMessage || "" : "",
539
+ isInvalid: Boolean(isTouched && meta?.isInvalid),
540
+ errorMessage: isTouched ? meta?.errorMessage || "" : "",
505
541
  onBlur: () => {
506
- if (touchedRef.current.get(compositeKey)) return;
542
+ if (metadataRef.current.get(compositeKey)?.isTouched) return;
507
543
  validateField(compositeKey, fieldPath, value);
508
- setTouched((prev) => new Map(prev).set(compositeKey, true));
544
+ setMetadata((prev) => {
545
+ const newMap = new Map(prev);
546
+ const current = newMap.get(compositeKey) || {
547
+ isTouched: false,
548
+ isInvalid: false,
549
+ errorMessage: ""
550
+ };
551
+ newMap.set(compositeKey, { ...current, isTouched: true });
552
+ return newMap;
553
+ });
509
554
  }
510
555
  };
511
556
  },
@@ -587,8 +632,7 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
587
632
  });
588
633
  if (itemId !== void 0) {
589
634
  const prefix = `${String(arrayKey)}.${itemId}.`;
590
- setTouched((prev) => removeCompositeKeysByPrefix(prev, prefix));
591
- setErrors((prev) => removeCompositeKeysByPrefix(prev, prefix));
635
+ setMetadata((prev) => removeCompositeKeysByPrefix(prev, prefix));
592
636
  }
593
637
  },
594
638
  removeById: (arrayKey, itemId) => {
@@ -600,8 +644,7 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
600
644
  return { ...prev, [arrayKey]: arr };
601
645
  });
602
646
  const prefix = `${String(arrayKey)}.${itemId}.`;
603
- setTouched((prev) => removeCompositeKeysByPrefix(prev, prefix));
604
- setErrors((prev) => removeCompositeKeysByPrefix(prev, prefix));
647
+ setMetadata((prev) => removeCompositeKeysByPrefix(prev, prefix));
605
648
  }
606
649
  },
607
650
  updateItem: (arrayKey, index, value) => {
@@ -639,10 +682,22 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
639
682
  }),
640
683
  [getIndex, arrayIdentifiers]
641
684
  );
642
- const onBlur = (id) => {
643
- validateField(String(id), String(id), stateRef.current[id]);
644
- setTouched((prev) => new Map(prev).set(String(id), true));
645
- };
685
+ const onBlur = useCallback(
686
+ (id) => {
687
+ validateField(String(id), String(id), stateRef.current[id]);
688
+ setMetadata((prev) => {
689
+ const newMap = new Map(prev);
690
+ const current = newMap.get(String(id)) || {
691
+ isTouched: false,
692
+ isInvalid: false,
693
+ errorMessage: ""
694
+ };
695
+ newMap.set(String(id), { ...current, isTouched: true });
696
+ return newMap;
697
+ });
698
+ },
699
+ [validateField]
700
+ );
646
701
  const polymorphicOnValueChange = useCallback(
647
702
  (...args) => {
648
703
  const value = args[args.length - 1];
@@ -665,48 +720,71 @@ function useForm(initialState, { rules, messages, arrayIdentifiers } = {}) {
665
720
  },
666
721
  [validateField]
667
722
  );
668
- return {
669
- state,
670
- setState,
671
- touched,
672
- errors: errors2,
673
- on,
674
- helpers,
675
- onBlur,
676
- onValueChange: polymorphicOnValueChange,
677
- onSelectionChange: polymorphicOnSelectionChange,
678
- isDirty: touched.size > 0,
679
- hasInvalidValues: validateAll,
680
- resetForm: (preservedKeys) => {
681
- if (preservedKeys && preservedKeys.length > 0) {
682
- const nextState = { ...initialState };
683
- preservedKeys.forEach((k) => {
684
- if (stateRef.current[k] !== void 0)
685
- nextState[k] = stateRef.current[k];
686
- });
687
- setState(nextState);
688
- } else {
689
- setState(initialState);
690
- }
691
- setTouched(/* @__PURE__ */ new Map());
692
- setErrors(/* @__PURE__ */ new Map());
723
+ const onSubmit = useCallback(
724
+ (fn) => (e) => {
725
+ e.preventDefault();
726
+ if (validateAll()) return;
727
+ fn(stateRef.current, e);
693
728
  },
694
- resetTouched: (preservedKeys) => {
695
- if (preservedKeys && preservedKeys.length > 0) {
696
- setTouched((prev) => {
697
- const next = /* @__PURE__ */ new Map();
698
- for (const [k, v] of prev.entries()) {
699
- if (preservedKeys.some((pk) => k.startsWith(String(pk)))) {
700
- next.set(k, v);
701
- }
702
- }
703
- return next;
704
- });
705
- } else {
706
- setTouched(/* @__PURE__ */ new Map());
707
- }
708
- }
709
- };
729
+ [validateAll]
730
+ );
731
+ return useMemo(
732
+ () => ({
733
+ state,
734
+ setState,
735
+ metadata,
736
+ on,
737
+ helpers,
738
+ onFieldChange: polymorphicOnValueChange,
739
+ onFieldBlur: onBlur,
740
+ onSelectionChange: polymorphicOnSelectionChange,
741
+ isDirty: Array.from(metadata.values()).some((m) => m.isTouched),
742
+ reset: (options) => {
743
+ const { preservedStateKeys, preserveTouched } = options || {};
744
+ if (preservedStateKeys && preservedStateKeys.length > 0) {
745
+ const nextState = { ...initialState };
746
+ preservedStateKeys.forEach((k) => {
747
+ if (stateRef.current[k] !== void 0)
748
+ nextState[k] = stateRef.current[k];
749
+ });
750
+ setState(nextState);
751
+ } else {
752
+ setState(initialState);
753
+ }
754
+ if (preserveTouched) {
755
+ setMetadata((prev) => {
756
+ const next = /* @__PURE__ */ new Map();
757
+ prev.forEach((v, k) => {
758
+ if (v.isTouched) {
759
+ next.set(k, {
760
+ isTouched: true,
761
+ isInvalid: false,
762
+ errorMessage: ""
763
+ });
764
+ }
765
+ });
766
+ return next;
767
+ });
768
+ } else {
769
+ setMetadata(/* @__PURE__ */ new Map());
770
+ }
771
+ },
772
+ onSubmit
773
+ }),
774
+ [
775
+ state,
776
+ setState,
777
+ metadata,
778
+ on,
779
+ helpers,
780
+ onBlur,
781
+ polymorphicOnValueChange,
782
+ polymorphicOnSelectionChange,
783
+ validateAll,
784
+ onSubmit,
785
+ initialState
786
+ ]
787
+ );
710
788
  }
711
789
  export {
712
790
  NextUIError,