added error handling, fixed authenticaton, added toaster

This commit is contained in:
lnn0q 2025-03-30 17:31:12 +03:00
parent 40c35bda13
commit b6b7cea210
18 changed files with 1327 additions and 68 deletions

View file

@ -0,0 +1,134 @@
'use client';
import type { ButtonProps, GroupProps, InputProps, StackProps } from '@chakra-ui/react';
import {
Box,
HStack,
IconButton,
Input,
InputGroup,
Stack,
mergeRefs,
useControllableState
} from '@chakra-ui/react';
import * as React from 'react';
import { LuEye, LuEyeOff } from 'react-icons/lu';
export interface PasswordVisibilityProps {
defaultVisible?: boolean;
visible?: boolean;
onVisibleChange?: (visible: boolean) => void;
visibilityIcon?: { on: React.ReactNode; off: React.ReactNode };
}
export interface PasswordInputProps extends InputProps, PasswordVisibilityProps {
rootProps?: GroupProps;
}
export const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
function PasswordInput(props, ref) {
const {
rootProps,
defaultVisible,
visible: visibleProp,
onVisibleChange,
visibilityIcon = { on: <LuEye />, off: <LuEyeOff /> },
...rest
} = props;
const [visible, setVisible] = useControllableState({
value: visibleProp,
defaultValue: defaultVisible || false,
onChange: onVisibleChange
});
const inputRef = React.useRef<HTMLInputElement>(null);
return (
<InputGroup
endElement={
<VisibilityTrigger
disabled={rest.disabled}
onPointerDown={e => {
if (rest.disabled) return;
if (e.button !== 0) return;
e.preventDefault();
setVisible(!visible);
}}
>
{visible ? visibilityIcon.off : visibilityIcon.on}
</VisibilityTrigger>
}
{...rootProps}
>
<Input {...rest} ref={mergeRefs(ref, inputRef)} type={visible ? 'text' : 'password'} />
</InputGroup>
);
}
);
const VisibilityTrigger = React.forwardRef<HTMLButtonElement, ButtonProps>(
function VisibilityTrigger(props, ref) {
return (
<IconButton
tabIndex={-1}
ref={ref}
me="-2"
aspectRatio="square"
size="sm"
variant="ghost"
height="calc(100% - {spacing.2})"
aria-label="Toggle password visibility"
{...props}
/>
);
}
);
interface PasswordStrengthMeterProps extends StackProps {
max?: number;
value: number;
}
export const PasswordStrengthMeter = React.forwardRef<HTMLDivElement, PasswordStrengthMeterProps>(
function PasswordStrengthMeter(props, ref) {
const { max = 4, value, ...rest } = props;
const percent = (value / max) * 100;
const { label, colorPalette } = getColorPalette(percent);
return (
<Stack align="flex-end" gap="1" ref={ref} {...rest}>
<HStack width="full" ref={ref} {...rest}>
{Array.from({ length: max }).map((_, index) => (
<Box
key={index}
height="1"
flex="1"
rounded="sm"
data-selected={index < value ? '' : undefined}
layerStyle="fill.subtle"
colorPalette="gray"
_selected={{
colorPalette,
layerStyle: 'fill.solid'
}}
/>
))}
</HStack>
{label && <HStack textStyle="xs">{label}</HStack>}
</Stack>
);
}
);
function getColorPalette(percent: number) {
switch (true) {
case percent < 33:
return { label: 'Low', colorPalette: 'red' };
case percent < 66:
return { label: 'Medium', colorPalette: 'orange' };
default:
return { label: 'High', colorPalette: 'green' };
}
}

View file

@ -0,0 +1,39 @@
'use client';
import {
Toaster as ChakraToaster,
Portal,
Spinner,
Stack,
Toast,
createToaster
} from '@chakra-ui/react';
export const toaster = createToaster({
placement: 'bottom-end',
pauseOnPageIdle: true
});
export const Toaster = () => {
return (
<Portal>
<ChakraToaster toaster={toaster} insetInline={{ mdDown: '4' }}>
{toast => (
<Toast.Root width={{ md: 'sm' }}>
{toast.type === 'loading' ? (
<Spinner size="sm" color="blue.solid" />
) : (
<Toast.Indicator />
)}
<Stack gap="1" flex="1" maxWidth="100%">
{toast.title && <Toast.Title>{toast.title}</Toast.Title>}
{toast.description && <Toast.Description>{toast.description}</Toast.Description>}
</Stack>
{toast.action && <Toast.ActionTrigger>{toast.action.label}</Toast.ActionTrigger>}
{toast.meta?.closable && <Toast.CloseTrigger />}
</Toast.Root>
)}
</ChakraToaster>
</Portal>
);
};

14
app/client/fragments.tsx Normal file
View file

@ -0,0 +1,14 @@
import { gql } from '@apollo/client';
export const sessionFragment = gql`
fragment Session on Session {
accessToken
refreshToken {
token
maxAge
secure
httpOnly
sameSite
}
}
`;

View file

