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

fix: fix setting ref values and pass down slots and attrs #250

Merged
merged 5 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions libs/core/src/__tests__/form/field.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,36 @@ describe('Form fields', () => {

expect(wrapper.html()).toMatchSnapshot();
});

it('it can invalidate a field', async () => {
expect.assertions(1);

const field = defineField({
component: 'input',
name: 'element',
ref: ref(''),
});

const {instance: form} = await generateTestForm<{element: string}>([field]);
const fieldInstance = form.getField('element');
fieldInstance.setInvalid();

expect(fieldInstance?.isValid.value).toBe(false);
});

it('can add an error to a field', async () => {
expect.assertions(1);

const field = defineField({
component: 'input',
name: 'element',
ref: ref(''),
});

const {instance: form} = await generateTestForm<{element: string}>([field]);
const fieldInstance = form.getField('element');
fieldInstance.addError('error message');

expect(fieldInstance?.errors.value).toEqual(['error message']);
});
});
78 changes: 43 additions & 35 deletions libs/core/src/form/Field.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// noinspection JSUnusedGlobalSymbols
import {ref, watch, toValue, reactive, type UnwrapNestedRefs, computed, markRaw, type Ref} from 'vue';
import {ref, watch, toValue, reactive, type UnwrapNestedRefs, computed, markRaw, type Ref, isRef} from 'vue';
import {isDefined} from '@vueuse/core';
import {type CustomHookItem, createHookManager} from '@myparcel-vfb/hook-manager';
import {isOfType, asyncEvery, type PromiseOr} from '@myparcel/ts-utils';
import {isRequired} from '../validators';
import {normalizeFieldConfiguration} from '../utils/normalizeFieldConfiguration';
import {useDynamicWatcher} from '../utils';
import {useDynamicWatcher, updateMaybeRef} from '../utils';
import {
type ToRecord,
type FieldConfiguration,
Expand Down Expand Up @@ -130,35 +130,6 @@ export class Field<Type = unknown, Props extends ComponentProps = ComponentProps
this.destroyHandles.value.push(stopRefWatcher);
}

private initializeWatchers(
config: FieldConfiguration<Type, Props>,
resolvedConfig: FieldConfiguration<Type, Props>,
): void {
(
[
[config.visibleWhen, this.isVisible, resolvedConfig.visible],
[config.disabledWhen, this.isDisabled, resolvedConfig.disabled],
[config.optionalWhen, this.isOptional, resolvedConfig.optional],
[config.readOnlyWhen, this.isReadOnly, resolvedConfig.readOnly],
] satisfies [
undefined | ((instance: FieldInstance<Type, Props>) => PromiseOr<boolean>),
Ref<boolean>,
boolean | undefined,
][]
).forEach(([configProperty, computedProperty, staticProperty]) => {
if (!isDefined(configProperty)) {
return;
}

computedProperty.value = staticProperty;

// @ts-expect-erro todo
const stopHandler = useDynamicWatcher(() => configProperty(this), computedProperty);

this.destroyHandles.value.push(stopHandler);
});
}

public blur = async (): Promise<void> => {
await this.hooks.execute('beforeBlur', this, toValue(this.ref));

Expand Down Expand Up @@ -189,19 +160,27 @@ export class Field<Type = unknown, Props extends ComponentProps = ComponentProps
};

public setValue(value: Type): void {
this.ref.value = value;
updateMaybeRef(this.ref, value);
}

public setDisabled(value: boolean): void {
this.isDisabled.value = value;
updateMaybeRef(this.isDisabled, value);
}

public setOptional(value: boolean): void {
this.isOptional.value = value;
updateMaybeRef(this.isOptional, value);
}

public setReadOnly(value: boolean): void {
this.isReadOnly.value = value;
updateMaybeRef(this.isReadOnly, value);
}

public addError(error: string): void {
updateMaybeRef(this.errors, [...toValue(this.errors), error]);
}

public setInvalid(): void {
updateMaybeRef(this.isValid, false);
}

public validate = async (): Promise<boolean> => {
Expand Down Expand Up @@ -251,6 +230,35 @@ export class Field<Type = unknown, Props extends ComponentProps = ComponentProps
return toValue(this.isValid);
};

