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

Field groups #4554

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/pages/api/composition-helpers.mdx
Expand Up @@ -2,7 +2,7 @@
layout: ../../layouts/PageLayout.astro
title: Composition Helpers
description: Various composable functions to compose validation logic into your components
order: 9
order: 10
---

import DocTip from '@/components/DocTip.vue';
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/api/configuration.mdx
Expand Up @@ -2,7 +2,7 @@
layout: ../../layouts/PageLayout.astro
title: Configuration
description: VeeValidate Global Config Reference
order: 8
order: 9
---

import DocTip from '@/components/DocTip.vue';
Expand Down
71 changes: 71 additions & 0 deletions docs/src/pages/api/field-group.mdx
@@ -0,0 +1,71 @@
---
layout: ../../layouts/PageLayout.astro
title: FieldGroup
description: API reference for the Field Group component
menuTitle: '<FieldGroup />'
order: 5
---

import CodeTitle from '@/components/CodeTitle.vue';
import DocBadge from '@/components/DocBadge.vue';

# FieldGroup <DocBadge title="v4.7" />

The `<FieldGroup />` component is used to provide state of group of fields. It is a renderless component, meaning it doesn't render anything of its own.

```vue-html
<Form>
<FieldGroup v-slot="{ meta }">
<Field name="addressField" type="text" />
<Field name="addressField2" type="text" />

Is address group valid ? {{ meta.valid }}
</FieldGroup>
<button>Submit</button>
</Form>
```

It can be nested which means there can be `FieldGroup` inside `FieldGroup` (like on example):

```vue-html
<Form>
<FieldGroup v-slot="{ meta }">
<Field name="firstName" type="text" />
<FieldGroup v-slot="{ meta: addressMeta }">
<Field name="addressField" type="text" />
<Field name="addressField2" type="text" />

Is address group valid ? {{ addressMeta.valid }}
</FieldGroup>
Is form group valid ? {{ meta.valid }} // will be true only when `firstName` and address fields are valid
</FieldGroup>
<button>Submit</button>
</Form>
```

## API Reference

### Props
### Props

| Prop | Type | Required/Default | Description |
| :-------------------- | :----------------------------- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| checkChildFieldGroups | `boolean` | `true` | Determines if the field group's final state will also check nested field groups |

### Slots

#### default

The default slot gives you access to the following props:

<CodeTitle level="4">

`meta: FieldGroupMeta`

</CodeTitle>
This is a **read-only** property which gives access to aggregated state of fields nested inside the `FormGroup` component.
```

### Ref

Ref gives access to the same `meta: FieldGroupMeta` value as slot.
2 changes: 1 addition & 1 deletion docs/src/pages/api/use-field-array.mdx
Expand Up @@ -3,7 +3,7 @@ layout: ../../layouts/PageLayout.astro
title: useFieldArray
description: API reference for the useFieldArray composition API function
menuTitle: useFieldArray()
order: 7
order: 8
---

import DocBadge from '@/components/DocBadge.vue';
Expand Down
50 changes: 50 additions & 0 deletions docs/src/pages/api/use-field-group.mdx
@@ -0,0 +1,50 @@
---
layout: ../../layouts/PageLayout.astro
title: useFieldGroup
description: API reference for the useFieldGroup composition API function
menuTitle: 'useFieldGroup()'
order: 5
---

import CodeTitle from '@/components/CodeTitle.vue';
import DocBadge from '@/components/DocBadge.vue';

# useFieldGroup <DocBadge title="v4.7" />

`useFieldGroup` composable is used to provide state of group of fields. It finds all fields created in the context of component and aggregates their state.

```vue
<template>
<Form>
<input v-model="value" />
<input v-model="value2" />
<button>Submit</button>
</Form>
</template>
<script setup>
import { useField, useFieldGroup } from 'vee-validate';

