UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

67 lines (66 loc) • 2.71 kB
import { createTanstackEngine } from "./engine/tanstack.mjs"; import { schemaToFormValidator } from "./schema.mjs"; //#region src/base-ui/FormKit/instance.ts const internals = /* @__PURE__ */ new WeakMap(); const getInternals = (form) => { const found = internals.get(form); if (!found) throw new Error("[@lobehub/ui/base-ui/form] form was not created by useForm"); return found; }; const isPlainObject = (value) => { if (typeof value !== "object" || value === null) return false; const proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; }; const leafPaths = (value, prefix = "") => { if (!isPlainObject(value) || prefix && Object.keys(value).length === 0) return prefix ? [prefix] : []; return Object.entries(value).flatMap(([key, child]) => leafPaths(child, prefix ? `${prefix}.${key}` : key)); }; const getIn = (value, path) => path.split(".").reduce((acc, key) => acc == null ? void 0 : acc[key], value); const setIn = (target, path, value) => { const keys = path.split("."); let cursor = target; keys.slice(0, -1).forEach((key) => { if (!isPlainObject(cursor[key])) cursor[key] = {}; cursor = cursor[key]; }); cursor[keys.at(-1)] = value; }; const createFormInstance = ({ initialValues, schema, validateOn }) => { const engine = createTanstackEngine(initialValues); if (schema) engine.setFormValidator(schemaToFormValidator(schema)); const source = (options) => options?.asUser ? "user" : "api"; const form = { getValue: ((name) => engine.getValue(name)), getValues: () => engine.getValues(), isDirty: () => engine.getStatus().dirty, isTouched: (name) => engine.isTouched(name), reset: (values) => engine.reset(values), resetField: (name) => engine.resetField(name), setErrors: (errors) => engine.setErrors(errors), setSchema: (next) => engine.setFormValidator(next ? schemaToFormValidator(next) : void 0), setValue: ((name, value, options) => engine.setValue(name, value, source(options))), setValues: (values, options) => { for (const path of leafPaths(values)) engine.setValue(path, getIn(values, path), source(options)); }, submit: () => engine.submit((values) => internals.get(form)?.onSubmit?.(values)), subscribe: (selector, callback) => { let selected = selector(engine.getValues()); return engine.subscribe(() => { const next = selector(engine.getValues()); if (Object.is(next, selected)) return; selected = next; callback(next); }); }, validate: (names) => engine.validate(names) }; internals.set(form, { engine, validateOn }); return form; }; //#endregion export { createFormInstance, getIn, getInternals, leafPaths, setIn }; //# sourceMappingURL=instance.mjs.map