private initializeWatchers(
config: FieldConfiguration<Type, Props>,
resolvedConfig: FieldConfiguration<Type, Props>,
): void {
(
[
[config.visibleWhen, this.isVisible, resolvedConfig.visible],
[config.disabledWhen, this.isDisabled, resolvedConfig.disabled],
[config.optionalWhen, this.isOptional, resolvedConfig.optional],
[config.readOnlyWhen, this.isReadOnly, resolvedConfig.readOnly],
] satisfies [
undefined | ((instance: FieldInstance<Type, Props>) => PromiseOr<boolean>),
Ref<boolean>,
boolean | undefined,
][]
).forEach(([configProperty, computedProperty, staticProperty]) => {
if (!isDefined(configProperty)) {
return;
}

// @ts-expect-error todo
computedProperty.value = staticProperty;

const stopHandler = useDynamicWatcher(() => configProperty(this), computedProperty);

this.destroyHandles.value.push(stopHandler);
});
}

private createValidators(config: FieldConfiguration<Type, Props>): void {
let validators: Validator<Type, Props>[] = [];

Expand Down
4 changes: 4 additions & 0 deletions libs/core/src/types/field.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,11 @@ export interface FieldInstance<Type = unknown, Props extends ComponentProps = Co

setReadOnly(optional: boolean): void;

addError(error: string): void;

setVisible(value: boolean): void;

setInvalid(): void;
}

export type ElementProp<Type = unknown, Props = ComponentProps> = UnwrapNestedRefs<FieldInstance<Type, Props>>;
Expand Down
4 changes: 2 additions & 2 deletions libs/core/src/utils/createField.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('createField', () => {
const field = createField({name: 'test', ref: ref('value'), component: 'input'});

expect(field).toStrictEqual({
Component: expect.objectContaining({render: expect.any(Function)}),
Component: expect.any(Function),
Errors: expect.objectContaining({__asyncLoader: expect.any(Function)}),
Label: expect.objectContaining({__asyncLoader: expect.any(Function)}),
field: {name: 'test', ref: 'value', component: 'input'},
Expand All @@ -38,7 +38,7 @@ describe('createField', () => {
const field = createField({name: 'test', ref: ref('value2'), component: testComponent});

expect(field).toStrictEqual({
Component: expect.objectContaining({render: expect.any(Function)}),
Component: expect.any(Function),
Errors: expect.objectContaining({__asyncLoader: expect.any(Function)}),
Label: expect.objectContaining({__asyncLoader: expect.any(Function)}),
field: {name: 'test', ref: 'value2', component: testComponent},
Expand Down
18 changes: 16 additions & 2 deletions libs/core/src/utils/createField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import FormElementWrapper from '../components/FormElementWrapper';

const createMainComponent = <Type = unknown, Props extends ComponentProps = ComponentProps>(
field: FieldConfiguration<Type, Props>,
attrs: Record<string, unknown>,
slots: Record<string, unknown>,
): Component => {
return defineComponent({
setup() {
Expand Down Expand Up @@ -62,7 +64,19 @@ const createMainComponent = <Type = unknown, Props extends ComponentProps = Comp
}

return (
this.element && h(FormElementWrapper, {...this.$attrs, form: this.form, element: this.element}, this.$slots)
this.element && h(
FormElementWrapper,
{
...attrs,
...this.$attrs,
form: this.form,
element: this.element
},
{
...this.$slots,
...slots,
}
)
);
},
});
Expand Down Expand Up @@ -123,7 +137,7 @@ export const createField = <Type = unknown, Props extends ComponentProps = Compo
return reactive({
field,
ref: (field.ref ?? ref<Type>()) as Type extends undefined ? undefined : Ref<Type>,
Component: markRaw(createMainComponent(field)),
Component: markRaw((_, ctx) => h(createMainComponent(field, ctx.attrs, ctx.slots))),
Errors: createAsyncComponent(() => createErrorComponent(field)),
Label: createAsyncComponent(() => createLabelComponent(field)),
});
Expand Down
1 change: 1 addition & 0 deletions libs/core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './defineField';
export * from './defineForm';
export * from './generateFieldName';
export * from './markComponentAsRaw';
export * from './updateMaybeRef';
export * from './useDynamicWatcher';
export {getDefaultFormConfiguration} from './getDefaultFormConfiguration';

Expand Down
10 changes: 10 additions & 0 deletions libs/core/src/utils/updateMaybeRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {isRef, type MaybeRef} from 'vue';

export const updateMaybeRef = <T>(maybeRef: MaybeRef<T>, value: T): void => {
if (isRef(maybeRef)) {
maybeRef.value = value;
return;
}

maybeRef = value;
};

Check warning on line 10 in libs/core/src/utils/updateMaybeRef.ts

View check run for this annotation

Codecov / codecov/patch

libs/core/src/utils/updateMaybeRef.ts#L9-L10

Added lines #L9 - L10 were not covered by tests
Loading