umami/src/app/(main)/profile/PasswordEditForm.tsx

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-02-04 16:44:20 +08:00
'use client';
2023-01-21 09:12:53 +08:00
import { useRef } from 'react';
import { Form, FormRow, FormInput, FormButtons, PasswordField, Button } from 'react-basics';
import { useApi, useMessages } from 'components/hooks';
2023-01-21 09:12:53 +08:00
2023-04-21 23:00:42 +08:00
export function PasswordEditForm({ onSave, onClose }) {
2023-03-23 05:05:55 +08:00
const { formatMessage, labels, messages } = useMessages();
2023-01-21 09:12:53 +08:00
const { post, useMutation } = useApi();
2023-12-04 13:35:20 +08:00
const { mutate, error, isPending } = useMutation({
mutationFn: (data: any) => post('/me/password', data),
});
2023-01-21 09:12:53 +08:00
const ref = useRef(null);
2023-12-03 19:07:03 +08:00
const handleSubmit = async (data: any) => {
2023-01-25 23:42:46 +08:00
mutate(data, {
2023-01-21 09:12:53 +08:00
onSuccess: async () => {
onSave();
onClose();
2023-01-21 09:12:53 +08:00
},
});
};
2023-12-03 19:07:03 +08:00
const samePassword = (value: string) => {
2023-01-21 09:12:53 +08:00
if (value !== ref?.current?.getValues('newPassword')) {
2023-01-25 23:42:46 +08:00
return formatMessage(messages.noMatchPassword);
2023-01-21 09:12:53 +08:00
}
return true;
};
return (
<Form ref={ref} onSubmit={handleSubmit} error={error}>
2023-01-25 23:42:46 +08:00
<FormRow label={formatMessage(labels.currentPassword)}>
<FormInput name="currentPassword" rules={{ required: 'Required' }}>
<PasswordField autoComplete="current-password" />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.newPassword)}>
2023-01-21 09:12:53 +08:00
<FormInput
name="newPassword"
rules={{
required: 'Required',
2023-04-19 07:00:33 +08:00
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) },
2023-01-21 09:12:53 +08:00
}}
>
2023-01-25 23:42:46 +08:00
<PasswordField autoComplete="new-password" />
2023-01-21 09:12:53 +08:00
</FormInput>
</FormRow>
2023-01-25 23:42:46 +08:00
<FormRow label={formatMessage(labels.confirmPassword)}>
2023-01-21 09:12:53 +08:00
<FormInput
name="confirmPassword"
rules={{
2023-01-25 23:42:46 +08:00
required: formatMessage(labels.required),
2023-04-19 07:00:33 +08:00
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) },
2023-01-21 09:12:53 +08:00
validate: samePassword,
}}
>
2023-01-25 23:42:46 +08:00
<PasswordField autoComplete="confirm-password" />
2023-01-21 09:12:53 +08:00
</FormInput>
</FormRow>
<FormButtons flex>
2023-12-04 13:35:20 +08:00
<Button type="submit" variant="primary" disabled={isPending}>
2023-01-25 23:42:46 +08:00
{formatMessage(labels.save)}
2023-01-21 09:12:53 +08:00
</Button>
2023-01-25 23:42:46 +08:00
<Button onClick={onClose}>{formatMessage(labels.cancel)}</Button>
2023-01-21 09:12:53 +08:00
</FormButtons>
</Form>
);
}
2023-04-21 23:00:42 +08:00
export default PasswordEditForm;