Skip to content
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

feat(core): field meta API #1216

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

harry-whorlow
Copy link
Contributor

reopened from #1125

Field.meta

From issue #1111 and discussion #709, this pr Introduces the Field.meta api to allow for extensible and easily accessible meta data to the field component.

example api

<form.Field
  name="foo"
  meta={({ values }) => ({
    disabled: values.someOtherField == null,
    ...
  })}
>
  {(field, meta) => 
  <Comp
    disabled={meta.disabled}
    ... >
  </Comp>

Tasks

  • Meta available to Field.children
  • MetaFn available to form.Field
  • Tests
  • LGTM 🚀

@harry-whorlow harry-whorlow changed the title Meta api 2 feat(core): field meta API Mar 4, 2025
Copy link

nx-cloud bot commented Mar 4, 2025

View your CI Pipeline Execution ↗ for commit 4964162.

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ❌ Failed 1m 45s View ↗
nx run-many --target=build --exclude=examples/** ❌ Failed 3s View ↗

☁️ Nx Cloud last updated this comment at 2025-03-04 10:32:39 UTC

@harry-whorlow harry-whorlow mentioned this pull request Mar 4, 2025
4 tasks
Comment on lines +1854 to +1875
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')
})
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants