Skip to content
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
6 changes: 5 additions & 1 deletion nuxt/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
addTemplate,
createResolver,
defineNuxtModule,
hasNuxtModule,
resolvePath
} from '@nuxt/kit';

Expand Down Expand Up @@ -53,7 +54,10 @@ export default defineNuxtModule<NuxtModuleOptions>({
write: true
});

addPlugin(resolver.resolve('./runtime/plugin'));
const hasI18n = hasNuxtModule('@nuxtjs/i18n');
const awaitsI18n = pluginOptions.syncI18n && hasI18n;

addPlugin(resolver.resolve(awaitsI18n ? './runtime/plugin-i18n' : './runtime/plugin'));

addComponent({ name: 'Form', export: 'Form', filePath: '@overgaming/valiform' });
addComponent({ name: 'Field', export: 'Field', filePath: '@overgaming/valiform' });
Expand Down
9 changes: 9 additions & 0 deletions nuxt/runtime/plugin-i18n.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { defineNuxtPlugin } from '#app';
import { setupFormsPlugin } from './setup';

export default defineNuxtPlugin({
name: 'valiform',
enforce: 'post',
dependsOn: ['i18n:plugin'],
setup: setupFormsPlugin
});
30 changes: 3 additions & 27 deletions nuxt/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,8 @@
import { defineNuxtPlugin } from '#app';
import { isRef } from 'vue';
import { FormsPlugin, registerRules } from '@overgaming/valiform';
// @ts-ignore virtual module resolved by Nuxt at build time
import { pluginOptions, valiformConfig } from '#build/valiform/options.mjs';
import { setupFormsPlugin } from './setup';

export default defineNuxtPlugin({
name: 'valiform',
enforce: 'post',
setup(nuxtApp) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { syncI18n, ...formsOpts } = pluginOptions;
const opts = { ...formsOpts };

if (valiformConfig?.locales) {
opts.locales = valiformConfig.locales;
}

if (syncI18n) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const i18n = (nuxtApp as any).$i18n;
if (i18n && i18n.locale) {
opts.locale = isRef(i18n.locale) ? i18n.locale : i18n.locale.value || i18n.locale;
}
}

nuxtApp.vueApp.use(FormsPlugin, opts);

if (valiformConfig?.rules) {
registerRules(valiformConfig.rules);
}
}
setup: setupFormsPlugin
});
27 changes: 27 additions & 0 deletions nuxt/runtime/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { FormsPlugin, registerRules } from '@overgaming/valiform';
// @ts-ignore virtual module resolved by Nuxt at build time
import { pluginOptions, valiformConfig } from '#build/valiform/options.mjs';

export function setupFormsPlugin(nuxtApp: any) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { syncI18n, ...formsOpts } = pluginOptions;
const opts = { ...formsOpts };

if (valiformConfig?.locales) {
opts.locales = valiformConfig.locales;
}

if (syncI18n) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const i18n = (nuxtApp as any).$i18n;
if (i18n && i18n.locale) {
opts.locale = i18n.locale;
}
}

nuxtApp.vueApp.use(FormsPlugin, opts);

if (valiformConfig?.rules) {
registerRules(valiformConfig.rules);
}
}
30 changes: 10 additions & 20 deletions src/components/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@
import { useFormStateContextProvider } from '../context/useFormStateContext';
import { useFormContextProvider } from '../context/useFormContext';
import { getValueByPath, setValueByPath } from '../utils/valueByPath';
import type { FieldState } from '../types';
import type { FieldState, FormSubmitHelpers } from '../types';

const emit = defineEmits<{
submit: [
values: Record<string, unknown>,
helpers: { setErrors: typeof setErrors; reset: typeof reset }
];
submit: [values: Record<string, unknown>, helpers: FormSubmitHelpers];
}>();