@ -0,0 +1,38 @@
import {
ApolloCache,
DefaultContext,
DocumentNode,
FetchResult,
MaybeMasked,
MutationFunctionOptions,
OperationVariables,
useMutation
} from '@apollo/client';
import { toaster } from '../components/ui/toaster';
interface UseToastMutationProps {
mutation: DocumentNode;
successMsg?: string;
}
interface UseToastMutationReturn<T> {
update: (
options?:
| MutationFunctionOptions<T, OperationVariables, DefaultContext, ApolloCache<any>>
| undefined
) => Promise<FetchResult<MaybeMasked<T>>>;
}
export function useToastMutation<T>(props: UseToastMutationProps): UseToastMutationReturn<T> {
const [update] = useMutation<T>(props.mutation, {
onCompleted: () => toaster.create({ description: props.successMsg, type: 'success' }),
onError: error => {
toaster.create({ description: `${error.message}`, type: 'error' });
console.error(error);
}
});
return {
update
};
}

View file

@ -2,6 +2,7 @@ import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import '@client/assets/styles/index.css';
import '@client/assets/styles/nerd-fonts-icons.css';
import { Provider } from '@client/components/ui/provider';
import { Toaster } from '@client/components/ui/toaster';
import { RouterProvider, createRouter } from '@tanstack/react-router';
import { StrictMode } from 'react';
import ReactDOM from 'react-dom/client';
@ -37,6 +38,7 @@ if (!rootElement.innerHTML) {
<StrictMode>
<ApolloProvider client={client}>
<Provider>
<Toaster />
<RouterProvider router={router} />
</Provider>
</ApolloProvider>

View file

@ -1,23 +1,24 @@
// import { gql, useQuery } from '@apollo/client';
import { gql } from '@apollo/client';
import { Heading, Input, Stack } from '@chakra-ui/react';
import { Button } from '@client/components/ui/button';
import { Field } from '@client/components/ui/field';
import { valibotResolver } from '@hookform/resolvers/valibot';
import { createFileRoute } from '@tanstack/react-router';
import { Session } from 'inspector';
import { useForm } from 'react-hook-form';
import * as v from 'valibot';
import { sessionFragment } from '../fragments';
import { useToastMutation } from '../hooks/useToastMutation';
export const Route = createFileRoute('/login')({
component: LoginComponent
});
function LoginComponent() {
// const { data } = useQuery(getBooksQuery);
return (
<Stack flexDirection={'column'} justifyContent={'center'} alignItems={'center'}>
<Heading>Login</Heading>
<Login />
<LoginForm />
</Stack>
);
}
@ -27,7 +28,12 @@ interface FormValues {
password: string;
}
function Login() {
function LoginForm() {
const { update: login } = useToastMutation<Session>({
mutation,
successMsg: 'Logged in successfully.'
});
const schema = v.pipe(
v.object({
email: v.pipe(v.string(), v.nonEmpty('Email is required'), v.email('Invalid email')),
@ -42,7 +48,19 @@ function Login() {
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
return (
<form onSubmit={handleSubmit(data => alert(data))}>
<form
onSubmit={handleSubmit(async values => {
const { data } = await login({
variables: {
input: {
email: values.email,
password: values.password
}
}
});
alert(JSON.stringify(data));
})}
>
<Stack>
<Field label="Email" invalid={errors.email != null} errorText={errors.email?.message}>
<Input {...register('email')} />
@ -60,12 +78,12 @@ function Login() {
);
}
/* const getBooksQuery = gql`
query BooksMany {
booksMany {
id
author
title
const mutation = gql`
mutation AuthLogin($input: LoginInput!) {
login(input: $input) {
...Session
}
}
`; */
${sessionFragment}
`;

View file

@ -1,23 +1,23 @@
// import { gql, useQuery } from '@apollo/client';
import { gql } from '@apollo/client';
import { Heading, Input, Stack } from '@chakra-ui/react';
import { Button } from '@client/components/ui/button';
import { Field } from '@client/components/ui/field';
import { Session } from '@generated/types';
import { valibotResolver } from '@hookform/resolvers/valibot';
import { createFileRoute } from '@tanstack/react-router';
import { createFileRoute, redirect } from '@tanstack/react-router';
import { useForm } from 'react-hook-form';
import * as v from 'valibot';
import { useToastMutation } from '../hooks/useToastMutation';
export const Route = createFileRoute('/register')({
component: RegisterComponent
});
function RegisterComponent() {
// const { data } = useQuery(getBooksQuery);
return (
<Stack flexDirection={'column'} justifyContent={'center'} alignItems={'center'}>
<Heading>Sign up</Heading>
<Register />
<SignUpForm />
</Stack>
);
}
@ -29,7 +29,9 @@ interface FormValues {
confirm_password: string;
}
function Register() {
function SignUpForm() {
const { update: signUp } = useToastMutation<Session>({ mutation });
const schema = v.pipe(
v.object({
email: v.pipe(v.string(), v.nonEmpty('Email is required'), v.email('Invalid email')),
@ -53,7 +55,20 @@ function Register() {
formState: { errors }
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
const onSubmit = handleSubmit(data => alert(data));
const onSubmit = handleSubmit(async values => {
await signUp({
variables: {
input: {
email: values.email,
username: values.username,
password: values.password
}
}
});
redirect({
to: '/login'
});
});
return (
<form onSubmit={onSubmit}>
@ -88,12 +103,8 @@ function Register() {
);
}
/* const getBooksQuery = gql`
query BooksMany {
booksMany {
id
author
title
}
const mutation = gql`
mutation AuthSignUp($input: RegisterInput!) {
signUp(input: $input)
}
`; */
`;