@rxdrag/form 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,983 @@
1
+ import * as React from "react";
2
+ import React__default, { createContext, useContext, useRef, useCallback, useMemo, useEffect, useId } from "react";
3
+ import { useForm, useStore } from "@tanstack/react-form";
4
+ import { useStore as useStore2 } from "@tanstack/react-form";
5
+ import { Button, cn, Label, InputGroup, InputGroupAddon, InputGroupInput, Textarea as Textarea$1, Select as Select$1, SelectTrigger, SelectValue, SelectContent, SelectItem, Checkbox as Checkbox$1 } from "@rxdrag/shadcn";
6
+ import { EyeClosedIcon, EyeIcon } from "@rxdrag/rxcms-common";
7
+ const AppFormContext = createContext(
8
+ void 0
9
+ );
10
+ function useAppFormContext() {
11
+ const ctx = useContext(AppFormContext);
12
+ if (!ctx)
13
+ throw new Error("useAppFormContext 必须在 <AppForm> 内使用");
14
+ return ctx;
15
+ }
16
+ function useMaybeAppFormContext() {
17
+ return useContext(AppFormContext);
18
+ }
19
+ const FieldNamePrefixContext = createContext("");
20
+ function useFieldNamePrefix() {
21
+ return useContext(FieldNamePrefixContext);
22
+ }
23
+ function joinFieldName(prefix, name) {
24
+ if (!prefix)
25
+ return name;
26
+ if (!name)
27
+ return prefix;
28
+ return `${prefix}.${name}`;
29
+ }
30
+ var jsxRuntime = { exports: {} };
31
+ var reactJsxRuntime_production = {};
32
+ /**
33
+ * @license React
34
+ * react-jsx-runtime.production.js
35
+ *
36
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
37
+ *
38
+ * This source code is licensed under the MIT license found in the
39
+ * LICENSE file in the root directory of this source tree.
40
+ */
41
+ var hasRequiredReactJsxRuntime_production;
42
+ function requireReactJsxRuntime_production() {
43
+ if (hasRequiredReactJsxRuntime_production)
44
+ return reactJsxRuntime_production;
45
+ hasRequiredReactJsxRuntime_production = 1;
46
+ var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
47
+ function jsxProd(type, config, maybeKey) {
48
+ var key = null;
49
+ void 0 !== maybeKey && (key = "" + maybeKey);
50
+ void 0 !== config.key && (key = "" + config.key);
51
+ if ("key" in config) {
52
+ maybeKey = {};
53
+ for (var propName in config)
54
+ "key" !== propName && (maybeKey[propName] = config[propName]);
55
+ } else
56
+ maybeKey = config;
57
+ config = maybeKey.ref;
58
+ return {
59
+ $$typeof: REACT_ELEMENT_TYPE,
60
+ type,
61
+ key,
62
+ ref: void 0 !== config ? config : null,
63
+ props: maybeKey
64
+ };
65
+ }
66
+ reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE;
67
+ reactJsxRuntime_production.jsx = jsxProd;
68
+ reactJsxRuntime_production.jsxs = jsxProd;
69
+ return reactJsxRuntime_production;
70
+ }
71
+ var reactJsxRuntime_development = {};
72
+ /**
73
+ * @license React
74
+ * react-jsx-runtime.development.js
75
+ *
76
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
77
+ *
78
+ * This source code is licensed under the MIT license found in the
79
+ * LICENSE file in the root directory of this source tree.
80
+ */
81
+ var hasRequiredReactJsxRuntime_development;
82
+ function requireReactJsxRuntime_development() {
83
+ if (hasRequiredReactJsxRuntime_development)
84
+ return reactJsxRuntime_development;
85
+ hasRequiredReactJsxRuntime_development = 1;
86
+ "production" !== process.env.NODE_ENV && function() {
87
+ function getComponentNameFromType(type) {
88
+ if (null == type)
89
+ return null;
90
+ if ("function" === typeof type)
91
+ return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
92
+ if ("string" === typeof type)
93
+ return type;
94
+ switch (type) {
95
+ case REACT_FRAGMENT_TYPE:
96
+ return "Fragment";
97
+ case REACT_PROFILER_TYPE:
98
+ return "Profiler";
99
+ case REACT_STRICT_MODE_TYPE:
100
+ return "StrictMode";
101
+ case REACT_SUSPENSE_TYPE:
102
+ return "Suspense";
103
+ case REACT_SUSPENSE_LIST_TYPE:
104
+ return "SuspenseList";
105
+ case REACT_ACTIVITY_TYPE:
106
+ return "Activity";
107
+ }
108
+ if ("object" === typeof type)
109
+ switch ("number" === typeof type.tag && console.error(
110
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
111
+ ), type.$$typeof) {
112
+ case REACT_PORTAL_TYPE:
113
+ return "Portal";
114
+ case REACT_CONTEXT_TYPE:
115
+ return type.displayName || "Context";
116
+ case REACT_CONSUMER_TYPE:
117
+ return (type._context.displayName || "Context") + ".Consumer";
118
+ case REACT_FORWARD_REF_TYPE:
119
+ var innerType = type.render;
120
+ type = type.displayName;
121
+ type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
122
+ return type;
123
+ case REACT_MEMO_TYPE:
124
+ return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
125
+ case REACT_LAZY_TYPE:
126
+ innerType = type._payload;
127
+ type = type._init;
128
+ try {
129
+ return getComponentNameFromType(type(innerType));
130
+ } catch (x) {
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+ function testStringCoercion(value) {
136
+ return "" + value;
137
+ }
138
+ function checkKeyStringCoercion(value) {
139
+ try {
140
+ testStringCoercion(value);
141
+ var JSCompiler_inline_result = false;
142
+ } catch (e) {
143
+ JSCompiler_inline_result = true;
144
+ }
145
+ if (JSCompiler_inline_result) {
146
+ JSCompiler_inline_result = console;
147
+ var JSCompiler_temp_const = JSCompiler_inline_result.error;
148
+ var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
149
+ JSCompiler_temp_const.call(
150
+ JSCompiler_inline_result,
151
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
152
+ JSCompiler_inline_result$jscomp$0
153
+ );
154
+ return testStringCoercion(value);
155
+ }
156
+ }
157
+ function getTaskName(type) {
158
+ if (type === REACT_FRAGMENT_TYPE)
159
+ return "<>";
160
+ if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
161
+ return "<...>";
162
+ try {
163
+ var name = getComponentNameFromType(type);
164
+ return name ? "<" + name + ">" : "<...>";
165
+ } catch (x) {
166
+ return "<...>";
167
+ }
168
+ }
169
+ function getOwner() {
170
+ var dispatcher = ReactSharedInternals.A;
171
+ return null === dispatcher ? null : dispatcher.getOwner();
172
+ }
173
+ function UnknownOwner() {
174
+ return Error("react-stack-top-frame");
175
+ }
176
+ function hasValidKey(config) {
177
+ if (hasOwnProperty.call(config, "key")) {
178
+ var getter = Object.getOwnPropertyDescriptor(config, "key").get;
179
+ if (getter && getter.isReactWarning)
180
+ return false;
181
+ }
182
+ return void 0 !== config.key;
183
+ }
184
+ function defineKeyPropWarningGetter(props, displayName) {
185
+ function warnAboutAccessingKey() {
186
+ specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
187
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
188
+ displayName
189
+ ));
190
+ }
191
+ warnAboutAccessingKey.isReactWarning = true;
192
+ Object.defineProperty(props, "key", {
193
+ get: warnAboutAccessingKey,
194
+ configurable: true
195
+ });
196
+ }
197
+ function elementRefGetterWithDeprecationWarning() {
198
+ var componentName = getComponentNameFromType(this.type);
199
+ didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
200
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
201
+ ));
202
+ componentName = this.props.ref;
203
+ return void 0 !== componentName ? componentName : null;
204
+ }
205
+ function ReactElement(type, key, props, owner, debugStack, debugTask) {
206
+ var refProp = props.ref;
207
+ type = {
208
+ $$typeof: REACT_ELEMENT_TYPE,
209
+ type,
210
+ key,
211
+ props,
212
+ _owner: owner
213
+ };
214
+ null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
215
+ enumerable: false,
216
+ get: elementRefGetterWithDeprecationWarning
217
+ }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
218
+ type._store = {};
219
+ Object.defineProperty(type._store, "validated", {
220
+ configurable: false,
221
+ enumerable: false,
222
+ writable: true,
223
+ value: 0
224
+ });
225
+ Object.defineProperty(type, "_debugInfo", {
226
+ configurable: false,
227
+ enumerable: false,
228
+ writable: true,
229
+ value: null
230
+ });
231
+ Object.defineProperty(type, "_debugStack", {
232
+ configurable: false,
233
+ enumerable: false,
234
+ writable: true,
235
+ value: debugStack
236
+ });
237
+ Object.defineProperty(type, "_debugTask", {
238
+ configurable: false,
239
+ enumerable: false,
240
+ writable: true,
241
+ value: debugTask
242
+ });
243
+ Object.freeze && (Object.freeze(type.props), Object.freeze(type));
244
+ return type;
245
+ }
246
+ function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
247
+ var children = config.children;
248
+ if (void 0 !== children)
249
+ if (isStaticChildren)
250
+ if (isArrayImpl(children)) {
251
+ for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++)
252
+ validateChildKeys(children[isStaticChildren]);
253
+ Object.freeze && Object.freeze(children);
254
+ } else
255
+ console.error(
256
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
257
+ );
258
+ else
259
+ validateChildKeys(children);
260
+ if (hasOwnProperty.call(config, "key")) {
261
+ children = getComponentNameFromType(type);
262
+ var keys = Object.keys(config).filter(function(k) {
263
+ return "key" !== k;
264
+ });
265
+ isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
266
+ didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error(
267
+ 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',
268
+ isStaticChildren,
269
+ children,
270
+ keys,
271
+ children
272
+ ), didWarnAboutKeySpread[children + isStaticChildren] = true);
273
+ }
274
+ children = null;
275
+ void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
276
+ hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
277
+ if ("key" in config) {
278
+ maybeKey = {};
279
+ for (var propName in config)
280
+ "key" !== propName && (maybeKey[propName] = config[propName]);
281
+ } else
282
+ maybeKey = config;
283
+ children && defineKeyPropWarningGetter(
284
+ maybeKey,
285
+ "function" === typeof type ? type.displayName || type.name || "Unknown" : type
286
+ );
287
+ return ReactElement(
288
+ type,
289
+ children,
290
+ maybeKey,
291
+ getOwner(),
292
+ debugStack,
293
+ debugTask
294
+ );
295
+ }
296
+ function validateChildKeys(node) {
297
+ isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
298
+ }
299
+ function isValidElement(object) {
300
+ return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
301
+ }
302
+ var React2 = React__default, REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
303
+ return null;
304
+ };
305
+ React2 = {
306
+ react_stack_bottom_frame: function(callStackForError) {
307
+ return callStackForError();
308
+ }
309
+ };
310
+ var specialPropKeyWarningShown;
311
+ var didWarnAboutElementRef = {};
312
+ var unknownOwnerDebugStack = React2.react_stack_bottom_frame.bind(
313
+ React2,
314
+ UnknownOwner
315
+ )();
316
+ var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
317
+ var didWarnAboutKeySpread = {};
318
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
319
+ reactJsxRuntime_development.jsx = function(type, config, maybeKey) {
320
+ var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
321
+ return jsxDEVImpl(
322
+ type,
323
+ config,
324
+ maybeKey,
325
+ false,
326
+ trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
327
+ trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
328
+ );
329
+ };
330
+ reactJsxRuntime_development.jsxs = function(type, config, maybeKey) {
331
+ var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
332
+ return jsxDEVImpl(
333
+ type,
334
+ config,
335
+ maybeKey,
336
+ true,
337
+ trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
338
+ trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
339
+ );
340
+ };
341
+ }();
342
+ return reactJsxRuntime_development;
343
+ }
344
+ if (process.env.NODE_ENV === "production") {
345
+ jsxRuntime.exports = requireReactJsxRuntime_production();
346
+ } else {
347
+ jsxRuntime.exports = requireReactJsxRuntime_development();
348
+ }
349
+ var jsxRuntimeExports = jsxRuntime.exports;
350
+ function useAppForm(opts) {
351
+ const submitRef = useRef(opts.onSubmit);
352
+ submitRef.current = opts.onSubmit;
353
+ const appOptionsRef = useRef(null);
354
+ if (!appOptionsRef.current) {
355
+ appOptionsRef.current = {
356
+ defaultValues: opts.defaultValues,
357
+ onSubmit: async ({ value }) => {
358
+ var _a;
359
+ await ((_a = submitRef.current) == null ? void 0 : _a.call(submitRef, value));
360
+ }
361
+ };
362
+ }
363
+ const form = useForm(appOptionsRef.current);
364
+ form.__appOptions = appOptionsRef.current;
365
+ return form;
366
+ }
367
+ function syncAppDefaults(form, next) {
368
+ const appOptions = form.__appOptions;
369
+ if (appOptions)
370
+ appOptions.defaultValues = next;
371
+ }
372
+ function refillForm(form, next) {
373
+ form.reset(next);
374
+ syncAppDefaults(form, next);
375
+ }
376
+ function commitForm(form, patch) {
377
+ const current = form.state.values;
378
+ refillForm(form, { ...current, ...patch });
379
+ }
380
+ function AppForm(props) {
381
+ const { form, children, className, style, onDirtyChange } = props;
382
+ const metasRef = useRef([]);
383
+ const registerFieldMeta = useCallback((meta) => {
384
+ metasRef.current = [...metasRef.current, meta];
385
+ return () => {
386
+ metasRef.current = metasRef.current.filter((m) => m !== meta);
387
+ };
388
+ }, []);
389
+ const getFieldMetas = useCallback(() => metasRef.current, []);
390
+ const ctx = useMemo(
391
+ () => ({ form, registerFieldMeta, getFieldMetas, name: props.name }),
392
+ [form, registerFieldMeta, getFieldMetas, props.name]
393
+ );
394
+ const isDefaultValue = useStore(form.store, (s) => s.isDefaultValue);
395
+ useEffect(() => {
396
+ onDirtyChange == null ? void 0 : onDirtyChange(!isDefaultValue);
397
+ }, [isDefaultValue, onDirtyChange]);
398
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(AppFormContext.Provider, { value: ctx, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
399
+ "form",
400
+ {
401
+ className,
402
+ style,
403
+ onSubmit: (e) => {
404
+ e.preventDefault();
405
+ e.stopPropagation();
406
+ void form.handleSubmit();
407
+ },
408
+ children
409
+ }
410
+ ) });
411
+ }
412
+ function SubmitButton(props) {
413
+ const { form } = useAppFormContext();
414
+ const isSubmitting = useStore(form.store, (s) => s.isSubmitting);
415
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
416
+ Button,
417
+ {
418
+ type: "submit",
419
+ className: "cursor-pointer",
420
+ loading: isSubmitting,
421
+ disabled: isSubmitting || props.disabled,
422
+ ...props
423
+ }
424
+ );
425
+ }
426
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
427
+ const URL_RE = /^https?:\/\/[^\s]+$/i;
428
+ function isEmpty(v) {
429
+ if (v === void 0 || v === null || v === "")
430
+ return true;
431
+ if (Array.isArray(v) && v.length === 0)
432
+ return true;
433
+ return false;
434
+ }
435
+ function buildFieldValidators(props, label) {
436
+ const { validateSchema, zodSchema } = props;
437
+ const required = props.required ?? (validateSchema == null ? void 0 : validateSchema.required);
438
+ const rules = validateSchema == null ? void 0 : validateSchema.rules;
439
+ if (!required && !zodSchema && !rules)
440
+ return void 0;
441
+ const requiredMessage = typeof required === "string" ? required : `请输入${typeof label === "string" ? label : ""}`;
442
+ const validate = ({ value }) => {
443
+ var _a, _b, _c;
444
+ if (required && isEmpty(value))
445
+ return requiredMessage;
446
+ if (!isEmpty(value)) {
447
+ const s = typeof value === "string" ? value : String(value ?? "");
448
+ if ((rules == null ? void 0 : rules.max) && s.length > rules.max.value) {
449
+ return rules.max.message || `长度不能超过 ${rules.max.value} 个字符`;
450
+ }
451
+ if ((rules == null ? void 0 : rules.min) && s.length < rules.min.value) {
452
+ return rules.min.message || `长度不能少于 ${rules.min.value} 个字符`;
453
+ }
454
+ if ((rules == null ? void 0 : rules.email) && !EMAIL_RE.test(s)) {
455
+ return typeof rules.email === "object" && rules.email.message || "请输入合法的邮箱";
456
+ }
457
+ if ((rules == null ? void 0 : rules.url) && !URL_RE.test(s)) {
458
+ return typeof rules.url === "object" && rules.url.message || "请输入合法的网址";
459
+ }
460
+ if (zodSchema) {
461
+ const r = zodSchema.safeParse(value);
462
+ if (!r.success)
463
+ return ((_c = (_b = (_a = r.error) == null ? void 0 : _a.issues) == null ? void 0 : _b[0]) == null ? void 0 : _c.message) || "格式不正确";
464
+ }
465
+ }
466
+ return void 0;
467
+ };
468
+ return { onChange: validate, onSubmit: validate };
469
+ }
470
+ function firstErrorMessage(errors) {
471
+ const e = errors == null ? void 0 : errors[0];
472
+ if (!e)
473
+ return void 0;
474
+ if (typeof e === "string")
475
+ return e;
476
+ if (typeof e === "object" && e && "message" in e)
477
+ return String(e.message);
478
+ return String(e);
479
+ }
480
+ const LEGACY_KEYS = [
481
+ "required",
482
+ "zodSchema",
483
+ "validateSchema",
484
+ "coerce",
485
+ "valueComputer",
486
+ "initialValue",
487
+ "defaultValue"
488
+ ];
489
+ function bindField(Component, options) {
490
+ const { displayDefault = "", controlType } = options || {};
491
+ return function BoundField(props) {
492
+ const all = props;
493
+ const { name, required, coerce } = all;
494
+ const { form, registerFieldMeta } = useAppFormContext();
495
+ const prefix = useFieldNamePrefix();
496
+ const fullName = name ? joinFieldName(prefix, name) : "";
497
+ const id = useId();
498
+ const rest = {};
499
+ for (const key of Object.keys(all)) {
500
+ if (key === "name")
501
+ continue;
502
+ if (LEGACY_KEYS.includes(key))
503
+ continue;
504
+ rest[key] = all[key];
505
+ }
506
+ const labelText = typeof rest.label === "string" ? rest.label : void 0;
507
+ useEffect(() => {
508
+ if (!name)
509
+ return;
510
+ return registerFieldMeta({ name: fullName, label: labelText, type: controlType });
511
+ }, [name, fullName, labelText, registerFieldMeta]);
512
+ const validators = buildFieldValidators(
513
+ { required, zodSchema: all.zodSchema, validateSchema: all.validateSchema },
514
+ labelText
515
+ );
516
+ if (!name) {
517
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
518
+ Component,
519
+ {
520
+ id,
521
+ ...required ? { requried: true } : void 0,
522
+ ...rest
523
+ }
524
+ );
525
+ }
526
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(form.Field, { name: fullName, validators, children: (field) => {
527
+ const raw = field.state.value;
528
+ const errorMessage = firstErrorMessage(field.state.meta.errors);
529
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
530
+ Component,
531
+ {
532
+ id,
533
+ ...required ? { requried: true } : void 0,
534
+ ...rest,
535
+ value: raw === void 0 || raw === null ? displayDefault : raw,
536
+ onValueChange: (v) => {
537
+ field.handleChange(coerce ? coerce(v) : v);
538
+ },
539
+ isInvalid: !!errorMessage,
540
+ errorMessage
541
+ }
542
+ );
543
+ } });
544
+ };
545
+ }
546
+ function Input(props) {
547
+ const {
548
+ id: idProp,
549
+ label,
550
+ labelPlacement,
551
+ description,
552
+ isInvalid,
553
+ errorMessage,
554
+ onValueChange,
555
+ startContent,
556
+ endContent,
557
+ className,
558
+ classNames,
559
+ size,
560
+ variant,
561
+ required,
562
+ requried,
563
+ onChange,
564
+ "aria-invalid": ariaInvalid,
565
+ ...rest
566
+ } = props;
567
+ const reactId = React.useId();
568
+ const id = idProp ?? reactId;
569
+ const requiredFlag = required ?? requried;
570
+ const invalid = Boolean(isInvalid || errorMessage);
571
+ const handleChange = (e) => {
572
+ onChange == null ? void 0 : onChange(e);
573
+ onValueChange == null ? void 0 : onValueChange(e.target.value);
574
+ };
575
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: cn("grid w-full gap-2", className, classNames == null ? void 0 : classNames.base), children: [
576
+ label && labelPlacement !== "inside" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Label, { className: cn("text-sm", classNames == null ? void 0 : classNames.label), htmlFor: id, children: [
577
+ label,
578
+ requiredFlag ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-destructive", children: "*" }) : null
579
+ ] }) : null,
580
+ /* @__PURE__ */ jsxRuntimeExports.jsxs(
581
+ InputGroup,
582
+ {
583
+ className: cn("overflow-hidden", classNames == null ? void 0 : classNames.inputWrapper),
584
+ "data-disabled": rest.disabled ? true : void 0,
585
+ size,
586
+ variant,
587
+ children: [
588
+ startContent ? /* @__PURE__ */ jsxRuntimeExports.jsx(InputGroupAddon, { align: "inline-start", children: startContent }) : null,
589
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
590
+ InputGroupInput,
591
+ {
592
+ "aria-invalid": ariaInvalid ?? invalid,
593
+ className: classNames == null ? void 0 : classNames.input,
594
+ id,
595
+ onChange: handleChange,
596
+ required: requiredFlag,
597
+ size,
598
+ ...rest
599
+ }
600
+ ),
601
+ endContent ? /* @__PURE__ */ jsxRuntimeExports.jsx(InputGroupAddon, { align: "inline-end", children: endContent }) : null
602
+ ]
603
+ }
604
+ ),
605
+ invalid ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: cn("text-xs text-destructive", classNames == null ? void 0 : classNames.errorMessage), children: errorMessage }) : description ? /* @__PURE__ */ jsxRuntimeExports.jsx(
606
+ "div",
607
+ {
608
+ className: cn("text-xs text-muted-foreground", classNames == null ? void 0 : classNames.description),
609
+ children: description
610
+ }
611
+ ) : null
612
+ ] });
613
+ }
614
+ function Textarea(props) {
615
+ const {
616
+ id: idProp,
617
+ label,
618
+ labelPlacement,
619
+ description,
620
+ isInvalid,
621
+ errorMessage,
622
+ onValueChange,
623
+ required,
624
+ requried,
625
+ minRows,
626
+ rows,
627
+ className,
628
+ classNames,
629
+ onChange,
630
+ "aria-invalid": ariaInvalid,
631
+ ...rest
632
+ } = props;
633
+ const rowsValue = rows ?? minRows;
634
+ const reactId = React.useId();
635
+ const id = idProp ?? reactId;
636
+ const invalid = Boolean(isInvalid || errorMessage);
637
+ const requiredFlag = required ?? requried;
638
+ const handleChange = (e) => {
639
+ onChange == null ? void 0 : onChange(e);
640
+ onValueChange == null ? void 0 : onValueChange(e.target.value);
641
+ };
642
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: cn("grid w-full gap-2", className, classNames == null ? void 0 : classNames.base), children: [
643
+ label && labelPlacement !== "inside" ? /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: cn("text-sm", classNames == null ? void 0 : classNames.label), htmlFor: id, children: label }) : null,
644
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
645
+ Textarea$1,
646
+ {
647
+ "aria-invalid": ariaInvalid ?? invalid,
648
+ className: classNames == null ? void 0 : classNames.textarea,
649
+ id,
650
+ onChange: handleChange,
651
+ required: requiredFlag,
652
+ rows: rowsValue,
653
+ ...rest
654
+ }
655
+ ),
656
+ invalid ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: cn("text-xs text-destructive", classNames == null ? void 0 : classNames.errorMessage), children: errorMessage }) : description ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: cn("text-xs text-muted-foreground", classNames == null ? void 0 : classNames.description), children: description }) : null
657
+ ] });
658
+ }
659
+ function Select(props) {
660
+ const {
661
+ id: idProp,
662
+ label,
663
+ labelPlacement,
664
+ placeholder,
665
+ description,
666
+ isInvalid,
667
+ errorMessage,
668
+ value,
669
+ onValueChange,
670
+ disabled,
671
+ className,
672
+ classNames,
673
+ children
674
+ } = props;
675
+ const reactId = React.useId();
676
+ const id = idProp ?? reactId;
677
+ const invalid = Boolean(isInvalid || errorMessage);
678
+ const valueString = value === void 0 || value === null ? void 0 : String(value);
679
+ const items = React.useMemo(() => {
680
+ return React.Children.toArray(children).map((child) => {
681
+ if (!React.isValidElement(child)) {
682
+ return null;
683
+ }
684
+ const optionValue = child.props.value ?? child.key;
685
+ if (optionValue === null || optionValue === void 0) {
686
+ return null;
687
+ }
688
+ const disabledFromChild = Boolean(
689
+ child.props.isDisabled || child.props.disabled
690
+ );
691
+ return {
692
+ value: String(optionValue),
693
+ label: child.props.children,
694
+ disabled: disabledFromChild
695
+ };
696
+ }).filter(Boolean);
697
+ }, [children]);
698
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: cn("grid w-full gap-2", classNames == null ? void 0 : classNames.base), children: [
699
+ label && labelPlacement !== "inside" ? /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: cn("text-sm", classNames == null ? void 0 : classNames.label), htmlFor: id, children: label }) : null,
700
+ /* @__PURE__ */ jsxRuntimeExports.jsxs(
701
+ Select$1,
702
+ {
703
+ value: valueString,
704
+ onValueChange: (v) => {
705
+ onValueChange == null ? void 0 : onValueChange(v);
706
+ },
707
+ children: [
708
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
709
+ SelectTrigger,
710
+ {
711
+ "aria-invalid": invalid,
712
+ className: cn(className, classNames == null ? void 0 : classNames.trigger),
713
+ disabled,
714
+ id,
715
+ children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder })
716
+ }
717
+ ),
718
+ /* @__PURE__ */ jsxRuntimeExports.jsx(SelectContent, { className: cn(classNames == null ? void 0 : classNames.content), children: items.map((item) => /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { disabled: item.disabled, value: item.value, children: item.label }, item.value)) })
719
+ ]
720
+ }
721
+ ),
722
+ invalid ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: cn("text-xs text-destructive", classNames == null ? void 0 : classNames.errorMessage), children: errorMessage }) : description ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: cn("text-xs text-muted-foreground", classNames == null ? void 0 : classNames.description), children: description }) : null
723
+ ] });
724
+ }
725
+ function SingleSelect(props) {
726
+ const { value, onValueChange, ...rest } = props;
727
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
728
+ Select,
729
+ {
730
+ ...rest,
731
+ onValueChange: (v) => onValueChange == null ? void 0 : onValueChange(v),
732
+ value
733
+ }
734
+ );
735
+ }
736
+ function Switch(props) {
737
+ const { value, onValueChange, size = "md", className, children, ...rest } = props;
738
+ const checked = Boolean(value);
739
+ const disabled = Boolean(rest.disabled);
740
+ const toggle = () => onValueChange == null ? void 0 : onValueChange(!checked);
741
+ const trackClass = cn(
742
+ "relative inline-flex shrink-0 cursor-pointer items-center rounded-full border border-border transition-colors",
743
+ checked ? "bg-primary" : "bg-muted",
744
+ disabled && "cursor-not-allowed opacity-50",
745
+ size === "sm" && "h-5 w-9",
746
+ size === "md" && "h-6 w-11",
747
+ size === "lg" && "h-7 w-14"
748
+ );
749
+ const thumbClass = cn(
750
+ "pointer-events-none inline-block rounded-full bg-background shadow transition-transform",
751
+ size === "sm" && "ml-0.5 size-4",
752
+ size === "md" && "ml-0.5 size-5",
753
+ size === "lg" && "ml-0.5 size-6",
754
+ checked && size === "sm" && "translate-x-4",
755
+ checked && size === "md" && "translate-x-5",
756
+ checked && size === "lg" && "translate-x-7"
757
+ );
758
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: cn("inline-flex items-center gap-2", className), children: [
759
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
760
+ "button",
761
+ {
762
+ "aria-checked": checked,
763
+ onClick: (e) => {
764
+ e.preventDefault();
765
+ if (disabled) {
766
+ return;
767
+ }
768
+ toggle();
769
+ },
770
+ role: "switch",
771
+ type: "button",
772
+ ...rest,
773
+ className: trackClass,
774
+ children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: thumbClass })
775
+ }
776
+ ),
777
+ children ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm cursor-pointer", children }) : null
778
+ ] });
779
+ }
780
+ function Checkbox(props) {
781
+ const { id: idProp, value, onValueChange, isInvalid, errorMessage, children } = props;
782
+ const reactId = React.useId();
783
+ const id = idProp ?? reactId;
784
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-1", children: [
785
+ /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
786
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
787
+ Checkbox$1,
788
+ {
789
+ "aria-invalid": isInvalid,
790
+ checked: !!value,
791
+ id,
792
+ onCheckedChange: (checked) => {
793
+ onValueChange == null ? void 0 : onValueChange(checked === true);
794
+ }
795
+ }
796
+ ),
797
+ children ? /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-sm", htmlFor: id, children }) : null
798
+ ] }),
799
+ isInvalid && errorMessage ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-destructive", children: errorMessage }) : null
800
+ ] });
801
+ }
802
+ function ColorInput(props) {
803
+ const { value, onValueChange } = props;
804
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
805
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
806
+ "input",
807
+ {
808
+ type: "color",
809
+ value,
810
+ onChange: (e) => onValueChange == null ? void 0 : onValueChange(e.target.value),
811
+ className: "w-10 h-10 rounded border border-border cursor-pointer"
812
+ }
813
+ ),
814
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
815
+ "input",
816
+ {
817
+ type: "text",
818
+ value,
819
+ onChange: (e) => onValueChange == null ? void 0 : onValueChange(e.target.value),
820
+ className: "border border-input rounded-md px-3 py-1.5 w-32"
821
+ }
822
+ )
823
+ ] });
824
+ }
825
+ function Password(props) {
826
+ const { endContent, ...rest } = props;
827
+ const [isVisible, setIsVisible] = React.useState(false);
828
+ const toggleVisibility = () => setIsVisible(!isVisible);
829
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
830
+ Input,
831
+ {
832
+ endContent: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
833
+ endContent,
834
+ /* @__PURE__ */ jsxRuntimeExports.jsx(
835
+ "button",
836
+ {
837
+ "aria-label": isVisible ? "Hide password" : "Show password",
838
+ className: "inline-flex size-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground",
839
+ onClick: toggleVisibility,
840
+ type: "button",
841
+ children: isVisible ? /* @__PURE__ */ jsxRuntimeExports.jsx(EyeClosedIcon, { className: "size-5" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(EyeIcon, { className: "size-5" })
842
+ }
843
+ )
844
+ ] }),
845
+ type: isVisible ? "text" : "password",
846
+ ...rest
847
+ }
848
+ );
849
+ }
850
+ const BaseInputField = bindField(Input, {
851
+ controlType: "text",
852
+ displayDefault: ""
853
+ });
854
+ function InputField(props) {
855
+ const coerce = props.type === "number" ? (raw) => {
856
+ const s = String(raw ?? "").trim();
857
+ if (s === "")
858
+ return void 0;
859
+ const n = Number(s);
860
+ return Number.isNaN(n) ? raw : n;
861
+ } : void 0;
862
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(BaseInputField, { coerce, ...props });
863
+ }
864
+ const TextareaField = bindField(Textarea, {
865
+ controlType: "textarea",
866
+ displayDefault: ""
867
+ });
868
+ const SelectField = bindField(Select, {
869
+ controlType: "select",
870
+ displayDefault: ""
871
+ });
872
+ const SingleSelectField = bindField(
873
+ SingleSelect,
874
+ { controlType: "select", displayDefault: "" }
875
+ );
876
+ const SwitchField = bindField(Switch, {
877
+ controlType: "switch",
878
+ displayDefault: false
879
+ });
880
+ const CheckboxField = bindField(Checkbox, {
881
+ controlType: "checkbox",
882
+ displayDefault: false
883
+ });
884
+ const PasswordField = bindField(Password, {
885
+ controlType: "password",
886
+ displayDefault: ""
887
+ });
888
+ const ColorField = bindField(ColorInput, {
889
+ controlType: "color",
890
+ displayDefault: ""
891
+ });
892
+ function toField(Component, options) {
893
+ const displayDefault = options && "defaultValue" in options ? options.defaultValue : (options == null ? void 0 : options.displayDefault) ?? "";
894
+ return bindField(Component, {
895
+ displayDefault,
896
+ controlType: options == null ? void 0 : options.controlType
897
+ });
898
+ }
899
+ function ObjectField(props) {
900
+ const parentPrefix = useFieldNamePrefix();
901
+ const prefix = joinFieldName(parentPrefix, props.name);
902
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(FieldNamePrefixContext.Provider, { value: prefix, children: props.children });
903
+ }
904
+ function getByPath(obj, path) {
905
+ if (!path)
906
+ return obj;
907
+ return path.split(".").reduce((acc, key) => acc == null ? acc : acc[key], obj);
908
+ }
909
+ function useFormValues() {
910
+ const { form } = useAppFormContext();
911
+ return useStore(form.store, (s) => s.values);
912
+ }
913
+ const useFormValue = useFormValues;
914
+ function useFieldValue(name) {
915
+ const { form } = useAppFormContext();
916
+ const prefix = useFieldNamePrefix();
917
+ const full = joinFieldName(prefix, name);
918
+ return useStore(form.store, (s) => getByPath(s.values, full));
919
+ }
920
+ function useFormModified() {
921
+ const { form } = useAppFormContext();
922
+ const isDefaultValue = useStore(form.store, (s) => s.isDefaultValue);
923
+ const setModified = useCallback(
924
+ (v) => {
925
+ if (!v) {
926
+ commitForm(form);
927
+ }
928
+ },
929
+ [form]
930
+ );
931
+ return { modified: !isDefaultValue, setModified };
932
+ }
933
+ async function validateForm(form) {
934
+ await form.validateAllFields("submit");
935
+ return { ok: !!form.state.isValid, value: form.state.values };
936
+ }
937
+ function useSetFieldValue() {
938
+ const { form } = useAppFormContext();
939
+ const prefix = useFieldNamePrefix();
940
+ return (name, value) => form.setFieldValue(joinFieldName(prefix, name), value);
941
+ }
942
+ export {
943
+ AppForm,
944
+ AppFormContext,
945
+ Checkbox,
946
+ CheckboxField,
947
+ ColorField,
948
+ ColorInput,
949
+ FieldNamePrefixContext,
950
+ Input,
951
+ InputField,
952
+ ObjectField,
953
+ Password,
954
+ PasswordField,
955
+ Select,
956
+ SelectField,
957
+ SingleSelect,
958
+ SingleSelectField,
959
+ SubmitButton,
960
+ Switch,
961
+ SwitchField,
962
+ Textarea,
963
+ TextareaField,
964
+ bindField,
965
+ buildFieldValidators,
966
+ commitForm,
967
+ firstErrorMessage,
968
+ joinFieldName,
969
+ refillForm,
970
+ toField,
971
+ useAppForm,
972
+ useAppFormContext,
973
+ useFieldNamePrefix,
974
+ useFieldValue,
975
+ useFormModified,
976
+ useFormValue,
977
+ useFormValues,
978
+ useMaybeAppFormContext,
979
+ useSetFieldValue,
980
+ useStore2 as useStore,
981
+ validateForm
982
+ };
983
+ //# sourceMappingURL=index.mjs.map