Skip to content

Commit

Permalink
feat: add useFormContext to inject typed forms closes #143
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Mar 2, 2025
1 parent bb01448 commit 38a039d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-eagles-mix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@formwerk/core': patch
---

feat: added useFormContext to inject parent forms
20 changes: 18 additions & 2 deletions packages/core/src/useForm/useForm.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -91,6 +91,8 @@ export interface FormDomProps {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const FormKey: InjectionKey<FormContext<any>> = Symbol('Formwerk FormKey');

export const FormContextKey: InjectionKey<FormReturns & FormActions<any, any>> = Symbol('Formwerk FormContextKey');

Check warning on line 94 in packages/core/src/useForm/useForm.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 94 in packages/core/src/useForm/useForm.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

export function useForm<
TSchema extends GenericFormSchema,
TInput extends FormObject = StandardSchemaV1.InferInput<TSchema>,
Expand Down Expand Up @@ -302,10 +304,24 @@ export function useForm<
registerForm(form as any);
}

provide(FormContextKey, form as any);

Check warning on line 307 in packages/core/src/useForm/useForm.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

return form as typeof baseReturns & FormActions<TInput, TOutput>;
}

/**
* Just a utility type helper to get the return type of the useForm composable.
*/
export type FormReturns = ReturnType<typeof useForm>;

export function useFormContext<TInput extends FormObject = FormObject, TOutput extends FormObject = TInput>() {
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<TInput, TOutput>;
}

0 comments on commit 38a039d

Please sign in to comment.