Skip to content

A self-hosted media server and file management system

2.7 KB
Raw Blame
<script setup lang="ts">
import type { FormField } from '@/types/types';

import { FormInput, FormLabel, FormErrorList } from '@/components/cedar-ui/form';
import { useRouter, RouterLink } from 'vue-router';
import { useAuthStore } from '@/stores/AuthStore';
import { storeToRefs } from 'pinia';
import { ButtonForm } from '@/components/cedar-ui/button';
import { register } from '@/service/authAPI';
import { ref } from 'vue';

import BaseForm from '@/components/forms/BaseForm.vue';
import FormItem from '@/components/forms/FormItem.vue';
import useForm from '@/composables/useForm';

const { userData } = storeToRefs(useAuthStore());

const router = useRouter();

const fields = ref<FormField[]>([
    { name: 'name', text: 'Username', type: 'text', required: true, autocomplete: 'name', placeholder: 'Username' },
    { name: 'email', text: 'Email', type: 'text', required: true, autocomplete: 'username email', placeholder: 'Email' },
    { name: 'password', text: 'Password', type: 'password', required: true, autocomplete: 'new-password', placeholder: 'Password' },
    { name: 'password_confirmation', text: 'Confirm Password', type: 'password', required: true, autocomplete: 'new-password', placeholder: 'Confirm Password' },
]);

const form = useForm({
    name: '',
    email: '',
    password: '',
    password_confirmation: '',
});

const handleRegister = async () => {
    form.submit(
        async (fields) => {
            return await register(fields);
        },
        {
            onSuccess: (response) => {
                userData.value = response.data.user;
                useAuthStore().clearGuestToken();
                router.push({ name: 'root' });
            },
            onError: () => {
                form.reset('password', 'password_confirmation');
            },
        },
    );
};
</script>

<template>
    <BaseForm @submit.prevent="handleRegister">
        <FormItem v-for="(field, index) in fields" :key="index">
            <FormLabel :for="field.name" :text="field.text" :subtext="field.subtext" />
            <FormInput v-model="form.fields[field.name]" :field="field" class="mt-0!" />
            <FormErrorList :errors="form.errors" :field-name="field.name" />
        </FormItem>
        <div class="flex flex-wrap items-center justify-end gap-2 gap-x-4 text-center">
            <RouterLink class="focus:ring-primary-muted text-foreground-1 hover:text-foreground-0 rounded-md underline focus:ring-2 focus:outline-hidden" to="/login">
                Already registered?
            </RouterLink>

            <ButtonForm variant="auth" type="submit" :disabled="form.processing" class="min-h-(--input-height)">Register</ButtonForm>
        </div>
    </BaseForm>
</template>