refactor(manage): update user settings

This commit is contained in:
Thomas Camlong committed 2026-01-28 12:19:31 +01:00
1 parent c16974b8db
commit e79efe06bb
1 file changed
+74 -177
@@ -5,12 +5,12 @@ import { Button, Card, Divider, Group, Radio, Select, SimpleGrid, Stack, Switch,
import type { DayOfWeek } from "@mantine/dates"; import type { DayOfWeek } from "@mantine/dates";
import dayjs from "dayjs"; import dayjs from "dayjs";
import localeData from "dayjs/plugin/localeData"; import localeData from "dayjs/plugin/localeData";
import { useForm } from "@tanstack/react-form";
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client"; import { revalidatePathActionAsync } from "@homarr/common/client";
import { env } from "@homarr/common/env"; import { env } from "@homarr/common/env";
import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { import {
@@ -47,17 +47,6 @@ const FIRST_DAY_OPTIONS: { value: DayOfWeek; labelKey: number }[] = [
{ value: 0, labelKey: 0 }, { value: 0, labelKey: 0 },
]; ];
const getErrorMessage = (errors: unknown[]): string | undefined => {
const messages = errors
.map((err) => {
if (typeof err === "string") return err;
if (err && typeof err === "object" && "message" in err) return String((err as { message: unknown }).message);
return null;
})
.filter(Boolean);
return messages.length > 0 ? messages.join(", ") : undefined;
};
interface UserGeneralSettingsFormProps { interface UserGeneralSettingsFormProps {
user: RouterOutputs["user"]["getById"]; user: RouterOutputs["user"]["getById"];
boardsData: Pick<Board, "id" | "name" | "logoImageUrl">[]; boardsData: Pick<Board, "id" | "name" | "logoImageUrl">[];
@@ -92,83 +81,70 @@ export const UserGeneralSettingsForm = ({
const changeFirstDayOfWeekMutation = clientApi.user.changeFirstDayOfWeek.useMutation(); const changeFirstDayOfWeekMutation = clientApi.user.changeFirstDayOfWeek.useMutation();
const changePingIconsEnabledMutation = clientApi.user.changePingIconsEnabled.useMutation(); const changePingIconsEnabledMutation = clientApi.user.changePingIconsEnabled.useMutation();
const hasChangesRef = useRef(false); const initialValues = buildInitialValues(user);
const initialValuesRef = useRef(initialValues);
const form = useForm({ const form = useZodForm(userGeneralSettingsSchema, {
defaultValues: buildInitialValues(user), initialValues,
validators: { });
onChange: userGeneralSettingsSchema,
}, const isDirtyRef = useRef(false);
onSubmit: async ({ value, formApi }) => { isDirtyRef.current = form.isDirty();
const parsed = userGeneralSettingsSchema.safeParse(value);
const weekDays = useMemo(() => dayjs.weekdays(false), []);
const mutations = [editProfileMutation, changeHomeBoardsMutation, changeSearchPreferencesMutation, changeFirstDayOfWeekMutation, changePingIconsEnabledMutation];
const isPending = mutations.some((m) => m.isPending);
useEffect(() => {
const handler = (e: BeforeUnloadEvent) => {
if (env.NODE_ENV === "development") return;
if (isDirtyRef.current) e.preventDefault();
};
window.addEventListener("beforeunload", handler);
return () => window.removeEventListener("beforeunload", handler);
}, []);
const handleSubmit = async (values: FormValues) => {
const parsed = userGeneralSettingsSchema.safeParse(values);
if (!parsed.success) return; if (!parsed.success) return;
const defaults = formApi.options.defaultValues as FormValues | undefined; const defaults = initialValuesRef.current;
if (!defaults) return; const changed = <K extends keyof FormValues>(...fields: K[]) =>
fields.some((f) => (f === "email" ? (values[f] || null) !== (defaults[f] || null) : values[f] !== defaults[f]));
const hasChanged = <K extends keyof FormValues>(field: K) => const saveActions: { when: boolean; action: () => Promise<unknown> }[] = [
field === "email" {
? (value[field] || null) !== (defaults[field] || null) when: isCredentialsUser && changed("name", "email"),
: value[field] !== defaults[field]; action: () => editProfileMutation.mutateAsync({ id: user.id, name: parsed.data.name, email: parsed.data.email ?? "" }),
},
const promises: Promise<unknown>[] = []; {
when: changed("homeBoardId", "mobileHomeBoardId"),
const profileChanged = hasChanged("name") || hasChanged("email"); action: () => changeHomeBoardsMutation.mutateAsync({ userId: user.id, homeBoardId: parsed.data.homeBoardId, mobileHomeBoardId: parsed.data.mobileHomeBoardId }),
if (isCredentialsUser && profileChanged) { },
promises.push( {
editProfileMutation.mutateAsync({ when: changed("defaultSearchEngineId", "openInNewTab"),
id: user.id, action: () => changeSearchPreferencesMutation.mutateAsync({ userId: user.id, defaultSearchEngineId: parsed.data.defaultSearchEngineId, openInNewTab: parsed.data.openInNewTab }),
name: parsed.data.name, },
email: parsed.data.email ?? "", {
}), when: changed("firstDayOfWeek"),
); action: () => changeFirstDayOfWeekMutation.mutateAsync({ id: user.id, firstDayOfWeek: parsed.data.firstDayOfWeek }),
} },
{
const boardsChanged = hasChanged("homeBoardId") || hasChanged("mobileHomeBoardId"); when: changed("pingIconsEnabled"),
if (boardsChanged) { action: () => changePingIconsEnabledMutation.mutateAsync({ id: user.id, pingIconsEnabled: parsed.data.pingIconsEnabled }),
promises.push( },
changeHomeBoardsMutation.mutateAsync({ ];
userId: user.id,
homeBoardId: parsed.data.homeBoardId,
mobileHomeBoardId: parsed.data.mobileHomeBoardId,
}),
);
}
const searchChanged = hasChanged("defaultSearchEngineId") || hasChanged("openInNewTab");
if (searchChanged) {
promises.push(
changeSearchPreferencesMutation.mutateAsync({
userId: user.id,
defaultSearchEngineId: parsed.data.defaultSearchEngineId,
openInNewTab: parsed.data.openInNewTab,
}),
);
}
if (hasChanged("firstDayOfWeek")) {
promises.push(
changeFirstDayOfWeekMutation.mutateAsync({
id: user.id,
firstDayOfWeek: parsed.data.firstDayOfWeek,
}),
);
}
if (hasChanged("pingIconsEnabled")) {
promises.push(
changePingIconsEnabledMutation.mutateAsync({
id: user.id,
pingIconsEnabled: parsed.data.pingIconsEnabled,
}),
);
}
const promises = saveActions.filter((s) => s.when).map((s) => s.action());
if (promises.length === 0) return; if (promises.length === 0) return;
try { try {
await Promise.all(promises); await Promise.all(promises);
formApi.reset({ ...parsed.data, email: parsed.data.email ?? "" }); const newValues = { ...parsed.data, email: parsed.data.email ?? "" };
initialValuesRef.current = newValues;
form.setInitialValues(newValues);
form.resetDirty();
await revalidatePathActionAsync(`/manage/users/${user.id}`); await revalidatePathActionAsync(`/manage/users/${user.id}`);
showSuccessNotification({ showSuccessNotification({
title: t("common.notification.update.success"), title: t("common.notification.update.success"),
@@ -180,30 +156,15 @@ export const UserGeneralSettingsForm = ({
message: t("common.notification.update.error"), message: t("common.notification.update.error"),
}); });
} }
},
});
hasChangesRef.current = !form.state.isDefaultValue;
const weekDays = useMemo(() => dayjs.weekdays(false), []);
useEffect(() => {
const handler = (e: BeforeUnloadEvent) => {
if (env.NODE_ENV === "development") return;
if (hasChangesRef.current) e.preventDefault();
}; };
window.addEventListener("beforeunload", handler);
return () => window.removeEventListener("beforeunload", handler); const handleDiscard = () => {
}, []); form.setValues(initialValuesRef.current);
form.resetDirty();
};
return ( return (
<form <form onSubmit={form.onSubmit(handleSubmit)}>
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
void form.handleSubmit();
}}
>
<Stack gap="lg"> <Stack gap="lg">
<SimpleGrid cols={{ base: 1, md: 2 }} spacing="lg" verticalSpacing="lg"> <SimpleGrid cols={{ base: 1, md: 2 }} spacing="lg" verticalSpacing="lg">
<Card withBorder bg="transparent"> <Card withBorder bg="transparent">
@@ -217,31 +178,17 @@ export const UserGeneralSettingsForm = ({
)} )}
</Stack> </Stack>
<Divider /> <Divider />
<form.Field name="name">
{({ state, handleChange, handleBlur }) => (
<TextInput <TextInput
disabled={!isCredentialsUser} disabled={!isCredentialsUser}
label={t("user.field.username.label")} label={t("user.field.username.label")}
withAsterisk withAsterisk
value={state.value} {...form.getInputProps("name")}
onChange={(e) => handleChange(e.target.value)}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
<form.Field name="email">
{({ state, handleChange, handleBlur }) => (
<TextInput <TextInput
disabled={!isCredentialsUser} disabled={!isCredentialsUser}
label={t("user.field.email.label")} label={t("user.field.email.label")}
value={state.value ?? ""} {...form.getInputProps("email")}
onChange={(e) => handleChange(e.target.value)}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
</Stack> </Stack>
</Card> </Card>
@@ -251,34 +198,20 @@ export const UserGeneralSettingsForm = ({
<Title order={3}>{tGeneral("item.board.title")}</Title> <Title order={3}>{tGeneral("item.board.title")}</Title>
</Stack> </Stack>
<Divider /> <Divider />
<form.Field name="homeBoardId">
{({ state, handleChange, handleBlur }) => (
<BoardSelect <BoardSelect
label={tGeneral("item.board.type.general")} label={tGeneral("item.board.type.general")}
clearable clearable
boards={boardsData} boards={boardsData}
w="100%" w="100%"
value={state.value} {...form.getInputProps("homeBoardId")}
onChange={handleChange}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
<form.Field name="mobileHomeBoardId">
{({ state, handleChange, handleBlur }) => (
<BoardSelect <BoardSelect
label={tGeneral("item.board.type.mobile")} label={tGeneral("item.board.type.mobile")}
clearable clearable
boards={boardsData} boards={boardsData}
w="100%" w="100%"
value={state.value} {...form.getInputProps("mobileHomeBoardId")}
onChange={handleChange}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
</Stack> </Stack>
</Card> </Card>
@@ -288,30 +221,16 @@ export const UserGeneralSettingsForm = ({
<Title order={3}>{tGeneral("item.search")}</Title> <Title order={3}>{tGeneral("item.search")}</Title>
</Stack> </Stack>
<Divider /> <Divider />
<form.Field name="defaultSearchEngineId">
{({ state, handleChange, handleBlur }) => (
<Select <Select
label={t("user.field.defaultSearchEngine.label")} label={t("user.field.defaultSearchEngine.label")}
w="100%" w="100%"
data={searchEnginesData} data={searchEnginesData}
value={state.value} {...form.getInputProps("defaultSearchEngineId")}
onChange={handleChange}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
<form.Field name="openInNewTab">
{({ state, handleChange, handleBlur }) => (
<Switch <Switch
label={t("user.field.openSearchInNewTab.label")} label={t("user.field.openSearchInNewTab.label")}
checked={state.value} {...form.getInputProps("openInNewTab", { type: "checkbox" })}
onChange={(e) => handleChange(e.currentTarget.checked)}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
</Stack> </Stack>
</Card> </Card>
@@ -323,53 +242,33 @@ export const UserGeneralSettingsForm = ({
<Divider /> <Divider />
{showLanguageSelector && <CurrentLanguageCombobox />} {showLanguageSelector && <CurrentLanguageCombobox />}
<Title order={4}>{tGeneral("item.firstDayOfWeek")}</Title> <Title order={4}>{tGeneral("item.firstDayOfWeek")}</Title>
<form.Field name="firstDayOfWeek"> <Radio.Group {...form.getInputProps("firstDayOfWeek")}>
{({ state, handleChange, handleBlur }) => (
<Radio.Group
value={String(state.value)}
onChange={(value) => handleChange(parseInt(value) as DayOfWeek)}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
>
<Group mt="xs" wrap="wrap"> <Group mt="xs" wrap="wrap">
{FIRST_DAY_OPTIONS.map(({ value: dayValue, labelKey }) => ( {FIRST_DAY_OPTIONS.map(({ value: dayValue, labelKey }) => (
<Radio key={dayValue} value={String(dayValue)} label={weekDays[labelKey]} /> <Radio key={dayValue} value={dayValue} label={weekDays[labelKey]} />
))} ))}
</Group> </Group>
</Radio.Group> </Radio.Group>
)}
</form.Field>
<Divider my="xs" /> <Divider my="xs" />
<Title order={4}>{tGeneral("item.accessibility")}</Title> <Title order={4}>{tGeneral("item.accessibility")}</Title>
<form.Field name="pingIconsEnabled">
{({ state, handleChange, handleBlur }) => (
<Switch <Switch
label={t("user.field.pingIconsEnabled.label")} label={t("user.field.pingIconsEnabled.label")}
checked={state.value} {...form.getInputProps("pingIconsEnabled", { type: "checkbox" })}
onChange={(e) => handleChange(e.currentTarget.checked)}
onBlur={handleBlur}
error={getErrorMessage(state.meta.errors)}
/> />
)}
</form.Field>
</Stack> </Stack>
</Card> </Card>
</SimpleGrid> </SimpleGrid>
<form.Subscribe
selector={(state) => ({ hasChanges: !state.isDefaultValue, isSubmitting: state.isSubmitting, canSubmit: state.canSubmit })}
>
{({ hasChanges, isSubmitting, canSubmit }) => (
<div style={{ position: "sticky", bottom: 20 }}> <div style={{ position: "sticky", bottom: 20 }}>
{hasChanges && ( {form.isDirty() && (
<Card withBorder> <Card withBorder>
<Group justify="space-between" wrap="wrap"> <Group justify="space-between" wrap="wrap">
<Text fw={500}>{t("common.unsavedChanges")}</Text> <Text fw={500}>{t("common.unsavedChanges")}</Text>
<Group> <Group>
<Button disabled={isSubmitting} variant="default" onClick={() => form.reset()}> <Button disabled={isPending} variant="default" onClick={handleDiscard}>
{t("common.action.discard")} {t("common.action.discard")}
</Button> </Button>
<Button loading={isSubmitting} type="submit" disabled={!canSubmit}> <Button loading={isPending} type="submit" disabled={!form.isValid()}>
{t("common.action.saveChanges")} {t("common.action.saveChanges")}
</Button> </Button>
</Group> </Group>
@@ -377,8 +276,6 @@ export const UserGeneralSettingsForm = ({
</Card> </Card>
)} )}
</div> </div>
)}
</form.Subscribe>
</Stack> </Stack>
</form> </form>
); );