@lehnihon/bit-form 2.1.2 → 2.2.1
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 +6 -0
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.cjs.map +1 -1
- package/dist/angular/index.d.cts +29 -17
- package/dist/angular/index.d.ts +29 -17
- package/dist/angular/index.js +1 -1
- package/dist/angular/index.js.map +1 -1
- package/dist/bus-B3pGaiFZ.d.cts +255 -0
- package/dist/bus-B3pGaiFZ.d.ts +255 -0
- package/dist/chunk-442A4FTZ.cjs +2 -0
- package/dist/chunk-442A4FTZ.cjs.map +1 -0
- package/dist/chunk-6FJEE6O3.js +133 -0
- package/dist/chunk-6FJEE6O3.js.map +1 -0
- package/dist/chunk-FOV24ACZ.js +2 -0
- package/dist/chunk-FOV24ACZ.js.map +1 -0
- package/dist/chunk-YWXX6XRV.cjs +133 -0
- package/dist/chunk-YWXX6XRV.cjs.map +1 -0
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/index.cjs +1 -1
- package/dist/devtools/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -6
- package/dist/index.d.ts +7 -6
- package/dist/index.js +1 -1
- package/dist/public-types-CtYuIAMP.d.cts +99 -0
- package/dist/public-types-Lq3eLstW.d.ts +99 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +5 -5
- package/dist/react/index.d.ts +5 -5
- package/dist/react/index.js +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.cjs.map +1 -1
- package/dist/react-native/index.d.cts +10 -12
- package/dist/react-native/index.d.ts +10 -12
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/resolvers/joi.d.cts +1 -1
- package/dist/resolvers/joi.d.ts +1 -1
- package/dist/resolvers/yup.d.cts +1 -1
- package/dist/resolvers/yup.d.ts +1 -1
- package/dist/resolvers/zod.d.cts +1 -1
- package/dist/resolvers/zod.d.ts +1 -1
- package/dist/{use-bit-watch-hA0AqCkC.d.ts → use-bit-persist-CWzGfovL.d.cts} +27 -19
- package/dist/{use-bit-watch-BRekIj2W.d.cts → use-bit-persist-hxJaKG2S.d.ts} +27 -19
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +45 -33
- package/dist/vue/index.d.ts +45 -33
- package/dist/vue/index.js +1 -1
- package/dist/vue/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/bus-vCbulIYH.d.cts +0 -141
- package/dist/bus-vCbulIYH.d.ts +0 -141
- package/dist/chunk-2QNUW6ZN.cjs +0 -133
- package/dist/chunk-2QNUW6ZN.cjs.map +0 -1
- package/dist/chunk-F6LJWWEW.js +0 -2
- package/dist/chunk-F6LJWWEW.js.map +0 -1
- package/dist/chunk-LPRLSFPT.cjs +0 -2
- package/dist/chunk-LPRLSFPT.cjs.map +0 -1
- package/dist/chunk-N6IA7HQL.js +0 -133
- package/dist/chunk-N6IA7HQL.js.map +0 -1
- package/dist/public-types-ChP5j3xc.d.ts +0 -69
- package/dist/public-types-Nv__uZTR.d.cts +0 -69
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
interface BitMask {
|
|
2
|
+
format: (value: any) => string;
|
|
3
|
+
parse: (value: string) => any;
|
|
4
|
+
}
|
|
5
|
+
interface PatternMaskOptions {
|
|
6
|
+
allowChars?: string;
|
|
7
|
+
customParse?: (value: string) => any;
|
|
8
|
+
saveRaw?: boolean;
|
|
9
|
+
guide?: boolean;
|
|
10
|
+
placeholderChar?: string;
|
|
11
|
+
}
|
|
12
|
+
interface CurrencyMaskConfig {
|
|
13
|
+
prefix?: string;
|
|
14
|
+
suffix?: string;
|
|
15
|
+
thousand: string;
|
|
16
|
+
decimal: string;
|
|
17
|
+
precision?: number;
|
|
18
|
+
allowNegative?: boolean;
|
|
19
|
+
saveRaw?: boolean;
|
|
20
|
+
}
|
|
21
|
+
interface DateMaskConfig extends PatternMaskOptions {
|
|
22
|
+
format?: "DD/MM/YYYY" | "YYYY-MM-DD";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type DeepPartial<T> = T extends object ? {
|
|
26
|
+
[P in keyof T]?: DeepPartial<T[P]>;
|
|
27
|
+
} : T;
|
|
28
|
+
type BitErrors<T> = {
|
|
29
|
+
[key: string]: string | undefined;
|
|
30
|
+
};
|
|
31
|
+
type BitTouched<T> = {
|
|
32
|
+
[key: string]: boolean | undefined;
|
|
33
|
+
};
|
|
34
|
+
type BitComputedFn<T> = (values: T) => any;
|
|
35
|
+
type BitTransformFn<T> = (value: any, allValues: T) => any;
|
|
36
|
+
interface BitState<T> {
|
|
37
|
+
values: T;
|
|
38
|
+
errors: BitErrors<T>;
|
|
39
|
+
touched: BitTouched<T>;
|
|
40
|
+
isValidating: Record<string, boolean>;
|
|
41
|
+
isValid: boolean;
|
|
42
|
+
isSubmitting: boolean;
|
|
43
|
+
isDirty: boolean;
|
|
44
|
+
}
|
|
45
|
+
interface BitFieldState<T extends object = any, TValue = unknown> {
|
|
46
|
+
value: TValue;
|
|
47
|
+
error: string | undefined;
|
|
48
|
+
touched: boolean;
|
|
49
|
+
isHidden: boolean;
|
|
50
|
+
isRequired: boolean;
|
|
51
|
+
isDirty: boolean;
|
|
52
|
+
isValidating: boolean;
|
|
53
|
+
}
|
|
54
|
+
type ValidatorFn<T> = (values: T, options?: {
|
|
55
|
+
scopeFields?: string[];
|
|
56
|
+
}) => Promise<BitErrors<T>> | BitErrors<T>;
|
|
57
|
+
/** Conditional logic: visibility and dynamic required. */
|
|
58
|
+
interface BitFieldConditional<T extends object = any> {
|
|
59
|
+
dependsOn?: string[];
|
|
60
|
+
showIf?: (values: T) => boolean;
|
|
61
|
+
requiredIf?: (values: T) => boolean;
|
|
62
|
+
/** Custom message when field is required but empty. Fallback: "required field". */
|
|
63
|
+
requiredMessage?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Field-level validation: async validation only. */
|
|
66
|
+
interface BitFieldValidation<T extends object = any> {
|
|
67
|
+
asyncValidate?: (value: any, values: T) => Promise<string | null | undefined>;
|
|
68
|
+
asyncValidateDelay?: number;
|
|
69
|
+
}
|
|
70
|
+
/** Full field definition: conditional, validation, transform, computed, mask, scope. */
|
|
71
|
+
interface BitFieldDefinition<T extends object = any> {
|
|
72
|
+
conditional?: BitFieldConditional<T>;
|
|
73
|
+
validation?: BitFieldValidation<T>;
|
|
74
|
+
transform?: BitTransformFn<T>;
|
|
75
|
+
computed?: BitComputedFn<T>;
|
|
76
|
+
/** Mask name (from registry) or BitMask instance. */
|
|
77
|
+
mask?: BitMask | string;
|
|
78
|
+
/** Scope name (e.g. wizard step). */
|
|
79
|
+
scope?: string;
|
|
80
|
+
}
|
|
81
|
+
interface DevToolsOptions {
|
|
82
|
+
enabled?: boolean;
|
|
83
|
+
mode?: "local" | "remote";
|
|
84
|
+
url?: string;
|
|
85
|
+
}
|
|
86
|
+
type BitPluginHookSource = "beforeValidate" | "afterValidate" | "beforeSubmit" | "afterSubmit" | "onFieldChange" | "setup" | "teardown" | "submit";
|
|
87
|
+
type BitFieldChangeOrigin = "setField" | "rebase" | "replaceValues" | "hydrate" | "array";
|
|
88
|
+
type BitArrayOperation = "push" | "prepend" | "insert" | "remove" | "move" | "swap";
|
|
89
|
+
interface BitFieldChangeMeta {
|
|
90
|
+
origin: BitFieldChangeOrigin;
|
|
91
|
+
operation?: BitArrayOperation;
|
|
92
|
+
index?: number;
|
|
93
|
+
from?: number;
|
|
94
|
+
to?: number;
|
|
95
|
+
}
|
|
96
|
+
interface BitFieldChangeEvent<T extends object = any> {
|
|
97
|
+
path: string;
|
|
98
|
+
previousValue: unknown;
|
|
99
|
+
nextValue: unknown;
|
|
100
|
+
values: Readonly<T>;
|
|
101
|
+
state: Readonly<BitState<T>>;
|
|
102
|
+
meta: BitFieldChangeMeta;
|
|
103
|
+
}
|
|
104
|
+
interface BitBeforeValidateEvent<T extends object = any> {
|
|
105
|
+
values: Readonly<T>;
|
|
106
|
+
state: Readonly<BitState<T>>;
|
|
107
|
+
scope?: string;
|
|
108
|
+
scopeFields?: string[];
|
|
109
|
+
}
|
|
110
|
+
interface BitAfterValidateEvent<T extends object = any> {
|
|
111
|
+
values: Readonly<T>;
|
|
112
|
+
state: Readonly<BitState<T>>;
|
|
113
|
+
scope?: string;
|
|
114
|
+
scopeFields?: string[];
|
|
115
|
+
errors: BitErrors<T>;
|
|
116
|
+
result: boolean;
|
|
117
|
+
aborted?: boolean;
|
|
118
|
+
}
|
|
119
|
+
interface BitBeforeSubmitEvent<T extends object = any> {
|
|
120
|
+
values: Readonly<T>;
|
|
121
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
122
|
+
state: Readonly<BitState<T>>;
|
|
123
|
+
}
|
|
124
|
+
interface BitAfterSubmitEvent<T extends object = any> {
|
|
125
|
+
values: Readonly<T>;
|
|
126
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
127
|
+
state: Readonly<BitState<T>>;
|
|
128
|
+
success: boolean;
|
|
129
|
+
error?: unknown;
|
|
130
|
+
invalid?: boolean;
|
|
131
|
+
}
|
|
132
|
+
interface BitPluginErrorEvent<T extends object = any> {
|
|
133
|
+
source: BitPluginHookSource;
|
|
134
|
+
pluginName?: string;
|
|
135
|
+
error: unknown;
|
|
136
|
+
event?: unknown;
|
|
137
|
+
values: Readonly<T>;
|
|
138
|
+
state: Readonly<BitState<T>>;
|
|
139
|
+
}
|
|
140
|
+
interface BitPluginContext<T extends object = any> {
|
|
141
|
+
storeId: string;
|
|
142
|
+
getState: () => Readonly<BitState<T>>;
|
|
143
|
+
getConfig: () => Readonly<BitConfig<T>>;
|
|
144
|
+
}
|
|
145
|
+
interface BitPluginHooks<T extends object = any> {
|
|
146
|
+
beforeValidate?: (event: BitBeforeValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
147
|
+
afterValidate?: (event: BitAfterValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
148
|
+
beforeSubmit?: (event: BitBeforeSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
149
|
+
afterSubmit?: (event: BitAfterSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
150
|
+
onFieldChange?: (event: BitFieldChangeEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
151
|
+
onError?: (event: BitPluginErrorEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
152
|
+
}
|
|
153
|
+
interface BitPlugin<T extends object = any> {
|
|
154
|
+
name: string;
|
|
155
|
+
setup?: (context: BitPluginContext<T>) => void | (() => void);
|
|
156
|
+
hooks?: BitPluginHooks<T>;
|
|
157
|
+
}
|
|
158
|
+
type BitMaybePromise<T> = T | Promise<T>;
|
|
159
|
+
interface BitPersistStorageAdapter {
|
|
160
|
+
getItem(key: string): BitMaybePromise<string | null>;
|
|
161
|
+
setItem(key: string, value: string): BitMaybePromise<void>;
|
|
162
|
+
removeItem(key: string): BitMaybePromise<void>;
|
|
163
|
+
}
|
|
164
|
+
type BitPersistMode = "values" | "dirtyValues";
|
|
165
|
+
interface BitPersistConfig<T extends object = any> {
|
|
166
|
+
enabled?: boolean;
|
|
167
|
+
key?: string;
|
|
168
|
+
storage?: BitPersistStorageAdapter;
|
|
169
|
+
autoSave?: boolean;
|
|
170
|
+
debounceMs?: number;
|
|
171
|
+
mode?: BitPersistMode;
|
|
172
|
+
serialize?: (payload: unknown) => string;
|
|
173
|
+
deserialize?: (raw: string) => Partial<T>;
|
|
174
|
+
onError?: (error: unknown) => void;
|
|
175
|
+
}
|
|
176
|
+
interface BitPersistResolvedConfig<T extends object = any> {
|
|
177
|
+
enabled: boolean;
|
|
178
|
+
key: string;
|
|
179
|
+
storage?: BitPersistStorageAdapter;
|
|
180
|
+
autoSave: boolean;
|
|
181
|
+
debounceMs: number;
|
|
182
|
+
mode: BitPersistMode;
|
|
183
|
+
serialize: (payload: unknown) => string;
|
|
184
|
+
deserialize: (raw: string) => Partial<T>;
|
|
185
|
+
onError?: (error: unknown) => void;
|
|
186
|
+
}
|
|
187
|
+
/** Validation config. */
|
|
188
|
+
interface BitValidationConfig<T> {
|
|
189
|
+
resolver?: ValidatorFn<T>;
|
|
190
|
+
delay?: number;
|
|
191
|
+
}
|
|
192
|
+
/** History config. */
|
|
193
|
+
interface BitHistoryConfig {
|
|
194
|
+
enabled?: boolean;
|
|
195
|
+
limit?: number;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* BitConfig - store configuration.
|
|
199
|
+
* @see CHANGELOG for migration from features to fields in 2.0.
|
|
200
|
+
*/
|
|
201
|
+
interface BitConfig<T extends object = any> {
|
|
202
|
+
/** Core */
|
|
203
|
+
name?: string;
|
|
204
|
+
initialValues?: T;
|
|
205
|
+
/** Central field config: conditional, validation, transform, computed, mask, scope. */
|
|
206
|
+
fields?: Record<string, BitFieldDefinition<T>>;
|
|
207
|
+
/** Schema-level validation */
|
|
208
|
+
validation?: BitValidationConfig<T>;
|
|
209
|
+
/** History (undo/redo) */
|
|
210
|
+
history?: BitHistoryConfig;
|
|
211
|
+
/** DevTools */
|
|
212
|
+
devTools?: boolean | DevToolsOptions;
|
|
213
|
+
/** Persistência local de rascunho */
|
|
214
|
+
persist?: BitPersistConfig<T>;
|
|
215
|
+
/** Plugins de lifecycle (observabilidade) */
|
|
216
|
+
plugins?: BitPlugin<T>[];
|
|
217
|
+
}
|
|
218
|
+
/** Return type of BitStore.getStepStatus, used by useBitScope/injectBitScope. */
|
|
219
|
+
interface ScopeStatus {
|
|
220
|
+
hasErrors: boolean;
|
|
221
|
+
isDirty: boolean;
|
|
222
|
+
errors: Record<string, string>;
|
|
223
|
+
}
|
|
224
|
+
/** Return type of validateStep, used by useBitScope/injectBitScope. */
|
|
225
|
+
interface ValidateScopeResult {
|
|
226
|
+
valid: boolean;
|
|
227
|
+
errors: Record<string, string>;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Type-safe path utilities
|
|
231
|
+
*
|
|
232
|
+
* These are used to strengthen typing for field paths (e.g. "user.email", "items.0.name").
|
|
233
|
+
*/
|
|
234
|
+
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
|
|
235
|
+
type BitPath<T, Prefix extends string = ""> = T extends Primitive ? never : T extends readonly (infer U)[] ? Prefix extends "" ? `${number}` | `${number}.${BitPath<U>}` : `${Prefix}.${number}` | `${Prefix}.${number}.${BitPath<U>}` : {
|
|
236
|
+
[K in keyof T & (string | number)]: T[K] extends Primitive ? Prefix extends "" ? `${K & (string | number)}` : `${Prefix}.${K & (string | number)}` : Prefix extends "" ? `${K & (string | number)}` | `${K & (string | number)}.${BitPath<T[K]>}` : `${Prefix}.${K & (string | number)}` | `${Prefix}.${K & (string | number)}.${BitPath<T[K]>}`;
|
|
237
|
+
}[keyof T & (string | number)];
|
|
238
|
+
type BitPathValue<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends `${number}` ? T extends readonly (infer U)[] ? BitPathValue<U, Rest> : never : K extends keyof T ? BitPathValue<T[K], Rest> : never : P extends `${number}` ? T extends readonly (infer U)[] ? U : never : P extends keyof T ? T[P] : never;
|
|
239
|
+
type BitArrayPath<T> = BitPath<T> extends infer P ? P extends string ? BitPathValue<T, P> extends readonly any[] ? P : never : never : never;
|
|
240
|
+
type BitArrayItem<A> = A extends readonly (infer U)[] ? U : A extends (infer U)[] ? U : never;
|
|
241
|
+
|
|
242
|
+
type BitBusListener<T extends object = any> = (storeId: string, newState: BitState<T>) => void;
|
|
243
|
+
interface BitFormGlobal {
|
|
244
|
+
stores: Record<string, unknown>;
|
|
245
|
+
listeners: Set<BitBusListener>;
|
|
246
|
+
dispatch: (storeId: string, state: BitState<any>) => void;
|
|
247
|
+
subscribe: (fn: BitBusListener) => () => void;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
declare global {
|
|
251
|
+
var __BIT_FORM__: BitFormGlobal | undefined;
|
|
252
|
+
}
|
|
253
|
+
declare const bitBus: BitFormGlobal;
|
|
254
|
+
|
|
255
|
+
export { type BitTouched as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitTransformFn as E, type BitValidationConfig as F, type DeepPartial as G, type ValidatorFn as H, bitBus as I, type DevToolsOptions as J, type BitPersistResolvedConfig as K, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldState as n, type BitFieldValidation as o, type BitHistoryConfig as p, type BitPath as q, type BitPathValue as r, type BitPersistConfig as s, type BitPersistMode as t, type BitPersistStorageAdapter as u, type BitPlugin as v, type BitPluginContext as w, type BitPluginErrorEvent as x, type BitPluginHooks as y, type BitState as z };
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
interface BitMask {
|
|
2
|
+
format: (value: any) => string;
|
|
3
|
+
parse: (value: string) => any;
|
|
4
|
+
}
|
|
5
|
+
interface PatternMaskOptions {
|
|
6
|
+
allowChars?: string;
|
|
7
|
+
customParse?: (value: string) => any;
|
|
8
|
+
saveRaw?: boolean;
|
|
9
|
+
guide?: boolean;
|
|
10
|
+
placeholderChar?: string;
|
|
11
|
+
}
|
|
12
|
+
interface CurrencyMaskConfig {
|
|
13
|
+
prefix?: string;
|
|
14
|
+
suffix?: string;
|
|
15
|
+
thousand: string;
|
|
16
|
+
decimal: string;
|
|
17
|
+
precision?: number;
|
|
18
|
+
allowNegative?: boolean;
|
|
19
|
+
saveRaw?: boolean;
|
|
20
|
+
}
|
|
21
|
+
interface DateMaskConfig extends PatternMaskOptions {
|
|
22
|
+
format?: "DD/MM/YYYY" | "YYYY-MM-DD";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type DeepPartial<T> = T extends object ? {
|
|
26
|
+
[P in keyof T]?: DeepPartial<T[P]>;
|
|
27
|
+
} : T;
|
|
28
|
+
type BitErrors<T> = {
|
|
29
|
+
[key: string]: string | undefined;
|
|
30
|
+
};
|
|
31
|
+
type BitTouched<T> = {
|
|
32
|
+
[key: string]: boolean | undefined;
|
|
33
|
+
};
|
|
34
|
+
type BitComputedFn<T> = (values: T) => any;
|
|
35
|
+
type BitTransformFn<T> = (value: any, allValues: T) => any;
|
|
36
|
+
interface BitState<T> {
|
|
37
|
+
values: T;
|
|
38
|
+
errors: BitErrors<T>;
|
|
39
|
+
touched: BitTouched<T>;
|
|
40
|
+
isValidating: Record<string, boolean>;
|
|
41
|
+
isValid: boolean;
|
|
42
|
+
isSubmitting: boolean;
|
|
43
|
+
isDirty: boolean;
|
|
44
|
+
}
|
|
45
|
+
interface BitFieldState<T extends object = any, TValue = unknown> {
|
|
46
|
+
value: TValue;
|
|
47
|
+
error: string | undefined;
|
|
48
|
+
touched: boolean;
|
|
49
|
+
isHidden: boolean;
|
|
50
|
+
isRequired: boolean;
|
|
51
|
+
isDirty: boolean;
|
|
52
|
+
isValidating: boolean;
|
|
53
|
+
}
|
|
54
|
+
type ValidatorFn<T> = (values: T, options?: {
|
|
55
|
+
scopeFields?: string[];
|
|
56
|
+
}) => Promise<BitErrors<T>> | BitErrors<T>;
|
|
57
|
+
/** Conditional logic: visibility and dynamic required. */
|
|
58
|
+
interface BitFieldConditional<T extends object = any> {
|
|
59
|
+
dependsOn?: string[];
|
|
60
|
+
showIf?: (values: T) => boolean;
|
|
61
|
+
requiredIf?: (values: T) => boolean;
|
|
62
|
+
/** Custom message when field is required but empty. Fallback: "required field". */
|
|
63
|
+
requiredMessage?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Field-level validation: async validation only. */
|
|
66
|
+
interface BitFieldValidation<T extends object = any> {
|
|
67
|
+
asyncValidate?: (value: any, values: T) => Promise<string | null | undefined>;
|
|
68
|
+
asyncValidateDelay?: number;
|
|
69
|
+
}
|
|
70
|
+
/** Full field definition: conditional, validation, transform, computed, mask, scope. */
|
|
71
|
+
interface BitFieldDefinition<T extends object = any> {
|
|
72
|
+
conditional?: BitFieldConditional<T>;
|
|
73
|
+
validation?: BitFieldValidation<T>;
|
|
74
|
+
transform?: BitTransformFn<T>;
|
|
75
|
+
computed?: BitComputedFn<T>;
|
|
76
|
+
/** Mask name (from registry) or BitMask instance. */
|
|
77
|
+
mask?: BitMask | string;
|
|
78
|
+
/** Scope name (e.g. wizard step). */
|
|
79
|
+
scope?: string;
|
|
80
|
+
}
|
|
81
|
+
interface DevToolsOptions {
|
|
82
|
+
enabled?: boolean;
|
|
83
|
+
mode?: "local" | "remote";
|
|
84
|
+
url?: string;
|
|
85
|
+
}
|
|
86
|
+
type BitPluginHookSource = "beforeValidate" | "afterValidate" | "beforeSubmit" | "afterSubmit" | "onFieldChange" | "setup" | "teardown" | "submit";
|
|
87
|
+
type BitFieldChangeOrigin = "setField" | "rebase" | "replaceValues" | "hydrate" | "array";
|
|
88
|
+
type BitArrayOperation = "push" | "prepend" | "insert" | "remove" | "move" | "swap";
|
|
89
|
+
interface BitFieldChangeMeta {
|
|
90
|
+
origin: BitFieldChangeOrigin;
|
|
91
|
+
operation?: BitArrayOperation;
|
|
92
|
+
index?: number;
|
|
93
|
+
from?: number;
|
|
94
|
+
to?: number;
|
|
95
|
+
}
|
|
96
|
+
interface BitFieldChangeEvent<T extends object = any> {
|
|
97
|
+
path: string;
|
|
98
|
+
previousValue: unknown;
|
|
99
|
+
nextValue: unknown;
|
|
100
|
+
values: Readonly<T>;
|
|
101
|
+
state: Readonly<BitState<T>>;
|
|
102
|
+
meta: BitFieldChangeMeta;
|
|
103
|
+
}
|
|
104
|
+
interface BitBeforeValidateEvent<T extends object = any> {
|
|
105
|
+
values: Readonly<T>;
|
|
106
|
+
state: Readonly<BitState<T>>;
|
|
107
|
+
scope?: string;
|
|
108
|
+
scopeFields?: string[];
|
|
109
|
+
}
|
|
110
|
+
interface BitAfterValidateEvent<T extends object = any> {
|
|
111
|
+
values: Readonly<T>;
|
|
112
|
+
state: Readonly<BitState<T>>;
|
|
113
|
+
scope?: string;
|
|
114
|
+
scopeFields?: string[];
|
|
115
|
+
errors: BitErrors<T>;
|
|
116
|
+
result: boolean;
|
|
117
|
+
aborted?: boolean;
|
|
118
|
+
}
|
|
119
|
+
interface BitBeforeSubmitEvent<T extends object = any> {
|
|
120
|
+
values: Readonly<T>;
|
|
121
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
122
|
+
state: Readonly<BitState<T>>;
|
|
123
|
+
}
|
|
124
|
+
interface BitAfterSubmitEvent<T extends object = any> {
|
|
125
|
+
values: Readonly<T>;
|
|
126
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
127
|
+
state: Readonly<BitState<T>>;
|
|
128
|
+
success: boolean;
|
|
129
|
+
error?: unknown;
|
|
130
|
+
invalid?: boolean;
|
|
131
|
+
}
|
|
132
|
+
interface BitPluginErrorEvent<T extends object = any> {
|
|
133
|
+
source: BitPluginHookSource;
|
|
134
|
+
pluginName?: string;
|
|
135
|
+
error: unknown;
|
|
136
|
+
event?: unknown;
|
|
137
|
+
values: Readonly<T>;
|
|
138
|
+
state: Readonly<BitState<T>>;
|
|
139
|
+
}
|
|
140
|
+
interface BitPluginContext<T extends object = any> {
|
|
141
|
+
storeId: string;
|
|
142
|
+
getState: () => Readonly<BitState<T>>;
|
|
143
|
+
getConfig: () => Readonly<BitConfig<T>>;
|
|
144
|
+
}
|
|
145
|
+
interface BitPluginHooks<T extends object = any> {
|
|
146
|
+
beforeValidate?: (event: BitBeforeValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
147
|
+
afterValidate?: (event: BitAfterValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
148
|
+
beforeSubmit?: (event: BitBeforeSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
149
|
+
afterSubmit?: (event: BitAfterSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
150
|
+
onFieldChange?: (event: BitFieldChangeEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
151
|
+
onError?: (event: BitPluginErrorEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
152
|
+
}
|
|
153
|
+
interface BitPlugin<T extends object = any> {
|
|
154
|
+
name: string;
|
|
155
|
+
setup?: (context: BitPluginContext<T>) => void | (() => void);
|
|
156
|
+
hooks?: BitPluginHooks<T>;
|
|
157
|
+
}
|
|
158
|
+
type BitMaybePromise<T> = T | Promise<T>;
|
|
159
|
+
interface BitPersistStorageAdapter {
|
|
160
|
+
getItem(key: string): BitMaybePromise<string | null>;
|
|
161
|
+
setItem(key: string, value: string): BitMaybePromise<void>;
|
|
162
|
+
removeItem(key: string): BitMaybePromise<void>;
|
|
163
|
+
}
|
|
164
|
+
type BitPersistMode = "values" | "dirtyValues";
|
|
165
|
+
interface BitPersistConfig<T extends object = any> {
|
|
166
|
+
enabled?: boolean;
|
|
167
|
+
key?: string;
|
|
168
|
+
storage?: BitPersistStorageAdapter;
|
|
169
|
+
autoSave?: boolean;
|
|
170
|
+
debounceMs?: number;
|
|
171
|
+
mode?: BitPersistMode;
|
|
172
|
+
serialize?: (payload: unknown) => string;
|
|
173
|
+
deserialize?: (raw: string) => Partial<T>;
|
|
174
|
+
onError?: (error: unknown) => void;
|
|
175
|
+
}
|
|
176
|
+
interface BitPersistResolvedConfig<T extends object = any> {
|
|
177
|
+
enabled: boolean;
|
|
178
|
+
key: string;
|
|
179
|
+
storage?: BitPersistStorageAdapter;
|
|
180
|
+
autoSave: boolean;
|
|
181
|
+
debounceMs: number;
|
|
182
|
+
mode: BitPersistMode;
|
|
183
|
+
serialize: (payload: unknown) => string;
|
|
184
|
+
deserialize: (raw: string) => Partial<T>;
|
|
185
|
+
onError?: (error: unknown) => void;
|
|
186
|
+
}
|
|
187
|
+
/** Validation config. */
|
|
188
|
+
interface BitValidationConfig<T> {
|
|
189
|
+
resolver?: ValidatorFn<T>;
|
|
190
|
+
delay?: number;
|
|
191
|
+
}
|
|
192
|
+
/** History config. */
|
|
193
|
+
interface BitHistoryConfig {
|
|
194
|
+
enabled?: boolean;
|
|
195
|
+
limit?: number;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* BitConfig - store configuration.
|
|
199
|
+
* @see CHANGELOG for migration from features to fields in 2.0.
|
|
200
|
+
*/
|
|
201
|
+
interface BitConfig<T extends object = any> {
|
|
202
|
+
/** Core */
|
|
203
|
+
name?: string;
|
|
204
|
+
initialValues?: T;
|
|
205
|
+
/** Central field config: conditional, validation, transform, computed, mask, scope. */
|
|
206
|
+
fields?: Record<string, BitFieldDefinition<T>>;
|
|
207
|
+
/** Schema-level validation */
|
|
208
|
+
validation?: BitValidationConfig<T>;
|
|
209
|
+
/** History (undo/redo) */
|
|
210
|
+
history?: BitHistoryConfig;
|
|
211
|
+
/** DevTools */
|
|
212
|
+
devTools?: boolean | DevToolsOptions;
|
|
213
|
+
/** Persistência local de rascunho */
|
|
214
|
+
persist?: BitPersistConfig<T>;
|
|
215
|
+
/** Plugins de lifecycle (observabilidade) */
|
|
216
|
+
plugins?: BitPlugin<T>[];
|
|
217
|
+
}
|
|
218
|
+
/** Return type of BitStore.getStepStatus, used by useBitScope/injectBitScope. */
|
|
219
|
+
interface ScopeStatus {
|
|
220
|
+
hasErrors: boolean;
|
|
221
|
+
isDirty: boolean;
|
|
222
|
+
errors: Record<string, string>;
|
|
223
|
+
}
|
|
224
|
+
/** Return type of validateStep, used by useBitScope/injectBitScope. */
|
|
225
|
+
interface ValidateScopeResult {
|
|
226
|
+
valid: boolean;
|
|
227
|
+
errors: Record<string, string>;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Type-safe path utilities
|
|
231
|
+
*
|
|
232
|
+
* These are used to strengthen typing for field paths (e.g. "user.email", "items.0.name").
|
|
233
|
+
*/
|
|
234
|
+
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
|
|
235
|
+
type BitPath<T, Prefix extends string = ""> = T extends Primitive ? never : T extends readonly (infer U)[] ? Prefix extends "" ? `${number}` | `${number}.${BitPath<U>}` : `${Prefix}.${number}` | `${Prefix}.${number}.${BitPath<U>}` : {
|
|
236
|
+
[K in keyof T & (string | number)]: T[K] extends Primitive ? Prefix extends "" ? `${K & (string | number)}` : `${Prefix}.${K & (string | number)}` : Prefix extends "" ? `${K & (string | number)}` | `${K & (string | number)}.${BitPath<T[K]>}` : `${Prefix}.${K & (string | number)}` | `${Prefix}.${K & (string | number)}.${BitPath<T[K]>}`;
|
|
237
|
+
}[keyof T & (string | number)];
|
|
238
|
+
type BitPathValue<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends `${number}` ? T extends readonly (infer U)[] ? BitPathValue<U, Rest> : never : K extends keyof T ? BitPathValue<T[K], Rest> : never : P extends `${number}` ? T extends readonly (infer U)[] ? U : never : P extends keyof T ? T[P] : never;
|
|
239
|
+
type BitArrayPath<T> = BitPath<T> extends infer P ? P extends string ? BitPathValue<T, P> extends readonly any[] ? P : never : never : never;
|
|
240
|
+
type BitArrayItem<A> = A extends readonly (infer U)[] ? U : A extends (infer U)[] ? U : never;
|
|
241
|
+
|
|
242
|
+
type BitBusListener<T extends object = any> = (storeId: string, newState: BitState<T>) => void;
|
|
243
|
+
interface BitFormGlobal {
|
|
244
|
+
stores: Record<string, unknown>;
|
|
245
|
+
listeners: Set<BitBusListener>;
|
|
246
|
+
dispatch: (storeId: string, state: BitState<any>) => void;
|
|
247
|
+
subscribe: (fn: BitBusListener) => () => void;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
declare global {
|
|
251
|
+
var __BIT_FORM__: BitFormGlobal | undefined;
|
|
252
|
+
}
|
|
253
|
+
declare const bitBus: BitFormGlobal;
|
|
254
|
+
|
|
255
|
+
export { type BitTouched as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitTransformFn as E, type BitValidationConfig as F, type DeepPartial as G, type ValidatorFn as H, bitBus as I, type DevToolsOptions as J, type BitPersistResolvedConfig as K, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldState as n, type BitFieldValidation as o, type BitHistoryConfig as p, type BitPath as q, type BitPathValue as r, type BitPersistConfig as s, type BitPersistMode as t, type BitPersistStorageAdapter as u, type BitPlugin as v, type BitPluginContext as w, type BitPluginErrorEvent as x, type BitPluginHooks as y, type BitState as z };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkYWXX6XRVcjs = require('./chunk-YWXX6XRV.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var k=_react.createContext.call(void 0, null),at= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, k.Provider,{value:t,children:e}),g= exports.b =()=>{let t=_react.useContext.call(void 0, k);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function St(){let t=g(),[e,s]=_react.useState.call(void 0, null),[m,n]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, null),u=_react.useCallback.call(void 0, ()=>{let p=t.getState(),b={isValid:p.isValid,isDirty:p.isDirty,isSubmitting:p.isSubmitting};return o.current&&o.current.isValid===b.isValid&&o.current.isDirty===b.isDirty&&o.current.isSubmitting===b.isSubmitting?o.current:(o.current=b,b)},[t]),c=_react.useCallback.call(void 0, p=>t.subscribeSelector(b=>({isValid:b.isValid,isDirty:b.isDirty,isSubmitting:b.isSubmitting}),()=>p()),[t]),i=_react.useSyncExternalStore.call(void 0, c,u,u),r=_react.useCallback.call(void 0, p=>b=>(_optionalChain([b, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(p)),[t]),a=_react.useCallback.call(void 0, p=>b=>(_optionalChain([b, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),s(null),t.submit(async(O,q)=>{try{let h=await p(O,q);n(h),s(null)}catch(h){_chunkYWXX6XRVcjs.i.call(void 0, h)?t.setServerErrors(_chunkYWXX6XRVcjs.j.call(void 0, h)):s(h instanceof Error?h:new Error(String(h)))}})),[t]),l=_react.useCallback.call(void 0, ()=>{t.reset(),s(null),n(null)},[t]),d=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),B=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),F=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),S=_react.useCallback.call(void 0, ()=>t.getDirtyValues(),[t]);return{meta:_react.useMemo.call(void 0, ()=>({...i,submitError:e,lastResponse:m}),[i,e,m]),getValues:d,getErrors:B,getTouched:F,getDirtyValues:S,submit:r,onSubmit:a,reset:l,setField:t.setField.bind(t),blurField:t.blurField.bind(t),replaceValues:t.replaceValues.bind(t),hydrate:t.hydrate.bind(t),rebase:t.rebase.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}var P=()=>Math.random().toString(36).substring(2,9);function Bt(t){let e=g(),s=_react.useCallback.call(void 0, ()=>{let r=e.getState(),a=_chunkYWXX6XRVcjs.f.call(void 0, r.values,t);return Array.isArray(a)?a:[]},[e,t]),m=_react.useCallback.call(void 0, r=>e.subscribePath(t,()=>r()),[e,t]),n=_react.useSyncExternalStore.call(void 0, m,s,s),[o,u]=_react.useState.call(void 0, ()=>n.map(P));_react.useEffect.call(void 0, ()=>{n.length!==o.length&&u(r=>{if(n.length>r.length){let a=n.length-r.length;return[...r,...Array(a).fill(null).map(P)]}return r.slice(0,n.length)})},[n.length]);let c=_react.useMemo.call(void 0, ()=>({append:r=>{u(a=>[...a,P()]),e.pushItem(t,r)},prepend:r=>{u(a=>[P(),...a]),e.prependItem(t,r)},insert:(r,a)=>{u(l=>{let d=[...l];return d.splice(r,0,P()),d}),e.insertItem(t,r,a)},remove:r=>{u(a=>a.filter((l,d)=>d!==r)),e.removeItem(t,r)},move:(r,a)=>{u(l=>{let d=[...l],[B]=d.splice(r,1);return d.splice(a,0,B),d}),e.moveItem(t,r,a)},swap:(r,a)=>{u(l=>{let d=[...l];return[d[r],d[a]]=[d[a],d[r]],d}),e.swapItems(t,r,a)},replace:r=>{u(r.map(P)),e.setField(t,r)},clear:()=>{u([]),e.setField(t,[])}}),[e,t]);return{fields:_react.useMemo.call(void 0, ()=>n.map((r,a)=>({key:o[a]||`temp-${a}`,value:r,index:a})),[n,o]),length:n.length,...c}}function Tt(t){let e=g(),s=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(t);return s.current&&s.current.hasErrors===c.hasErrors&&s.current.isDirty===c.isDirty&&Object.keys(s.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([i,r])=>s.current.errors[i]===r)?s.current:(s.current=c,c)},[e,t]),n=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),m,m),o=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:t}),i=e.getStepErrors(t);return{valid:c,errors:i}},[e,t]),u=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:n,errors:n.errors,validate:o,getErrors:u,isValid:!n.hasErrors,isDirty:n.isDirty}}function wt(t){let e=g(),[s,m]=_react.useState.call(void 0, 0),n=_nullishCoalesce(t[s], () => ("")),o=_react.useRef.call(void 0, null),u=_react.useCallback.call(void 0, ()=>{let S=e.getStepStatus(n);return o.current&&o.current.hasErrors===S.hasErrors&&o.current.isDirty===S.isDirty&&Object.keys(o.current.errors).length===Object.keys(S.errors).length&&Object.entries(S.errors).every(([f,p])=>o.current.errors[f]===p)?o.current:(o.current=S,S)},[e,n]),c=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),u,u),i=_react.useCallback.call(void 0, async()=>{let S=await e.validate({scope:n}),f=e.getStepErrors(n);return{valid:S,errors:f}},[e,n]),r=_react.useCallback.call(void 0, ()=>e.getStepErrors(n),[e,n]),a=_react.useCallback.call(void 0, async()=>{let S=e.getScopeFields(n);if(e.hasValidationsInProgress(S))return!1;let f=await e.validate({scope:n});if(f)m(p=>Math.min(p+1,t.length-1));else{let p=e.getStepErrors(n),b=Object.keys(p);b.length>0&&e.markFieldsTouched(b)}return f},[e,n,t.length]),l=_react.useCallback.call(void 0, ()=>{m(S=>Math.max(S-1,0))},[]),d=_react.useCallback.call(void 0, S=>{m(Math.max(0,Math.min(S-1,t.length-1)))},[t.length]),B=s===0,F=s>=t.length-1;return{step:s+1,stepIndex:s,scope:n,next:a,prev:l,goTo:d,isFirst:B,isLast:F,status:c,errors:c.errors,isValid:!c.hasErrors,isDirty:c.isDirty,validate:i,getErrors:r}}function Ot(t){let e=g(),s=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let o=_chunkYWXX6XRVcjs.f.call(void 0, e.getState().values,t);return s.current!==null&&_chunkYWXX6XRVcjs.e.call(void 0, s.current,o)?s.current:(s.current=o,o)},[e,t]),n=_react.useCallback.call(void 0, o=>e.subscribe(o),[e]);return _react.useSyncExternalStore.call(void 0, n,m,m)}function Lt(){let t=g(),[e,s]=_react.useState.call(void 0, !1),[m,n]=_react.useState.call(void 0, !1),[o,u]=_react.useState.call(void 0, null),c=_react.useCallback.call(void 0, async()=>{n(!0),u(null);try{return await t.restorePersisted()}catch(l){return u(l instanceof Error?l:new Error(String(l))),!1}finally{n(!1)}},[t]),i=_react.useCallback.call(void 0, async()=>{s(!0),u(null);try{await t.forceSave()}catch(l){u(l instanceof Error?l:new Error(String(l)))}finally{s(!1)}},[t]),r=_react.useCallback.call(void 0, async()=>{u(null);try{await t.clearPersisted()}catch(l){u(l instanceof Error?l:new Error(String(l)))}},[t]),a=_react.useMemo.call(void 0, ()=>({isSaving:e,isRestoring:m,error:o}),[e,m,o]);return{restore:c,save:i,clear:r,meta:a}}function zt(t){let e=g(),s=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>()=>{e.unregisterField&&e.unregisterField(t)},[e,t]);let m=_react.useCallback.call(void 0, ()=>{let i=e.getFieldState(t);if(s.current&&s.current.value===i.value&&s.current.error===i.error&&s.current.touched===i.touched&&s.current.isHidden===i.isHidden&&s.current.isRequired===i.isRequired&&s.current.isDirty===i.isDirty&&s.current.isValidating===i.isValidating)return s.current;let r={value:i.value,error:i.error,touched:i.touched,isHidden:i.isHidden,isRequired:i.isRequired,isDirty:i.isDirty,isValidating:i.isValidating};return s.current=r,r},[e,t]),n=_react.useCallback.call(void 0, i=>e.subscribeSelector(()=>e.getFieldState(t),()=>i()),[e,t]),o=_react.useSyncExternalStore.call(void 0, n,m,m),u=_react.useCallback.call(void 0, i=>e.setField(t,i),[e,t]),c=_react.useCallback.call(void 0, ()=>e.blurField(t),[e,t]);return{fieldState:o,setValue:u,setBlur:c,store:e}}exports.a = at; exports.b = g; exports.c = St; exports.d = zt; exports.e = Bt; exports.f = Tt; exports.g = wt; exports.h = Ot; exports.i = Lt;
|
|
2
|
+
//# sourceMappingURL=chunk-442A4FTZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-442A4FTZ.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","state","nextMeta","subscribeMeta","cb","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","dirtyValues","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","getDirtyValues","useMemo","generateId","useBitArray","path","getSnapshot","value","getDeepValue","subscribeArray","data","ids","setIds","useEffect","prevIds","diff","methods","prev","index","newIds","_","i","from","to","item","indexA","indexB","items"],"mappings":"AAAA,yuBAA6D,8BCAZ,+CAW3C,IARAA,CAAAA,CAAaC,kCAAAA,IAA2C,CAAA,CAEjDC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,EAGMC,6BAAAA,CAACL,CAAW,QAAA,CAAX,CAAoB,KAAA,CAAOG,CAAAA,CAAQ,QAAA,CAAAC,CAAAA,CAAS,CAAA,CAEtCE,CAAAA,aAAc,CAAA,CAAA,EAAwB,CACjD,IAAMH,CAAAA,CAAQI,+BAAAA,CAAqB,CAAA,CACnC,EAAA,CAAI,CAACJ,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,6DACF,CAAA,CACF,OAAOA,CACT,CAAA,CCpBA,SAUgBK,EAAAA,CAAAA,CAA+B,CAC7C,IAAML,CAAAA,CAAQG,CAAAA,C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C,CAAA,CAAI,CAACP,CAAAA,CAAOO,CAAM,CAAA,CAAGP,CAAAA,CAAOM,CAAM,CAAC,CAAA,CAC3DN,CACT,CAAC,CAAA,CACDtD,CAAAA,CAAM,SAAA,CAAUwC,CAAAA,CAAMoB,CAAAA,CAAQC,CAAM,CACtC,CAAA,CACA,OAAA,CAAUC,CAAAA,EAAkB,CAC1Bf,CAAAA,CAAOe,CAAAA,CAAM,GAAA,CAAIxB,CAAU,CAAC,CAAA,CAC5BtC,CAAAA,CAAM,QAAA,CACJwC,CAAAA,CACAsB,CACF,CACF,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXf,CAAAA,CAAO,CAAC,CAAC,CAAA,CACT/C,CAAAA,CAAM,QAAA,CACJwC,CAAAA,CACA,CAAC,CACH,CACF,CACF,CAAA,CAAA,CACA,CAACxC,CAAAA,CAAOwC,CAAI,CACd,CAAA,CAYA,MAAO,CACL,MAAA,CAXaH,4BAAAA,CACb,CAAA,EACGQ,CAAAA,CAAgB,GAAA,CAAI,CAACc,CAAAA,CAAYN,CAAAA,CAAAA,EAAAA,CAAmB,CACnD,GAAA,CAAKP,CAAAA,CAAIO,CAAK,CAAA,EAAK,CAAA,KAAA,EAAQA,CAAK,CAAA,CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-442A4FTZ.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport type { BitStoreApi } from \"../core\";\n\nconst BitContext = createContext<BitStoreApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStoreApi<any>;\n children: React.ReactNode;\n}) => <BitContext.Provider value={store}>{children}</BitContext.Provider>;\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitStoreApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport { isValidationErrorShape, extractServerErrors } from \"../core/utils\";\n\nexport function useBitForm<T extends object>() {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const subscribeMeta = useCallback(\n (cb: () => void) =>\n store.subscribeSelector(\n (state) => ({\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n }),\n () => cb(),\n ),\n [store],\n );\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const submit = useCallback(\n (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n return store.submit(onSuccess);\n };\n },\n [store],\n );\n\n const onSubmit = useCallback(\n (handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values, dirtyValues) => {\n try {\n const result = await handler(values, dirtyValues);\n setLastResponse(result);\n setSubmitError(null);\n } catch (err) {\n if (isValidationErrorShape(err)) {\n store.setServerErrors(extractServerErrors(err));\n } else {\n setSubmitError(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n }\n });\n };\n },\n [store],\n );\n\n const reset = useCallback(() => {\n store.reset();\n setSubmitError(null);\n setLastResponse(null);\n }, [store]);\n\n const getValues = useCallback(() => store.getState().values, [store]);\n const getErrors = useCallback(() => store.getState().errors, [store]);\n const getTouched = useCallback(() => store.getState().touched, [store]);\n const getDirtyValues = useCallback(() => store.getDirtyValues(), [store]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n setField: store.setField.bind(store),\n blurField: store.blurField.bind(store),\n replaceValues: store.replaceValues.bind(store),\n hydrate: store.hydrate.bind(store),\n rebase: store.rebase.bind(store),\n setValues: store.setValues.bind(store),\n setError: store.setError.bind(store),\n setErrors: store.setErrors.bind(store),\n setServerErrors: store.setServerErrors.bind(store),\n validate: store.validate.bind(store),\n // Array mutations (grouped)\n mutations: {\n pushItem: store.pushItem.bind(store),\n removeItem: store.removeItem.bind(store),\n prependItem: store.prependItem.bind(store),\n insertItem: store.insertItem.bind(store),\n moveItem: store.moveItem.bind(store),\n swapItems: store.swapItems.bind(store),\n },\n };\n}\n","import {\n useCallback,\n useSyncExternalStore,\n useState,\n useMemo,\n useEffect,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\n\nconst generateId = () => Math.random().toString(36).substring(2, 9);\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n return Array.isArray(value) ? (value as Item[]) : [];\n }, [store, path]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\n\n const [ids, setIds] = useState<string[]>(() =>\n (data as Item[]).map(generateId),\n );\n\n useEffect(() => {\n if (data.length !== ids.length) {\n setIds((prevIds) => {\n if (data.length > prevIds.length) {\n const diff = data.length - prevIds.length;\n return [...prevIds, ...Array(diff).fill(null).map(generateId)];\n }\n return prevIds.slice(0, data.length);\n });\n }\n }, [data.length]);\n\n const methods = useMemo(\n () => ({\n append: (value: Item) => {\n setIds((prev) => [...prev, generateId()]);\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n setIds((prev) => [generateId(), ...prev]);\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n setIds((prev) => {\n const newIds = [...prev];\n newIds.splice(index, 0, generateId());\n return newIds;\n });\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n setIds((prev) => prev.filter((_, i) => i !== index));\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n return newIds;\n });\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n return newIds;\n });\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n setIds(items.map(generateId));\n store.setField(\n path as unknown as BitPath<TForm>,\n items as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n clear: () => {\n setIds([]);\n store.setField(\n path as unknown as BitPath<TForm>,\n [] as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n }),\n [store, path],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: ids[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data, ids],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n"]}
|