Repository navigation
Minor Changes
-
#190
ce5885dThanks @tristendillon! - Lists moved into a newarrays()plugin. It brings item keys that follow the items and the array commandspush,insert,removeandmove.Items,useItemsandcreateItemstake only array handles of forms that have it. A form with no lists no longer ships any of this, which saves about 550 B brotli. A form with a list pays about 150 B more than before.form.Itemsandscope.Itemsare gone. ImportItemsfrom the adapter and pass it the array's handle:// Before <form.Items name="tasks">{(task, index) => ...}</form.Items> // After import { Items } from "@lunarhue/forms-react"; // or "@lunarhue/forms-solid" <Items handle={form.root.at("tasks")}>{(task, index) => ...}</Items>
To migrate, add
arrays()to every form that renders or changes a list:import { arrays } from "@lunarhue/forms-react/plugins"; // or "@lunarhue/forms-solid/plugins" const forms = createForms({ plugins: [arrays()] });
You can also put it in a single definition's
plugins. Without it, passing an array handle toItems,useItemsorcreateItems, or calling a command, is a type error that says "Add arrays() to this form's plugins". Code without types that calls a command throwsarrays:missingin development, and the command does nothing in production.A component that takes an array field and renders or changes it says so in its type, as
ArrayHandle<string[], typeof arrays>. It then fits only forms witharrays(). A plugin whose setup calls the commands should listarraysinrequires.PluginContext.storeis now typed with the names of the plugin'srequires, so such a plugin gets the commands in its types.A form without
arrays()can still hold an array and replace it whole withsetValue. Its rows are then keyed by position (k0,k1, ...), so a row's state, such as touched, belongs to the position. IfsetValueshortens the list and a later write lengthens it again, the rows past the old end come back under their old keys with their old state. Witharrays()they stay gone and new rows get new keys, as before. -
#203
5638f90Thanks @tristendillon! -errorsByKind(handle), a new core function the adapters re-export, returns a field's validation errors grouped by the kind of validator that set them:{ schema, form, field }.schemaholds the definition's schema errors,formthe errors fromvalidate.form, andfieldthose fromvalidate.fieldsandregisterValidator, in the order they were added. A thrown validator's error goes under its validator's kind. Errors fromsetErrorsaren't included, since the snapshot'suserErrorshas them. It is a read, not a subscription, and a standalone function rather than a store method, so a form that never calls it doesn't ship it. The newErrorsByKind<E>andValidatorKindtypes name the result and its keys. -
#200
bcc99bbThanks @tristendillon! - Errors fromsetErrorsnow make a field invalid, and core can list every invalid field.invalidFields(store), a new core function, returns every field with an error, in form order, as{ field, name, errors }. The root comes first, with name"".subscribeInvalid(store, listener)fires when that list may change. Both are standalone functions rather than store methods, so a form that never lists its errors doesn't ship them.useInvalidFields(form)in React andcreateInvalidFields(form)in Solid follow the list, so an error summary is a few lines. The newInvalidField<E>type names an entry.The field snapshot has a new
userErrorsmember, the errorssetErrorsput there. They come last inerrors, so the validation errors areerrors.slice(0, errors.length - userErrors.length).Breaking changes:
snapshot.invalidis true for a field with onlysetErrorserrors. Before, it counted validation errors only. Code that readinvalidto mean "a validator failed" should checkerrors.length > userErrors.lengthinstead. The form'svalidhasn't changed, so server errors still don't block the next submit.store.firstInvalid()andstore.disabledInvalid()now include fields with onlysetErrorserrors. After a server refuses a save,firstInvalid()returns the field it named, so the app can focus it. The adapters still don't move focus afteronSubmitsets errors, because that submit succeeded.DisabledInvalid<E>is now an alias ofInvalidField<E>. Its shape is unchanged.
-
#230
23b8befThanks @tristendillon! - A definition's validators go through two functions:validate.fieldstakesfieldValidators({...})andvalidate.formtakesformValidator(check). Core and both adapters export them. A form that uses neither doesn't ship the code that walks a validator tree or reads anErrorMap.validate.onis gone: wrap a check invalidateOn(check, timing), or setvalidateoncreateFormsfor every form.// Before validate: { on: "input", fields: { username: checkName }, form: checkOrder, } // After validate: { fields: fieldValidators({ username: validateOn(checkName, "input") }), form: formValidator(validateOn(checkOrder, "input")), }
Written inline in
define, both take the form's value type, with a schema plugin'sDraftwhere there is one. Defined on their own, they need it as a type argument:fieldValidators<Order>({...}). A schema passed toformValidatoralone types the set by its input. -
#284
c8a59a2Thanks @tristendillon! -definein/minitakes a function of per-form options, as the main entry's does:forms.define((options: { q: string }) => ({ defaultValues: { q: options.q } })). The function runs once per store.createStore(options, instance?)anduseForm(definition, options, settings?)take the options first, and a plain config still takes none.useFormreads the options on the first render only. Mini'sdefinetype parameters are now<V, S, O, R>, soOsits where it does on the main entry. -
#262
2ee8b18Thanks @tristendillon! - New experimental entries,@lunarhue/forms-core/miniand@lunarhue/forms-react/mini, for small forms such as a search box or a login. A search form on/miniis about 2.6 kB brotli with React external, against about 11 kB on the main entry. Expect breaking changes in minor releases while it is experimental./minikeepscreateForms().define(),useForm,form.Form,form.Field,form.State,inputProps,fieldValidators, Standard Schema validation,setErrors,resetand thetransform,textandobserveparts, pinned at a field withforms.fieldset(...parts).at(name). Every member has the same name and call as in the main entry, and its types are a subset of the main entry's, so a form moves up by changing the import. Validators run sync, on blur and on submit, then on each change once the field was blurred, has an error, or the form was submitted.It leaves out async validation, plugins, arrays, object fields in
form.Field, dirty state, meta, native mode and devtools. Passing a plugin or a plugin's part to itsdefineis a type error.By default a
/miniform wakes every listener on each change, which is the least code.createForms({ subscribe: perField() })wakes only the fields that changed, for about 220 B more. The main entry takes the same option and ignores it, since it always wakes per field. -
#182
d6b2008Thanks @tristendillon! -dirtyandchanges()exist in the types only on forms withdirty(). Readingdirtyfrom a form or field snapshot, fromuseField,useFormState, aField,form.Stateor the Solid readers, or callingstore.changes(), is a type error without it, and so is givingequals. The snapshots still holddirty: falseat runtime. In developmentchanges()withoutdirty()now throwsdirty:missinginstead of loggingdirty:untracked, and in production it returns an empty list.Stores and snapshots take the installed plugin names as a new last type parameter. Handles and the adapters' field types take the plugins by factory, before the error type. A component that reads
dirtyfrom its field types it asFieldApi<string, typeof dirty>and then fits only forms withdirty().AnyFormStore<E, "dirty">is a store of any form that has it.One
Plugin<A, N, M, F, S>type replacesPlugin,HookPlugin,SchemaPlugin,DirtyPlugin,AnyPluginandAnyHookPlugin. UsePluginsfor a list of any plugins.defineSchemaPlugin(adapter)is gone. WritedefinePlugin({ name, schema: adapter }).A plugin with field or form meta must give
initialMetaorinitialFormMeta, so itsmetaandformMetareaders never returnundefined. Meta with no sensible start putsundefinedin its type and starts frominitialMeta: undefined.IfDirty,HasDirtyandEqualsNeedsDirtyare replaced by oneNeedstype.HasSchemaPlugin,PluginSchemas,MetaSource,WhenandPluginDefinitionare no longer exported.PluginNamesandPluginsOfare new exports.FormStore<V, FormError>no longer fits a parameter typedFormStore<V, unknown>. Make such a helper generic over the error type. -
#256
b96e3b5Thanks @tristendillon! -definePluginreturns a factory instead of a plugin. Call it to get the plugin for a form'splugins, the way the built-ins work:const collapseSpaces = definePlugin({ name: "collapseSpaces", setup: () => ({ beforeWrite: (write) => (typeof write.value === "string" ? write.value.replace(/ {2,}/g, " ") : write.value) }), }); createForms({ plugins: [collapseSpaces()] });
A second parameter on
setuptypes the factory's options, andinitialValuegets them too. Without one, the factory takes no arguments.The meta readers moved from the plugin to the factory:
history.formMeta(state)andupload.meta(field), with no instance to keep around.part(plugin, config)from/pluginsmakes a plugin's parts, withconfigtyped from theparthook's second parameter, so hand-written parts aren't needed.Partnames the plugin by its factory too:Part<typeof limit, string>, where it used to take the name. The part's value type comes from where it goes. To fix it in a helper, annotate the return type or pass both type arguments:const limited = (max: number): Part<typeof limit, string> => part(limit, max); const limited = (max: number) => part<typeof limit, string>(limit, max);
A part can also bring hooks of its own and need no plugin.
part<V>(hooks)takes the hooks, or a function of the part's context that returns them, typed for the valueV. Three helpers cover the common cases:transform<V>((value, write) => ...)changes each write at its path, and the value there when it attaches. Returnrefuseto stop the write.text<V>(display, afterInput?)sets the text a text input shows.observe<V>((value, ctx) => ...)runs when it attaches and after each batch that wrote at its path. Write throughctx.write.
const trimmed = transform<string>((value) => value.trim()); const slug = observe<Post>((post, ctx) => ctx.write(() => ctx.at("slug").setValue(slugify(post.title))));
These parts run after every plugin's hooks. A store sets up their hooks from the parts it knows when it is made: the parts after a definition's config, and those on the field types and fieldsets of its
createForms. A fieldset made after the store, on a store whose plugins have no hooks, throwsparts:latein development.defineFieldandfieldsettake lists of parts too, so a helper can return several.Masks moved to a new
/textentry, on core and both adapters, and themask()plugin is gone.masked,cleaned,displayed,digits,upperandreplaceTextcome from@lunarhue/forms-react/textor@lunarhue/forms-solid/text, and a masked field type needs nothing inplugins:// Before import { digits, mask, masked } from "@lunarhue/forms-react/plugins"; const forms = createForms({ plugins: [mask()], fields: { PhoneField } }); // After import { digits, masked } from "@lunarhue/forms-react/text"; const forms = createForms({ fields: { PhoneField } });
requirestakes factories, asrequires: () => [dirty], and also orders the hooks: a plugin's run after the ones it requires.afteris gone. Withrequires: () => [dirty],ctx.storehaschanges()and thedirtyflags.Components and fieldsets name plugins by factory, not by name:
// Before function ChangedMark({ field }: { field: FieldApi<string, FormError, "dirty"> }) {} const Billing = forms.fieldset<Billing, "rules">(ruled({ ... })); // After function ChangedMark({ field }: { field: FieldApi<string, typeof dirty> }) {} const Billing = forms.fieldset<Billing, typeof rules>(ruled({ ... }));
FieldApi's parameters are now<T, P, E>: the plugins come before the error type. Name several plugins as a union,typeof dirty | typeof history. The handle types follow the same order:FieldHandle,LeafHandle,ObjectHandle,ArrayHandleandItemHandleare<V, P, E>, as inArrayHandle<Tag[], typeof arrays>, andAnyFieldHandleis<P, E>. A fieldset's type written out isFieldset<V, P, E, F, I>, withPthe plugins its parts need andIthe shared plugins. The name-keyed forms that inference produces areNamedFieldHandle,NamedArrayHandle,NamedFieldsetand so on.Renames for plugin authors:
- The
attachhook ispart, and its context hasvalue()for the value at the part's path andat(name)for a field below it. - The plugin-level
initialisinitialValue. - The
onSubmithook isbeforeSubmit. ctx.attachments(path)isctx.parts(path), and theAttachmenttype isAttachedPart.- The part hook
editisafterInput. It anddisplayare part hooks only. - The part
initialhook is gone. A part'sbeforeWriteruns once on attach withcause: "attach", which does the same job.
persist(key, storage)is nowpersist(key)orpersist({ key, storage }). -
#287
d49c9a6Thanks @tristendillon! - Plugins and parts get anonBlur(path)hook. It runs on every blur through a field'shandleBlur, not only the first one that setstouched, so a plugin can save or clean up a field each time the user leaves it. It runs inside the blur's batch, after the field is touched and its blur validators ran, and writes it makes throughctx.writeland in that batch.setTouched(true)doesn't run it. A part gets only the blurs at or below its path. Forms without hook plugins or parts don't grow. -
#182
337d9d1Thanks @tristendillon! - Plugins that work per field now take parts. A part is a plugin's config for one place: a field type, a fieldset or a form. The plugin goes in the form's plugins once, with no config, and its parts go where they apply. Using a field type or fieldset whose parts need a plugin the form lacks is a type error, such asAdd rules() to this form's plugins: AddressField uses it. Without types the store throwsplugins:missingin development.defineField(component, ...parts)from the adapters makes a field type. Register it infieldslike a component. Its parts attach at each field it renders, the first time it renders it.forms.fieldset(schema, ...parts)andforms.fieldset<V>(...parts)take parts for each field the fieldset is used on, andforms.define(config, ...parts)takes parts for the whole form.PhoneField.at(name)andBilling.at(name)pin a field type's or fieldset's parts at one field, fordefine, so they attach when the store is made.Fieldset scopes now carry the plugin names their parts need, so the field components a fieldset renders are checked against them.
To migrate a mask, put
masked(...)from/texton the field type that renders the field. It needs no plugin:// Before const contact = forms.define({ defaultValues, plugins: [mask({ phone: { clean: digits, display: formatPhone } })] }); // After import { digits, masked } from "@lunarhue/forms-react/text"; const PhoneField = defineField(PhoneInput, masked({ clean: digits, display: formatPhone })); const forms = createForms({ fields: { PhoneField } }); const contact = forms.define({ defaultValues });
A wildcard such as
"lines.*.sku"becomes a field type on the row's component. A field that may not render before its value matters, such as one on a later step, takesPhoneField.at("phone")after the config.mask'snameoption is gone: a field type can carry twomaskedparts, which clean in order, and the first display wins.To migrate rules, install
rules()and passruled(...)after the config. It takes the value type from the definition, so it needs no type argument. Readhiddenwithrules.meta(field):// Before const orderRules = rules<Order>({ street: (value) => ({ disabled: value.pickup }) }); const order = forms.define({ defaultValues, plugins: [orderRules] }); orderRules.meta(field).hidden; // After const order = forms.define({ defaultValues }, ruled({ street: (value) => ({ disabled: value.pickup }) })); rules.meta(field).hidden;
Rules on a fieldset get the fieldset's value:
forms.fieldset(Billing, ruled({ ... })). To write rules apart from a definition, name the type, asruled<Order>({ ... }).A plugin list can hold
false,nullorundefined, as inplugins: [rules(), dev && devtools()]. The form skips them, and the types count a plugin that may be missing as not installed.For plugin authors:
definePlugintakespart(ctx, config), which runs once per path a part attaches at and returns hooks for that path. Its hooks get writes at or above the path walked down to it, and a refuse there refuses the whole write.part(limit, config)makes the parts, withconfigtyped from that parameter:part(limit, { max: 20 }).requires: () => [dirty]names plugins a plugin needs. The form must install them, or it is a type error. The plugin's hooks run after theirs, andctx.pluginsholds their APIs.ctx.installedlists the store's plugins in hook order, andctx.parts(path)the parts attached at a path and above.- A part's
beforeWriteruns once on the value at its path when it attaches, withcause: "attach". That write makes no record. A value it changes moves the baseline with it while the field isn't dirty, and a reset to the initial values keeps it clean. FieldDisplaymeta is gone. ReturndisplayandafterInputhooks frompartinstead.
New exports:
PartandPartsfrom core, anddefineFieldandFieldTypefrom the adapters. Core also exportsattachfor the adapters, andMetaHolder,PluginMembers,NestedandDefinePartsbecause declarations name them. Those are internal. -
#166
cf1b97eThanks @tristendillon! - Every first-class plugin now comes from onepluginsentry, and the per-plugin entries are gone. Your bundler still drops the plugins you don't import, so bundles don't grow. Change your imports:Before After @lunarhue/forms-core/plugins/bind@lunarhue/forms-core/plugins@lunarhue/forms-core/plugins/dirty@lunarhue/forms-core/plugins@lunarhue/forms-core/plugins/history@lunarhue/forms-core/plugins@lunarhue/forms-core/plugins/mask@lunarhue/forms-core/text, which hasmaskedand nomask()plugin@lunarhue/forms-core/plugins/persist@lunarhue/forms-core/plugins@lunarhue/forms-core/plugins/rebase@lunarhue/forms-core/plugins@lunarhue/forms-core/plugins/rules@lunarhue/forms-core/plugins@lunarhue/forms-react/plugins/<name>@lunarhue/forms-react/plugins@lunarhue/forms-solid/plugins/<name>@lunarhue/forms-solid/pluginsImports from two plugins merge into one line, such as
import { dirty, rebase } from "@lunarhue/forms-react/plugins".@lunarhue/forms-core/plugins/testingstays where it is, so test helpers can't reach an app bundle by accident.The React and Solid packages now carry core's declarations in their own, and their main entries re-export the plugin types, such as
HistoryApiandRulesPlugin. Declarations that tsc writes for your code name only the adapter, so they type-check under pnpm or Bun's isolated installs, where your project can't see@lunarhue/forms-core. Each adapter ships three to six bundled.d.tsfiles in place of one per source file.@lunarhue/forms-bindimportsbindfrom the new entry, so it needs this version of core. -
#210
77c06c5Thanks @tristendillon! -fieldOf(element)now works in production for apps that opt in. CalltrackElements()before the form renders, and from then on the adapters' refs record which field each element belongs to. Elements mounted before that call aren't recorded. Development needs no call, as before.trackElements(listener)also takes a listener that gets every element a ref records or forgets, with its field handle, or its store for a<form>element, and the adapter's name. React before 19 doesn't say which element left, so those removals come late, the next time the adapter looks at that field's elements.Without the call, the adapters cost about 30 to 40 B more, brotli, for the slot the refs report to.
-
#282
5ec1188Thanks @tristendillon! - A submit whoseonSubmitleaves errors on the form withsetErrorsnow ends"invalid", not"succeeded". That is how the docs say to handle a server that refuses the save, and nothing was saved, so it no longer reads as a success.baselineOnSubmit()leaves the refused values dirty instead of taking them as the baseline, and React and Solid move focus to the first field the server refused, as they do after a failed validation.Validation errors don't count, so a field the user breaks while the save runs doesn't turn a real save into a refusal. Errors cleared before
onSubmitreturns don't count either.When upgrading:
- Code that set errors in
onSubmitand then checked for"succeeded", or read a message from itsresult, now sees{ status: "invalid" }with no result. Show the refusal from the errors you set, such as the root's errors for aformmessage. - A plugin's
onSubmittedgets the submitted value asinputfor such a submit, though its status is"invalid". It is still undefined when validation or a plugin stopped the submit. - To focus the refused field you no longer need to call
store.firstInvalid()after the submit. PassfocusOnInvalid: falseto keep focus where it was.
- Code that set errors in
-
#283
72b0b6bThanks @tristendillon! -store.reset({ values })sets new values and makes them the baseline in one step, and clears touched, edited and error state asreset()does. Use it after a save or a refetch when the user's edits should go: withdirty()the form is clean afterwards, and a laterreset()comes back to these values. It works in/minitoo. -
#204
315ff3dThanks @tristendillon! - Handles are strict in their value type. A component that asks forArrayHandle<Tag[]>no longer takes the handle of aWideTag[]with more keys, since itspushandsetValuewould store items without them. The same holds for object handles and forHandleOf<typeof fieldset>. A handle of a form with more plugins still fits one that asks for fewer.To keep a reusable component that takes wider values, make it generic. A fieldset component passes its type parameter as the second argument of
HandleOf:// Before function AddressFields(props: { field: HandleOf<typeof AddressFieldset> }) { ... } // After function AddressFields<A extends Address>(props: { field: HandleOf<typeof AddressFieldset, A> }) { ... }
A list component is generic in its item type and takes a function that makes a full item, since it can't build the keys it doesn't know:
function TagList<T extends Tag>(props: { tags: ArrayHandle<T[], FormError, "arrays">; create: (base: Tag) => T }) { // props.tags.push(props.create({ id: 1, name: "" })) }
Inside such a component,
field.at("city")reads as its type in the constraint, so it fits aFieldApi<string>component. Some things still need help:useInputPropsandcreateInputPropsread the value type from the handle's own type. Type the child first:const city: FieldHandle<string> = field.at("city").- A merge write on a generic object,
field.setValue({ city: "Oslo" }), doesn't type-check. Write the child:field.at("city").setValue("Oslo"). - A child that is an object itself stays generic and needs a generic component of its own.
- A generic handle passes only to props with the same plugin list. Type props as
HandleOf<typeof fieldset, A>so they share the fieldset's.
Type changes that come with it:
setValueon object and array handles, andpushandinserton array handles, are properties instead of methods.FieldHandle<V>distributes over a genericV's constraint, which is how the children of a generic handle resolve. For concrete types it gives the same handles as before.fieldset.scope(handle)infers the handle's type, andScopeandScopeMemberstake the root's value type as a last, optional parameter.HandleOftakes an optional second parameter, the value type. It defaults to the fieldset's.- In Solid, a
FieldTypeis checked exactly against the component type it was made with.
-
#200
17da5a8Thanks @tristendillon! - Errors for a field name the form doesn't have now land on the root. Before,setErrors({ fields: { nope: ... } })and a form validator'sfieldsput them on a path nothing renders, so the user never saw them. A server that renames a field no longer makes its errors disappear. They show with the form's errors, after theformones, and development warns with the new codefield:unknown, once per name.A name counts as a field when each step exists in the form's value: a key its object has, or an index its array has. A key the value lacks still counts while something renders or validates a field there, such as an optional field with an input. Names under a missing object count too, since the value can't say what it would hold.
store.pathOf(name)is new. It returns the stable path of a dotted name, such asrows.0.title, orundefinedwhen no field has it. Use it to route errors for unknown names somewhere else, such as a toast:const unknown = Object.keys(serverErrors).filter((name) => store.pathOf(name) === undefined);
store.fieldAt(path)uses the same rule, so it now returnsundefinedfor a key the value lacks while nothing renders or validates it. Code that calledfieldAtto write a field that isn't in the value yet should walk the handles instead, asstore.root.at("nickname"), which still makes a handle for any key.Errors for a name that went to a hidden path before now land on the root. Two effects to check when upgrading:
- A form whose root errors aren't rendered can now hide these errors there instead. Render the root's errors, as
submit:unseenshows. - An error that only some name reached now sits on the root, so
field.peek().errorsat that name is empty and the root's list is longer.
- A form whose root errors aren't rendered can now hide these errors there instead. Render the root's errors, as
-
#166
eaf3086Thanks @tristendillon! - Validation is built into core again. A form with no plugins can takevalidateon its definition and avalidateprop on a field, andfield.validate()andregisterValidatorwork instead of throwing.validation()is gone, along with theplugins/validationentry of core, React and Solid. Drop it from yourpluginslist.defineSchemaPluginmoved to@lunarhue/forms-core/plugins. Schema plugins such asvalibot()andzod()now only give a schema's default values. A schema whose library has no plugin installed still needs completedefaultValues, and leaving them out is a type error that namesNoSchemaPlugin.Removed types:
IfValidation,HasValidation,ValidationNotInstalled,SchemaNeedsValidation,ValidationPlugin, andValidatePropForin the adapters.ScopeandFieldsetin the adapters lose their plugin type parameter, and so do the bound component types under them. Thevalidation:definitionandvalidation:validatorerrors are gone.The main entry of core grows by about 1.9 kB brotli, since it now carries the runner.
-
#273
8919befThanks @tristendillon! - Newpipe(...checks)runs validators one after another on the same value and stops at the first that returns an error. Put cheap checks before a server check, and the server check runs only once they pass:username: pipe( (name) => (name.length < 3 ? { message: "Use at least 3 characters." } : undefined), debounced(async (name, { signal }) => ((await isTaken(name, signal)) ? { message: "That name is taken." } : undefined), 400), ),
While its checks answer at once, so does the pipe. A failing sync check never starts the debounced one after it, so the field doesn't show
validating. Submit andvalidate()skip a debounce inside a pipe, even one the pipe hasn't reached yet. The checks can be field validators, form validators, Standard Schemas or wrapped checks, and a schema's issues still go throughmapError. Wrap the pipe invalidateOnto set its timing. -
#230
5533930Thanks @tristendillon! - Validator timing moves from an options object to three wrappers:debounced(check, ms),validateOn(check, "input" | "blur" | "submit")andrecheckOnSubmit(check). Each takes a validator function or a Standard Schema, returns a check that goes anywhere a bare one does, and nests in any order. The{ validate, debounce, on, recheckOnSubmit }object is gone, along with theValidatorOptionsandFormValidatorOptionstypes.// Before username: { validate: checkName, debounce: 400, on: "input", recheckOnSubmit: true } // After username: recheckOnSubmit(validateOn(debounced(checkName, 400), "input"))
The same goes for
validate.form, thevalidateprop,useValidator,createValidatorandregisterValidator.A wrapped schema is a function, typed as
WrappedSchema<Input>. Written inline in a JSXvalidateprop it no longer registers again on every render, which a new schema object did.debouncedon a schema hands the validator'ssignalthrough, so a newer run ends the wait. -
#166
5dd368cThanks @tristendillon! - The adapters no longer export a type for each function's signature. Each one only named the type of a function you can already import, so usetypeofon the function instead.Removed from
@lunarhue/forms-react:CreateForms,UseForm,UseFormContext,UseDisabledErrors,UseField,UseFormState,UseItems,UseValidator,UseInputProps,UseFieldRefandErrorId. Writetypeof useFormforUseForm, and the same for the others.Removed from
@lunarhue/forms-solid:CreateForms,CreateForm,UseFormContext,CreateDisabledErrors,CreateField,CreateItems,CreateValidator,CreateInputPropsandFieldRef. Writetypeof createFormforCreateForm, and the same for the others.DefineFieldsetis gone too. Its type is nowSolidForms<P, E, F>["fieldset"].To get at part of a signature, use
Parameters<typeof x>orReturnType<typeof x>, or the named type it is built from, such asFormsOptionsfor the options ofcreateForms. For a function with overloads these utilities read the last overload only.The doc comments moved from the removed types to the functions, so your editor shows the same text on hover.
-
#199
7c6ceefThanks @tristendillon! - NewelementsOf(handle)andfieldOf(element)exports.elementsOflists the elements a field's ref got that are still in the document, in document order.fieldOfgoes the other way and returns the field's handle, the same objectstore.fieldAt(path)gives. It doesn't look at ancestors, so walkparentElementorevent.composedPath()from an element inside a custom input.fieldOfworks in development only for now and returnsundefinedin production, where the map behind it isn't built. Production bundles that don't import these stay the same size. -
#166
558a887Thanks @tristendillon! -inputPropsis a function you import instead of a method on the field object. A form that binds its fields by hand no longer ships the props builder.// Before <input {...field.inputProps({ kind: "number" })} /> // After import { inputProps } from "@lunarhue/forms-react"; // or "@lunarhue/forms-solid" <input {...inputProps(field, { kind: "number" })} />
Field objects now carry the pieces
inputPropsis built from, so a component library's input, checkbox or select can bind to a field directly:text,setText(text, from?),setNumberText(text, empty?),handleBlurandref.setTextkeeps a mask's caret in place, andsetNumberTextkeeps text such as1.while the user types. Whenrefgets a native input, textarea or select that shows something other than the field's state, as after a browser restores a form on reload, it puts the field's state back.Removed types:
InputPropsMethodin React andInputPropsOfin Solid.useInputPropsandcreateInputPropsstill take a field handle. -
#285
3392deeThanks @tristendillon! - NewisFocused(handle)export. It is true while focus is on one of the field's elements or inside one, such as the input inside a custom component registered withuseFieldReforfieldRef. It reads the same elements aselementsOf, so it works in production with notrackElements()call, and it returns false on the server.Use it in a
rebase()resolve to keep the field the user is in, even before they type:form.plugins.rebase(form.root, fresh, (leaf) => { const field = form.store.fieldAt(leaf.path); return leaf.edited || (field !== undefined && isFocused(field)) ? "keep" : "take"; });
-
#270
c731974Thanks @tristendillon! -createForms({ fields })in@lunarhue/forms-react/miniregisters plain field components, as the main entry does:<form.TextField name="email" label="Email" />checks the name and value type and passes the component's own props through. A component written against mini'sFieldApiworks unchanged on the main entry.defineFieldentries still need the main entry. It adds about 60 B brotli to/mini. -
#204
c349432Thanks @tristendillon! - A registered component typedFieldApi<string | undefined>now takes required string fields as well as optional ones, from a type given todefineor from a schema. Before, it took only the optional ones, and aFieldApi<string>component took only the required ones, so no text component could render both. Checkboxes work the same way withFieldApi<boolean | undefined>, andnullin the type works likeundefined.A
FieldApi<string>component still rejects optional fields, so itsfield.valuestays astring.To render optional fields with an existing component, add
undefinedto its type and handle it where the component readsfield.value.inputPropsalready shows it as an empty input or an unticked checkbox.// Before: <form.TextField name="nick" /> didn't compile for `nick?: string` function TextField(props: { field: FieldApi<string>; label: string }) { ... } // After: takes `name: string` and `nick?: string` function TextField(props: { field: FieldApi<string | undefined>; label: string }) { ... }
The type checker doesn't stop such a component from writing
undefinedinto a required field, the same gap aFieldApi<number>component has.In a component generic over its value, pass an optional child by
name. Its handle fromfield.at("nick")doesn't fit yet. -
#230
67cd4a3Thanks @tristendillon! -inputPropsno longer takes akind. Each kind of element has its own function, and each one type-checks only on a field of the value type it writes:Function Element Field type inputProps(field, { type }?)text-like <input>string textareaProps(field)<textarea>string selectProps(field, { empty }?)<select>string numberProps(field, { empty }?)<input type="number">number rangeProps(field)<input type="range">number checkboxProps(field)<input type="checkbox">boolean checkboxGroupProps(field, value)one box of a group array of strings or numbers radioProps(field, value)one radio string, number or boolean A form ships only the functions it calls, so a form with text inputs only is about 530 B brotli smaller than before.
emptyis still required when the field's type has noundefined.// Before <input {...inputProps(field, { kind: "number", empty: 0 })} /> <input {...inputProps(field, { kind: "radio", value: "pro" })} /> <input {...inputProps(field, { kind: "checkbox", value: "urgent" })} /> // After <input {...numberProps(field, { empty: 0 })} /> <input {...radioProps(field, "pro")} /> <input {...checkboxGroupProps(field, "urgent")} />
useInputPropsis gone.useField(handle)now returns the field object, the same oneform.Fieldgives its children, so pass that to a props function.useField(handle, select, isEqual?)is unchanged.// Before <input {...useInputProps(handle, { kind: "checkbox" })} /> // After <input {...checkboxProps(useField(handle))} />
field.setNumberTextis gone, andfield.textno longer holds the text typed in a number input. Bind a number input by hand withnumberPieces(field, { empty }?), which returns that text with its ownsetTextandhandleBlur:// Before <Input value={field.text} onValueChange={(text) => field.setNumberText(text)} onBlur={field.handleBlur} /> // After const number = numberPieces(field); <Input value={number.text} onValueChange={(text) => number.setText(text)} onBlur={number.handleBlur} />
The types
TextareaOptions,NumberInputOptions,CheckboxInputOptions,CheckboxGroupOptions,RadioInputOptionsandSelectOptionsare gone.EmptyOption<V>names the{ empty }option,RangeInputPropsthe props of a range input, andNumberPieceswhatnumberPiecesreturns.NumberInputPropsis for number inputs only. -
#230
64c01e2Thanks @tristendillon! - React 18 is now the default build. It calls React's ownuseSyncExternalStoreanduseIdand leaves out the fallbacks for React 16.8 and 17, which saves about 200 B brotli. The fallbacks moved to a legacy build that an app picks with the@lunarhue/react-legacyresolve condition. On React 16.8 or 17 without it, a development build throwsreact:legacywhen the adapter loads.Apps on React 18 or 19 change nothing. Apps on React 16.8 or 17 add the condition to their bundler:
// Vite resolve: { conditions: ["@lunarhue/react-legacy", ...defaultClientConditions] }, ssr: { resolve: { conditions: ["@lunarhue/react-legacy", ...defaultServerConditions], externalConditions: ["@lunarhue/react-legacy"], }, }, // webpack or Rspack resolve: { conditionNames: ["@lunarhue/react-legacy", "..."] } // esbuild. Custom conditions drop the default `module`, so list it again. conditions: ["@lunarhue/react-legacy", "module"] // Next with webpack webpack(config) { config.resolve.conditionNames = ["@lunarhue/react-legacy", ...(config.resolve.conditionNames ?? ["..."])]; return config; } // Next with Turbopack, which has no conditions setting turbopack: { resolveAlias: { "#lunarhue/react": "@lunarhue/forms-react/legacy" } }
A server that loads the adapter from
node_moduleswithout bundling it runs Node withNODE_OPTIONS=--conditions=@lunarhue/react-legacy. -
#230
5c3dbf8Thanks @tristendillon! -inputPropsno longer takes akind, andcreateInputPropsis gone. Each kind of element has its own function, the same set as in@lunarhue/forms-react, and each one type-checks only on a field of the value type it writes. The same holds for./v1.Function Element Field type inputProps(field, { type, describedBy }?)text-like <input>string textareaProps(field, { describedBy }?)<textarea>string selectProps(field, { empty, describedBy }?)<select>string numberProps(field, { empty, describedBy }?)<input type="number">number rangeProps(field, { describedBy }?)<input type="range">number checkboxProps(field, { describedBy }?)<input type="checkbox">boolean checkboxGroupProps(field, value, { describedBy }?)one box of a group array of strings or numbers radioProps(field, value, { describedBy }?)one radio string, number or boolean describedByworks as before: its ids go inaria-describedbyahead of the error id.emptyis still required when the field's type has noundefined.selectPropsnow takes it too, and writes it when the user picks an option whose value is"". The props still read the field through getters, so each one updates the element on its own.// Before <input {...inputProps(field, { kind: "number", empty: 0 })} /> <input {...inputProps(field, { kind: "radio", value: "pro", describedBy: "plan-hint" })} /> <input {...inputProps(field, { kind: "checkbox", value: "urgent" })} /> <input {...inputProps(field, { kind: "number", type: "range" })} /> // After <input {...numberProps(field, { empty: 0 })} /> <input {...radioProps(field, "pro", { describedBy: "plan-hint" })} /> <input {...checkboxGroupProps(field, "urgent")} /> <input {...rangeProps(field)} />
For a handle, make the field object with
createField(handle)and pass that:// Before <input {...createInputProps(handle, { kind: "checkbox" })} /> // After <input {...checkboxProps(createField(handle))} />
field.setNumberTextis gone, andfield.textno longer holds the text typed in a number input.field.handleBlurno longer drops that text either. Bind a number input by hand withnumberPieces(field, { empty }?), which returns that text with its ownsetTextandhandleBlur:// Before <input value={field.text} onInput={(event) => field.setNumberText(event.currentTarget.value)} onBlur={field.handleBlur} /> // After const number = numberPieces(field); <input value={number.text} onInput={(event) => number.setText(event.currentTarget.value)} onBlur={number.handleBlur} />
A range input now writes
valueAsNumber, and puts the slider back while the field is read-only.inputPropsandtextareaPropsnow take a field of a union of string literals, as in React.The types
CheckableProps,ControlProps,InputOptions,TextareaOptions,NumberInputOptions,NumberInputType,CheckboxOptions,CheckboxGroupOptions,RadioOptionsandSelectOptionsare gone.BaseInputPropstakes the place ofControlProps.CheckboxInputProps,CheckboxGroupInputPropsandRadioInputPropsreplaceCheckableProps, andRangeInputPropsnames the props of a range input.DescribedByOptionnames the{ describedBy }option,EmptyOption<V>the{ empty }option, andNumberPieceswhatnumberPiecesreturns.NumberInputPropsis for number inputs only. -
#192
f20e7baThanks @tristendillon! -@lunarhue/forms-solid/v1is a working Solid 1 adapter forsolid-js1.8 and later. It exports the same functions and types as the main entry and is built from the same source, so moving a form between Solid 1 and Solid 2 means changing the import.import { createForm, createForms, inputProps } from "@lunarhue/forms-solid/v1";
./v1doesn't need@solidjs/web, which is an optional peer. Solid 1 applies writes at once, while Solid 2 batches them until the next flush, so code that counts renders or effect runs can see more of them on Solid 1.signal()from@lunarhue/forms-bindneeds Solid 2. On Solid 1, bind a store withbind()from@lunarhue/forms-solid/plugins. -
#288
42c6cbcThanks @tristendillon! -zustand()with a slice handsupdatethe store's state as a second argument, so a slice inside a map can keep its sibling keys:update: (summary, state) => ({ summaries: { ...state.summaries, [key]: summary } }). A one-argumentupdateworks as before.A new
isEqualoption says when two slices match,Object.isby default. Pass it whenselectbuilds a new object each time, such as({ verdict, body }) => ({ verdict, body }), and store changes to other fields no longer write into the form. -
#210
d15b1afThanks @tristendillon! - New package@lunarhue/forms-devtools, with thedevtools()plugin andsyncDevtools(). Each form with the plugin registers with the page while it is mounted, and the plugin logs its last 500 writes and its submissions.enableddecides whether the panel shows, and the panel loads as a chunk of its own the first time a form'senabledreads true. The panel is empty for now.dev && devtools()leaves all of it out of production. -
#210
4a5bf86Thanks @tristendillon! - The devtools panel can inspect fields on the page. With the inspect button on, or while Alt is held, a card shows the facts of the field under the pointer, and a click pins it and selects the field's row. Hovering a row of the Fields tab outlines that field's elements. -
#210
8e1ea20Thanks @tristendillon! - The devtools panel has a Log tab, with the form's writes and submissions newest first, each write's cause and submissions a reset aborted, and a Plugins tab, with the form's plugins in hook order and each one's form meta and API. -
#210
b79a909Thanks @tristendillon! - The devtools panel. It docks in a corner of the page and lists the forms on the page by their storeid. Pick mode outlines each form so you can click the one to inspect. The Fields tab shows the value tree with each field's flags, and a selected field's value against its baseline, display text, errors by source, attached plugins and last write. The panel is a chunk of its own with Preact bundled in, and renders in a shadow root. It reads the forms on each animation frame while it's open and never subscribes to a store.
Patch Changes
-
#166
c4e1b11Thanks @tristendillon! - Thedeferredandidledelivery code moved out of the plugin host and now comes withdefinePlugin. The built-in plugins that only usesync, which arebind,rules,rebaseandbaselineOnSubmit, no longer bring it, so a form that installs only those is smaller. Plugins made withdefinePluginwork as before. -
#291
28e77e2Thanks @tristendillon! -pipe()now clears a previous step's error as soon as a newer run passes that step, instead of keeping the stale error visible while a later async ordebouncedstep is still running. When the same step re-runs (such as a server check on a new value), its existing error stays until the new check settles. -
#230
fc15100Thanks @tristendillon! - Trim a few code paths in the store and the React ref handling.stats()now returns zero counts in a production build, since only tests and leak checks read it. Nothing else changes for apps, so there's nothing to migrate. -
#186
2a68c4dThanks @tristendillon! - Production builds no longer carry the errors page link. Error messages there give the code, and the link stays in development messages, as in core. -
#286
57a2f97Thanks @tristendillon! - The doc comments oninputProps, the field'srefanduseFieldRefnow say how to pass a field's ref under React Compiler.ref={field.ref}makes the Compiler treat the whole field object as a ref and skip the component, so take it out first withconst { ref } = field, or useuseFieldRef(handle). -
#166
a6b0e06Thanks @tristendillon! - The adapters stop exporting the types they only use to build other types. None of them shows up in a declaration TypeScript infers for your code, so a.d.tsyou emit doesn't change. If you imported one by name, use the public type it feeds instead, such asScope,FieldApior the input props types, or copy the definition into your code.Removed from
@lunarhue/forms-react:AcceptedHandle,AcceptedValues,ArrayHandleLike,BoundFieldComponents,CheckedFields,ChoiceFieldOf,EmptyOption,FieldByHandle,FieldByName,FieldComponentType,FieldPropOf,FormStateSource,InputHandleLike,InputOptionsFor,InputPropsFor,ItemsByHandle,ItemsByName,NameFitting,NameFittingChoice,NoOptionsArgs,ObjectHandleLike,PropsOf,ReservedName,ReservedProp,UseFormArgs,ValidatorHandleLike.Removed from
@lunarhue/forms-solid:AnyComponent,ArrayHandleLike,BoundFieldComponents,CheckedFields,ChoiceFieldOf,ChoicePath,ComponentHandle,CreateFormArgs,FieldCommands,FieldErrorOf,FieldTypes,FieldValueOf,FitPath,FitsComponent,IsBoolean,IsChoice,IsNumber,IsOption,IsOptionList,IsText,OwnProps,PropsOf,ReservedName,ReservedProp,ValidatorHandleLike.React keeps
OwnPropsOf, because the inferred type of a bound field component names it. -
#197
06ffb0bThanks @tristendillon! - Moving a row inItemskeeps focus on the row's input. Solid 1, and Solid 2 in browsers withoutmoveBeforesuch as Safari, take a moved row out of the document for a moment, which blurred the input.Itemsnow focuses it again once the move is done. -
#198
d9a1e25Thanks @tristendillon! - The schema and bind declarations bundle core's types, as the adapters' do. A project that installs an adapter withvalibot(),zod(),zustand()orsignal()under a strict install (pnpm, Bun isolated) no longer gets TS2307 for@lunarhue/forms-corein the declarations it emits. Each entry also exports the type its plugin returns,PluginorBindPlugin. Both packages' declarations grow by about 73 kB. -
#292
d11751dThanks @tristendillon! - Fixzustand()overload inference when combining slice options (select/update/isEqual) with shared options (incoming/initial), sostate,value,previous, andnextare inferred without explicit type arguments. -
#229
f2ca593Thanks @tristendillon! - The devtools panel is closer to its design. A row's flags are icons, and hovering one shows what it means and its detail: the errors for invalid, baseline against value for dirty, the last write for edited. The field card shows only value, baseline and the field's writes with their causes. A row's pointer button scrolls the field's element into view. A filter box narrows the Fields tab by name, with a toggle for just the fields with errors. The bar shows how the last submission went, such assubmit failed. -
#254
53ebbe8Thanks @tristendillon! - The devtools panel renders nothing at 640px wide and below. Phones get no dock, no bottom sheet, no form outlines and no inspecting. Narrowing the window to that width unmounts the panel, and widening it brings the panel back. -
#228
8144131Thanks @tristendillon! - The devtools panel matches its design: while it's on, every form has a dashed outline with its name on a tag, and clicking the tag selects the form, so the pick button is gone. Inspecting stays on after a click, and hovering a label inspects the field it labels. A form with anidthe adapter made up shows asform 1,form 2and so on. Menus open from their buttons, the clear button replaces the chevron in the form chip, the panel is as wide as the dock, scrollbars are thin and dark, and every icon button has a tooltip. -
#233
62a6829Thanks @tristendillon! - The devtools panel's styles are Tailwind utilities, compiled into the panel chunk at build time. The panel looks and works as before. -
#233
ade1903Thanks @tristendillon! - The devtools panel's source is TSX on Preact's JSX runtime, and its icons come from Lucide. It works as before. -
#233
72d73b8Thanks @tristendillon! - The devtools panel no longer shows the last submission in its bar. A row's flags keep fixed places, a click anywhere on a row selects its field, and long values keep their start and end in the cards instead of widening them. The on-page field card drops the form's name and stays open while the pointer crosses from a label to its input. Outlines sit under the page's dialogs and drawers, and a hidden form, such as one in an inactive tab, no longer leaves an outline in the corner of the window.