diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 125b43010d..545114b6c7 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -222,6 +222,13 @@ function Input( } }, [props.value]); + // Uncontrolled inputs, such as react-hook-form fields, get their value through the ref. + React.useEffect(() => { + if (internalRef.current) { + setCharCount(internalRef.current.value.length); + } + }, []); + const handleBlur = (ev: React.SyntheticEvent) => { setFocused(false); diff --git a/app/scenes/ApiKeyNew/index.tsx b/app/scenes/ApiKeyNew/index.tsx index 11e277526d..edf0238700 100644 --- a/app/scenes/ApiKeyNew/index.tsx +++ b/app/scenes/ApiKeyNew/index.tsx @@ -1,5 +1,6 @@ import { endOfDay } from "date-fns"; import * as React from "react"; +import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; @@ -21,24 +22,38 @@ type Props = { onSubmit: () => void; }; +interface FormData { + name: string; + scope: string; + expiryType: ExpiryType; + expiresAt?: Date; +} + function ApiKeyNew({ onSubmit }: Props) { - const [name, setName] = React.useState(""); - const [scope, setScope] = React.useState(""); - const [expiryType, setExpiryType] = React.useState( - ExpiryType.Month - ); - const currentDate = React.useRef(new Date()); - const [expiresAt, setExpiresAt] = React.useState(() => - calculateExpiryDate(currentDate.current, expiryType) - ); - const [isSaving, setIsSaving] = React.useState(false); + const [currentDate] = React.useState(() => new Date()); + const { register, handleSubmit, formState, setValue, control } = + useForm({ + mode: "all", + defaultValues: { + name: "", + scope: "", + expiryType: ExpiryType.Month, + expiresAt: calculateExpiryDate(currentDate, ExpiryType.Month), + }, + }); + const [expiryType, expiresAt] = useWatch({ + control, + name: ["expiryType", "expiresAt"], + }); const { apiKeys } = useStores(); const { t } = useTranslation(); const userLocale = useUserLocale(); const submitDisabled = - isSaving || !name || (!expiresAt && expiryType !== ExpiryType.NoExpiration); + formState.isSubmitting || + !formState.isValid || + (!expiresAt && expiryType !== ExpiryType.NoExpiration); const expiryOptions = React.useMemo( () => @@ -50,40 +65,31 @@ function ApiKeyNew({ onSubmit }: Props) { [] ); - const handleNameChange = React.useCallback( - (event: React.ChangeEvent) => { - setName(event.target.value); + const handleExpiryTypeChange = React.useCallback( + (value: string) => { + const expiry = value as ExpiryType; + setValue("expiryType", expiry); + setValue("expiresAt", calculateExpiryDate(currentDate, expiry)); }, - [] + [currentDate, setValue] ); - const handleScopeChange = React.useCallback( - (event: React.ChangeEvent) => { - setScope(event.target.value); + const handleSelectCustomDate = React.useCallback( + (date: Date) => { + setValue("expiresAt", endOfDay(date)); }, - [] + [setValue] ); - const handleExpiryTypeChange = React.useCallback((value: string) => { - const expiry = value as ExpiryType; - setExpiryType(expiry); - setExpiresAt(calculateExpiryDate(currentDate.current, expiry)); - }, []); - - const handleSelectCustomDate = React.useCallback((date: Date) => { - setExpiresAt(endOfDay(date)); - }, []); - - const handleSubmit = React.useCallback( - async (ev: React.SyntheticEvent) => { - ev.preventDefault(); - setIsSaving(true); - + const handleFormSubmit = React.useCallback( + async (data: FormData) => { try { await apiKeys.create({ - name, - expiresAt: expiresAt?.toISOString(), - scope: scope ? scope.split(/[\s,]+/).filter(Boolean) : undefined, + name: data.name, + expiresAt: data.expiresAt?.toISOString(), + scope: data.scope + ? data.scope.split(/[\s,]+/).filter(Boolean) + : undefined, }); toast.success( t( @@ -93,22 +99,19 @@ function ApiKeyNew({ onSubmit }: Props) { onSubmit(); } catch (err) { toast.error(errToString(err)); - } finally { - setIsSaving(false); } }, - [t, name, scope, expiresAt, onSubmit, apiKeys] + [t, onSubmit, apiKeys] ); return ( -
+ @@ -151,7 +153,7 @@ function ApiKeyNew({ onSubmit }: Props) {
diff --git a/app/scenes/Settings/components/GroupDialogs.tsx b/app/scenes/Settings/components/GroupDialogs.tsx index a9c24bbc01..52a1b6598c 100644 --- a/app/scenes/Settings/components/GroupDialogs.tsx +++ b/app/scenes/Settings/components/GroupDialogs.tsx @@ -1,6 +1,7 @@ import { debounce } from "es-toolkit/compat"; import { observer } from "mobx-react"; import * as React from "react"; +import { Controller, useForm, useWatch } from "react-hook-form"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; @@ -48,153 +49,96 @@ type Props = { onSubmit: () => void; }; +interface GroupFormData { + name: string; + description: string; + icon: string | null; + color: string | null; + disableMentions: boolean; +} + export function CreateGroupDialog() { const { dialogs, groups } = useStores(); - const { t } = useTranslation(); - const [name, setName] = React.useState(); - const [description, setDescription] = React.useState(); - const [icon, setIcon] = React.useState(null); - const [color, setColor] = React.useState(null); - const [isSaving, setIsSaving] = React.useState(false); - - const handleIconChange = React.useCallback( - (newIcon: string | null, newColor: string | null) => { - setIcon(newIcon); - setColor(newColor); - }, - [] - ); const handleSubmit = React.useCallback( - async (ev: React.SyntheticEvent) => { - ev.preventDefault(); - setIsSaving(true); - - const group = new Group( - { - name, - description, - icon, - color, - }, - groups - ); - - try { - await group.save(); - dialogs.closeAllModals(); - history.push(settingsPath("groups", group.id, "members")); - } catch (err) { - toast.error(errToString(err)); - } finally { - setIsSaving(false); - } + async (data: GroupFormData) => { + const group = new Group({ ...data }, groups); + await group.save(); + dialogs.closeAllModals(); + history.push(settingsPath("groups", group.id, "members")); }, - [dialogs, groups, name, description, icon, color] + [dialogs, groups] ); - return ( -
- - - Groups are for organizing your team. They work best when centered - around a function or a responsibility — Support or Engineering, for - example. - - - - setName(e.target.value)} - value={name} - maxLength={GroupValidation.maxNameLength} - prefix={ - - } - showCharacterCount - required - autoFocus - flex - /> - setDescription(e.target.value)} - value={description || ""} - maxLength={GroupValidation.maxDescriptionLength} - flex - /> - - - You’ll be able to add people to the group next. - - - -
- ); + return ; } export function EditGroupDialog({ group, onSubmit }: Props) { - const { t } = useTranslation(); - const [name, setName] = React.useState(group.name); - const [description, setDescription] = React.useState(group.description || ""); - const [icon, setIcon] = React.useState(group.icon); - const [color, setColor] = React.useState(group.color); - const [disableMentions, setDisableMentions] = React.useState( - group.disableMentions || false - ); - const [isSaving, setIsSaving] = React.useState(false); const handleSubmit = React.useCallback( - async (ev: React.SyntheticEvent) => { - ev.preventDefault(); - setIsSaving(true); - - try { - await group.save({ - name, - description, - icon, - color, - disableMentions, - }); - onSubmit(); - } catch (err) { - toast.error(errToString(err)); - } finally { - setIsSaving(false); - } + async (data: GroupFormData) => { + await group.save({ ...data }); + onSubmit(); }, - [group, onSubmit, name, description, icon, color, disableMentions] + [group, onSubmit] ); + return ; +} + +function GroupForm({ + group, + onSubmit, +}: { + group?: Group; + onSubmit: (data: GroupFormData) => Promise; +}) { + const { t } = useTranslation(); + const { register, handleSubmit, formState, setValue, control } = + useForm({ + mode: "all", + defaultValues: { + name: group?.name ?? "", + description: group?.description ?? "", + icon: group?.icon ?? null, + color: group?.color ?? null, + disableMentions: group?.disableMentions ?? false, + }, + }); + const [name, icon, color] = useWatch({ + control, + name: ["name", "icon", "color"], + }); + const disabled = group?.isExternallyManaged; + const handleIconChange = React.useCallback( (newIcon: string | null, newColor: string | null) => { - setIcon(newIcon); - setColor(newColor); + setValue("icon", newIcon); + setValue("color", newColor); }, - [] + [setValue] ); - const handleNameChange = React.useCallback( - (ev: React.ChangeEvent) => { - setName(ev.target.value); + const handleFormSubmit = React.useCallback( + async (data: GroupFormData) => { + try { + await onSubmit(data); + } catch (err) { + toast.error(errToString(err)); + } }, - [] + [onSubmit] ); return ( -
+ - {group.isExternallyManaged ? ( + {!group ? ( + + Groups are for organizing your team. They work best when centered + around a function or a responsibility — Support or Engineering, for + example. + + ) : group.isExternallyManaged ? ( This group is managed by an external authentication provider. The name and description are synced automatically and cannot be changed. @@ -210,8 +154,7 @@ export function EditGroupDialog({ group, onSubmit }: Props) { } showCharacterCount - disabled={group.isExternallyManaged} + disabled={disabled} required autoFocus flex @@ -231,25 +174,46 @@ export function EditGroupDialog({ group, onSubmit }: Props) { type="textarea" label={t("Description")} placeholder={t("Optional")} - onChange={(e) => setDescription(e.target.value)} - value={description} + {...register("description")} maxLength={GroupValidation.maxDescriptionLength} - disabled={group.isExternallyManaged} + disabled={disabled} flex /> - + {group && ( + ( + + )} + /> + )} + {!group && ( + + You’ll be able to add people to the group next. + + )} - ); diff --git a/plugins/gitea/client/components/GiteaConnectDialog.tsx b/plugins/gitea/client/components/GiteaConnectDialog.tsx index a2b74ec342..576df97568 100644 --- a/plugins/gitea/client/components/GiteaConnectDialog.tsx +++ b/plugins/gitea/client/components/GiteaConnectDialog.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; import { errToString } from "@shared/utils/error"; @@ -11,6 +12,12 @@ import { client } from "~/utils/ApiClient"; import { redirectTo } from "~/utils/urls"; import { GiteaUtils } from "../../shared/GiteaUtils"; +interface FormData { + url: string; + clientId: string; + clientSecret: string; +} + /** * Dialog that collects the details of a Gitea instance and its OAuth * application, then starts the OAuth flow. @@ -18,32 +25,26 @@ import { GiteaUtils } from "../../shared/GiteaUtils"; export function GiteaConnectDialog() { const { t } = useTranslation(); const { dialogs } = useStores(); - const [url, setUrl] = React.useState(""); - const [clientId, setClientId] = React.useState(""); - const [clientSecret, setClientSecret] = React.useState(""); - const [saving, setSaving] = React.useState(false); + const { register, handleSubmit, formState } = useForm({ + defaultValues: { url: "", clientId: "", clientSecret: "" }, + }); const redirectUri = GiteaUtils.callbackUrl(); - const handleSubmit = React.useCallback( - async (ev: React.FormEvent) => { - ev.preventDefault(); - setSaving(true); - + const handleFormSubmit = React.useCallback( + async (data: FormData) => { try { const res = await client.post("/gitea.connect", { - url: url.trim().replace(/\/+$/, ""), - clientId: clientId.trim(), - clientSecret: clientSecret.trim(), + url: data.url.trim().replace(/\/+$/, ""), + clientId: data.clientId.trim(), + clientSecret: data.clientSecret.trim(), }); dialogs.closeAllModals(); redirectTo(res.data.redirectUrl); } catch (err) { toast.error(errToString(err)); - } finally { - setSaving(false); } }, - [url, clientId, clientSecret, dialogs] + [dialogs] ); const handleFocusRedirectUri = React.useCallback( @@ -52,7 +53,7 @@ export function GiteaConnectDialog() { ); return ( -
+ @@ -70,8 +71,7 @@ export function GiteaConnectDialog() { setUrl(ev.currentTarget.value)} + {...register("url")} pattern="https://.*" title={t("URL must start with https")} required @@ -80,26 +80,19 @@ export function GiteaConnectDialog() { setClientId(ev.currentTarget.value)} + {...register("clientId")} required /> setClientSecret(ev.currentTarget.value)} + {...register("clientSecret")} type="password" required /> - diff --git a/plugins/gitlab/client/components/GitLabConnectDialog.tsx b/plugins/gitlab/client/components/GitLabConnectDialog.tsx index 04aa2f19ff..0bdeede49b 100644 --- a/plugins/gitlab/client/components/GitLabConnectDialog.tsx +++ b/plugins/gitlab/client/components/GitLabConnectDialog.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import styled from "styled-components"; import { toast } from "sonner"; @@ -13,6 +14,12 @@ import useStores from "~/hooks/useStores"; import { client } from "~/utils/ApiClient"; import { redirectTo } from "~/utils/urls"; +interface FormData { + url: string; + clientId: string; + clientSecret: string; +} + /** * Dialog that presents the user with options to connect to GitLab Cloud * or a self-managed GitLab instance. @@ -23,9 +30,9 @@ function GitLabConnectDialog() { const [showCustomForm, setShowCustomForm] = React.useState( !env.GITLAB_CLIENT_ID ); - const [customUrl, setCustomUrl] = React.useState(""); - const [clientId, setClientId] = React.useState(""); - const [clientSecret, setClientSecret] = React.useState(""); + const { register, handleSubmit } = useForm({ + defaultValues: { url: "", clientId: "", clientSecret: "" }, + }); const [saving, setSaving] = React.useState(false); const handleConnect = React.useCallback( @@ -53,21 +60,19 @@ function GitLabConnectDialog() { }, [handleConnect]); const handleConnectCustom = React.useCallback( - async (ev: React.FormEvent) => { - ev.preventDefault(); - const url = customUrl.trim().replace(/\/+$/, ""); + async (data: FormData) => { await handleConnect({ - url, - clientId: clientId.trim() || undefined, - clientSecret: clientSecret.trim() || undefined, + url: data.url.trim().replace(/\/+$/, ""), + clientId: data.clientId.trim() || undefined, + clientSecret: data.clientSecret.trim() || undefined, }); }, - [customUrl, clientId, clientSecret, handleConnect] + [handleConnect] ); if (showCustomForm) { return ( - + Enter the details for your GitLab instance. @@ -75,8 +80,7 @@ function GitLabConnectDialog() { setCustomUrl(ev.currentTarget.value)} + {...register("url")} pattern="https://.*" title={t("URL must start with https")} required @@ -85,15 +89,13 @@ function GitLabConnectDialog() { setClientId(ev.currentTarget.value)} + {...register("clientId")} required /> setClientSecret(ev.currentTarget.value)} + {...register("clientSecret")} type="password" required /> @@ -107,15 +109,7 @@ function GitLabConnectDialog() { {t("Back")} )} - diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index b5cf5fecf9..1ae4b69bb2 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -1423,13 +1423,13 @@ "Check server logs for more details.": "Check server logs for more details.", "{{userName}} requested": "{{userName}} requested", "Groups are for organizing your team. They work best when centered around a function or a responsibility — Support or Engineering, for example.": "Groups are for organizing your team. They work best when centered around a function or a responsibility — Support or Engineering, for example.", - "Description": "Description", - "Optional": "Optional", - "You’ll be able to add people to the group next.": "You’ll be able to add people to the group next.", "This group is managed by an external authentication provider. The name and description are synced automatically and cannot be changed.": "This group is managed by an external authentication provider. The name and description are synced automatically and cannot be changed.", "You can edit the name of this group at any time, but doing so too often might confuse your teammates.": "You can edit the name of this group at any time, but doing so too often might confuse your teammates.", + "Description": "Description", + "Optional": "Optional", "Hidden": "Hidden", "Prevent this group from being mentionable in documents or comments": "Prevent this group from being mentionable in documents or comments", + "You’ll be able to add people to the group next.": "You’ll be able to add people to the group next.", "Are you sure about that? Deleting the {{groupName}} group will cause its members to lose access to collections and documents that it is associated with.": "Are you sure about that? Deleting the {{groupName}} group will cause its members to lose access to collections and documents that it is associated with.", "Are you sure about that? Deleting {{ count }} group will cause its members to lose access to collections and documents that it is associated with.": "Are you sure about that? Deleting {{ count }} group will cause its members to lose access to collections and documents that it is associated with.", "Are you sure about that? Deleting {{ count }} group will cause its members to lose access to collections and documents that it is associated with._plural": "Are you sure about that? Deleting {{ count }} groups will cause their members to lose access to collections and documents that they are associated with.",