const model = defineModel<Record<string, unknown>>({
Expand Down Expand Up @@ -59,22 +56,15 @@
emit('submit', model.value, { setErrors, reset });
};

const setErrors = (...args: unknown[]): void => {
if (args.length === 1) {
const errorInput = args[0];

if (typeof errorInput === 'object' && !Array.isArray(errorInput) && errorInput !== null) {
Object.keys(errorInput as Record<string, unknown>).forEach((key) => {
setErrors(key, (errorInput as Record<string, unknown>)[key]);
});
return;
}

errors.value = Array.isArray(errorInput) ? (errorInput as string[]) : [errorInput as string];
} else if (args.length === 2) {
const [fieldName, errorInput] = args as [string, string | string[]];
fields.value[fieldName]?.setErrors(errorInput);
const setErrors = (input: string | string[] | Record<string, string | string[]>): void => {
if (typeof input === 'object' && !Array.isArray(input) && input !== null) {
Object.keys(input).forEach((key) => {
fields.value[key]?.setErrors(input[key]);
});
return;
}

errors.value = Array.isArray(input) ? input : [input];
};

const reset = (): void => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/__tests__/Form.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ describe('Form', () => {
props: {
handleSubmit: (
_values: Record<string, unknown>,
{ setErrors }: { setErrors: (...args: unknown[]) => void }
{ setErrors }: { setErrors: (input: typeof apiErrors) => void }
) => {
setErrors(apiErrors);
},
Expand Down
6 changes: 2 additions & 4 deletions src/components/__tests__/components/ExampleForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
import Field from '../../Field.vue';
import CustomInput from './CustomInput.vue';
import { useLocale } from '../../../composables/useLocale';
import type { FormSubmitHelpers } from '../../../types';

interface FormValues {
name: string;
Expand All @@ -78,10 +79,7 @@

const props = withDefaults(
defineProps<{
handleSubmit?: (
values: Record<string, unknown>,
helpers: { setErrors: (...args: unknown[]) => void; reset: () => void }
) => void;
handleSubmit?: (values: Record<string, unknown>, helpers: FormSubmitHelpers) => void;
initialValues?: FormValues;
}>(),
{
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export type {
FieldContext,
FieldState,
FormContext,
FormSubmitHelpers,
FormSubmitHandler,
InputProps,
RuleFunction,
RuleOptions,
Expand Down
14 changes: 13 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ export interface FieldContext {

// ─── Form ─────────────────────────────────────────────────────────────────────

export type SetErrorsInput = string | string[] | Record<string, string | string[]>;

export interface FormStateContext {
getFields: () => Record<string, FieldState>;
getField: (name: string) => FieldState | undefined;
Expand All @@ -80,10 +82,20 @@ export interface FormContext {
errors: Ref<string[]>;
fields: Ref<Record<string, FieldState>>;
reset: () => void;
setErrors: (...args: unknown[]) => void;
setErrors: (input: SetErrorsInput) => void;
validate: () => void;
}

export type FormSubmitHelpers = {
setErrors: (input: SetErrorsInput) => void;
reset: () => void;
};

export type FormSubmitHandler<T extends Record<string, unknown> = Record<string, unknown>> = (
values: T,
helpers: FormSubmitHelpers
) => void | Promise<void>;

// ─── Locale ───────────────────────────────────────────────────────────────────

export interface LocaleContextData {
Expand Down
4 changes: 3 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export default defineConfig({
nuxt: resolve(__dirname, 'nuxt/module.ts'),
// Runtime plugin compiled separately so Nuxt can inject it into the user's app.
// #app and #build/* are Nuxt virtual modules resolved at the user's build time.
'runtime/plugin': resolve(__dirname, 'nuxt/runtime/plugin.ts')
'runtime/plugin': resolve(__dirname, 'nuxt/runtime/plugin.ts'),
'runtime/plugin-i18n': resolve(__dirname, 'nuxt/runtime/plugin-i18n.ts'),
'runtime/setup': resolve(__dirname, 'nuxt/runtime/setup.ts')
},
formats: ['es', 'cjs']
},
Expand Down
Loading