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

feat: focusOptions changes, replaced focusName - with field and index, added focusOptions to all array methods #107

Merged
merged 5 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 1 addition & 3 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@
</div>
<button
type="button"
@click="
prepend({ firstName: 'prepend' }, { focusName: 'arrayField.0.firstName' })
"
@click="prepend({ firstName: 'prepend' }, { name: 'firstName' })"
>
Prepend
</button>
Expand Down
55 changes: 38 additions & 17 deletions src/components/ValidationFieldArray.vue
Original file line number Diff line number Diff line change
Expand Up @@ -83,49 +83,70 @@ function touch() {
pristine.value = false;
}

function append(value: Record<string, unknown>, options?: FocusOptions) {
function append(value: Record<string, unknown>, focusOptions: FocusOptions = null) {
value[keyName.value] = getId(value);
fields.value.push(value);
touch();
handleFocus(options);
if (focusOptions) {
// by default focus on last field
handleFocus({ index: fields.value.length - 1, ...focusOptions });
}
}
function prepend(value: Record<string, unknown>, options?: FocusOptions) {
function prepend(value: Record<string, unknown>, focusOptions: FocusOptions = null) {
value[keyName.value] = getId(value);
fields.value.unshift(value);
touch();
handleFocus(options);
if (focusOptions) {
// by default focus on first field
handleFocus(focusOptions);
}
}
function insert(index: number, value: Record<string, unknown>, options?: FocusOptions) {
function insert(index: number, value: Record<string, unknown>, focusOptions: FocusOptions = null) {
value[keyName.value] = getId(value);
fields.value.splice(index, 0, value);
touch();
handleFocus(options);
if (focusOptions) {
// by default focus on inserted field
handleFocus({ index, ...focusOptions });
}
}
function swap(from: number, to: number) {
function swap(from: number, to: number, focusOptions: FocusOptions = null) {
const temp = fields.value[from];
fields.value[from] = fields.value[to];
fields.value[to] = temp;
touch();
if (focusOptions) {
// by default focus on swapped field
handleFocus({ index: to, ...focusOptions });
}
}
function move(from: number, to: number) {
function move(from: number, to: number, focusOptions: FocusOptions = null) {
fields.value.splice(to, 0, fields.value.splice(from, 1)[0]);
touch();
if (focusOptions) {
// by default focus on moved field
handleFocus({ index: to, ...focusOptions });
}
}
function remove(index: number) {
function remove(index: number, focusOptions: FocusOptions = null) {
fields.value.splice(index, 1);
touch();

if (focusOptions && fields.value.length) {
// by default focus on previous field, if there is no previous field focus on first field
handleFocus({ index: Math.max(index - 1, 0), ...focusOptions });
}
}

function handleFocus(options?: FocusOptions) {
if (!options) {
return;
function handleFocus({ field, index = 0 }: FocusOptions) {
if (!field) {
throw new Error(`Field name is required for focus, please provide field name in focus options`);
}

const itemName = `${name.value}.${index || 0}.${field}`;
nextTick(() => {
const fieldComponent = fieldComponents.value.find(({ name }) => name === options.focusName);
if (!fieldComponent) {
return;
}
fieldComponent.onFocus();
const fieldComponent = fieldComponents.value.find(({ name }) => name === itemName);
fieldComponent?.onFocus();
});
}

Expand Down
3 changes: 2 additions & 1 deletion src/types/field-array.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export interface FocusOptions {
focusName: string;
field: string;
index?: number;
}
15 changes: 12 additions & 3 deletions tests/unit/ValidationFieldArray.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import { yupResolver } from '@vue-validate-form/resolvers';
import { nextTick } from 'vue';
Expand All @@ -21,12 +21,14 @@ const resolver = yupResolver(

describe('ValidationFieldArray', () => {
let wrapper;
let handleFocus;

const createComponent = ({ props } = {}) => {
wrapper = mount(ValidationForm, {
props,
attachTo: document.body
});
handleFocus = vi.spyOn(wrapper.vm, 'handleFocus');
};

it('should render array fields', async () => {
Expand Down Expand Up @@ -146,7 +148,8 @@ describe('ValidationFieldArray', () => {
await nextTick();
expect(wrapper.findAllComponents(BaseInput).length).toBe(3);

await wrapper.find('#append').trigger('click', { firstName: 'new name' });
await wrapper.find('#append').trigger('click');
expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.1.firstName' });

const baseInputWrappers = wrapper.findAllComponents(BaseInput);
expect(baseInputWrappers.length).toBe(4);
Expand Down Expand Up @@ -202,6 +205,7 @@ describe('ValidationFieldArray', () => {
});

await wrapper.find('#remove').trigger('click');
expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.0.firstName' });

expect(wrapper.findComponent(FormInfo).props().errors).toEqual({
'my.nested.value': [],
Expand Down Expand Up @@ -271,7 +275,8 @@ describe('ValidationFieldArray', () => {
]
});

await wrapper.find('#prepend').trigger('click', { firstName: 'new name' });
await wrapper.find('#prepend').trigger('click');
expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.0.firstName' });

expect(wrapper.findComponent(FormInfo).props().errors).toEqual({
'my.nested.value': [],
Expand Down Expand Up @@ -354,6 +359,7 @@ describe('ValidationFieldArray', () => {
]
});
expect(wrapper.findComponent(FormInfo).props().values.arrayField[1].type).toEqual(undefined);
expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.1.firstName' });
expect(wrapper.findAllComponents(BaseInput).at(3).props().modelValue).toBe('insert');
});

Expand Down Expand Up @@ -407,6 +413,7 @@ describe('ValidationFieldArray', () => {
const formInfoWrapper = wrapper.findComponent(FormInfo);

await wrapper.find('#swap').trigger('click');
expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.2.firstName' });

expect(formInfoWrapper.props().errors).toEqual({
'my.nested.value': [],
Expand Down Expand Up @@ -540,6 +547,8 @@ describe('ValidationFieldArray', () => {

await wrapper.find('#move').trigger('click');

expect(handleFocus).toHaveBeenLastCalledWith({ name: 'arrayField.2.firstName' });

expect(formInfoWrapper.props().errors).toEqual({
'my.nested.value': [],
'my-input': [],
Expand Down
42 changes: 35 additions & 7 deletions tests/unit/ValidationForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@
<div v-for="(field, index) in fields" :key="field.id">
<ValidationField :name="`${arrayName}.${index}.id`" />
<ValidationField :name="`${arrayName}.${index}.type`" />
<ValidationField :name="`${arrayName}.${index}.firstName`">
<ValidationField
:name="`${arrayName}.${index}.firstName`"
@should-focus="handleFocus"
>
<template
#default="{
modelValue,
Expand All @@ -122,14 +125,36 @@
</template>
</ValidationField>
</div>
<button id="append" type="button" @click="append">Append</button>
<button id="prepend" type="button" @click="prepend">Prepend</button>
<button id="insert" type="button" @click="insert(1, { firstName: 'insert' })">
<button
id="append"
type="button"
@click="append({ firstName: 'new name' }, { field: 'firstName' })"
>
Append
</button>
<button
id="prepend"
type="button"
@click="prepend({ firstName: 'new name' }, { field: 'firstName' })"
>
Prepend
</button>
<button
id="insert"
type="button"
@click="insert(1, { firstName: 'insert' }, { field: 'firstName' })"
>
Insert
</button>
<button id="swap" type="button" @click="swap(0, 2)">Swap</button>
<button id="move" type="button" @click="move(0, 2)">Move</button>
<button id="remove" type="button" @click="remove(1)">Remove</button>
<button id="swap" type="button" @click="swap(0, 2, { field: 'firstName' })">
Swap
</button>
<button id="move" type="button" @click="move(0, 2, { field: 'firstName' })">
Move
</button>
<button id="remove" type="button" @click="remove(1, { field: 'firstName' })">
Remove
</button>
<button
id="arrayChange"
type="button"
Expand Down Expand Up @@ -217,6 +242,9 @@ export default {
methods: {
onSubmit(values, options) {
this.$emit('submit', values, options);
},
handleFocus({ name }) {
document.querySelector(`[name="${name}"]`)?.focus();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше выкидывать событие и проверять через https://test-utils.vuejs.org/api/#emitted

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, если правильно тебя понял, то теперь откидываю эмиты наверх и считываю было ли в последнем эмите то что мне надо

}
}
};
Expand Down
Loading