easy-forms-core 1.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.
@@ -0,0 +1,637 @@
1
+ /**
2
+ * Tipos de campos soportados
3
+ */
4
+ type FieldType = 'text' | 'email' | 'number' | 'password' | 'textarea' | 'select' | 'checkbox' | 'radio' | 'switch' | 'date' | 'file' | 'array' | 'group' | 'custom';
5
+ /**
6
+ * Tipos de validaciones soportadas
7
+ */
8
+ type ValidationType = 'required' | 'email' | 'minLength' | 'maxLength' | 'min' | 'max' | 'pattern' | 'custom';
9
+ /**
10
+ * Validación base
11
+ */
12
+ interface BaseValidation {
13
+ type: ValidationType;
14
+ message?: string;
15
+ }
16
+ /**
17
+ * Validaciones específicas
18
+ */
19
+ interface RequiredValidation extends BaseValidation {
20
+ type: 'required';
21
+ }
22
+ interface EmailValidation extends BaseValidation {
23
+ type: 'email';
24
+ }
25
+ interface MinLengthValidation extends BaseValidation {
26
+ type: 'minLength';
27
+ value: number;
28
+ }
29
+ interface MaxLengthValidation extends BaseValidation {
30
+ type: 'maxLength';
31
+ value: number;
32
+ }
33
+ interface MinValidation extends BaseValidation {
34
+ type: 'min';
35
+ value: number;
36
+ }
37
+ interface MaxValidation extends BaseValidation {
38
+ type: 'max';
39
+ value: number;
40
+ }
41
+ interface PatternValidation extends BaseValidation {
42
+ type: 'pattern';
43
+ value: string | RegExp;
44
+ }
45
+ interface CustomValidation extends BaseValidation {
46
+ type: 'custom';
47
+ validator: (value: any) => boolean | Promise<boolean>;
48
+ }
49
+ /**
50
+ * Unión de todas las validaciones
51
+ */
52
+ type Validation = RequiredValidation | EmailValidation | MinLengthValidation | MaxLengthValidation | MinValidation | MaxValidation | PatternValidation | CustomValidation;
53
+ /**
54
+ * Campo base
55
+ */
56
+ interface BaseField {
57
+ type: FieldType;
58
+ name: string;
59
+ label?: string;
60
+ placeholder?: string;
61
+ defaultValue?: any;
62
+ validations?: Validation[];
63
+ props?: Record<string, any>;
64
+ disabled?: boolean;
65
+ hidden?: boolean;
66
+ description?: string;
67
+ }
68
+ /**
69
+ * Campo de texto
70
+ */
71
+ interface TextField extends BaseField {
72
+ type: 'text' | 'email' | 'password';
73
+ }
74
+ /**
75
+ * Campo numérico
76
+ */
77
+ interface NumberField extends BaseField {
78
+ type: 'number';
79
+ min?: number;
80
+ max?: number;
81
+ step?: number;
82
+ }
83
+ /**
84
+ * Campo textarea
85
+ */
86
+ interface TextareaField extends BaseField {
87
+ type: 'textarea';
88
+ rows?: number;
89
+ cols?: number;
90
+ }
91
+ /**
92
+ * Campo select
93
+ */
94
+ interface SelectField extends BaseField {
95
+ type: 'select';
96
+ options: Array<{
97
+ label: string;
98
+ value: any;
99
+ } | string>;
100
+ multiple?: boolean;
101
+ }
102
+ /**
103
+ * Campo checkbox
104
+ */
105
+ interface CheckboxField extends BaseField {
106
+ type: 'checkbox';
107
+ checked?: boolean;
108
+ }
109
+ /**
110
+ * Campo radio
111
+ */
112
+ interface RadioField extends BaseField {
113
+ type: 'radio';
114
+ options: Array<{
115
+ label: string;
116
+ value: any;
117
+ } | string>;
118
+ }
119
+ /**
120
+ * Campo switch
121
+ */
122
+ interface SwitchField extends BaseField {
123
+ type: 'switch';
124
+ checked?: boolean;
125
+ }
126
+ /**
127
+ * Campo date
128
+ */
129
+ interface DateField extends BaseField {
130
+ type: 'date';
131
+ min?: string;
132
+ max?: string;
133
+ }
134
+ /**
135
+ * Campo file
136
+ */
137
+ interface FileField extends BaseField {
138
+ type: 'file';
139
+ accept?: string;
140
+ multiple?: boolean;
141
+ }
142
+ /**
143
+ * Campo array
144
+ */
145
+ interface ArrayField extends BaseField {
146
+ type: 'array';
147
+ itemSchema: FormSchema;
148
+ minItems?: number;
149
+ maxItems?: number;
150
+ }
151
+ /**
152
+ * Campo group
153
+ */
154
+ interface GroupField extends BaseField {
155
+ type: 'group';
156
+ fields: Field[];
157
+ }
158
+ /**
159
+ * Campo custom
160
+ */
161
+ interface CustomField extends BaseField {
162
+ type: 'custom';
163
+ component: string;
164
+ }
165
+ /**
166
+ * Unión de todos los tipos de campos
167
+ */
168
+ type Field = TextField | NumberField | TextareaField | SelectField | CheckboxField | RadioField | SwitchField | DateField | FileField | ArrayField | GroupField | CustomField;
169
+ /**
170
+ * Step para formularios wizard
171
+ */
172
+ interface Step {
173
+ title: string;
174
+ description?: string;
175
+ fields: Field[];
176
+ }
177
+ /**
178
+ * Tipos de temas disponibles
179
+ */
180
+ type FormTheme = 'plano' | 'tradicional' | 'material' | 'rounded-shadow' | 'lines';
181
+ /**
182
+ * Colores personalizados del formulario
183
+ */
184
+ interface FormColors {
185
+ primary?: string;
186
+ secondary?: string;
187
+ error?: string;
188
+ success?: string;
189
+ text?: string;
190
+ border?: string;
191
+ background?: string;
192
+ }
193
+ /**
194
+ * Schema del formulario
195
+ */
196
+ interface FormSchema {
197
+ fields?: Field[];
198
+ steps?: Step[];
199
+ }
200
+ /**
201
+ * Estado del formulario
202
+ */
203
+ interface FormState {
204
+ values: Record<string, any>;
205
+ errors: Record<string, string[]>;
206
+ touched: Record<string, boolean>;
207
+ isValid: boolean;
208
+ isSubmitting: boolean;
209
+ }
210
+ /**
211
+ * Estado de wizard
212
+ */
213
+ interface WizardState {
214
+ currentStep: number;
215
+ totalSteps: number;
216
+ completedSteps: number[];
217
+ }
218
+ /**
219
+ * Evento de submit
220
+ */
221
+ interface SubmitEventDetail {
222
+ values: Record<string, any>;
223
+ isValid: boolean;
224
+ errors: Record<string, string[]>;
225
+ }
226
+ /**
227
+ * Evento de change
228
+ */
229
+ interface ChangeEventDetail {
230
+ field: string;
231
+ value: any;
232
+ values: Record<string, any>;
233
+ }
234
+ /**
235
+ * Evento de error
236
+ */
237
+ interface ErrorEventDetail {
238
+ errors: Record<string, string[]>;
239
+ field?: string;
240
+ }
241
+ /**
242
+ * Evento de step change
243
+ */
244
+ interface StepChangeEventDetail {
245
+ currentStep: number;
246
+ previousStep: number;
247
+ totalSteps: number;
248
+ }
249
+ /**
250
+ * Componente personalizado para inyección
251
+ */
252
+ type CustomComponent = (props: {
253
+ field: Field;
254
+ value: any;
255
+ error?: string;
256
+ onChange: (value: any) => void;
257
+ onBlur: () => void;
258
+ }) => HTMLElement | null;
259
+ /**
260
+ * Registro de componentes personalizados
261
+ */
262
+ interface ComponentRegistry {
263
+ [key: string]: CustomComponent;
264
+ }
265
+
266
+ declare const BrowserHTMLElement: {
267
+ new (): HTMLElement;
268
+ prototype: HTMLElement;
269
+ };
270
+ /**
271
+ * Web Component principal EasyForm
272
+ */
273
+ declare class EasyForm extends BrowserHTMLElement {
274
+ private stateManager;
275
+ protected shadow: ShadowRoot;
276
+ private customComponents;
277
+ private isRendering;
278
+ static get observedAttributes(): string[];
279
+ constructor();
280
+ /**
281
+ * Obtiene el schema
282
+ */
283
+ get schema(): FormSchema | null;
284
+ /**
285
+ * Establece el schema
286
+ */
287
+ set schema(value: FormSchema | null);
288
+ /**
289
+ * Se llama cuando el componente se conecta al DOM
290
+ */
291
+ connectedCallback(): void;
292
+ /**
293
+ * Se llama cuando un atributo cambia
294
+ */
295
+ attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
296
+ /**
297
+ * Maneja el cambio de schema
298
+ */
299
+ private handleSchemaChange;
300
+ /**
301
+ * Renderiza el formulario
302
+ */
303
+ private render;
304
+ /**
305
+ * Preserva los valores actuales del DOM antes de re-renderizar
306
+ * Retorna un objeto con los valores preservados
307
+ */
308
+ private preserveCurrentValues;
309
+ /**
310
+ * Renderiza campos normales
311
+ */
312
+ private renderFields;
313
+ /**
314
+ * Renderiza un campo
315
+ */
316
+ private renderField;
317
+ /**
318
+ * Renderiza un grupo de campos
319
+ */
320
+ private renderGroup;
321
+ /**
322
+ * Renderiza un array dinámico
323
+ */
324
+ private renderArray;
325
+ /**
326
+ * Renderiza un campo custom
327
+ */
328
+ private renderCustom;
329
+ /**
330
+ * Renderiza wizard
331
+ */
332
+ private renderWizard;
333
+ /**
334
+ * Maneja el cambio de un campo
335
+ */
336
+ private handleFieldChange;
337
+ /**
338
+ * Maneja el blur de un campo
339
+ */
340
+ private handleFieldBlur;
341
+ /**
342
+ * Actualiza solo un campo específico sin re-renderizar todo el formulario
343
+ */
344
+ private updateSingleField;
345
+ /**
346
+ * Busca un campo por nombre en el schema
347
+ */
348
+ private findFieldInSchema;
349
+ /**
350
+ * Maneja el submit del formulario
351
+ */
352
+ private handleSubmit;
353
+ /**
354
+ * Emite evento de error
355
+ */
356
+ private emitError;
357
+ /**
358
+ * Emite evento de cambio de step
359
+ */
360
+ private emitStepChange;
361
+ /**
362
+ * Registra componentes personalizados
363
+ */
364
+ registerComponents(components: ComponentRegistry): void;
365
+ /**
366
+ * Obtiene el tema del formulario
367
+ */
368
+ get theme(): FormTheme;
369
+ /**
370
+ * Establece el tema del formulario
371
+ */
372
+ set theme(value: FormTheme);
373
+ /**
374
+ * Obtiene los colores personalizados
375
+ */
376
+ get colors(): FormColors | null;
377
+ /**
378
+ * Establece los colores personalizados
379
+ */
380
+ set colors(value: FormColors | null);
381
+ /**
382
+ * Configura estilos básicos
383
+ */
384
+ private setupStyles;
385
+ }
386
+
387
+ /**
388
+ * Gestor de estado del formulario
389
+ */
390
+ declare class StateManager {
391
+ private state;
392
+ private wizardState;
393
+ private schema;
394
+ private parser;
395
+ private validator;
396
+ constructor();
397
+ /**
398
+ * Crea el estado inicial
399
+ */
400
+ private createInitialState;
401
+ /**
402
+ * Inicializa el schema
403
+ */
404
+ initializeSchema(schema: FormSchema): void;
405
+ /**
406
+ * Inicializa los valores por defecto
407
+ */
408
+ private initializeValues;
409
+ /**
410
+ * Inicializa el valor de un campo
411
+ */
412
+ private initializeFieldValue;
413
+ /**
414
+ * Inicializa el estado del wizard
415
+ */
416
+ private initializeWizard;
417
+ /**
418
+ * Obtiene el estado actual
419
+ */
420
+ getState(): FormState;
421
+ /**
422
+ * Obtiene el estado del wizard
423
+ */
424
+ getWizardState(): WizardState | null;
425
+ /**
426
+ * Obtiene un valor del formulario
427
+ */
428
+ getValue(fieldName: string): any;
429
+ /**
430
+ * Establece un valor
431
+ */
432
+ setValue(fieldName: string, value: any): Promise<void>;
433
+ /**
434
+ * Establece un valor sin validar (útil para preservar valores durante re-renderizado)
435
+ */
436
+ setValueWithoutValidation(fieldName: string, value: any): void;
437
+ /**
438
+ * Valida un campo específico
439
+ */
440
+ validateField(fieldName: string): Promise<void>;
441
+ /**
442
+ * Valida todo el formulario
443
+ */
444
+ validateForm(): Promise<Record<string, string[]>>;
445
+ /**
446
+ * Actualiza la validez del formulario
447
+ */
448
+ private updateValidity;
449
+ /**
450
+ * Marca un campo como touched
451
+ */
452
+ setTouched(fieldName: string): void;
453
+ /**
454
+ * Obtiene los errores de un campo
455
+ */
456
+ getErrors(fieldName: string): string[];
457
+ /**
458
+ * Obtiene todos los errores
459
+ */
460
+ getAllErrors(): Record<string, string[]>;
461
+ /**
462
+ * Resetea el formulario
463
+ */
464
+ reset(): void;
465
+ /**
466
+ * Avanza al siguiente step del wizard
467
+ */
468
+ nextStep(): boolean;
469
+ /**
470
+ * Retrocede al step anterior del wizard
471
+ */
472
+ previousStep(): boolean;
473
+ /**
474
+ * Va a un step específico
475
+ */
476
+ goToStep(stepIndex: number): boolean;
477
+ /**
478
+ * Marca un step como completado
479
+ */
480
+ completeStep(stepIndex: number): void;
481
+ /**
482
+ * Establece el estado de submitting
483
+ */
484
+ setSubmitting(isSubmitting: boolean): void;
485
+ /**
486
+ * Obtiene los campos del step actual
487
+ */
488
+ getCurrentStepFields(): Field[];
489
+ }
490
+
491
+ /**
492
+ * Motor de validaciones
493
+ */
494
+ declare class ValidationEngine {
495
+ /**
496
+ * Valida un campo con todas sus validaciones
497
+ */
498
+ validateField(field: Field, value: any): Promise<string[]>;
499
+ /**
500
+ * Valida un valor con una validación específica
501
+ */
502
+ private validateValue;
503
+ /**
504
+ * Valida campo requerido
505
+ */
506
+ private validateRequired;
507
+ /**
508
+ * Valida email
509
+ */
510
+ private validateEmail;
511
+ /**
512
+ * Valida longitud mínima
513
+ */
514
+ private validateMinLength;
515
+ /**
516
+ * Valida longitud máxima
517
+ */
518
+ private validateMaxLength;
519
+ /**
520
+ * Valida valor mínimo
521
+ */
522
+ private validateMin;
523
+ /**
524
+ * Valida valor máximo
525
+ */
526
+ private validateMax;
527
+ /**
528
+ * Valida patrón regex
529
+ */
530
+ private validatePattern;
531
+ /**
532
+ * Valida con función personalizada
533
+ */
534
+ private validateCustom;
535
+ /**
536
+ * Obtiene mensaje por defecto para una validación
537
+ */
538
+ private getDefaultMessage;
539
+ /**
540
+ * Valida todos los campos de un formulario
541
+ */
542
+ validateForm(fields: Field[], values: Record<string, any>): Promise<Record<string, string[]>>;
543
+ }
544
+
545
+ /**
546
+ * Parser del schema JSON
547
+ */
548
+ declare class SchemaParser {
549
+ /**
550
+ * Parsea y valida un schema
551
+ */
552
+ parse(schema: FormSchema): ParsedSchema;
553
+ /**
554
+ * Normaliza y valida campos
555
+ */
556
+ private normalizeFields;
557
+ /**
558
+ * Valida el tipo de campo
559
+ */
560
+ private validateFieldType;
561
+ /**
562
+ * Aplica valores por defecto a un campo
563
+ */
564
+ private applyDefaults;
565
+ /**
566
+ * Obtiene todos los campos de un schema (incluyendo nested)
567
+ */
568
+ getAllFields(schema: FormSchema): Field[];
569
+ }
570
+ /**
571
+ * Schema parseado
572
+ */
573
+ interface ParsedSchema {
574
+ fields: Field[];
575
+ steps?: Step[];
576
+ isWizard: boolean;
577
+ }
578
+
579
+ /**
580
+ * Obtiene los colores con valores por defecto
581
+ */
582
+ declare function getColors(colors?: FormColors): Required<FormColors>;
583
+ /**
584
+ * Genera estilos CSS para un tema específico
585
+ */
586
+ declare function getThemeStyles(theme: FormTheme, colors: Required<FormColors>): string;
587
+
588
+ /**
589
+ * Utilidades generales
590
+ */
591
+ /**
592
+ * Convierte un valor a string para atributos HTML
593
+ */
594
+ declare function attributeValue(value: any): string;
595
+ /**
596
+ * Parsea un valor desde un atributo HTML
597
+ */
598
+ declare function parseAttributeValue(value: string | null): any;
599
+ /**
600
+ * Genera un ID único
601
+ */
602
+ declare function generateId(prefix?: string): string;
603
+ /**
604
+ * Obtiene el valor anidado de un objeto usando notación de punto
605
+ */
606
+ declare function getNestedValue(obj: Record<string, any>, path: string): any;
607
+ /**
608
+ * Establece un valor anidado en un objeto usando notación de punto
609
+ */
610
+ declare function setNestedValue(obj: Record<string, any>, path: string, value: any): void;
611
+ /**
612
+ * Valida si un email es válido
613
+ */
614
+ declare function isValidEmail(email: string): boolean;
615
+ /**
616
+ * Sanitiza un string para usar como ID de HTML
617
+ */
618
+ declare function sanitizeId(str: string): string;
619
+
620
+ /**
621
+ * Factory para crear inputs
622
+ */
623
+ declare function createInput(field: Field, value: any, error: string | undefined, onChange: (value: any) => void, onBlur: () => void): HTMLElement;
624
+ /**
625
+ * Registra un componente personalizado
626
+ */
627
+ declare function registerComponent(type: string, component: CustomComponent): void;
628
+ /**
629
+ * Registra múltiples componentes
630
+ */
631
+ declare function registerComponents(components: Record<string, CustomComponent>): void;
632
+ /**
633
+ * Obtiene un componente personalizado
634
+ */
635
+ declare function getCustomComponent(type: string): CustomComponent | undefined;
636
+
637
+ export { type ArrayField, type BaseField, type BaseValidation, type ChangeEventDetail, type CheckboxField, type ComponentRegistry, type CustomComponent, type CustomField, type CustomValidation, type DateField, EasyForm, type EmailValidation, type ErrorEventDetail, type Field, type FieldType, type FileField, type FormColors, type FormSchema, type FormState, type FormTheme, type GroupField, type MaxLengthValidation, type MaxValidation, type MinLengthValidation, type MinValidation, type NumberField, type PatternValidation, type RadioField, type RequiredValidation, SchemaParser, type SelectField, StateManager, type Step, type StepChangeEventDetail, type SubmitEventDetail, type SwitchField, type TextField, type TextareaField, type Validation, ValidationEngine, type ValidationType, type WizardState, attributeValue, createInput, generateId, getColors, getCustomComponent, getNestedValue, getThemeStyles, isValidEmail, parseAttributeValue, registerComponent, registerComponents, sanitizeId, setNestedValue };