feat: complete automatic mobile board UX

This commit is contained in:
ajnart committed 2026-07-28 19:39:13 +02:00
1 parent cf83e0d849
commit 7959c20d88
87 files changed
+2850 -570

No files matched your search

@@ -18,6 +18,8 @@ import { isNullOrWhitespace } from "@homarr/common";
import { userAgent } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import type { WidgetKind } from "@homarr/definitions";
import { getQueryCacheAsync } from "@homarr/redis";
import { getI18n } from "@homarr/translation/server";
@@ -54,7 +56,12 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
const resolvedParams = await params;
const queryClient = getQueryClient();
const [board, session, requestHeaders] = await Promise.all([getInitialBoard(resolvedParams), auth(), headers()]);
const [board, session, requestHeaders, boardSettings] = await Promise.all([
getInitialBoard(resolvedParams),
auth(),
headers(),
getServerSettingByKeyAsync(db, "board"),
]);
const deviceType = userAgent(new Headers(requestHeaders)).device.type;
const itemsMap = board.items.reduce((acc, item) => {
@@ -70,7 +77,9 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
const [integrations] = await Promise.all([
getIntegrationsWithPermissionsAsync(session),
...Array.from(itemsMap)
.filter(([kind]) => shouldPrefetchWidgetForRequest(kind, deviceType))
.filter(([kind]) =>
shouldPrefetchWidgetForRequest(kind, deviceType, boardSettings.enableAutomaticMobileLayout),
)
.map(([kind, items]) =>
prefetchForKindAsync(kind, queryClient, items).catch((error) => {
logger.error(
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
import { Box, Button, Divider, Drawer, Group, Menu, ScrollArea, Stack, Text } from "@mantine/core";
@@ -29,7 +29,8 @@ import {
import { clientApi } from "@homarr/api/client";
import { signOut, useSession } from "@homarr/auth/client";
import { getDesktopLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import type { BoardEditAction, BoardEditActionEvent } from "@homarr/boards/edit-mode";
import { boardEditActionEventName, requestBoardEditAction, useEditMode } from "@homarr/boards/edit-mode";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { env } from "@homarr/common/env";
import { hotkeys } from "@homarr/definitions";
@@ -61,6 +62,8 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool
const isMobile = useIsMobileBoard();
const t = useI18n();
usePreventLeaveWithDirty(isEditMode);
if (isMobile) {
return <MobileMoreMenu showSettings={hasChangeAccess && !demoReadOnly} />;
}
@@ -215,8 +218,6 @@ const EditModeMenu = ({ demoReadOnly, hidden }: { demoReadOnly: boolean; hidden:
}, [board, isEditMode, demoReadOnly, saveBoard, open, discardDemoChanges, hidden]);
useHotkeys([[hotkeys.toggleBoardEdit, toggle]]);
usePreventLeaveWithDirty(isEditMode);
if (hidden) return null;
return (
@@ -269,6 +270,7 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
const tProfile = useScopedI18n("common.userAvatar.menu");
const reduceMotion = useReducedMotion();
const [opened, disclosure] = useDisclosure(false);
const [isSigningOut, setIsSigningOut] = useState(false);
const moreTriggerRef = useRef<HTMLButtonElement>(null);
const pendingSectionAnchorId = useRef<string | null>(null);
const desktopLayout = getDesktopLayout(board);
@@ -290,6 +292,26 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
moreTriggerRef.current?.focus({ preventScroll: true });
};
const handleSignOut = useCallback(async () => {
setIsSigningOut(true);
try {
const response = await signOut({ redirect: false });
if (typeof response.url !== "string" || response.url.length === 0) {
throw new Error("Sign out did not return a success URL");
}
window.location.replace(logoutUrl ?? "/auth/login");
return true;
} catch {
setIsSigningOut(false);
showErrorNotification({
title: tProfile("logoutError.title"),
message: tProfile("logoutError.message"),
});
return false;
}
}, [logoutUrl, tProfile]);
return (
<>
<HeaderButton ref={moreTriggerRef} onClick={disclosure.open} aria-label={t("board.mobile.more")}>
@@ -391,13 +413,8 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
size="lg"
justify="flex-start"
leftSection={<IconLogout size={20} />}
onClick={() => {
void signOut({ redirect: false })
.catch(() => undefined)
.then(() => {
window.location.assign(logoutUrl ?? "/auth/login");
});
}}
loading={isSigningOut}
onClick={() => requestBoardEditAction(handleSignOut)}
>
{tProfile("logout")}
</Button>
@@ -432,62 +449,207 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
);
};
const anchorSelector = "a[href]:not([target='_blank'])";
const anchorSelector = "a[href]:not([target='_blank']):not([download])";
const usePreventLeaveWithDirty = (isDirty: boolean) => {
const t = useI18n();
const { openConfirmModal } = useConfirmModal();
const router = useRouter();
const dependenciesRef = useRef({ openConfirmModal, router, t });
useEffect(() => {
dependenciesRef.current = { openConfirmModal, router, t };
}, [openConfirmModal, router, t]);
useEffect(() => {
if (!isDirty) return;
const handleClick = (event: Event) => {
const target = (event.target as HTMLElement).closest("a");
const guardStateKey = "__homarrBoardEditGuard";
const guardId = `${Date.now()}-${Math.random()}`;
let guardedUrl = window.location.href;
let isLeaving = false;
let isConfirming = false;
let isActionPending = false;
let shouldRemoveGuardEntry = true;
let didPageHide = false;
let departureFallbackTimer: number | undefined;
if (!target) {
console.warn("No anchor element found for click event", event);
return;
const pushGuardEntry = () => {
window.history.pushState(
{
...(window.history.state as Record<string, unknown> | null),
[guardStateKey]: guardId,
},
document.title,
guardedUrl,
);
};
const rearmGuard = () => {
window.clearTimeout(departureFallbackTimer);
departureFallbackTimer = undefined;
isLeaving = false;
shouldRemoveGuardEntry = true;
if (
window.location.href === guardedUrl &&
(window.history.state as Record<string, unknown> | null)?.[guardStateKey] !== guardId
) {
pushGuardEntry();
}
};
event.preventDefault();
const scheduleDepartureFallback = () => {
window.clearTimeout(departureFallbackTimer);
departureFallbackTimer = window.setTimeout(() => {
departureFallbackTimer = undefined;
if (!didPageHide) {
guardedUrl = window.location.href;
rearmGuard();
}
}, 1_000);
};
openConfirmModal({
title: t("board.action.edit.confirmLeave.title"),
children: t("board.action.edit.confirmLeave.message"),
onConfirm() {
router.push(target.href);
const openLeaveConfirmation = (action: BoardEditAction) => {
if (isConfirming) return;
isConfirming = true;
const dependencies = dependenciesRef.current;
dependencies.openConfirmModal({
title: dependencies.t("board.action.edit.confirmLeave.title"),
children: dependencies.t("board.action.edit.confirmLeave.message"),
async onConfirm() {
isActionPending = true;
isLeaving = true;
shouldRemoveGuardEntry = false;
didPageHide = false;
try {
const result = await action();
if (result === false) {
rearmGuard();
} else {
scheduleDepartureFallback();
}
} catch {
rearmGuard();
} finally {
isActionPending = false;
isConfirming = false;
}
},
onClose() {
if (!isActionPending) {
isConfirming = false;
}
},
confirmProps: {
children: t("common.action.discard"),
children: dependencies.t("common.action.discard"),
},
});
};
const handlePopState = (event: Event) => {
window.history.pushState(null, document.title, window.location.href);
pushGuardEntry();
const handleClick = (event: MouseEvent) => {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey ||
!(event.target instanceof Element)
) {
return;
}
const target = event.target.closest<HTMLAnchorElement>(anchorSelector);
if (!target) return;
event.preventDefault();
const destination = new URL(target.href, window.location.href);
openLeaveConfirmation(() => {
if (destination.origin === window.location.origin) {
dependenciesRef.current.router.replace(`${destination.pathname}${destination.search}${destination.hash}`);
} else {
window.location.replace(destination.href);
}
return true;
});
};
const handlePopState = () => {
if (isActionPending) {
if (
window.location.href === guardedUrl &&
(window.history.state as Record<string, unknown> | null)?.[guardStateKey] !== guardId
) {
pushGuardEntry();
}
return;
}
if (isLeaving) return;
pushGuardEntry();
openLeaveConfirmation(() => {
window.history.go(-2);
return true;
});
};
const handleBoardEditAction = (event: Event) => {
event.preventDefault();
openLeaveConfirmation((event as BoardEditActionEvent).detail.action);
};
const handlePageShow = (event: PageTransitionEvent) => {
if (!event.persisted) return;
didPageHide = false;
guardedUrl = window.location.href;
isLeaving = false;
isConfirming = false;
shouldRemoveGuardEntry = true;
if ((window.history.state as Record<string, unknown> | null)?.[guardStateKey] !== guardId) {
pushGuardEntry();
}
};
const handlePageHide = () => {
didPageHide = true;
};
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (env.NODE_ENV === "development") return;
if (isLeaving || env.NODE_ENV === "development") return;
event.preventDefault();
event.returnValue = true;
};
const anchors = document.querySelectorAll(anchorSelector);
anchors.forEach((link) => {
link.addEventListener("click", handleClick);
});
document.addEventListener("click", handleClick, true);
document.addEventListener(boardEditActionEventName, handleBoardEditAction);
window.addEventListener("popstate", handlePopState);
window.addEventListener("pagehide", handlePageHide);
window.addEventListener("pageshow", handlePageShow);
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
anchors.forEach((link) => {
link.removeEventListener("click", handleClick);
});
document.removeEventListener("click", handleClick, true);
document.removeEventListener(boardEditActionEventName, handleBoardEditAction);
window.removeEventListener("popstate", handlePopState);
window.removeEventListener("pagehide", handlePageHide);
window.removeEventListener("pageshow", handlePageShow);
window.removeEventListener("beforeunload", handleBeforeUnload);
window.clearTimeout(departureFallbackTimer);
if (
shouldRemoveGuardEntry &&
window.location.href === guardedUrl &&
(window.history.state as Record<string, unknown> | null)?.[guardStateKey] === guardId
) {
window.history.back();
}
};
}, [isDirty]);
};
@@ -4,14 +4,18 @@ import { shouldPrefetchWidgetForRequest } from "./_prefetch-policy";
describe("shouldPrefetchWidgetForRequest", () => {
test.each(["mobile", "tablet"])("defers downloads for %s requests", (deviceType) => {
expect(shouldPrefetchWidgetForRequest("downloads", deviceType)).toBe(false);
expect(shouldPrefetchWidgetForRequest("downloads", deviceType, true)).toBe(false);
});
test("keeps downloads prefetched for desktop requests", () => {
expect(shouldPrefetchWidgetForRequest("downloads", undefined)).toBe(true);
expect(shouldPrefetchWidgetForRequest("downloads", undefined, true)).toBe(true);
});
test("keeps downloads prefetched for legacy responsive mobile boards", () => {
expect(shouldPrefetchWidgetForRequest("downloads", "mobile", false)).toBe(true);
});
test.each(["app", "bookmarks"] as const)("keeps eager %s data prefetched on mobile", (kind) => {
expect(shouldPrefetchWidgetForRequest(kind, "mobile")).toBe(true);
expect(shouldPrefetchWidgetForRequest(kind, "mobile", true)).toBe(true);
});
});
@@ -1,7 +1,11 @@
import type { WidgetKind } from "@homarr/definitions";
export const shouldPrefetchWidgetForRequest = (kind: WidgetKind, deviceType: string | undefined) => {
export const shouldPrefetchWidgetForRequest = (
kind: WidgetKind,
deviceType: string | undefined,
enableAutomaticMobileLayout: boolean,
) => {
const isMobileDevice = deviceType === "mobile" || deviceType === "tablet";
return kind !== "downloads" || !isMobileDevice;
return kind !== "downloads" || !isMobileDevice || !enableAutomaticMobileLayout;
};
@@ -1,19 +1,42 @@
"use client";
import { Button, Fieldset, Group, Input, Slider, Stack, Text } from "@mantine/core";
import { Button, Fieldset, Grid, Group, Input, NumberInput, Slider, Stack, Text, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { getDesktopLayout } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client";
import { boardSaveLayoutSchema } from "@homarr/validation/board";
import { boardSaveLayoutSchema, boardSaveLayoutsSchema } from "@homarr/validation/board";
import type { Board } from "../../_types";
interface Props {
board: Board;
enableAutomaticMobileLayout: boolean;
}
export const LayoutSettingsContent = ({ board }: Props) => {
const getNextAvailableBreakpoint = (layouts: Array<{ breakpoint: number }>) => {
const breakpoints = new Set(layouts.map((layout) => layout.breakpoint));
const commonBreakpoints = [0, 480, 768, 1024, 1200, 1440, 1920];
const commonBreakpoint = commonBreakpoints.find((breakpoint) => !breakpoints.has(breakpoint));
if (commonBreakpoint !== undefined) return commonBreakpoint;
for (let breakpoint = 0; breakpoint <= 32767; breakpoint++) {
if (!breakpoints.has(breakpoint)) return breakpoint;
}
throw new Error("No responsive layout breakpoints are available");
};
export const LayoutSettingsContent = ({ board, enableAutomaticMobileLayout }: Props) =>
enableAutomaticMobileLayout ? (
<AutomaticLayoutSettingsContent board={board} />
) : (
<ResponsiveLayoutSettingsContent board={board} />
);
const AutomaticLayoutSettingsContent = ({ board }: Pick<Props, "board">) => {
const t = useI18n();
const utils = clientApi.useUtils();
const desktopLayout = getDesktopLayout(board);
@@ -45,13 +68,20 @@ export const LayoutSettingsContent = ({ board }: Props) => {
{t("board.setting.section.layout.desktop.description")}
</Text>
<Input.Wrapper label={t("layout.field.columnCount.label")}>
<Slider mt="xs" min={1} max={24} step={1} {...form.getInputProps("columnCount")} />
<Slider
mt="xs"
min={1}
max={24}
step={1}
thumbLabel={t("layout.field.columnCount.label")}
{...form.getInputProps("columnCount")}
/>
</Input.Wrapper>
</Stack>
</Fieldset>
<Text c="dimmed" size="sm">
{t("board.setting.section.layout.mobile.description")}
{t("board.setting.section.layout.mobile.automaticDescription")}
</Text>
<Group justify="end">
@@ -63,3 +93,124 @@ export const LayoutSettingsContent = ({ board }: Props) => {
</form>
);
};
const ResponsiveLayoutSettingsContent = ({ board }: Pick<Props, "board">) => {
const t = useI18n();
const utils = clientApi.useUtils();
const form = useZodForm(boardSaveLayoutsSchema.omit({ id: true }).required(), {
initialValues: {
layouts: board.layouts,
},
});
const { mutate: saveLayouts, isPending } = clientApi.board.saveLayouts.useMutation({
onSuccess(layouts) {
const values = { layouts };
form.setValues(values);
form.resetDirty(values);
},
onSettled() {
void utils.board.getBoardByName.invalidate({ name: board.name });
void utils.board.getHomeBoard.invalidate();
},
});
return (
<form
onSubmit={form.onSubmit((values) => {
saveLayouts({
id: board.id,
...values,
});
})}
>
<Stack>
<Text c="dimmed" size="sm">
{t("board.setting.section.layout.responsive.description")}
</Text>
<Stack gap="sm">
<Group justify="space-between" align="center">
<Text fw={500}>{t("board.setting.section.layout.responsive.title")}</Text>
<Button
variant="subtle"
onClick={() => {
form.setValues({
layouts: [
...form.values.layouts,
{
id: createId(),
name: t("board.setting.section.layout.responsive.defaultName"),
columnCount: 10,
breakpoint: getNextAvailableBreakpoint(form.values.layouts),
},
],
});
}}
>
{t("board.setting.section.layout.responsive.action.add")}
</Button>
</Group>
{form.values.layouts.map((layout, index) => (
<Fieldset key={layout.id} legend={layout.name} bg="transparent">
<Grid>
<Grid.Col span={{ sm: 12, md: 6 }}>
<TextInput {...form.getInputProps(`layouts.${index}.name`)} label={t("layout.field.name.label")} />
</Grid.Col>
<Grid.Col span={{ sm: 12, md: 6 }}>
<Input.Wrapper label={t("layout.field.columnCount.label")}>
<Slider
mt="xs"
min={1}
max={24}
step={1}
thumbLabel={t("layout.field.columnCount.label")}
{...form.getInputProps(`layouts.${index}.columnCount`)}
/>
</Input.Wrapper>
</Grid.Col>
<Grid.Col span={{ sm: 12, md: 6 }}>
<NumberInput
{...form.getInputProps(`layouts.${index}.breakpoint`)}
label={t("layout.field.breakpoint.label")}
description={t("layout.field.breakpoint.description")}
min={0}
max={32767}
allowDecimal={false}
allowNegative={false}
/>
</Grid.Col>
</Grid>
{form.values.layouts.length >= 2 && (
<Group justify="end">
<Button
variant="subtle"
onClick={() => {
form.setValues((previous) => {
const previousLayouts = previous.layouts ?? [];
return previousLayouts.length >= 2
? {
layouts: previousLayouts.filter((filteredLayout) => filteredLayout.id !== layout.id),
}
: previous;
});
}}
>
{t("common.action.remove")}
</Button>
</Group>
)}
</Fieldset>
))}
</Stack>
<Group justify="end">
<Button type="submit" loading={isPending}>
{t("common.action.saveChanges")}
</Button>
</Group>
</Stack>
</form>
);
};
@@ -90,7 +90,10 @@ export default async function BoardSettingsPage(props: Props) {
<GeneralSettingsContent board={board} />
</AccordionItemFor>
<AccordionItemFor value="layout" icon={IconLayout}>
<LayoutSettingsContent board={board} />
<LayoutSettingsContent
board={board}
enableAutomaticMobileLayout={boardSettings.enableAutomaticMobileLayout}
/>
</AccordionItemFor>
<AccordionItemFor value="background" icon={IconPhoto}>
<BackgroundSettingsContent board={board} />
@@ -48,13 +48,22 @@ export const BoardSwitcherLogo = () => {
<ScrollArea.Autosize mah={320}>
{boards.map((availableBoard) => {
const isCurrent = availableBoard.id === board.id;
if (isCurrent) {
return (
<Menu.Item key={availableBoard.id} leftSection={<IconCheck size={20} />} aria-current="page" disabled>
<Text truncate title={availableBoard.name}>
{availableBoard.name}
</Text>
</Menu.Item>
);
}
return (
<Menu.Item
key={availableBoard.id}
component={Link}
href={`/boards/${availableBoard.name}`}
leftSection={isCurrent ? <IconCheck size={20} /> : <IconLayoutBoard size={20} />}
aria-current={isCurrent ? "page" : undefined}
leftSection={<IconLayoutBoard size={20} />}
>
<Text truncate title={availableBoard.name}>
{availableBoard.name}
+1
View File
@@ -107,6 +107,7 @@ export default async function Layout(props: {
board: {
homeBoardId: serverSettings.board.homeBoardId,
mobileHomeBoardId: serverSettings.board.mobileHomeBoardId,
enableAutomaticMobileLayout: serverSettings.board.enableAutomaticMobileLayout,
enableStatusByDefault: serverSettings.board.enableStatusByDefault,
forceDisableStatus: serverSettings.board.forceDisableStatus,
},
@@ -33,6 +33,13 @@ export const BoardSettingsForm = ({ defaultValues }: { defaultValues: ServerSett
{...form.getInputProps("mobileHomeBoardId")}
/>
<Text fw={500}>{tBoard("mobileLayout.title")}</Text>
<Switch
{...form.getInputProps("enableAutomaticMobileLayout", { type: "checkbox" })}
label={tBoard("mobileLayout.enable.label")}
description={tBoard("mobileLayout.enable.description")}
/>
<Text fw={500}>{tBoard("status.title")}</Text>
<Switch
{...form.getInputProps("enableStatusByDefault", { type: "checkbox" })}
@@ -1,6 +1,7 @@
"use client";
import { Button, Group, Stack } from "@mantine/core";
import { useRouter } from "next/navigation";
import { clientApi } from "@homarr/api/client";
import { useForm } from "@homarr/form";
@@ -17,6 +18,7 @@ export const CommonSettingsForm = <TKey extends keyof ServerSettings>({
defaultValues: ServerSettings[TKey];
children: (form: ReturnType<typeof useForm<ServerSettings[TKey]>>) => React.ReactNode;
}) => {
const router = useRouter();
const t = useI18n();
const tSettings = useScopedI18n("management.page.settings");
const { mutateAsync, isPending } = clientApi.serverSettings.saveSettings.useMutation({
@@ -24,6 +26,7 @@ export const CommonSettingsForm = <TKey extends keyof ServerSettings>({
showSuccessNotification({
message: tSettings("notification.success.message"),
});
router.refresh();
},
onError() {
showErrorNotification({