react-hook-form SUX

develop^2
Alex Gleason 2023-03-29 19:54:35 -05:00
rodzic 9c78a37844
commit eb055339d8
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
3 zmienionych plików z 79 dodań i 45 usunięć

Wyświetl plik

@ -1,10 +1,9 @@
import clsx from 'clsx'; import clsx from 'clsx';
import React, { useMemo } from 'react'; import React, { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl'; import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import Icon from 'soapbox/components/icon'; import Icon from 'soapbox/components/icon';
import { Avatar, Button, Column, Form, FormActions, FormGroup, HStack, Input, Text, Textarea } from 'soapbox/components/ui'; import { Avatar, Button, Column, Form, FormActions, FormGroup, HStack, Input, Spinner, Text, Textarea } from 'soapbox/components/ui';
import { useAppSelector, useInstance } from 'soapbox/hooks'; import { useAppSelector, useInstance } from 'soapbox/hooks';
import { useGroup, useUpdateGroup } from 'soapbox/hooks/api'; import { useGroup, useUpdateGroup } from 'soapbox/hooks/api';
import { isDefaultAvatar, isDefaultHeader } from 'soapbox/utils/accounts'; import { isDefaultAvatar, isDefaultHeader } from 'soapbox/utils/accounts';
@ -96,13 +95,6 @@ const AvatarPicker = React.forwardRef<HTMLInputElement, IMediaInput>(({ src, onC
); );
}); });
interface EditGroupForm {
display_name: string
note: string
avatar?: FileList
header?: FileList
}
interface IEditGroup { interface IEditGroup {
params: { params: {
id: string id: string
@ -113,44 +105,47 @@ const EditGroup: React.FC<IEditGroup> = ({ params: { id: groupId } }) => {
const intl = useIntl(); const intl = useIntl();
const instance = useInstance(); const instance = useInstance();
const { group } = useGroup(groupId); const { group, isLoading } = useGroup(groupId);
const { updateGroup } = useUpdateGroup(groupId); const { updateGroup } = useUpdateGroup(groupId);
const [isSubmitting, setIsSubmitting] = useState(false);
const avatarField = useImageField({ maxPixels: 400 * 400, preview: nonDefaultAvatar(group?.avatar) });
const headerField = useImageField({ maxPixels: 1920 * 1080, preview: nonDefaultHeader(group?.header) });
const displayNameField = useTextField(group?.display_name);
const noteField = useTextField(group?.note);
const maxName = Number(instance.configuration.getIn(['groups', 'max_characters_name'])); const maxName = Number(instance.configuration.getIn(['groups', 'max_characters_name']));
const maxNote = Number(instance.configuration.getIn(['groups', 'max_characters_description'])); const maxNote = Number(instance.configuration.getIn(['groups', 'max_characters_description']));
const { register, handleSubmit, formState: { isSubmitting }, watch } = useForm<EditGroupForm>({
values: group ? {
display_name: group.display_name,
note: group.note,
} : undefined,
});
const avatarSrc = usePreview(watch('avatar')?.item(0)) || nonDefaultAvatar(group?.avatar);
const headerSrc = usePreview(watch('header')?.item(0)) || nonDefaultHeader(group?.header);
const attachmentTypes = useAppSelector( const attachmentTypes = useAppSelector(
state => state.instance.configuration.getIn(['media_attachments', 'supported_mime_types']) as ImmutableList<string>, state => state.instance.configuration.getIn(['media_attachments', 'supported_mime_types']) as ImmutableList<string>,
)?.filter(type => type.startsWith('image/')).toArray().join(','); )?.filter(type => type.startsWith('image/')).toArray().join(',');
async function onSubmit(data: EditGroupForm) { async function handleSubmit() {
const avatar = data.avatar?.item(0); setIsSubmitting(true);
const header = data.header?.item(0);
await updateGroup({ await updateGroup({
display_name: data.display_name, display_name: displayNameField.value,
note: data.note, note: noteField.value,
avatar: avatar ? await resizeImage(avatar, 400 * 400) : undefined, avatar: avatarField.file,
header: header ? await resizeImage(header, 1920 * 1080) : undefined, header: headerField.file,
}); });
setIsSubmitting(false);
}
if (isLoading) {
return <Spinner />;
} }
return ( return (
<Column label={intl.formatMessage(messages.heading)}> <Column label={intl.formatMessage(messages.heading)}>
<Form onSubmit={handleSubmit(onSubmit)}> <Form onSubmit={handleSubmit}>
<div className='relative mb-12 flex'> <div className='relative mb-12 flex'>
<HeaderPicker src={headerSrc} accept={attachmentTypes} disabled={isSubmitting} {...register('header')} /> <HeaderPicker accept={attachmentTypes} disabled={isSubmitting} {...headerField} />
<AvatarPicker src={avatarSrc} accept={attachmentTypes} disabled={isSubmitting} {...register('avatar')} /> <AvatarPicker accept={attachmentTypes} disabled={isSubmitting} {...avatarField} />
</div> </div>
<FormGroup <FormGroup
labelText={<FormattedMessage id='manage_group.fields.name_label' defaultMessage='Group name (required)' />} labelText={<FormattedMessage id='manage_group.fields.name_label' defaultMessage='Group name (required)' />}
@ -158,7 +153,8 @@ const EditGroup: React.FC<IEditGroup> = ({ params: { id: groupId } }) => {
<Input <Input
type='text' type='text'
placeholder={intl.formatMessage(messages.groupNamePlaceholder)} placeholder={intl.formatMessage(messages.groupNamePlaceholder)}
{...register('display_name', { maxLength: maxName })} {...displayNameField}
maxLength={maxName}
/> />
</FormGroup> </FormGroup>
<FormGroup <FormGroup
@ -167,7 +163,8 @@ const EditGroup: React.FC<IEditGroup> = ({ params: { id: groupId } }) => {
<Textarea <Textarea
autoComplete='off' autoComplete='off'
placeholder={intl.formatMessage(messages.groupDescriptionPlaceholder)} placeholder={intl.formatMessage(messages.groupDescriptionPlaceholder)}
{...register('note', { maxLength: maxNote })} {...noteField}
maxLength={maxNote}
/> />
</FormGroup> </FormGroup>
@ -189,4 +186,53 @@ function usePreview(file: File | null | undefined): string | undefined {
}, [file]); }, [file]);
} }
function useTextField(initialValue: string | undefined) {
const [value, setValue] = useState(initialValue);
const hasInitialValue = typeof initialValue === 'string';
const onChange: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement> = (e) => {
setValue(e.target.value);
};
useEffect(() => {
if (hasInitialValue) {
setValue(initialValue);
}
}, [hasInitialValue]);
return {
value,
onChange,
};
}
interface UseImageFieldOpts {
maxPixels?: number
preview?: string
}
function useImageField(opts: UseImageFieldOpts = {}) {
const [file, setFile] = useState<File>();
const src = usePreview(file) || opts.preview;
const onChange: React.ChangeEventHandler<HTMLInputElement> = ({ target: { files } }) => {
const file = files?.item(0) || undefined;
if (file) {
if (typeof opts.maxPixels === 'number') {
resizeImage(file, opts.maxPixels)
.then((f) => setFile(f))
.catch(console.error);
} else {
setFile(file);
}
}
};
return {
src,
file,
onChange,
};
}
export default EditGroup; export default EditGroup;

Wyświetl plik

@ -52,7 +52,6 @@
"@fontsource/inter": "^4.5.1", "@fontsource/inter": "^4.5.1",
"@fontsource/roboto-mono": "^4.5.8", "@fontsource/roboto-mono": "^4.5.8",
"@gamestdio/websocket": "^0.3.2", "@gamestdio/websocket": "^0.3.2",
"@hookform/resolvers": "^3.0.0",
"@jest/globals": "^29.0.0", "@jest/globals": "^29.0.0",
"@lcdp/offline-plugin": "^5.1.0", "@lcdp/offline-plugin": "^5.1.0",
"@metamask/providers": "^10.0.0", "@metamask/providers": "^10.0.0",
@ -148,7 +147,6 @@
"react-datepicker": "^4.8.0", "react-datepicker": "^4.8.0",
"react-dom": "^18.0.0", "react-dom": "^18.0.0",
"react-helmet": "^6.1.0", "react-helmet": "^6.1.0",
"react-hook-form": "^7.43.8",
"react-hot-toast": "^2.4.0", "react-hot-toast": "^2.4.0",
"react-hotkeys": "^1.1.4", "react-hotkeys": "^1.1.4",
"react-immutable-pure-component": "^2.2.2", "react-immutable-pure-component": "^2.2.2",

Wyświetl plik

@ -1959,11 +1959,6 @@
qs "^6.10.1" qs "^6.10.1"
xcase "^2.0.1" xcase "^2.0.1"
"@hookform/resolvers@^3.0.0":
version "3.0.0"
resolved "https://registry.yarnpkg.com/@hookform/resolvers/-/resolvers-3.0.0.tgz#bb9346f1550a472a980af5b08e549366c788ff76"
integrity sha512-SQPefakODpyq25b/phHXDKCdRrEfPcCXV7B4nAa139wE1DxufYbbNAjeo0T04ZXBokRxZ+wD8iA1kkVMa3QwjQ==
"@humanwhocodes/config-array@^0.11.8": "@humanwhocodes/config-array@^0.11.8":
version "0.11.8" version "0.11.8"
resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.11.8.tgz#03595ac2075a4dc0f191cc2131de14fbd7d410b9" resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.11.8.tgz#03595ac2075a4dc0f191cc2131de14fbd7d410b9"
@ -14550,11 +14545,6 @@ react-helmet@^6.1.0:
react-fast-compare "^3.1.1" react-fast-compare "^3.1.1"
react-side-effect "^2.1.0" react-side-effect "^2.1.0"
react-hook-form@^7.43.8:
version "7.43.8"
resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.43.8.tgz#189fe4fb31e15c280b529cc3041249ed12108d75"
integrity sha512-BQm+Ge5KjTk1EchDBRhdP8Pkb7MArO2jFF+UWYr3rtvh6197khi22uloLqlWeuY02ItlCzPunPsFt1/q9wQKnw==
react-hot-toast@^2.4.0: react-hot-toast@^2.4.0:
version "2.4.0" version "2.4.0"
resolved "https://registry.yarnpkg.com/react-hot-toast/-/react-hot-toast-2.4.0.tgz#b91e7a4c1b6e3068fc599d3d83b4fb48668ae51d" resolved "https://registry.yarnpkg.com/react-hot-toast/-/react-hot-toast-2.4.0.tgz#b91e7a4c1b6e3068fc599d3d83b4fb48668ae51d"