Skip to content

feat(core): field meta API #1216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 111 additions & 14 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
FieldInfo,
FormApi,
FormAsyncValidateOrFn,
FormState,
FormValidateAsyncFn,
FormValidateFn,
FormValidateOrFn,
Expand Down Expand Up @@ -100,6 +101,7 @@ export type FieldValidateFn<
any,
any,
any,
any,
any
>
}) => unknown
Expand Down Expand Up @@ -183,6 +185,7 @@ export type FieldValidateAsyncFn<
any,
any,
any,
any,
any
>
signal: AbortSignal
Expand Down Expand Up @@ -265,10 +268,39 @@ export type FieldListenerFn<
any,
any,
any,
any,
any
>
}) => void

/**
* @private
*/
export type FieldMetaFn<
TParentData,
TFormOnMount extends undefined | FormValidateOrFn<TParentData>,
TFormOnChange extends undefined | FormValidateOrFn<TParentData>,
TFormOnChangeAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnBlur extends undefined | FormValidateOrFn<TParentData>,
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnServer extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object,
> = (
props: FormState<
TParentData,
TFormOnMount,
TFormOnChange,
TFormOnChangeAsync,
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer
>,
) => TFieldMetaExtension

export interface FieldValidators<
TParentData,
TName extends DeepKeys<TParentData>,
Expand Down Expand Up @@ -383,6 +415,15 @@ export interface FieldOptions<
TOnSubmitAsync extends
| undefined
| FieldAsyncValidateOrFn<TParentData, TName, TData>,
TFormOnMount extends undefined | FormValidateOrFn<TParentData>,
TFormOnChange extends undefined | FormValidateOrFn<TParentData>,
TFormOnChangeAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnBlur extends undefined | FormValidateOrFn<TParentData>,
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnServer extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object,
> {
/**
* The field name. The type will be `DeepKeys<TParentData>` to ensure your name is a deep key of the parent dataset.
Expand Down Expand Up @@ -436,13 +477,30 @@ export interface FieldOptions<
any,
any,
any,
any
any,
TFieldMetaExtension
>
>
/**
* A list of listeners which attach to the corresponding events
*/
listeners?: FieldListeners<TParentData, TName, TData>

/**
* A list of listeners which attach to the corresponding events
*/
meta?: FieldMetaFn<
TParentData,
TFormOnMount,
TFormOnChange,
TFormOnChangeAsync,
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TFieldMetaExtension
>
/**
* Disable the `flat(1)` operation on `field.errors`. This is useful if you want to keep the error structure as is. Not suggested for most use-cases.
*/
Expand Down Expand Up @@ -492,6 +550,7 @@ export interface FieldApiOptions<
| FormAsyncValidateOrFn<TParentData>,
in out TFormOnServer extends undefined | FormAsyncValidateOrFn<TParentData>,
in out TParentSubmitMeta,
in out TFieldMetaExtension extends object,
> extends FieldOptions<
TParentData,
TName,
Expand All @@ -502,7 +561,16 @@ export interface FieldApiOptions<
TOnBlur,
TOnBlurAsync,
TOnSubmit,
TOnSubmitAsync
TOnSubmitAsync,
TFormOnMount,
TFormOnChange,
TFormOnChangeAsync,
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TFieldMetaExtension
> {
form: FormApi<
TParentData,
Expand Down Expand Up @@ -542,6 +610,7 @@ export type FieldMetaBase<
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object = {},
> = {
/**
* A flag indicating whether the field has been touched.
Expand Down Expand Up @@ -575,7 +644,7 @@ export type FieldMetaBase<
* A flag indicating whether the field is currently being validated.
*/
isValidating: boolean
}
} & TFieldMetaExtension

export type AnyFieldMetaBase = FieldMetaBase<
any,
Expand All @@ -594,6 +663,7 @@ export type AnyFieldMetaBase = FieldMetaBase<
any,
any,
any,
any,
any
>

Expand Down Expand Up @@ -621,6 +691,7 @@ export type FieldMetaDerived<
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object = {},
> = {
/**
* An array of errors related to the field value.
Expand Down Expand Up @@ -660,7 +731,7 @@ export type FieldMetaDerived<
* A flag indicating whether the field's current value is the default value
*/
isDefaultValue: boolean
}
} & TFieldMetaExtension

export type AnyFieldMetaDerived = FieldMetaDerived<
any,
Expand All @@ -679,6 +750,7 @@ export type AnyFieldMetaDerived = FieldMetaDerived<
any,
any,
any,
any,
any
>

Expand Down Expand Up @@ -709,6 +781,7 @@ export type FieldMeta<
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object = {},
> = FieldMetaBase<
TParentData,
TName,
Expand All @@ -726,7 +799,8 @@ export type FieldMeta<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
> &
FieldMetaDerived<
TParentData,
Expand All @@ -745,7 +819,8 @@ export type FieldMeta<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
>

