chore: Use react-hook-form in group, API key, Gitea and GitLab forms (#14837)

* chore: Use react-hook-form in group, API key, Gitea and GitLab forms

* Rely on native validation in Gitea and GitLab connect forms

* Sync Input character count for uncontrolled fields on mount
This commit is contained in:
Tom Moor authored and GitHub committed 2026-12-04 22:18:11 -05:00
1 parent 9fd3254a8d
commit fea8ab65a7
6 files changed
+204 -244

No files matched your search

+7
View File
@@ -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);
+48 -46
View File
@@ -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>(
ExpiryType.Month
);
const currentDate = React.useRef<Date>(new Date());
const [expiresAt, setExpiresAt] = React.useState<Date | undefined>(() =>
calculateExpiryDate(currentDate.current, expiryType)
);
const [isSaving, setIsSaving] = React.useState(false);
const [currentDate] = React.useState(() => new Date());
const { register, handleSubmit, formState, setValue, control } =
useForm<FormData>({
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<Option[]>(
() =>
@@ -50,40 +65,31 @@ function ApiKeyNew({ onSubmit }: Props) {
[]
);
const handleNameChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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 (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<Flex column>
<Input
type="text"
label={t("Name")}
placeholder={t("Development")}
onChange={handleNameChange}
value={name}
{...register("name", { required: true })}
minLength={ApiKeyValidation.minNameLength}
maxLength={ApiKeyValidation.maxNameLength}
required
@@ -119,8 +122,7 @@ function ApiKeyNew({ onSubmit }: Props) {
type="text"
label={t("Scopes")}
placeholder="documents.info"
onChange={handleScopeChange}
value={scope}
{...register("scope")}
flex
/>
<Text type="secondary" size="small" as="p">
@@ -151,7 +153,7 @@ function ApiKeyNew({ onSubmit }: Props) {
</Flex>
<Flex justify="flex-end">
<Button type="submit" disabled={submitDisabled}>
{isSaving ? `${t("Creating")}…` : t("Create")}
{formState.isSubmitting ? `${t("Creating")}…` : t("Create")}
</Button>
</Flex>
</form>
+104 -140
View File
@@ -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<string | undefined>();
const [description, setDescription] = React.useState<string | undefined>();
const [icon, setIcon] = React.useState<string | null>(null);
const [color, setColor] = React.useState<string | null>(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 (
<form onSubmit={handleSubmit}>
<Text as="p" type="secondary">
<Trans>
Groups are for organizing your team. They work best when centered
around a function or a responsibility — Support or Engineering, for
example.
</Trans>
</Text>
<Flex column>
<Input
type="text"
label={t("Name")}
onChange={(e) => setName(e.target.value)}
value={name}
maxLength={GroupValidation.maxNameLength}
prefix={
<GroupIconPicker
icon={icon}
color={color}
initial={(name ?? "").charAt(0).toUpperCase()}
onChange={handleIconChange}
/>
}
showCharacterCount
required
autoFocus
flex
/>
<Input
type="textarea"
label={t("Description")}
placeholder={t("Optional")}
onChange={(e) => setDescription(e.target.value)}
value={description || ""}
maxLength={GroupValidation.maxDescriptionLength}
flex
/>
</Flex>
<Text as="p" type="secondary">
<Trans>You’ll be able to add people to the group next.</Trans>
</Text>
<Button type="submit" disabled={isSaving || !name}>
{isSaving ? `${t("Creating")}…` : t("Continue")}
</Button>
</form>
);
return <GroupForm onSubmit={handleSubmit} />;
}
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 <GroupForm group={group} onSubmit={handleSubmit} />;
}
function GroupForm({
group,
onSubmit,
}: {
group?: Group;
onSubmit: (data: GroupFormData) => Promise<void>;
}) {
const { t } = useTranslation();
const { register, handleSubmit, formState, setValue, control } =
useForm<GroupFormData>({
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<HTMLInputElement>) => {
setName(ev.target.value);
const handleFormSubmit = React.useCallback(
async (data: GroupFormData) => {
try {
await onSubmit(data);
} catch (err) {
toast.error(errToString(err));
}
},
[]
[onSubmit]
);
return (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<Text as="p" type="secondary">
{group.isExternallyManaged ? (
{!group ? (
<Trans>
Groups are for organizing your team. They work best when centered
around a function or a responsibility — Support or Engineering, for
example.
</Trans>
) : group.isExternallyManaged ? (
<Trans>
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) {
<Input
type="text"
label={t("Name")}
onChange={handleNameChange}
value={name}
{...register("name", { required: true })}
maxLength={GroupValidation.maxNameLength}
prefix={
<GroupIconPicker
@@ -222,7 +165,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
/>
<Switch
id="mentions"
label={t("Hidden")}
note={t(
"Prevent this group from being mentionable in documents or comments"
)}
checked={disableMentions}
onChange={setDisableMentions}
/>
{group && (
<Controller
control={control}
name="disableMentions"
render={({ field }) => (
<Switch
id="mentions"
label={t("Hidden")}
note={t(
"Prevent this group from being mentionable in documents or comments"
)}
checked={field.value}
onChange={field.onChange}
/>
)}
/>
)}
</Flex>
{!group && (
<Text as="p" type="secondary">
<Trans>You’ll be able to add people to the group next.</Trans>
</Text>
)}
<Button type="submit" disabled={isSaving || !name}>
{isSaving ? `${t("Saving")}…` : t("Save")}
<Button
type="submit"
disabled={formState.isSubmitting || !formState.isValid}
>
{group
? formState.isSubmitting
? `${t("Saving")}…`
: t("Save")
: formState.isSubmitting
? `${t("Creating")}…`
: t("Continue")}
</Button>
</form>
);
@@ -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<FormData>({
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 (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<Flex column gap={12}>
<Text as="p" type="secondary">
<Trans>
@@ -70,8 +71,7 @@ export function GiteaConnectDialog() {
<Input
label={t("Gitea URL")}
placeholder="https://gitea.example.com"
value={url}
onChange={(ev) => setUrl(ev.currentTarget.value)}
{...register("url")}
pattern="https://.*"
title={t("URL must start with https")}
required
@@ -80,26 +80,19 @@ export function GiteaConnectDialog() {
<Input
label={t("Client ID")}
placeholder={t("OAuth application ID")}
value={clientId}
onChange={(ev) => setClientId(ev.currentTarget.value)}
{...register("clientId")}
required
/>
<Input
label={t("Client secret")}
placeholder={t("OAuth application secret")}
value={clientSecret}
onChange={(ev) => setClientSecret(ev.currentTarget.value)}
{...register("clientSecret")}
type="password"
required
/>
<Flex justify="flex-end">
<Button
type="submit"
disabled={
!url.trim() || !clientId.trim() || !clientSecret.trim() || saving
}
>
{saving ? `${t("Connecting")}…` : t("Connect")}
<Button type="submit" disabled={formState.isSubmitting}>
{formState.isSubmitting ? `${t("Connecting")}…` : t("Connect")}
</Button>
</Flex>
</Flex>
@@ -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<FormData>({
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 (
<form onSubmit={handleConnectCustom}>
<form onSubmit={handleSubmit(handleConnectCustom)}>
<Flex column gap={12}>
<Text as="p" type="secondary">
<Trans>Enter the details for your GitLab instance.</Trans>
@@ -75,8 +80,7 @@ function GitLabConnectDialog() {
<Input
label={t("GitLab URL")}
placeholder="https://gitlab.example.com"
value={customUrl}
onChange={(ev) => setCustomUrl(ev.currentTarget.value)}
{...register("url")}
pattern="https://.*"
title={t("URL must start with https")}
required
@@ -85,15 +89,13 @@ function GitLabConnectDialog() {
<Input
label={t("Client ID")}
placeholder={t("OAuth application ID")}
value={clientId}
onChange={(ev) => setClientId(ev.currentTarget.value)}
{...register("clientId")}
required
/>
<Input
label={t("Client secret")}
placeholder={t("OAuth application secret")}
value={clientSecret}
onChange={(ev) => setClientSecret(ev.currentTarget.value)}
{...register("clientSecret")}
type="password"
required
/>
@@ -107,15 +109,7 @@ function GitLabConnectDialog() {
{t("Back")}
</Button>
)}
<Button
type="submit"
disabled={
!customUrl.trim() ||
!clientId.trim() ||
!clientSecret.trim() ||
saving
}
>
<Button type="submit" disabled={saving}>
{saving ? `${t("Connecting")}…` : t("Connect")}
</Button>
</Flex>
+3 -3
View File
@@ -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 <em>{{groupName}}</em> group will cause its members to lose access to collections and documents that it is associated with.": "Are you sure about that? Deleting the <em>{{groupName}}</em> 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.",