refactor(spotlight): registry-driven preferences with data-driven hook
Replace 5 per-preference children files with a single preference-registry.tsx that auto-generates CMDK children via factory functions. Rewrite useUserPreferences from ~347 lines to ~160 lines by deriving mutation dispatch, pending state, and optimistic values from preference definitions. Simplify settings-children.tsx and groups.tsx to iterate over visiblePreferenceDefinitions instead of maintaining manual mappings. Deleted: board.tsx, color-scheme.tsx, first-day-of-week.tsx, search-engine.tsx, registry.ts Net reduction: ~261 lines across 9 files.
This commit is contained in:
1 parent
f6592b27a1
commit
5501ee6a7d
9 files changed
+336
-599
No files matched your search
@@ -1,47 +0,0 @@
|
|||||||
import { useUserPreference } from "../../../../preferences/use-user-preference";
|
|
||||||
import type { UserPreferenceKey } from "@homarr/settings";
|
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
|
||||||
|
|
||||||
import { clientApi } from "@homarr/api/client";
|
|
||||||
|
|
||||||
import { createChildrenOptions } from "../../../../lib/children";
|
|
||||||
import { createLoadingPreferenceAction, PreferenceDetailHeader } from "./action-row";
|
|
||||||
import { createSelectablePreferenceActions } from "./selectable-actions";
|
|
||||||
|
|
||||||
interface BoardChildrenOptionsConfig {
|
|
||||||
preferenceKey: Extract<UserPreferenceKey, "homeBoardId" | "mobileHomeBoardId">;
|
|
||||||
}
|
|
||||||
|
|
||||||
const boardDetailTitleKeys = {
|
|
||||||
homeBoardId: "homeBoardId.children.detail.title",
|
|
||||||
mobileHomeBoardId: "mobileHomeBoardId.children.detail.title",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const createBoardChildrenOptions = (config: BoardChildrenOptionsConfig) =>
|
|
||||||
createChildrenOptions<Record<string, unknown>>({
|
|
||||||
useActions: (_, query) => {
|
|
||||||
const { value, setValue, isPending } = useUserPreference(config.preferenceKey);
|
|
||||||
const currentValue = value as string | null;
|
|
||||||
const boardsQuery = clientApi.board.getAllBoards.useQuery();
|
|
||||||
const t = useScopedI18n("search.mode.command.group.preferences.option");
|
|
||||||
|
|
||||||
if (boardsQuery.isLoading) {
|
|
||||||
return [createLoadingPreferenceAction()];
|
|
||||||
}
|
|
||||||
|
|
||||||
return createSelectablePreferenceActions({
|
|
||||||
query,
|
|
||||||
currentValue,
|
|
||||||
noneLabel: t("board.none"),
|
|
||||||
unavailableLabel: t("board.unavailable"),
|
|
||||||
items: (boardsQuery.data ?? []).map((board) => ({
|
|
||||||
key: board.id,
|
|
||||||
label: board.name,
|
|
||||||
value: board.id,
|
|
||||||
})),
|
|
||||||
onSelect: (nextValue) => setValue(nextValue as never),
|
|
||||||
isPending,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
DetailComponent: () => <PreferenceDetailHeader titleKey={boardDetailTitleKeys[config.preferenceKey]} />,
|
|
||||||
});
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import type { ColorScheme } from "@homarr/definitions";
|
|
||||||
import { colorSchemes } from "@homarr/definitions";
|
|
||||||
import { useUserPreference } from "../../../../preferences/use-user-preference";
|
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
|
||||||
|
|
||||||
import { createChildrenOptions } from "../../../../lib/children";
|
|
||||||
import { createCheckmarkPreferenceAction, PreferenceDetailHeader } from "./action-row";
|
|
||||||
|
|
||||||
export const colorSchemeChildrenOptions = createChildrenOptions<Record<string, unknown>>({
|
|
||||||
useActions: () => {
|
|
||||||
const tOptions = useScopedI18n("common.colorScheme.options");
|
|
||||||
const { value, setValue, isPending } = useUserPreference("colorScheme");
|
|
||||||
const currentValue = value as ColorScheme;
|
|
||||||
|
|
||||||
return colorSchemes.map((scheme) =>
|
|
||||||
createCheckmarkPreferenceAction({
|
|
||||||
key: scheme,
|
|
||||||
label: tOptions(scheme),
|
|
||||||
isSelected: currentValue === scheme,
|
|
||||||
onSelect: () => setValue(scheme as never),
|
|
||||||
isPending,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
DetailComponent: () => <PreferenceDetailHeader titleKey="colorScheme.children.detail.title" />,
|
|
||||||
});
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import type { DayOfWeek } from "@mantine/dates";
|
|
||||||
import dayjs from "dayjs";
|
|
||||||
import localeData from "dayjs/plugin/localeData";
|
|
||||||
|
|
||||||
import { useUserPreference } from "../../../../preferences/use-user-preference";
|
|
||||||
|
|
||||||
import { createChildrenOptions } from "../../../../lib/children";
|
|
||||||
import { createCheckmarkPreferenceAction, PreferenceDetailHeader } from "./action-row";
|
|
||||||
|
|
||||||
dayjs.extend(localeData);
|
|
||||||
|
|
||||||
const firstDayOfWeekOptions: DayOfWeek[] = [1, 6, 0];
|
|
||||||
const weekDays = dayjs.weekdays(false);
|
|
||||||
|
|
||||||
export const firstDayOfWeekChildrenOptions = createChildrenOptions<Record<string, unknown>>({
|
|
||||||
useActions: () => {
|
|
||||||
const { value, setValue, isPending } = useUserPreference("firstDayOfWeek");
|
|
||||||
const currentValue = value as DayOfWeek;
|
|
||||||
|
|
||||||
return firstDayOfWeekOptions.map((day) =>
|
|
||||||
createCheckmarkPreferenceAction({
|
|
||||||
key: day.toString(),
|
|
||||||
label: weekDays[day] ?? day.toString(),
|
|
||||||
isSelected: currentValue === day,
|
|
||||||
onSelect: () => setValue(day as never),
|
|
||||||
isPending,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
DetailComponent: () => <PreferenceDetailHeader titleKey="firstDayOfWeek.children.detail.title" />,
|
|
||||||
});
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
import {
|
|
||||||
IconActivity,
|
|
||||||
IconCalendarWeek,
|
|
||||||
IconDeviceDesktop,
|
|
||||||
IconExternalLink,
|
|
||||||
IconHome,
|
|
||||||
IconLanguage,
|
|
||||||
IconLayoutBoard,
|
|
||||||
IconSearch,
|
|
||||||
IconSettings,
|
|
||||||
IconWorldWww,
|
|
||||||
} from "@tabler/icons-react";
|
|
||||||
|
|
||||||
import { userPreferenceDefinitions } from "@homarr/settings";
|
|
||||||
import type { UserPreferenceKey } from "@homarr/settings";
|
|
||||||
import type { TablerIcon } from "@homarr/ui";
|
|
||||||
|
|
||||||
import type { createChildrenOptions } from "../../../../lib/children";
|
|
||||||
import { languageChildrenOptions } from "../language";
|
|
||||||
import { createBoardChildrenOptions } from "./board";
|
|
||||||
import { colorSchemeChildrenOptions } from "./color-scheme";
|
|
||||||
import { firstDayOfWeekChildrenOptions } from "./first-day-of-week";
|
|
||||||
import { searchEngineChildrenOptions } from "./search-engine";
|
|
||||||
|
|
||||||
type ChildrenPreferenceKey =
|
|
||||||
| "colorScheme"
|
|
||||||
| "locale"
|
|
||||||
| "defaultSearchEngineId"
|
|
||||||
| "firstDayOfWeek"
|
|
||||||
| "homeBoardId"
|
|
||||||
| "mobileHomeBoardId";
|
|
||||||
|
|
||||||
type PreferenceChildrenOptionsFactory = ReturnType<typeof createChildrenOptions<Record<string, unknown>>>;
|
|
||||||
|
|
||||||
export const preferenceIcons: Record<UserPreferenceKey, TablerIcon> = {
|
|
||||||
colorScheme: IconDeviceDesktop,
|
|
||||||
locale: IconLanguage,
|
|
||||||
defaultSearchEngineId: IconSearch,
|
|
||||||
openSearchInNewTab: IconExternalLink,
|
|
||||||
ddgBangs: IconWorldWww,
|
|
||||||
firstDayOfWeek: IconCalendarWeek,
|
|
||||||
homeBoardId: IconHome,
|
|
||||||
mobileHomeBoardId: IconLayoutBoard,
|
|
||||||
pingIconsEnabled: IconActivity,
|
|
||||||
fullPreferencesPage: IconSettings,
|
|
||||||
};
|
|
||||||
|
|
||||||
export const preferenceChildrenOptionsByKey: Record<ChildrenPreferenceKey, PreferenceChildrenOptionsFactory> = {
|
|
||||||
colorScheme: colorSchemeChildrenOptions,
|
|
||||||
locale: languageChildrenOptions,
|
|
||||||
defaultSearchEngineId: searchEngineChildrenOptions,
|
|
||||||
firstDayOfWeek: firstDayOfWeekChildrenOptions,
|
|
||||||
homeBoardId: createBoardChildrenOptions({ preferenceKey: "homeBoardId" }),
|
|
||||||
mobileHomeBoardId: createBoardChildrenOptions({ preferenceKey: "mobileHomeBoardId" }),
|
|
||||||
};
|
|
||||||
|
|
||||||
export const visiblePreferenceDefinitions = (isAuthenticated: boolean) =>
|
|
||||||
userPreferenceDefinitions.filter((definition) => definition.guest || isAuthenticated);
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { clientApi } from "@homarr/api/client";
|
|
||||||
import { useUserPreference } from "../../../../preferences/use-user-preference";
|
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
|
||||||
|
|
||||||
import { createChildrenOptions } from "../../../../lib/children";
|
|
||||||
import { createLoadingPreferenceAction, PreferenceDetailHeader } from "./action-row";
|
|
||||||
import { createSelectablePreferenceActions } from "./selectable-actions";
|
|
||||||
|
|
||||||
export const searchEngineChildrenOptions = createChildrenOptions<Record<string, unknown>>({
|
|
||||||
useActions: (_, query) => {
|
|
||||||
const { value, setValue, isPending } = useUserPreference("defaultSearchEngineId");
|
|
||||||
const currentValue = value as string | null;
|
|
||||||
const searchEnginesQuery = clientApi.searchEngine.getSelectable.useQuery();
|
|
||||||
const t = useScopedI18n("search.mode.command.group.preferences.option");
|
|
||||||
|
|
||||||
if (searchEnginesQuery.isLoading) {
|
|
||||||
return [createLoadingPreferenceAction()];
|
|
||||||
}
|
|
||||||
|
|
||||||
return createSelectablePreferenceActions({
|
|
||||||
query,
|
|
||||||
currentValue,
|
|
||||||
noneLabel: t("searchEngine.none"),
|
|
||||||
unavailableLabel: t("searchEngine.unavailable"),
|
|
||||||
items: (searchEnginesQuery.data ?? []).map((engine) => ({
|
|
||||||
key: engine.value,
|
|
||||||
label: engine.label,
|
|
||||||
value: engine.value,
|
|
||||||
})),
|
|
||||||
onSelect: (nextValue) => setValue(nextValue as never),
|
|
||||||
isPending,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
DetailComponent: () => <PreferenceDetailHeader titleKey="defaultSearchEngineId.children.detail.title" />,
|
|
||||||
});
|
|
||||||
@@ -9,6 +9,7 @@ import { clientApi } from "@homarr/api/client";
|
|||||||
import { useSession } from "@homarr/auth/client";
|
import { useSession } from "@homarr/auth/client";
|
||||||
import type { ColorScheme } from "@homarr/definitions";
|
import type { ColorScheme } from "@homarr/definitions";
|
||||||
import type { UserPreferenceKey } from "@homarr/settings";
|
import type { UserPreferenceKey } from "@homarr/settings";
|
||||||
|
import { visiblePreferenceDefinitions } from "@homarr/settings";
|
||||||
import { localeConfigurations } from "@homarr/translation";
|
import { localeConfigurations } from "@homarr/translation";
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
import type { TablerIcon } from "@homarr/ui";
|
import type { TablerIcon } from "@homarr/ui";
|
||||||
@@ -17,7 +18,7 @@ import { createChildrenOptions } from "../../../../lib/children";
|
|||||||
import type { ChildrenAction } from "../../../../lib/children";
|
import type { ChildrenAction } from "../../../../lib/children";
|
||||||
import { interaction } from "../../../../lib/interaction";
|
import { interaction } from "../../../../lib/interaction";
|
||||||
import { useUserPreferences } from "../../../../preferences/use-user-preference";
|
import { useUserPreferences } from "../../../../preferences/use-user-preference";
|
||||||
import { preferenceChildrenOptionsByKey, preferenceIcons, visiblePreferenceDefinitions } from "./registry";
|
import { preferenceChildrenOptionsByKey, preferenceIcons } from "../../../../preferences/preference-registry";
|
||||||
|
|
||||||
dayjs.extend(localeData);
|
dayjs.extend(localeData);
|
||||||
|
|
||||||
@@ -25,17 +26,7 @@ type SettingsAction = ChildrenAction<Record<string, unknown>>;
|
|||||||
|
|
||||||
const weekDays = dayjs.weekdays(false);
|
const weekDays = dayjs.weekdays(false);
|
||||||
|
|
||||||
const BooleanRow = ({
|
const BooleanRow = ({ label, Icon, checked, isPending }: { label: string; Icon: TablerIcon; checked: boolean; isPending: boolean }) => (
|
||||||
label,
|
|
||||||
Icon,
|
|
||||||
checked,
|
|
||||||
isPending,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
Icon: TablerIcon;
|
|
||||||
checked: boolean;
|
|
||||||
isPending: boolean;
|
|
||||||
}) => (
|
|
||||||
<Group mx="md" my="sm" wrap="nowrap" justify="space-between" w="100%">
|
<Group mx="md" my="sm" wrap="nowrap" justify="space-between" w="100%">
|
||||||
<Group wrap="nowrap" gap="sm">
|
<Group wrap="nowrap" gap="sm">
|
||||||
<Icon stroke={1.5} size={20} />
|
<Icon stroke={1.5} size={20} />
|
||||||
@@ -51,9 +42,7 @@ const SelectRow = ({ label, Icon, valueLabel }: { label: string; Icon: TablerIco
|
|||||||
<Icon stroke={1.5} size={20} />
|
<Icon stroke={1.5} size={20} />
|
||||||
<Text>{label}</Text>
|
<Text>{label}</Text>
|
||||||
</Group>
|
</Group>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">{valueLabel}</Text>
|
||||||
{valueLabel}
|
|
||||||
</Text>
|
|
||||||
</Group>
|
</Group>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -64,6 +53,8 @@ const LinkRow = ({ label, Icon }: { label: string; Icon: TablerIcon }) => (
|
|||||||
</Group>
|
</Group>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const SELECT_KINDS = new Set(["select", "searchEngine", "board"]);
|
||||||
|
|
||||||
const useSettingsActions = (_: Record<string, unknown>, query: string): SettingsAction[] => {
|
const useSettingsActions = (_: Record<string, unknown>, query: string): SettingsAction[] => {
|
||||||
const t = useScopedI18n("search.mode.command.group.preferences.option");
|
const t = useScopedI18n("search.mode.command.group.preferences.option");
|
||||||
const tColorScheme = useScopedI18n("common.colorScheme.options");
|
const tColorScheme = useScopedI18n("common.colorScheme.options");
|
||||||
@@ -72,97 +63,65 @@ const useSettingsActions = (_: Record<string, unknown>, query: string): Settings
|
|||||||
const normalizedQuery = query.trim().toLowerCase();
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
const preferences = useUserPreferences();
|
const preferences = useUserPreferences();
|
||||||
|
|
||||||
const colorScheme = preferences.getPreference("colorScheme");
|
|
||||||
const locale = preferences.getPreference("locale");
|
|
||||||
const defaultSearchEngineId = preferences.getPreference("defaultSearchEngineId");
|
|
||||||
const openSearchInNewTab = preferences.getPreference("openSearchInNewTab");
|
|
||||||
const ddgBangs = preferences.getPreference("ddgBangs");
|
|
||||||
const firstDayOfWeek = preferences.getPreference("firstDayOfWeek");
|
|
||||||
const homeBoardId = preferences.getPreference("homeBoardId");
|
|
||||||
const mobileHomeBoardId = preferences.getPreference("mobileHomeBoardId");
|
|
||||||
const pingIconsEnabled = preferences.getPreference("pingIconsEnabled");
|
|
||||||
|
|
||||||
const boardsQuery = clientApi.board.getAllBoards.useQuery(undefined, { enabled: isAuthenticated });
|
const boardsQuery = clientApi.board.getAllBoards.useQuery(undefined, { enabled: isAuthenticated });
|
||||||
const searchEnginesQuery = clientApi.searchEngine.getSelectable.useQuery(undefined, { enabled: isAuthenticated });
|
const searchEnginesQuery = clientApi.searchEngine.getSelectable.useQuery(undefined, { enabled: isAuthenticated });
|
||||||
|
|
||||||
const boards = boardsQuery.data ?? [];
|
const valueLabelResolvers: Record<string, () => string> = {
|
||||||
const engines = searchEnginesQuery.data ?? [];
|
colorScheme: () => tColorScheme(preferences.getPreference("colorScheme").value as ColorScheme),
|
||||||
|
locale: () => {
|
||||||
const prefState: Record<
|
const val = preferences.getPreference("locale").value;
|
||||||
Exclude<UserPreferenceKey, "fullPreferencesPage">,
|
return localeConfigurations[val as keyof typeof localeConfigurations]?.name ?? String(val);
|
||||||
{ value: unknown; setValue: (v: never) => void; isPending: boolean }
|
},
|
||||||
> = {
|
defaultSearchEngineId: () =>
|
||||||
colorScheme,
|
searchEnginesQuery.data?.find((e) => e.value === preferences.getPreference("defaultSearchEngineId").value)?.label ?? t("searchEngine.none" as never),
|
||||||
locale,
|
firstDayOfWeek: () => weekDays[preferences.getPreference("firstDayOfWeek").value as DayOfWeek] ?? "",
|
||||||
defaultSearchEngineId,
|
homeBoardId: () =>
|
||||||
openSearchInNewTab,
|
boardsQuery.data?.find((b) => b.id === preferences.getPreference("homeBoardId").value)?.name ?? t("board.none" as never),
|
||||||
ddgBangs,
|
mobileHomeBoardId: () =>
|
||||||
firstDayOfWeek,
|
boardsQuery.data?.find((b) => b.id === preferences.getPreference("mobileHomeBoardId").value)?.name ?? t("board.none" as never),
|
||||||
homeBoardId,
|
|
||||||
mobileHomeBoardId,
|
|
||||||
pingIconsEnabled,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const valueLabels: Record<Exclude<UserPreferenceKey, "fullPreferencesPage">, string> = {
|
return visiblePreferenceDefinitions(isAuthenticated)
|
||||||
colorScheme: tColorScheme(colorScheme.value as ColorScheme),
|
.map((definition): SettingsAction | null => {
|
||||||
locale: localeConfigurations[locale.value as keyof typeof localeConfigurations]?.name ?? String(locale.value),
|
const label = t(`${definition.key}.label` as never);
|
||||||
defaultSearchEngineId:
|
const Icon = preferenceIcons[definition.key];
|
||||||
engines.find((e) => e.value === defaultSearchEngineId.value)?.label ?? t("searchEngine.none"),
|
|
||||||
openSearchInNewTab: "",
|
|
||||||
ddgBangs: "",
|
|
||||||
firstDayOfWeek: weekDays[firstDayOfWeek.value as DayOfWeek] ?? String(firstDayOfWeek.value),
|
|
||||||
homeBoardId: boards.find((b) => b.id === homeBoardId.value)?.name ?? t("board.none"),
|
|
||||||
mobileHomeBoardId: boards.find((b) => b.id === mobileHomeBoardId.value)?.name ?? t("board.none"),
|
|
||||||
pingIconsEnabled: "",
|
|
||||||
};
|
|
||||||
|
|
||||||
const definitions = visiblePreferenceDefinitions(isAuthenticated);
|
const matchesSearch = [label, ...definition.aliases].some((v) => v.toLowerCase().includes(normalizedQuery));
|
||||||
|
if (!matchesSearch) return null;
|
||||||
|
|
||||||
return definitions.flatMap((definition): SettingsAction[] => {
|
if (definition.kind === "boolean") {
|
||||||
const label = t(`${definition.key}.label` as never);
|
const pref = preferences.getPreference(definition.key);
|
||||||
const Icon = preferenceIcons[definition.key];
|
return {
|
||||||
|
|
||||||
const matchesSearch = [label, ...definition.aliases].some((value) => value.toLowerCase().includes(normalizedQuery));
|
|
||||||
if (!matchesSearch) return [];
|
|
||||||
|
|
||||||
if (definition.kind === "boolean") {
|
|
||||||
const state = prefState[definition.key as keyof typeof prefState];
|
|
||||||
const checked = state.value as boolean;
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
key: definition.key,
|
key: definition.key,
|
||||||
Component: () => <BooleanRow label={label} Icon={Icon} checked={checked} isPending={state.isPending} />,
|
Component: () => <BooleanRow label={label} Icon={Icon} checked={pref.value as boolean} isPending={pref.isPending} />,
|
||||||
useInteraction: interaction.javaScript(() => ({
|
useInteraction: interaction.javaScript(() => ({
|
||||||
onSelect: state.isPending ? () => undefined : () => state.setValue(!checked as never),
|
onSelect: pref.isPending ? () => undefined : () => pref.setValue(!(pref.value as boolean) as never),
|
||||||
closeSpotlightOnTrigger: false,
|
closeSpotlightOnTrigger: false,
|
||||||
})),
|
})),
|
||||||
},
|
};
|
||||||
];
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (definition.kind === "link") {
|
if (definition.kind === "link") {
|
||||||
return [
|
return {
|
||||||
{
|
|
||||||
key: definition.key,
|
key: definition.key,
|
||||||
Component: () => <LinkRow label={label} Icon={Icon} />,
|
Component: () => <LinkRow label={label} Icon={Icon} />,
|
||||||
useInteraction: interaction.link(() => ({
|
useInteraction: interaction.link(() => ({ href: `/manage/users/${session?.user.id ?? ""}/general` })),
|
||||||
href: `/manage/users/${session?.user.id ?? ""}/general`,
|
};
|
||||||
})),
|
}
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
const childrenKey = definition.key as keyof typeof preferenceChildrenOptionsByKey;
|
if (SELECT_KINDS.has(definition.kind)) {
|
||||||
return [
|
const children = preferenceChildrenOptionsByKey[definition.key];
|
||||||
{
|
if (!children) return null;
|
||||||
key: definition.key,
|
return {
|
||||||
Component: () => (
|
key: definition.key,
|
||||||
<SelectRow label={label} Icon={Icon} valueLabel={valueLabels[definition.key as keyof typeof valueLabels]} />
|
Component: () => <SelectRow label={label} Icon={Icon} valueLabel={valueLabelResolvers[definition.key]?.() ?? ""} />,
|
||||||
),
|
useInteraction: interaction.children(children),
|
||||||
useInteraction: interaction.children(preferenceChildrenOptionsByKey[childrenKey]),
|
};
|
||||||
},
|
}
|
||||||
];
|
|
||||||
});
|
return null;
|
||||||
|
})
|
||||||
|
.filter((action): action is SettingsAction => action !== null);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const settingsChildrenOptions = createChildrenOptions<Record<string, unknown>>({
|
export const settingsChildrenOptions = createChildrenOptions<Record<string, unknown>>({
|
||||||
@@ -172,9 +131,7 @@ export const settingsChildrenOptions = createChildrenOptions<Record<string, unkn
|
|||||||
return (
|
return (
|
||||||
<Stack mx="md" my="sm" gap="xs">
|
<Stack mx="md" my="sm" gap="xs">
|
||||||
<Text>{t("title")}</Text>
|
<Text>{t("title")}</Text>
|
||||||
<Text size="xs" c="dimmed">
|
<Text size="xs" c="dimmed">{t("children.detail.backHint")}</Text>
|
||||||
{t("children.detail.backHint")}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,28 +3,18 @@ import { IconSettings } from "@tabler/icons-react";
|
|||||||
|
|
||||||
import { useSession } from "@homarr/auth/client";
|
import { useSession } from "@homarr/auth/client";
|
||||||
import { colorSchemes } from "@homarr/definitions";
|
import { colorSchemes } from "@homarr/definitions";
|
||||||
import { userPreferenceDefinitions } from "@homarr/settings";
|
import { visiblePreferenceDefinitions } from "@homarr/settings";
|
||||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import { createGroup } from "../../lib/group";
|
import { createGroup } from "../../lib/group";
|
||||||
import { preferenceChildrenOptionsByKey, preferenceIcons } from "../command/children/preferences/registry";
|
import { preferenceChildrenOptionsByKey, preferenceIcons } from "../../preferences/preference-registry";
|
||||||
import { settingsChildrenOptions } from "../command/children/preferences/settings-children";
|
import { settingsChildrenOptions } from "../command/children/preferences/settings-children";
|
||||||
|
|
||||||
const normalizeSearchValue = (value: string) => value.trim().toLowerCase();
|
|
||||||
|
|
||||||
type PreferenceChildKey = Extract<keyof typeof preferenceChildrenOptionsByKey, string>;
|
|
||||||
|
|
||||||
type PreferencesGroupOption =
|
type PreferencesGroupOption =
|
||||||
| {
|
| { key: "settings"; preferenceKey: null }
|
||||||
key: "settings";
|
| { key: string; preferenceKey: string };
|
||||||
preferenceKey: null;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
key: PreferenceChildKey;
|
|
||||||
preferenceKey: PreferenceChildKey;
|
|
||||||
};
|
|
||||||
|
|
||||||
const settingsOption = { key: "settings", preferenceKey: null } satisfies PreferencesGroupOption;
|
const settingsOption: PreferencesGroupOption = { key: "settings", preferenceKey: null };
|
||||||
|
|
||||||
export const preferencesGroup = createGroup<PreferencesGroupOption>({
|
export const preferencesGroup = createGroup<PreferencesGroupOption>({
|
||||||
keyPath: "key",
|
keyPath: "key",
|
||||||
@@ -33,40 +23,37 @@ export const preferencesGroup = createGroup<PreferencesGroupOption>({
|
|||||||
const t = useI18n();
|
const t = useI18n();
|
||||||
const tColorScheme = useScopedI18n("common.colorScheme.options");
|
const tColorScheme = useScopedI18n("common.colorScheme.options");
|
||||||
const { data: session } = useSession();
|
const { data: session } = useSession();
|
||||||
const isAuthenticated = Boolean(session?.user);
|
const definitions = visiblePreferenceDefinitions(Boolean(session?.user));
|
||||||
const visibleDefinitions = userPreferenceDefinitions.filter((definition) => definition.guest || isAuthenticated);
|
const q = query.trim().toLowerCase();
|
||||||
const normalizedQuery = normalizeSearchValue(query);
|
|
||||||
if (normalizedQuery.length === 0) return [settingsOption];
|
|
||||||
|
|
||||||
const settingsSearchValues = [
|
if (q.length === 0) return [settingsOption];
|
||||||
t("search.mode.command.group.preferences.title"),
|
|
||||||
...visibleDefinitions.flatMap((definition) => definition.aliases),
|
|
||||||
];
|
|
||||||
|
|
||||||
const matchingPreferenceOptions = visibleDefinitions.flatMap((definition): PreferencesGroupOption[] => {
|
const matching = definitions.flatMap((def): PreferencesGroupOption[] => {
|
||||||
const label = t(`search.mode.command.group.preferences.option.${definition.key}.label` as never);
|
if (!preferenceChildrenOptionsByKey[def.key]) return [];
|
||||||
|
const label = t(`search.mode.command.group.preferences.option.${def.key}.label` as never);
|
||||||
const searchValues = [
|
const searchValues = [
|
||||||
label,
|
label,
|
||||||
...definition.aliases,
|
...def.aliases,
|
||||||
...(definition.key === "colorScheme" ? colorSchemes.map((scheme) => tColorScheme(scheme)) : []),
|
...(def.key === "colorScheme" ? colorSchemes.map((s) => tColorScheme(s)) : []),
|
||||||
];
|
];
|
||||||
if (!searchValues.some((value) => normalizeSearchValue(value).includes(normalizedQuery))) return [];
|
if (!searchValues.some((v) => v.toLowerCase().includes(q))) return [];
|
||||||
if (!(definition.key in preferenceChildrenOptionsByKey)) return [];
|
return [{ key: def.key, preferenceKey: def.key }];
|
||||||
const preferenceKey = definition.key as PreferenceChildKey;
|
|
||||||
|
|
||||||
return [{ key: preferenceKey, preferenceKey }];
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (matchingPreferenceOptions.length > 0) return matchingPreferenceOptions;
|
if (matching.length > 0) return matching;
|
||||||
|
|
||||||
return settingsSearchValues.some((value) => normalizeSearchValue(value).includes(normalizedQuery))
|
const allSearchValues = [
|
||||||
? [settingsOption]
|
t("search.mode.command.group.preferences.title"),
|
||||||
: [];
|
...definitions.flatMap((d) => d.aliases),
|
||||||
|
];
|
||||||
|
return allSearchValues.some((v) => v.toLowerCase().includes(q)) ? [settingsOption] : [];
|
||||||
},
|
},
|
||||||
Component: (option) => {
|
Component: (option) => {
|
||||||
const t = useScopedI18n("search.mode.command.group.preferences");
|
const t = useScopedI18n("search.mode.command.group.preferences");
|
||||||
const tOption = useScopedI18n("search.mode.command.group.preferences.option");
|
const tOption = useScopedI18n("search.mode.command.group.preferences.option");
|
||||||
const Icon = option.preferenceKey ? preferenceIcons[option.preferenceKey] : IconSettings;
|
const Icon = option.preferenceKey
|
||||||
|
? preferenceIcons[option.preferenceKey as keyof typeof preferenceIcons]
|
||||||
|
: IconSettings;
|
||||||
const label = option.preferenceKey ? tOption(`${option.preferenceKey}.label` as never) : t("title");
|
const label = option.preferenceKey ? tOption(`${option.preferenceKey}.label` as never) : t("title");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -79,6 +66,8 @@ export const preferencesGroup = createGroup<PreferencesGroupOption>({
|
|||||||
filter: () => true,
|
filter: () => true,
|
||||||
useInteraction: (option) => ({
|
useInteraction: (option) => ({
|
||||||
type: "children",
|
type: "children",
|
||||||
...(option.preferenceKey ? preferenceChildrenOptionsByKey[option.preferenceKey]({}) : settingsChildrenOptions({})),
|
...(option.preferenceKey
|
||||||
|
? preferenceChildrenOptionsByKey[option.preferenceKey as keyof typeof preferenceChildrenOptionsByKey]!({})
|
||||||
|
: settingsChildrenOptions({})),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
IconActivity,
|
||||||
|
IconCalendarWeek,
|
||||||
|
IconDeviceDesktop,
|
||||||
|
IconExternalLink,
|
||||||
|
IconHome,
|
||||||
|
IconLanguage,
|
||||||
|
IconLayoutBoard,
|
||||||
|
IconSearch,
|
||||||
|
IconSettings,
|
||||||
|
IconWorldWww,
|
||||||
|
} from "@tabler/icons-react";
|
||||||
|
import type { DayOfWeek } from "@mantine/dates";
|
||||||
|
import dayjs from "dayjs";
|
||||||
|
import localeData from "dayjs/plugin/localeData";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import { colorSchemes } from "@homarr/definitions";
|
||||||
|
import type { UserPreferenceKey } from "@homarr/settings";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
import type { TablerIcon } from "@homarr/ui";
|
||||||
|
|
||||||
|
import { createChildrenOptions } from "../lib/children";
|
||||||
|
import {
|
||||||
|
createCheckmarkPreferenceAction,
|
||||||
|
createLoadingPreferenceAction,
|
||||||
|
PreferenceDetailHeader,
|
||||||
|
} from "../modes/command/children/preferences/action-row";
|
||||||
|
import { createSelectablePreferenceActions } from "../modes/command/children/preferences/selectable-actions";
|
||||||
|
import { languageChildrenOptions } from "../modes/command/children/language";
|
||||||
|
import { useUserPreference } from "./use-user-preference";
|
||||||
|
|
||||||
|
dayjs.extend(localeData);
|
||||||
|
|
||||||
|
type ChildrenFactory = ReturnType<typeof createChildrenOptions<Record<string, unknown>>>;
|
||||||
|
|
||||||
|
export const preferenceIcons: Record<UserPreferenceKey, TablerIcon> = {
|
||||||
|
colorScheme: IconDeviceDesktop,
|
||||||
|
locale: IconLanguage,
|
||||||
|
defaultSearchEngineId: IconSearch,
|
||||||
|
openSearchInNewTab: IconExternalLink,
|
||||||
|
ddgBangs: IconWorldWww,
|
||||||
|
firstDayOfWeek: IconCalendarWeek,
|
||||||
|
homeBoardId: IconHome,
|
||||||
|
mobileHomeBoardId: IconLayoutBoard,
|
||||||
|
pingIconsEnabled: IconActivity,
|
||||||
|
fullPreferencesPage: IconSettings,
|
||||||
|
};
|
||||||
|
|
||||||
|
const createStaticChildren = (
|
||||||
|
preferenceKey: UserPreferenceKey,
|
||||||
|
useOptions: () => Array<{ key: string; label: string; value: unknown }>,
|
||||||
|
): ChildrenFactory =>
|
||||||
|
createChildrenOptions<Record<string, unknown>>({
|
||||||
|
useActions: () => {
|
||||||
|
const { value, setValue, isPending } = useUserPreference(preferenceKey);
|
||||||
|
return useOptions().map((opt) =>
|
||||||
|
createCheckmarkPreferenceAction({
|
||||||
|
key: opt.key,
|
||||||
|
label: opt.label,
|
||||||
|
isSelected: value === opt.value,
|
||||||
|
onSelect: () => setValue(opt.value as never),
|
||||||
|
isPending,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
DetailComponent: () => <PreferenceDetailHeader titleKey={`${preferenceKey}.children.detail.title`} />,
|
||||||
|
});
|
||||||
|
|
||||||
|
const createAsyncSelectableChildren = <TItem,>(
|
||||||
|
preferenceKey: UserPreferenceKey,
|
||||||
|
useQuery: () => { data: TItem[] | undefined; isLoading: boolean },
|
||||||
|
mapItem: (item: TItem) => { key: string; label: string; value: string },
|
||||||
|
noneKey: string,
|
||||||
|
unavailableKey: string,
|
||||||
|
): ChildrenFactory =>
|
||||||
|
createChildrenOptions<Record<string, unknown>>({
|
||||||
|
useActions: (_, query) => {
|
||||||
|
const { value, setValue, isPending } = useUserPreference(preferenceKey);
|
||||||
|
const result = useQuery();
|
||||||
|
const t = useScopedI18n("search.mode.command.group.preferences.option");
|
||||||
|
|
||||||
|
if (result.isLoading) return [createLoadingPreferenceAction()];
|
||||||
|
|
||||||
|
return createSelectablePreferenceActions({
|
||||||
|
query,
|
||||||
|
currentValue: value as string | null,
|
||||||
|
noneLabel: t(noneKey as never),
|
||||||
|
unavailableLabel: t(unavailableKey as never),
|
||||||
|
items: (result.data ?? []).map(mapItem),
|
||||||
|
onSelect: (v) => setValue(v as never),
|
||||||
|
isPending,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
DetailComponent: () => <PreferenceDetailHeader titleKey={`${preferenceKey}.children.detail.title`} />,
|
||||||
|
});
|
||||||
|
|
||||||
|
const weekDays = dayjs.weekdays(false);
|
||||||
|
const firstDayOfWeekOptions: DayOfWeek[] = [1, 6, 0];
|
||||||
|
|
||||||
|
export const preferenceChildrenOptionsByKey: Partial<Record<UserPreferenceKey, ChildrenFactory>> = {
|
||||||
|
colorScheme: createStaticChildren("colorScheme", () => {
|
||||||
|
const t = useScopedI18n("common.colorScheme.options");
|
||||||
|
return colorSchemes.map((s) => ({ key: s, label: t(s), value: s }));
|
||||||
|
}),
|
||||||
|
locale: languageChildrenOptions,
|
||||||
|
defaultSearchEngineId: createAsyncSelectableChildren(
|
||||||
|
"defaultSearchEngineId",
|
||||||
|
() => clientApi.searchEngine.getSelectable.useQuery(),
|
||||||
|
(e) => ({ key: e.value, label: e.label, value: e.value }),
|
||||||
|
"searchEngine.none",
|
||||||
|
"searchEngine.unavailable",
|
||||||
|
),
|
||||||
|
firstDayOfWeek: createStaticChildren("firstDayOfWeek", () =>
|
||||||
|
firstDayOfWeekOptions.map((day) => ({
|
||||||
|
key: day.toString(),
|
||||||
|
label: weekDays[day] ?? day.toString(),
|
||||||
|
value: day,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
homeBoardId: createAsyncSelectableChildren(
|
||||||
|
"homeBoardId",
|
||||||
|
() => clientApi.board.getAllBoards.useQuery(),
|
||||||
|
(b) => ({ key: b.id, label: b.name, value: b.id }),
|
||||||
|
"board.none",
|
||||||
|
"board.unavailable",
|
||||||
|
),
|
||||||
|
mobileHomeBoardId: createAsyncSelectableChildren(
|
||||||
|
"mobileHomeBoardId",
|
||||||
|
() => clientApi.board.getAllBoards.useQuery(),
|
||||||
|
(b) => ({ key: b.id, label: b.name, value: b.id }),
|
||||||
|
"board.none",
|
||||||
|
"board.unavailable",
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -10,76 +10,59 @@ import { useSession } from "@homarr/auth/client";
|
|||||||
import type { ColorScheme } from "@homarr/definitions";
|
import type { ColorScheme } from "@homarr/definitions";
|
||||||
import { showErrorNotification } from "@homarr/notifications";
|
import { showErrorNotification } from "@homarr/notifications";
|
||||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||||
|
import {
|
||||||
|
userPreferenceDefinitions,
|
||||||
|
userPreferenceDefinitionByKey,
|
||||||
|
} from "@homarr/settings";
|
||||||
import type { UserPreferenceKey } from "@homarr/settings";
|
import type { UserPreferenceKey } from "@homarr/settings";
|
||||||
import { useSettings } from "@homarr/settings";
|
import { useSettings } from "@homarr/settings";
|
||||||
import { useChangeLocale, useCurrentLocale, useI18n } from "@homarr/translation/client";
|
import { useChangeLocale, useCurrentLocale, useI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
const optimisticPreferenceKeys = new Set<UserPreferenceKey>([
|
// --- Optimistic store (module-level, shared across all hook instances) ---
|
||||||
"defaultSearchEngineId",
|
|
||||||
"openSearchInNewTab",
|
|
||||||
"ddgBangs",
|
|
||||||
"firstDayOfWeek",
|
|
||||||
"homeBoardId",
|
|
||||||
"mobileHomeBoardId",
|
|
||||||
"pingIconsEnabled",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const optimisticPreferencesRef: { current: Partial<Record<UserPreferenceKey, unknown>> } = { current: {} };
|
const optimisticRef: { current: Partial<Record<UserPreferenceKey, unknown>> } = { current: {} };
|
||||||
let optimisticPreferencesVersion = 0;
|
let optimisticVersion = 0;
|
||||||
const optimisticPreferenceListeners = new Set<() => void>();
|
const optimisticListeners = new Set<() => void>();
|
||||||
|
|
||||||
const searchPreferenceKeys = ["defaultSearchEngineId", "openSearchInNewTab", "ddgBangs"] as const;
|
const notifyListeners = () => {
|
||||||
const homeBoardPreferenceKeys = ["homeBoardId", "mobileHomeBoardId"] as const;
|
optimisticVersion += 1;
|
||||||
|
optimisticListeners.forEach((fn) => fn());
|
||||||
const notifyOptimisticPreferenceListeners = () => {
|
|
||||||
optimisticPreferencesVersion += 1;
|
|
||||||
optimisticPreferenceListeners.forEach((listener) => listener());
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const subscribeToOptimisticPreferenceChanges = (listener: () => void) => {
|
const subscribeOptimistic = (listener: () => void) => {
|
||||||
optimisticPreferenceListeners.add(listener);
|
optimisticListeners.add(listener);
|
||||||
return () => optimisticPreferenceListeners.delete(listener);
|
return () => optimisticListeners.delete(listener);
|
||||||
};
|
};
|
||||||
|
|
||||||
const setOptimisticPreference = (preferenceKey: UserPreferenceKey, value: unknown) => {
|
const setOptimistic = (key: UserPreferenceKey, value: unknown) => {
|
||||||
optimisticPreferencesRef.current[preferenceKey] = value;
|
optimisticRef.current[key] = value;
|
||||||
notifyOptimisticPreferenceListeners();
|
notifyListeners();
|
||||||
};
|
};
|
||||||
|
|
||||||
const clearOptimisticPreferences = (keys: readonly UserPreferenceKey[]) => {
|
const clearOptimistic = (keys: readonly UserPreferenceKey[]) => {
|
||||||
let changed = false;
|
let changed = false;
|
||||||
keys.forEach((preferenceKey) => {
|
for (const key of keys) {
|
||||||
changed ||= preferenceKey in optimisticPreferencesRef.current;
|
changed ||= key in optimisticRef.current;
|
||||||
delete optimisticPreferencesRef.current[preferenceKey];
|
delete optimisticRef.current[key];
|
||||||
});
|
|
||||||
if (!changed) return;
|
|
||||||
|
|
||||||
notifyOptimisticPreferenceListeners();
|
|
||||||
};
|
|
||||||
|
|
||||||
const getEffectivePreferenceValue = (preferenceKey: UserPreferenceKey, settings: SettingsContextProps): unknown => {
|
|
||||||
const optimisticValue = optimisticPreferencesRef.current[preferenceKey];
|
|
||||||
if (optimisticValue !== undefined) {
|
|
||||||
return optimisticValue;
|
|
||||||
}
|
}
|
||||||
|
if (changed) notifyListeners();
|
||||||
const settingsValues: Partial<Record<UserPreferenceKey, unknown>> = {
|
|
||||||
defaultSearchEngineId: settings.defaultSearchEngineId,
|
|
||||||
openSearchInNewTab: settings.openSearchInNewTab,
|
|
||||||
ddgBangs: settings.ddgBangs,
|
|
||||||
firstDayOfWeek: settings.firstDayOfWeek,
|
|
||||||
homeBoardId: settings.homeBoardId,
|
|
||||||
mobileHomeBoardId: settings.mobileHomeBoardId,
|
|
||||||
pingIconsEnabled: settings.pingIconsEnabled,
|
|
||||||
};
|
|
||||||
|
|
||||||
return settingsValues[preferenceKey];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const refreshAfterMutation = (router: ReturnType<typeof useRouter>) => {
|
const CLIENT_ONLY_GROUPS = new Set(["colorScheme", "locale"]);
|
||||||
router.refresh();
|
|
||||||
|
const isDbBacked = (key: UserPreferenceKey) => {
|
||||||
|
const group = userPreferenceDefinitionByKey[key].mutationGroup;
|
||||||
|
return group !== null && !CLIENT_ONLY_GROUPS.has(group);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getGroupKeys = (key: UserPreferenceKey): UserPreferenceKey[] => {
|
||||||
|
const group = userPreferenceDefinitionByKey[key].mutationGroup;
|
||||||
|
if (!group) return [key];
|
||||||
|
return userPreferenceDefinitions.filter((d) => d.mutationGroup === group).map((d) => d.key);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Hook ---
|
||||||
|
|
||||||
export const useUserPreferences = () => {
|
export const useUserPreferences = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const settings = useSettings();
|
const settings = useSettings();
|
||||||
@@ -91,257 +74,125 @@ export const useUserPreferences = () => {
|
|||||||
const currentLocale = useCurrentLocale();
|
const currentLocale = useCurrentLocale();
|
||||||
const { changeLocale } = useChangeLocale();
|
const { changeLocale } = useChangeLocale();
|
||||||
const t = useI18n();
|
const t = useI18n();
|
||||||
const pendingGroupsRef = useRef({
|
const userId = session?.user.id;
|
||||||
search: false,
|
const pendingRef = useRef<Record<string, boolean>>({});
|
||||||
homeBoards: false,
|
|
||||||
firstDayOfWeek: false,
|
|
||||||
pingIcons: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
useSyncExternalStore(
|
useSyncExternalStore(subscribeOptimistic, () => optimisticVersion, () => optimisticVersion);
|
||||||
subscribeToOptimisticPreferenceChanges,
|
|
||||||
() => optimisticPreferencesVersion,
|
|
||||||
() => optimisticPreferencesVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
const showPreferenceErrorNotification = () => {
|
const refresh = () => router.refresh();
|
||||||
showErrorNotification({
|
|
||||||
message: t("search.mode.command.group.preferences.notification.error.message"),
|
const searchMutation = clientApi.user.changeSearchPreferences.useMutation({ onSuccess: refresh });
|
||||||
});
|
const homeBoardsMutation = clientApi.user.changeHomeBoards.useMutation({ onSuccess: refresh });
|
||||||
|
const firstDayMutation = clientApi.user.changeFirstDayOfWeek.useMutation({ onSuccess: refresh });
|
||||||
|
const pingMutation = clientApi.user.changePingIconsEnabled.useMutation({ onSuccess: refresh });
|
||||||
|
|
||||||
|
const getEffective = (key: UserPreferenceKey): unknown =>
|
||||||
|
key in optimisticRef.current
|
||||||
|
? optimisticRef.current[key]
|
||||||
|
: settingsRef.current[key as keyof SettingsContextProps];
|
||||||
|
|
||||||
|
const pick = (field: UserPreferenceKey, changedKey: UserPreferenceKey, value: unknown) =>
|
||||||
|
field === changedKey ? value : getEffective(field);
|
||||||
|
|
||||||
|
const groupDispatchers: Record<string, (key: UserPreferenceKey, value: unknown) => Promise<unknown>> = {
|
||||||
|
searchPreferences: (key, value) =>
|
||||||
|
searchMutation.mutateAsync({
|
||||||
|
userId: userId!,
|
||||||
|
defaultSearchEngineId: pick("defaultSearchEngineId", key, value) as string | null,
|
||||||
|
openInNewTab: pick("openSearchInNewTab", key, value) as boolean,
|
||||||
|
ddgBangsEnabled: pick("ddgBangs", key, value) as boolean,
|
||||||
|
}),
|
||||||
|
homeBoards: (key, value) =>
|
||||||
|
homeBoardsMutation.mutateAsync({
|
||||||
|
userId: userId!,
|
||||||
|
homeBoardId: pick("homeBoardId", key, value) as string | null,
|
||||||
|
mobileHomeBoardId: pick("mobileHomeBoardId", key, value) as string | null,
|
||||||
|
}),
|
||||||
|
firstDayOfWeek: (_key, value) =>
|
||||||
|
firstDayMutation.mutateAsync({ id: userId!, firstDayOfWeek: value as DayOfWeek }),
|
||||||
|
pingIconsEnabled: (_key, value) =>
|
||||||
|
pingMutation.mutateAsync({ id: userId!, pingIconsEnabled: value as boolean }),
|
||||||
};
|
};
|
||||||
|
|
||||||
const { mutateAsync: mutateSearchPreferencesAsync, isPending: isSearchPreferencesPending } =
|
const groupPending: Record<string, boolean> = {
|
||||||
clientApi.user.changeSearchPreferences.useMutation({
|
searchPreferences: searchMutation.isPending,
|
||||||
onSuccess: () => refreshAfterMutation(router),
|
homeBoards: homeBoardsMutation.isPending,
|
||||||
});
|
firstDayOfWeek: firstDayMutation.isPending,
|
||||||
|
pingIconsEnabled: pingMutation.isPending,
|
||||||
|
};
|
||||||
|
|
||||||
const { mutateAsync: mutateHomeBoardsAsync, isPending: isHomeBoardsPending } =
|
const persistedValues = useMemo<Record<UserPreferenceKey, unknown>>(() => {
|
||||||
clientApi.user.changeHomeBoards.useMutation({
|
const values: Record<string, unknown> = {
|
||||||
onSuccess: () => refreshAfterMutation(router),
|
|
||||||
});
|
|
||||||
|
|
||||||
const { mutateAsync: mutateFirstDayOfWeekAsync, isPending: isFirstDayOfWeekPending } =
|
|
||||||
clientApi.user.changeFirstDayOfWeek.useMutation({
|
|
||||||
onSuccess: () => refreshAfterMutation(router),
|
|
||||||
});
|
|
||||||
|
|
||||||
const { mutateAsync: mutatePingIconsEnabledAsync, isPending: isPingIconsPending } =
|
|
||||||
clientApi.user.changePingIconsEnabled.useMutation({
|
|
||||||
onSuccess: () => refreshAfterMutation(router),
|
|
||||||
});
|
|
||||||
|
|
||||||
const userId = session?.user.id;
|
|
||||||
|
|
||||||
const persistedValues = useMemo<Record<UserPreferenceKey, unknown>>(
|
|
||||||
() => ({
|
|
||||||
colorScheme: colorScheme as ColorScheme,
|
colorScheme: colorScheme as ColorScheme,
|
||||||
locale: currentLocale,
|
locale: currentLocale,
|
||||||
defaultSearchEngineId: settings.defaultSearchEngineId,
|
|
||||||
openSearchInNewTab: settings.openSearchInNewTab,
|
|
||||||
ddgBangs: settings.ddgBangs,
|
|
||||||
firstDayOfWeek: settings.firstDayOfWeek,
|
|
||||||
homeBoardId: settings.homeBoardId,
|
|
||||||
mobileHomeBoardId: settings.mobileHomeBoardId,
|
|
||||||
pingIconsEnabled: settings.pingIconsEnabled,
|
|
||||||
fullPreferencesPage: userId ? `/manage/users/${userId}/general` : null,
|
fullPreferencesPage: userId ? `/manage/users/${userId}/general` : null,
|
||||||
}),
|
};
|
||||||
[
|
for (const def of userPreferenceDefinitions) {
|
||||||
colorScheme,
|
if (def.key in values) continue;
|
||||||
currentLocale,
|
values[def.key] = settings[def.key as keyof SettingsContextProps];
|
||||||
settings.defaultSearchEngineId,
|
}
|
||||||
settings.openSearchInNewTab,
|
return values as Record<UserPreferenceKey, unknown>;
|
||||||
settings.ddgBangs,
|
}, [colorScheme, currentLocale, userId, settings]);
|
||||||
settings.firstDayOfWeek,
|
|
||||||
settings.homeBoardId,
|
|
||||||
settings.mobileHomeBoardId,
|
|
||||||
settings.pingIconsEnabled,
|
|
||||||
userId,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
const getValue = (preferenceKey: UserPreferenceKey) =>
|
|
||||||
preferenceKey in optimisticPreferencesRef.current
|
|
||||||
? optimisticPreferencesRef.current[preferenceKey]
|
|
||||||
: persistedValues[preferenceKey];
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
clearOptimisticPreferences(
|
const matchedKeys = Object.entries(persistedValues)
|
||||||
Object.entries(persistedValues)
|
.filter(([key, value]) => optimisticRef.current[key as UserPreferenceKey] === value)
|
||||||
.filter(
|
.map(([key]) => key as UserPreferenceKey);
|
||||||
([preferenceKey, value]) => optimisticPreferencesRef.current[preferenceKey as UserPreferenceKey] === value,
|
clearOptimistic(matchedKeys);
|
||||||
)
|
|
||||||
.map(([preferenceKey]) => preferenceKey as UserPreferenceKey),
|
|
||||||
);
|
|
||||||
}, [persistedValues]);
|
}, [persistedValues]);
|
||||||
|
|
||||||
const setPersistedValueAsync = async (key: UserPreferenceKey, value: never) => {
|
const getValue = (key: UserPreferenceKey) =>
|
||||||
const currentSettings = settingsRef.current;
|
key in optimisticRef.current ? optimisticRef.current[key] : persistedValues[key];
|
||||||
|
|
||||||
const setters: Record<UserPreferenceKey, (nextValue: never) => Promise<void> | void> = {
|
const isPreferencePending = (key: UserPreferenceKey): boolean => {
|
||||||
colorScheme: (nextValue) => setColorScheme(nextValue as ColorScheme),
|
const group = userPreferenceDefinitionByKey[key].mutationGroup;
|
||||||
locale: (nextValue) => changeLocale(nextValue as typeof currentLocale),
|
if (!group || CLIENT_ONLY_GROUPS.has(group)) return false;
|
||||||
defaultSearchEngineId: async (nextValue) => {
|
return (groupPending[group] ?? false) || (pendingRef.current[group] ?? false);
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.search) return;
|
|
||||||
pendingGroupsRef.current.search = true;
|
|
||||||
try {
|
|
||||||
await mutateSearchPreferencesAsync({
|
|
||||||
userId,
|
|
||||||
defaultSearchEngineId: nextValue as string | null,
|
|
||||||
openInNewTab: getEffectivePreferenceValue("openSearchInNewTab", currentSettings) as boolean,
|
|
||||||
ddgBangsEnabled: getEffectivePreferenceValue("ddgBangs", currentSettings) as boolean,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.search = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
openSearchInNewTab: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.search) return;
|
|
||||||
pendingGroupsRef.current.search = true;
|
|
||||||
try {
|
|
||||||
await mutateSearchPreferencesAsync({
|
|
||||||
userId,
|
|
||||||
defaultSearchEngineId: getEffectivePreferenceValue("defaultSearchEngineId", currentSettings) as
|
|
||||||
| string
|
|
||||||
| null,
|
|
||||||
openInNewTab: nextValue as boolean,
|
|
||||||
ddgBangsEnabled: getEffectivePreferenceValue("ddgBangs", currentSettings) as boolean,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.search = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
ddgBangs: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.search) return;
|
|
||||||
pendingGroupsRef.current.search = true;
|
|
||||||
try {
|
|
||||||
await mutateSearchPreferencesAsync({
|
|
||||||
userId,
|
|
||||||
defaultSearchEngineId: getEffectivePreferenceValue("defaultSearchEngineId", currentSettings) as
|
|
||||||
| string
|
|
||||||
| null,
|
|
||||||
openInNewTab: getEffectivePreferenceValue("openSearchInNewTab", currentSettings) as boolean,
|
|
||||||
ddgBangsEnabled: nextValue as boolean,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.search = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
firstDayOfWeek: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.firstDayOfWeek) return;
|
|
||||||
pendingGroupsRef.current.firstDayOfWeek = true;
|
|
||||||
try {
|
|
||||||
await mutateFirstDayOfWeekAsync({ id: userId, firstDayOfWeek: nextValue as DayOfWeek });
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.firstDayOfWeek = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
homeBoardId: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.homeBoards) return;
|
|
||||||
pendingGroupsRef.current.homeBoards = true;
|
|
||||||
try {
|
|
||||||
await mutateHomeBoardsAsync({
|
|
||||||
userId,
|
|
||||||
homeBoardId: nextValue as string | null,
|
|
||||||
mobileHomeBoardId: getEffectivePreferenceValue("mobileHomeBoardId", currentSettings) as string | null,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.homeBoards = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mobileHomeBoardId: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.homeBoards) return;
|
|
||||||
pendingGroupsRef.current.homeBoards = true;
|
|
||||||
try {
|
|
||||||
await mutateHomeBoardsAsync({
|
|
||||||
userId,
|
|
||||||
homeBoardId: getEffectivePreferenceValue("homeBoardId", currentSettings) as string | null,
|
|
||||||
mobileHomeBoardId: nextValue as string | null,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.homeBoards = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
pingIconsEnabled: async (nextValue) => {
|
|
||||||
if (!userId) return;
|
|
||||||
if (pendingGroupsRef.current.pingIcons) return;
|
|
||||||
pendingGroupsRef.current.pingIcons = true;
|
|
||||||
try {
|
|
||||||
await mutatePingIconsEnabledAsync({ id: userId, pingIconsEnabled: nextValue as boolean });
|
|
||||||
} finally {
|
|
||||||
pendingGroupsRef.current.pingIcons = false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
fullPreferencesPage: () => undefined,
|
|
||||||
};
|
|
||||||
|
|
||||||
await setters[key](value);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const isPreferencePending = (key: UserPreferenceKey) => {
|
const clientSetters: Partial<Record<UserPreferenceKey, (value: unknown) => void>> = {
|
||||||
if (searchPreferenceKeys.includes(key as never))
|
colorScheme: (value) => setColorScheme(value as ColorScheme),
|
||||||
return isSearchPreferencesPending || pendingGroupsRef.current.search;
|
locale: (value) => changeLocale(value as typeof currentLocale),
|
||||||
if (homeBoardPreferenceKeys.includes(key as never))
|
fullPreferencesPage: () => undefined,
|
||||||
return isHomeBoardsPending || pendingGroupsRef.current.homeBoards;
|
|
||||||
if (key === "firstDayOfWeek") return isFirstDayOfWeekPending || pendingGroupsRef.current.firstDayOfWeek;
|
|
||||||
if (key === "pingIconsEnabled") return isPingIconsPending || pendingGroupsRef.current.pingIcons;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const setValueAsync = async (key: UserPreferenceKey, value: never) => {
|
const setValueAsync = async (key: UserPreferenceKey, value: unknown) => {
|
||||||
if (optimisticPreferenceKeys.has(key) && !userId) return;
|
if (isDbBacked(key) && !userId) return;
|
||||||
if (isPreferencePending(key)) return;
|
if (isPreferencePending(key)) return;
|
||||||
|
|
||||||
if (optimisticPreferenceKeys.has(key)) {
|
const clientSetter = clientSetters[key];
|
||||||
setOptimisticPreference(key, value);
|
if (clientSetter) {
|
||||||
|
clientSetter(value);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setOptimistic(key, value);
|
||||||
|
const group = userPreferenceDefinitionByKey[key].mutationGroup!;
|
||||||
|
const dispatcher = groupDispatchers[group];
|
||||||
|
if (!dispatcher) return;
|
||||||
|
|
||||||
|
pendingRef.current[group] = true;
|
||||||
try {
|
try {
|
||||||
await setPersistedValueAsync(key, value);
|
await dispatcher(key, value);
|
||||||
} catch {
|
} catch {
|
||||||
if (searchPreferenceKeys.includes(key as never)) {
|
clearOptimistic(getGroupKeys(key));
|
||||||
clearOptimisticPreferences(searchPreferenceKeys);
|
showErrorNotification({
|
||||||
} else if (homeBoardPreferenceKeys.includes(key as never)) {
|
message: t("search.mode.command.group.preferences.notification.error.message"),
|
||||||
clearOptimisticPreferences(homeBoardPreferenceKeys);
|
});
|
||||||
} else {
|
} finally {
|
||||||
clearOptimisticPreferences([key]);
|
pendingRef.current[group] = false;
|
||||||
}
|
|
||||||
showPreferenceErrorNotification();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const pendingStates: Record<UserPreferenceKey, boolean> = {
|
|
||||||
colorScheme: false,
|
|
||||||
locale: false,
|
|
||||||
defaultSearchEngineId: isPreferencePending("defaultSearchEngineId"),
|
|
||||||
openSearchInNewTab: isPreferencePending("openSearchInNewTab"),
|
|
||||||
ddgBangs: isPreferencePending("ddgBangs"),
|
|
||||||
firstDayOfWeek: isPreferencePending("firstDayOfWeek"),
|
|
||||||
homeBoardId: isPreferencePending("homeBoardId"),
|
|
||||||
mobileHomeBoardId: isPreferencePending("mobileHomeBoardId"),
|
|
||||||
pingIconsEnabled: isPreferencePending("pingIconsEnabled"),
|
|
||||||
fullPreferencesPage: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getPreference(preferenceKey: UserPreferenceKey) {
|
getPreference(preferenceKey: UserPreferenceKey) {
|
||||||
return {
|
return {
|
||||||
value: getValue(preferenceKey),
|
value: getValue(preferenceKey),
|
||||||
setValue: (value: never) => setValueAsync(preferenceKey, value),
|
setValue: (value: never) => setValueAsync(preferenceKey, value),
|
||||||
isPending: pendingStates[preferenceKey],
|
isPending: isPreferencePending(preferenceKey),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useUserPreference = (key: UserPreferenceKey) => {
|
export const useUserPreference = (key: UserPreferenceKey) => useUserPreferences().getPreference(key);
|
||||||
const preferences = useUserPreferences();
|
|
||||||
|
|
||||||
return preferences.getPreference(key);
|
|
||||||
};
|
|
||||||
Reference in new issue
Block a user