@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/README.md +227 -46
- package/dist/index.d.mts +48 -57
- package/dist/index.d.ts +48 -57
- package/dist/index.js +379 -294
- package/dist/index.mjs +367 -289
- package/package.json +45 -37
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(
|
|
66
|
-
const result = new Map(
|
|
67
|
-
for (const key of
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
},
|
|
128
|
-
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
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
locale
|
|
170
|
-
|
|
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
|
-
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
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
|
-
|
|
307
|
-
errorsRef.current = errors2;
|
|
307
|
+
metadataRef.current = metadata;
|
|
308
308
|
const indexMap = useMemo(() => {
|
|
309
|
-
const
|
|
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
|
-
|
|
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
|
|
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
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
-
|
|
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
|
-
[
|
|
389
|
+
[]
|
|
356
390
|
);
|
|
357
391
|
const validateField = useCallback(
|
|
358
|
-
(compositeKey, fieldPath, value
|
|
359
|
-
let
|
|
360
|
-
if (
|
|
361
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
411
|
+
return false;
|
|
381
412
|
},
|
|
382
|
-
[getRule,
|
|
413
|
+
[getRule, runValidation, validationSchema]
|
|
383
414
|
);
|
|
384
415
|
const validateAll = useCallback(() => {
|
|
385
|
-
if (!
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
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
|
-
|
|
425
|
-
|
|
426
|
-
|
|
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:
|
|
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] =
|
|
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:
|
|
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] =
|
|
520
|
+
nestedArr[index] = finalValue;
|
|
475
521
|
pItem[nestedField] = nestedArr;
|
|
476
|
-
|
|
477
|
-
parentArr[pIndex] = updatedItem;
|
|
522
|
+
parentArr[pIndex] = pItem;
|
|
478
523
|
return { ...prev, [parentKey]: parentArr };
|
|
479
524
|
}
|
|
480
525
|
return prev;
|
|
481
526
|
});
|
|
482
|
-
|
|
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
|
|
500
|
-
const isTouched =
|
|
535
|
+
const meta = metadataRef.current.get(compositeKey);
|
|
536
|
+
const isTouched = meta?.isTouched;
|
|
501
537
|
return {
|
|
502
538
|
id: compositeKey,
|
|
503
|
-
isInvalid: Boolean(isTouched &&
|
|
504
|
-
errorMessage: isTouched ?
|
|
539
|
+
isInvalid: Boolean(isTouched && meta?.isInvalid),
|
|
540
|
+
errorMessage: isTouched ? meta?.errorMessage || "" : "",
|
|
505
541
|
onBlur: () => {
|
|
506
|
-
if (
|
|
542
|
+
if (metadataRef.current.get(compositeKey)?.isTouched) return;
|
|
507
543
|
validateField(compositeKey, fieldPath, value);
|
|
508
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 = (
|
|
643
|
-
|
|
644
|
-
|
|
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
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
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
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
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,
|