export type AnyFieldMeta = FieldMeta<
Expand All @@ -765,6 +840,7 @@ export type AnyFieldMeta = FieldMeta<
any,
any,
any,
any,
any
>

Expand Down Expand Up @@ -795,6 +871,7 @@ export type FieldState<
TFormOnBlurAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFormOnSubmit extends undefined | FormValidateOrFn<TParentData>,
TFormOnSubmitAsync extends undefined | FormAsyncValidateOrFn<TParentData>,
TFieldMetaExtension extends object,
> = {
/**
* The current value of the field.
Expand All @@ -820,7 +897,8 @@ export type FieldState<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
>
}

Expand Down Expand Up @@ -848,6 +926,7 @@ export type AnyFieldApi = FieldApi<
any,
any,
any,
any,
any
>

Expand Down Expand Up @@ -900,6 +979,7 @@ export class FieldApi<
| FormAsyncValidateOrFn<TParentData>,
in out TFormOnServer extends undefined | FormAsyncValidateOrFn<TParentData>,
in out TParentSubmitMeta,
in out TFieldMetaExtension extends object,
> {
/**
* A reference to the form API instance.
Expand All @@ -923,7 +1003,8 @@ export class FieldApi<
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TParentSubmitMeta
TParentSubmitMeta,
TFieldMetaExtension
>['form']
/**
* The field name.
Expand Down Expand Up @@ -951,7 +1032,8 @@ export class FieldApi<
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TParentSubmitMeta
TParentSubmitMeta,
TFieldMetaExtension
> = {} as any
/**
* The field state store.
Expand All @@ -974,7 +1056,8 @@ export class FieldApi<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
>
>
/**
Expand Down Expand Up @@ -1012,7 +1095,8 @@ export class FieldApi<
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TParentSubmitMeta
TParentSubmitMeta,
TFieldMetaExtension
>,
) {
this.form = opts.form as never
Expand Down Expand Up @@ -1052,7 +1136,8 @@ export class FieldApi<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
>
},
})
Expand Down Expand Up @@ -1136,6 +1221,11 @@ export class FieldApi<
fieldApi: this,
})

this.setMeta((prev) => ({
...prev,
...this.options.meta?.(this.form.state),
}))

return cleanup
}

Expand All @@ -1162,7 +1252,8 @@ export class FieldApi<
TFormOnSubmit,
TFormOnSubmitAsync,
TFormOnServer,
TParentSubmitMeta
TParentSubmitMeta,
TFieldMetaExtension
>,
) => {
this.options = opts as never
Expand Down Expand Up @@ -1211,6 +1302,11 @@ export class FieldApi<

this.triggerOnChangeListener()

this.setMeta((prev) => ({
...prev,
...this.options.meta?.(this.form.state),
}))

this.validate('change')
}

Expand Down Expand Up @@ -1238,7 +1334,8 @@ export class FieldApi<
TFormOnBlur,
TFormOnBlurAsync,
TFormOnSubmit,
TFormOnSubmitAsync
TFormOnSubmitAsync,
TFieldMetaExtension
>
>,
) => this.form.setFieldMeta(this.name, updater)
Expand Down
1 change: 1 addition & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ export type FieldInfo<TFormData> = {
any,
any,
any,
any,
any
> | null
/**
Expand Down
23 changes: 23 additions & 0 deletions packages/form-core/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2457,4 +2457,27 @@ describe('field api', () => {

expect(field.getMeta().errorSourceMap.onChange).toEqual('field')
})

it('should have user defined meta and react to value change', () => {
const form = new FormApi({
defaultValues: {
name: 'Stegosaurus',
},
})
form.mount()

const nameField = new FieldApi({
form,
name: 'name',
meta: ({ values }) => ({
dinosaur: values.name === 'Stegosaurus' ? 'dino' : 'notDino',
}),
})

nameField.mount()
expect(nameField.getMeta().dinosaur).toEqual('dino')

nameField.handleChange('Cat')
expect(nameField.getMeta().dinosaur).toEqual('notDino')
})
Comment on lines +2461 to +2482
Copy link
Contributor Author

@harry-whorlow harry-whorlow Mar 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fulopkovacs

so this works nicely, but the issue is if I do something like form.state.fieldMeta.name I can't infer the user defined meta.

Do you have any suggestions on how to get it to form? I've tried a few things but can't get it to work. 🙃

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ugh, this does seem to be complex problem. I spent about 2 hours thinking about it, but couldn't come up with a solution.

Here's what I see now

Up until this point we had no need to infer the type of a field's meta, because it was the same for all of them (isDirty, errorMap, etc.). Because of this, it was enough to create a generic AnyFieldMeta type that we could use in the methods of FormApi, like getFieldMeta:

  getFieldMeta = <TField extends DeepKeys<TFormData>>(
    field: TField,
  ): AnyFieldMeta | undefined => {
    return this.state.fieldMeta[field]
  }

Compare this to the getFieldValue method, where the return type depends on the specific field whose value we're looking for:

  getFieldValue = <TField extends DeepKeys<TFormData>>(
    field: TField,
  ): DeepValue<TFormData, TField> => getBy(this.state.values, field)

DeepValue receives the name of the field (TField) as a type argument and uses it to get the type of the returned value from the form's data (TFormData).

I think DeepValue has access to the type of the field's value, because you initiate the FormApi class with it:

    const form = new FormApi({
      defaultValues: {
        name: 'Stegosaurus',
      } // this form can have only 1 field whose name must be `"name"` 
    })
    
    const formWithAge = new FormApi({
      defaultValues: {
        name: 'Stegosaurus',
      } as {name: string, age?: number} // this form can have an `age` field too
    })
    
    const hobbyField = new FieldApi({
      form,
      name: 'hobby', // throws an error, because it's not a valid field name
    })

How to solve this problem?

In order to have a proper FormFieldMeta type instead of a generic AnyFieldMeta type in the FormApi class, we need to define the field's meta types during the initialization of the FormApi class.

So it could look something like this:

    const formWithAge = new FormApi({
      defaultValues: {
        name: 'Stegosaurus',
      },
      fieldMeta: {
       name: ({ values }) => ({
        dinosaur: values.name === 'Stegosaurus' ? 'dino' : 'notDino',
      })
    })

Ofc, it would be better to only pass down the types of the field's custom meta properties, and define those later.

    const formWithAge = new FormApi({
      defaultValues: {
        name: 'Stegosaurus',
      },
      fieldMeta: {} as {name: {dinosaur: 'dino' | 'notDino'})
    })

Honestly, this is not the best possible API we could have, but the best one I could come up with at 0:37 🤣...

If the FormApi is aware of the possible meta fields mapped to field names, then we can have a type like FormFieldMeta<TFormFieldMetaData, TField>, where TFormFieldMetaData is the type of fieldMeta in the example above, and TField is the name of the field.

Bad news

I'll be away from the keyboard for 4 days from today (maybe I can be still reached today, but definitely not from tomorrow). 😢 You probably have more questions/comments, feel free to write them, and I'll answer when I'm back!

Copy link
Contributor Author

@harry-whorlow harry-whorlow Mar 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fulopkovacs I was thinking the same thing, I think there was a small dwindling light of hope that perhaps it was just my inability to code. Maybe I've just sold myself short...

Given your suggested answer would it also make sense to have a baseMetaExtension too? I ask this because of #715 where a proposed solution was to store a Ref in the meta. Which makes sense to me, but having to add the Ref meta to every field, especially if you have a lot of fields could result in lots of boilerplate.

I'll have a poke around in the mean time, enjoy the time away from the keyboard 🤟

Copy link
Contributor

@fulopkovacs fulopkovacs Mar 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I've just sold myself short...

You probably did! 🤣

Given you're suggested answer would it also make sense to have a baseMetaExtension too?

🤔 Hmmm, do you image the API look like this 👇 ?

    const formWithAge = new FormApi({
      defaultValues: {
        name: 'Stegosaurus',
        age: 0,
      },
      fieldMeta: {
          name: ({ values }) => ({
            dinosaur: values.name === 'Stegosaurus' ? 'dino' : 'notDino',
          }),
       },
      baseMetaExtension: {
         ref: null as null | HTMLInputElement
      }
    })

After reading the discussion you mentioned (#715), I understand why we would need something like this, and I support it, but I still have a weird feeling about it for some reason. Maybe I'm just not fond of the name baseMetaExtension. What do you think about something like defaultCustomFieldMeta? From what I understand now, we would have to assign default values to the shared custom field meta properties when we create the form, so a name with default in it sounds fitting, plus it looks similar to defaultValues.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fulopkovacs sounds good to me, if it's cool with you I'll spin the defaultCustomFieldMeta into its own separate PR and get that out as it seems #715 is asked every other week.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new PR would depend on this one, right? In that case, we can create a new PR, but we could also just put some info about these changes into the description of this PR, and reference it whenever someone asks about this issue. I prefer the latter, but feel free to go with the new PR if you want to.

But even before that, could you bring up this proposed API (defaultCustomFieldMeta or whatever we'll go with) in the Discord too? I'm fine with it, but maybe other maintainers have different ideas!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fulopkovacs actually... you've got a good point it would. we shall keep it as one then... and yes I will drop it into the discord.

})
Loading