Skip to content

Commit

Permalink
feat(core): field meta API
Browse files Browse the repository at this point in the history
  • Loading branch information
Harry Whorlow committed Jan 22, 2025
1 parent cf165af commit 2dd8d44
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import {
standardSchemaValidator,
} from './standardSchemaValidator'
import { getAsyncValidatorArray, getBy, getSyncValidatorArray } from './utils'
import type { FieldInfo, FieldsErrorMapFromValidator, FormApi } from './FormApi'
import type {
FieldInfo,
FieldsErrorMapFromValidator,
FormApi,
FormState,
} from './FormApi'
import type { StandardSchemaV1 } from './standardSchemaValidator'
import type {
UpdateMetaOptions,
Expand Down Expand Up @@ -116,6 +121,13 @@ export type FieldListenerFn<
fieldApi: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>
}) => void

/**
* @private
*/
export type FieldMetaFn<TFormData, TMetaExtension extends object> = (
props: FormState<TFormData>,
) => FieldMetaExtension<TMetaExtension>

export interface FieldValidators<
TParentData,
TName extends DeepKeys<TParentData>,
Expand Down Expand Up @@ -285,6 +297,7 @@ export interface FieldListeners<
export interface FieldOptions<
TParentData,
TName extends DeepKeys<TParentData>,
TMetaExtension extends object,
TFieldValidator extends
| Validator<DeepValue<TParentData, TName>, unknown>
| undefined = undefined,
Expand Down Expand Up @@ -337,6 +350,7 @@ export interface FieldOptions<
TFormValidator,
TData
>
meta?: FieldMetaFn<FormData, TMetaExtension>
}

/**
Expand Down Expand Up @@ -396,10 +410,15 @@ export type FieldMetaDerived = {
isPristine: boolean
}

export type FieldMetaExtension<TMetaExtension extends object = {}> =
TMetaExtension

/**
* An object type representing the metadata of a field in a form.
*/
export type FieldMeta = FieldMetaBase & FieldMetaDerived
export type FieldMeta<TMetaExtension extends object = {}> = FieldMetaBase &
FieldMetaDerived &
FieldMetaExtension<TMetaExtension>

/**
* An object type representing the state of a field.
Expand Down Expand Up @@ -597,6 +616,11 @@ export class FieldApi<
fieldApi: this,
})

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

return cleanup
}

Expand Down Expand Up @@ -661,6 +685,8 @@ export class FieldApi<

getMeta = () => this.store.state.meta

meta = this.store.state.meta

/**
* Sets the field metadata.
*/
Expand Down

0 comments on commit 2dd8d44

Please sign in to comment.