const { meta } = useFieldGroup();
const { value, errorMessage } = useField('name', inputValue => !!inputValue);
const { value: value2, errorMessage } = useField('name2', inputValue => !!inputValue);
</script>
```

## API Reference

### Props

| Prop | Type | Required/Default | Description |
| :-------------------- | :----------------------------- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| checkChildFieldGroups | `boolean` | `true` | Determines if the field group's final state will also check nested field groups |

### Slots
### Composable API

The following sections documents each available property on the `useFieldGroup` composable.

<CodeTitle level="4">
`meta: FieldGroupMeta`
</CodeTitle>

Contains useful information/flags about the field status, should be treated as **read only**.
2 changes: 1 addition & 1 deletion docs/src/pages/api/use-field.mdx
Expand Up @@ -3,7 +3,7 @@ layout: ../../layouts/PageLayout.astro
title: useField
description: API reference for the useField composition API function
menuTitle: useField()
order: 5
order: 6
---

import DocTip from '@/components/DocTip.vue';
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/api/use-form.mdx
Expand Up @@ -3,7 +3,7 @@ layout: ../../layouts/PageLayout.astro
title: useForm
description: API reference for the useForm composition API function
menuTitle: useForm()
order: 6
order: 7
---

import DocTip from '@/components/DocTip.vue';
Expand Down
22 changes: 12 additions & 10 deletions packages/vee-validate/src/Field.ts
@@ -1,19 +1,19 @@
import {
h,
defineComponent,
toRef,
SetupContext,
resolveDynamicComponent,
computed,
defineComponent,
h,
PropType,
VNode,
resolveDynamicComponent,
SetupContext,
toRef,
UnwrapRef,
VNode,
} from 'vue';
import { getConfig } from './config';
import { RuleExpression, useField } from './useField';
import { normalizeChildren, hasCheckedAttr, shouldHaveValueBinding, isPropPresent } from './utils';
import { hasCheckedAttr, isPropPresent, normalizeChildren, shouldHaveValueBinding } from './utils';
import { IS_ABSENT } from './symbols';
import { FieldMeta, InputType } from './types';
import { FieldExposedContext, FieldMeta, InputType } from './types';
import { FieldContext } from '.';
import { isCallable } from '../../shared';

Expand Down Expand Up @@ -245,7 +245,7 @@ const FieldImpl = /** #__PURE__ */ defineComponent({
};
}

ctx.expose({
const context: FieldExposedContext = {
value,
meta,
errors,
Expand All @@ -255,7 +255,9 @@ const FieldImpl = /** #__PURE__ */ defineComponent({
reset: resetField,
validate: validateField,
handleChange,
});
};

ctx.expose(context);

return () => {
const tag = resolveDynamicComponent(resolveTag(props, ctx)) as string;
Expand Down
43 changes: 43 additions & 0 deletions packages/vee-validate/src/FieldGroup.ts
@@ -0,0 +1,43 @@
import { defineComponent, UnwrapRef, VNode } from 'vue';
import { FieldGroupContext, FieldGroupMeta } from './types';
import { normalizeChildren } from './utils';
import { useFieldGroup } from './useFieldGroup';

const FieldGroupImpl = /** #__PURE__ */ defineComponent({
name: 'FieldGroup',
inheritAttrs: false,
props: {
checkChildFieldGroups: {
type: Boolean,
default: false,
},
},
setup(props: any, ctx: any) {
const { meta } = useFieldGroup(() => props.withChildFieldGroups);

ctx.expose({
meta,
});

function slotProps() {
return {
meta,
};
}

return () => {
const children = normalizeChildren(undefined, ctx, slotProps);

return children;
};
},
});

export const FieldGroup = FieldGroupImpl as typeof FieldGroupImpl & {
new (): {
meta: FieldGroupMeta;
$slots: {
default: (arg: UnwrapRef<FieldGroupContext>) => VNode[];
};
};
};
2 changes: 2 additions & 0 deletions packages/vee-validate/src/index.ts
Expand Up @@ -3,12 +3,14 @@ export { defineRule } from './defineRule';
export { configure } from './config';
export { normalizeRules, isNotNestedPath, cleanupNonNestedPath } from './utils';
export { Field } from './Field';
export { FieldGroup } from './FieldGroup';
export { Form } from './Form';
export { FieldArray } from './FieldArray';
export { ErrorMessage } from './ErrorMessage';
export { useField, FieldOptions, RuleExpression } from './useField';
export { useForm, FormOptions } from './useForm';
export { useFieldArray } from './useFieldArray';
export { useFieldGroup } from './useFieldGroup';
export * from './types';
export { useResetForm } from './useResetForm';
export { useIsFieldDirty } from './useIsFieldDirty';
Expand Down
4 changes: 3 additions & 1 deletion packages/vee-validate/src/symbols.ts
@@ -1,8 +1,10 @@
import { InjectionKey } from 'vue';
import { PrivateFormContext, PrivateFieldContext } from './types';
import { PrivateFormContext, PrivateFieldContext, PrivateFieldGroupContext } from './types';

export const FormContextKey: InjectionKey<PrivateFormContext> = Symbol('vee-validate-form');

export const FieldContextKey: InjectionKey<PrivateFieldContext<unknown>> = Symbol('vee-validate-field-instance');

export const FieldGroupContextKey: InjectionKey<PrivateFieldGroupContext> = Symbol('vee-validate-field-group');

export const IS_ABSENT = Symbol('Default empty value');
41 changes: 41 additions & 0 deletions packages/vee-validate/src/types/forms.ts
Expand Up @@ -163,6 +163,47 @@ export interface PrivateFieldContext<TValue = unknown> {

export type FieldContext<TValue = unknown> = Omit<PrivateFieldContext<TValue>, 'id' | 'instances'>;

export interface FieldExposedContext<TValue = unknown> {
value: FieldContext<TValue>['value'];
meta: FieldContext<TValue>['meta'];
errors: FieldContext<TValue>['errors'];
errorMessage: FieldContext<TValue>['errorMessage'];
setErrors: FieldContext<TValue>['setErrors'];
setTouched: FieldContext<TValue>['setTouched'];
reset: FieldContext<TValue>['resetField'];
validate: FieldContext<TValue>['validate'];
handleChange: FieldContext<TValue>['handleChange'];
}

export interface FieldGroupMeta {
touched: boolean;
dirty: boolean;
valid: boolean;
validated: boolean;
pending: boolean;
}

export interface FieldGroupContext {
meta: FieldGroupMeta;
}

export interface FieldContextForFieldGroup<TValue = unknown> {
value: FieldContext<TValue>['value'];
meta: FieldContext<TValue>['meta'];
errors: FieldContext<TValue>['errors'];
errorMessage: FieldContext<TValue>['errorMessage'];
}

export interface FieldGroupContextForParent {
fields: Ref<FieldContextForFieldGroup[]>;
meta: MaybeRefOrGetter<FieldGroupMeta>;
}

export interface PrivateFieldGroupContext {
fields: Ref<FieldContextForFieldGroup[]>;
groups: Ref<FieldGroupContextForParent[]>;
}

export type GenericValidateFunction<TValue = unknown> = (
value: TValue,
ctx: FieldValidationMetaInfo,
Expand Down
26 changes: 25 additions & 1 deletion packages/vee-validate/src/useField.ts
Expand Up @@ -12,6 +12,7 @@ import {
MaybeRef,
MaybeRefOrGetter,
unref,
markRaw,
} from 'vue';
import { klona as deepCopy } from 'klona/full';
import { validate as validateValue } from './validate';
Expand All @@ -27,6 +28,7 @@ import {
PrivateFormContext,
YupSchema,
InputType,
FieldContextForFieldGroup,
} from './types';
import {
normalizeRules,
Expand All @@ -43,7 +45,7 @@ import {
isTypedSchema,
} from './utils';
import { isCallable, normalizeFormPath } from '../../shared';
import { FieldContextKey, FormContextKey, IS_ABSENT } from './symbols';
import { FieldContextKey, FieldGroupContextKey, FormContextKey, IS_ABSENT } from './symbols';
import { useFieldState } from './useFieldState';
import { refreshInspector, registerSingleFieldWithDevtools } from './devtools';

Expand Down Expand Up @@ -120,6 +122,8 @@ function _useField<TValue = unknown>(

const injectedForm = controlled ? injectWithSelf(FormContextKey) : undefined;
const form = (controlForm as PrivateFormContext | undefined) || injectedForm;
const fieldGroup = injectWithSelf(FieldGroupContextKey, null);

const name = computed(() => normalizeFormPath(toValue(path)));

const validator = computed(() => {
Expand Down Expand Up @@ -343,6 +347,26 @@ function _useField<TValue = unknown>(
}
}

let fieldGroupData: FieldContextForFieldGroup | null = null;

if (fieldGroup) {
fieldGroupData = markRaw({
value: field.value,
meta: field.meta,
errors: field.errors,
errorMessage: field.errorMessage,
});
fieldGroup.fields.value = [...fieldGroup.fields.value, fieldGroupData];

onBeforeUnmount(() => {
if (fieldGroup && fieldGroupData) {
fieldGroup.fields.value = fieldGroup.fields.value.filter(
(_fieldGroupData: FieldContextForFieldGroup) => _fieldGroupData !== fieldGroupData,
);
}
});
}

// if no associated form return the field API immediately
if (!form) {
return field;
Expand Down