diff --git a/.changeset/smart-eagles-mix.md b/.changeset/smart-eagles-mix.md new file mode 100644 index 00000000..f27ff4eb --- /dev/null +++ b/.changeset/smart-eagles-mix.md @@ -0,0 +1,5 @@ +--- +'@formwerk/core': patch +--- + +feat: added useFormContext to inject parent forms diff --git a/packages/core/src/useForm/useForm.ts b/packages/core/src/useForm/useForm.ts index a9004c0f..84431812 100644 --- a/packages/core/src/useForm/useForm.ts +++ b/packages/core/src/useForm/useForm.ts @@ -1,7 +1,7 @@ -import { InjectionKey, MaybeRefOrGetter, onMounted, provide, reactive, readonly, Ref, ref } from 'vue'; +import { inject, InjectionKey, MaybeRefOrGetter, onMounted, provide, reactive, readonly, Ref, ref } from 'vue'; import type { StandardSchemaV1 } from '@standard-schema/spec'; import { registerForm } from '@formwerk/devtools'; -import { cloneDeep, useUniqId } from '../utils/common'; +import { cloneDeep, useUniqId, warn } from '../utils/common'; import { FormObject, MaybeAsync, @@ -91,6 +91,8 @@ export interface FormDomProps { // eslint-disable-next-line @typescript-eslint/no-explicit-any export const FormKey: InjectionKey> = Symbol('Formwerk FormKey'); +export const FormContextKey: InjectionKey> = Symbol('Formwerk FormContextKey'); + export function useForm< TSchema extends GenericFormSchema, TInput extends FormObject = StandardSchemaV1.InferInput, @@ -302,6 +304,8 @@ export function useForm< registerForm(form as any); } + provide(FormContextKey, form as any); + return form as typeof baseReturns & FormActions; } @@ -309,3 +313,15 @@ export function useForm< * Just a utility type helper to get the return type of the useForm composable. */ export type FormReturns = ReturnType; + +export function useFormContext() { + const ctx = inject(FormContextKey, null); + + if (__DEV__) { + if (!ctx) { + warn('useFormContext must be used within a Formwerk form or one of its descendants.'); + } + } + + return ctx as FormReturns & FormActions; +}