Revert "feat: complete automatic mobile board UX"

This reverts commit 7959c20d88.
This commit is contained in:
ajnart committed 2026-07-29 20:06:47 +02:00
1 parent dba9a250ff
commit b612fb9a89
85 files changed
+565 -2867

No files matched your search

+2 -5
View File
@@ -80,9 +80,6 @@ The OpenAPI and MCP APIs include board management endpoints for common automatio
- Change board visibility - Change board visibility
- Update board visual and behavior settings - Update board visual and behavior settings
- Set desktop and mobile home boards for the current user - Set desktop and mobile home boards for the current user
- Configure global board defaults such as public home boards, automatic mobile layout mode, and status behavior - Configure global board defaults such as public home boards and status behavior
- Configure saved responsive layouts through Homarr's board settings UI when a server uses legacy mobile layout mode
Use the interactive API reference to inspect the exact request body for OpenAPI endpoints under the `boards` and Use the interactive API reference to inspect the exact request body for each endpoint under the `boards` and `settings` tags.
`settings` tags. Saved responsive layouts are intentionally not exposed as an OpenAPI or MCP replacement operation
because omitting a layout would remove it.
+4 -10
View File
@@ -84,29 +84,23 @@ Homarr will fall back to the Homarr logo if nothing is set.
### Layout ### Layout
The available controls depend on the server-wide **Use automatic mobile layout** setting under `Management` > `Settings` > `Boards`. In this section you can configure the number of columns in the desktop layout.
Items and sections can be moved and resized on desktop while the board is in edit mode. Items and sections can be moved and resized on desktop while the board is in edit mode.
Changing the column count automatically adjusts item positions and sizes to fit the new grid. Changing the column count automatically adjusts item positions and sizes to fit the new grid.
<img src={layoutLargeImage} height={256} /> <img src={layoutLargeImage} height={256} />
#### Automatic mobile layout #### Mobile layout
When automatic mobile layout is enabled, the board settings contain one desktop column-count control. Phones use an automatic, read-only layout with exactly two columns in both portrait and landscape. Tablets use this layout at widths up to 48em. Items follow the visual order of the desktop layout and are limited to two columns wide and three rows high. Phones use an automatic, read-only layout with exactly two columns in both portrait and landscape. Tablets use this layout at widths up to 48em. Items follow the visual order of the desktop layout and are limited to two columns wide and three rows high.
Named categories and dynamic sections appear as lightweight headings and section shortcuts, but never as layout containers. Their items are included directly in the automatic grid, even when a category is collapsed on desktop. Layout and item-configuration menus stay locked on mobile; links, refresh actions, automations, notebook content and checklists, and widget details remain interactive according to the user's normal permissions. Named categories and dynamic sections appear as lightweight headings and section shortcuts, but never as layout containers. Their items are included directly in the automatic grid, even when a category is collapsed on desktop. Layout and widget configuration stay locked on mobile; links, refresh actions, automations, and widget details remain interactive.
App items use compact tiles. Widgets can opt into a compact summary, and larger widgets provide a full-screen detail view. Widgets farther down a long board are loaded shortly before they enter the viewport while their space is preserved with a skeleton. App items use compact tiles. Widgets can opt into a compact summary, and larger widgets provide a full-screen detail view. Widgets farther down a long board are loaded shortly before they enter the viewport while their space is preserved with a skeleton.
To rearrange, add, remove, resize, or configure board items, open the board on a larger screen. To rearrange, add, remove, resize, or configure board items, open the board on a larger screen.
#### Saved responsive layouts
When automatic mobile layout is disabled, each board uses its saved responsive layouts. Board editors can add named layouts, choose their column counts and viewport breakpoints, and edit the selected layout directly on mobile.
Enabling automatic mode does not delete these layouts. Homarr continues to maintain item and section placements for them, so an administrator can switch the server back to responsive mode later without losing the previous mobile arrangement.
### Background ### Background
#### Background image URL #### Background image URL
+4 -30
View File
@@ -9,12 +9,10 @@ tags:
--- ---
# Settings # Settings
The settings page has a few options that will be applied to the entire Homarr application. The settings page has a few options that will be applied to the entire Homarr application.
They may require a full page reload for changes to apply. They may require a full page reload for changes to apply.
## Analytics ## Analytics
By default, Homarr is collecting anonymous analytics to identify issues and prioritize bugfixes and improvements. By default, Homarr is collecting anonymous analytics to identify issues and prioritize bugfixes and improvements.
The data is never shared with any third-parties and is fully GDPR & CCPA compliant. The data is never shared with any third-parties and is fully GDPR & CCPA compliant.
The software being used is [Umami Analytics](https://umami.is/) which is fully open source. The software being used is [Umami Analytics](https://umami.is/) which is fully open source.
@@ -23,29 +21,25 @@ The main server software can be found [here](https://github.com/umami-software/u
A full list of the collected data by default can be found here: https://umami.is/docs/metric-definitions. A full list of the collected data by default can be found here: https://umami.is/docs/metric-definitions.
We understand that you might not want Homarr to communicate with our services. We understand that you might not want Homarr to communicate with our services.
By unchecking the `Send anonymous analytics` checkbox and reloading the full page, all communication by Umami will be disabled and no data will be collected. By unchecking the ``Send anonymous analytics`` checkbox and reloading the full page, all communication by Umami will be disabled and no data will be collected.
If you are paranoid, you can permanently block `umami.homarr.dev` from your DNS / firewall. If you are paranoid, you can permanently block ``umami.homarr.dev`` from your DNS / firewall.
Additionally, you opt in to more data collection to help us provide more useful data. Additionally, you opt in to more data collection to help us provide more useful data.
### Integration data ### Integration data
Enabling this optional data will send the types of integrations (e.g. SABnzbd, Sonarr, ...) and how many you have configured of them. Enabling this optional data will send the types of integrations (e.g. SABnzbd, Sonarr, ...) and how many you have configured of them.
This will not include any URLs, names, secrets, errors and others. This is disabled by default. This will not include any URLs, names, secrets, errors and others. This is disabled by default.
### Widget data ### Widget data
Enabling this optional data will send the types of widgets (e.g. downloads, media streams, iframe, ...) and how many you have configured of them. Enabling this optional data will send the types of widgets (e.g. downloads, media streams, iframe, ...) and how many you have configured of them.
This will not include any URLs, names, secrets, errors and others. This is disabled by default. This will not include any URLs, names, secrets, errors and others. This is disabled by default.
### Users data ### Users data
Enabling this optional data will send the count of users and whether you activated SSO. Enabling this optional data will send the count of users and whether you activated SSO.
This will not include any usernames, passwords, emails, URLs, authentication flows or client IDs. This will not include any usernames, passwords, emails, URLs, authentication flows or client IDs.
This is disabled by default. This is disabled by default.
## Search Engine Optimization (SEO) ## Search Engine Optimization (SEO)
Big companies [like Google, Microsoft, Baidu and Yandex](https://de.wikipedia.org/wiki/Web-Index) will use [web crawlers](https://de.wikipedia.org/wiki/Webcrawler) to index the Internet for new websites & pages. Big companies [like Google, Microsoft, Baidu and Yandex](https://de.wikipedia.org/wiki/Web-Index) will use [web crawlers](https://de.wikipedia.org/wiki/Webcrawler) to index the Internet for new websites & pages.
This is desirable in many cases (for example when selling products in an online shop) but can lead to unwanted traffic and attention to your personal dashboard. This is desirable in many cases (for example when selling products in an online shop) but can lead to unwanted traffic and attention to your personal dashboard.
Homarr is requesting the crawlers to not index Homarr instances by default for this reason. Homarr is requesting the crawlers to not index Homarr instances by default for this reason.
@@ -53,26 +47,22 @@ If you use Homarr as a public website and want it to be searchable on these sear
Please note that Homarr doesn't have control over what the crawlers do; it is a mere request to them to not perform these actions but will not guarantee that your website doesn't land on some index. Please note that Homarr doesn't have control over what the crawlers do; it is a mere request to them to not perform these actions but will not guarantee that your website doesn't land on some index.
### No index ### No index
This will ask crawlers to not index your Homarr instance on any indexes. This will ask crawlers to not index your Homarr instance on any indexes.
It is up to the crawler to properly respect this request. It is up to the crawler to properly respect this request.
By default, this setting is enabled. Disabling it will allow indexing. By default, this setting is enabled. Disabling it will allow indexing.
### No follow ### No follow
If indexing is allowed, crawlers will also attempt to follow any links on your page to further "discover" new parts of the Internet and on your website. If indexing is allowed, crawlers will also attempt to follow any links on your page to further "discover" new parts of the Internet and on your website.
By default, this setting is enabled and will ask crawlers to not follow any links. By default, this setting is enabled and will ask crawlers to not follow any links.
Crawler of different companies may behave differently when indexing is prohibited and following is allowed. Crawler of different companies may behave differently when indexing is prohibited and following is allowed.
### No translate ### No translate
Google and Chrome on Android will prompt users to translate pages that are not in their device language. Google and Chrome on Android will prompt users to translate pages that are not in their device language.
This can lead to some shifting and can be undesired in some cases. By enabling this, This can lead to some shifting and can be undesired in some cases. By enabling this,
you ask crawlers to never translate and never prompt users for translation. you ask crawlers to never translate and never prompt users for translation.
It should be noted that some browsers will ignore this and translate regardless. It should be noted that some browsers will ignore this and translate regardless.
### No site links search box ### No site links search box
This setting is exclusive to Google. This setting is exclusive to Google.
[Google will create a box below your domain](https://developers.google.com/search/docs/appearance/structured-data/sitelinks-searchbox) that lists the paths that were discovered by the "folowing". [Google will create a box below your domain](https://developers.google.com/search/docs/appearance/structured-data/sitelinks-searchbox) that lists the paths that were discovered by the "folowing".
The user can search them directly in Google. The user can search them directly in Google.
@@ -81,22 +71,8 @@ This setting is disabled by default.
## Boards ## Boards
### Automatic mobile layout
**Use automatic mobile layout** controls mobile rendering for every board on the server:
- Enabled: phones and small tablets use Homarr's read-only, two-column mobile view. Mobile layout editing is hidden.
- Disabled: boards use their saved responsive layouts and users with board modification access can edit layouts on mobile.
This setting is enabled by default for new instances. During an upgrade, Homarr keeps it disabled when it detects existing custom responsive layouts, including boards with multiple layouts or a non-default saved layout. Instances that only contain the canonical desktop layout use the new automatic mode. Once an administrator saves an explicit choice, later upgrades preserve it.
Saved responsive layouts are retained while automatic mode is enabled, so switching between the modes is reversible. Reload any board tabs that were already open when the setting changed.
The automatic-layout setting is independent from the global mobile board below: one controls how a board is rendered, while the other controls which board opens on a detected mobile device.
### Global home board ### Global home board
You can set a global home board that will be used for all users that have not set a home board themselves.
You can set a global home board that will be used for all users that have not set a home board themselves.
It will also be used for anonymous users. It will also be used for anonymous users.
Note that the board must be public to be used as a global home board. Note that the board must be public to be used as a global home board.
@@ -121,11 +97,9 @@ You can decide if the app status should be disabled for all boards.
## Appearance ## Appearance
### Default color scheme ### Default color scheme
You can set the default color scheme for all users that have not set a color scheme themselves. You can set the default color scheme for all users that have not set a color scheme themselves.
## Culture ## Culture
### Default language ### Default language
You can set the default language for all users that have not set a language themselves.
You can set the default language for all users that have not set a language themselves.
@@ -18,8 +18,6 @@ import { isNullOrWhitespace } from "@homarr/common";
import { userAgent } from "@homarr/common/server"; import { userAgent } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error"; 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 type { WidgetKind } from "@homarr/definitions";
import { getQueryCacheAsync } from "@homarr/redis"; import { getQueryCacheAsync } from "@homarr/redis";
import { getI18n } from "@homarr/translation/server"; import { getI18n } from "@homarr/translation/server";
@@ -56,12 +54,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
const resolvedParams = await params; const resolvedParams = await params;
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const [board, session, requestHeaders, boardSettings] = await Promise.all([ const [board, session, requestHeaders] = await Promise.all([getInitialBoard(resolvedParams), auth(), headers()]);
getInitialBoard(resolvedParams),
auth(),
headers(),
getServerSettingByKeyAsync(db, "board"),
]);
const deviceType = userAgent(new Headers(requestHeaders)).device.type; const deviceType = userAgent(new Headers(requestHeaders)).device.type;
const itemsMap = board.items.reduce((acc, item) => { const itemsMap = board.items.reduce((acc, item) => {
@@ -77,9 +70,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
const [integrations] = await Promise.all([ const [integrations] = await Promise.all([
getIntegrationsWithPermissionsAsync(session), getIntegrationsWithPermissionsAsync(session),
...Array.from(itemsMap) ...Array.from(itemsMap)
.filter(([kind]) => .filter(([kind]) => shouldPrefetchWidgetForRequest(kind, deviceType))
shouldPrefetchWidgetForRequest(kind, deviceType, boardSettings.enableAutomaticMobileLayout),
)
.map(([kind, items]) => .map(([kind, items]) =>
prefetchForKindAsync(kind, queryClient, items).catch((error) => { prefetchForKindAsync(kind, queryClient, items).catch((error) => {
logger.error( logger.error(
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour"; import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
import { Box, Button, Divider, Drawer, Group, Menu, ScrollArea, Stack, Text } from "@mantine/core"; import { Box, Button, Divider, Drawer, Group, Menu, ScrollArea, Stack, Text } from "@mantine/core";
@@ -29,8 +29,7 @@ import {
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { signOut, useSession } from "@homarr/auth/client"; import { signOut, useSession } from "@homarr/auth/client";
import { getDesktopLayout, useRequiredBoard } from "@homarr/boards/context"; import { getDesktopLayout, useRequiredBoard } from "@homarr/boards/context";
import type { BoardEditAction, BoardEditActionEvent } from "@homarr/boards/edit-mode"; import { useEditMode } from "@homarr/boards/edit-mode";
import { boardEditActionEventName, requestBoardEditAction, useEditMode } from "@homarr/boards/edit-mode";
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 { hotkeys } from "@homarr/definitions"; import { hotkeys } from "@homarr/definitions";
@@ -62,8 +61,6 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool
const isMobile = useIsMobileBoard(); const isMobile = useIsMobileBoard();
const t = useI18n(); const t = useI18n();
usePreventLeaveWithDirty(isEditMode);
if (isMobile) { if (isMobile) {
return <MobileMoreMenu showSettings={hasChangeAccess && !demoReadOnly} />; return <MobileMoreMenu showSettings={hasChangeAccess && !demoReadOnly} />;
} }
@@ -218,6 +215,8 @@ const EditModeMenu = ({ demoReadOnly, hidden }: { demoReadOnly: boolean; hidden:
}, [board, isEditMode, demoReadOnly, saveBoard, open, discardDemoChanges, hidden]); }, [board, isEditMode, demoReadOnly, saveBoard, open, discardDemoChanges, hidden]);
useHotkeys([[hotkeys.toggleBoardEdit, toggle]]); useHotkeys([[hotkeys.toggleBoardEdit, toggle]]);
usePreventLeaveWithDirty(isEditMode);
if (hidden) return null; if (hidden) return null;
return ( return (
@@ -270,7 +269,6 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
const tProfile = useScopedI18n("common.userAvatar.menu"); const tProfile = useScopedI18n("common.userAvatar.menu");
const reduceMotion = useReducedMotion(); const reduceMotion = useReducedMotion();
const [opened, disclosure] = useDisclosure(false); const [opened, disclosure] = useDisclosure(false);
const [isSigningOut, setIsSigningOut] = useState(false);
const moreTriggerRef = useRef<HTMLButtonElement>(null); const moreTriggerRef = useRef<HTMLButtonElement>(null);
const pendingSectionAnchorId = useRef<string | null>(null); const pendingSectionAnchorId = useRef<string | null>(null);
const desktopLayout = getDesktopLayout(board); const desktopLayout = getDesktopLayout(board);
@@ -292,26 +290,6 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
moreTriggerRef.current?.focus({ preventScroll: true }); 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 ( return (
<> <>
<HeaderButton ref={moreTriggerRef} onClick={disclosure.open} aria-label={t("board.mobile.more")}> <HeaderButton ref={moreTriggerRef} onClick={disclosure.open} aria-label={t("board.mobile.more")}>
@@ -413,8 +391,13 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
size="lg" size="lg"
justify="flex-start" justify="flex-start"
leftSection={<IconLogout size={20} />} leftSection={<IconLogout size={20} />}
loading={isSigningOut} onClick={() => {
onClick={() => requestBoardEditAction(handleSignOut)} void signOut({ redirect: false })
.catch(() => undefined)
.then(() => {
window.location.assign(logoutUrl ?? "/auth/login");
});
}}
> >
{tProfile("logout")} {tProfile("logout")}
</Button> </Button>
@@ -449,207 +432,62 @@ const MobileMoreMenu = ({ showSettings }: { showSettings: boolean }) => {
); );
}; };
const anchorSelector = "a[href]:not([target='_blank']):not([download])"; const anchorSelector = "a[href]:not([target='_blank'])";
const usePreventLeaveWithDirty = (isDirty: boolean) => { const usePreventLeaveWithDirty = (isDirty: boolean) => {
const t = useI18n(); const t = useI18n();
const { openConfirmModal } = useConfirmModal(); const { openConfirmModal } = useConfirmModal();
const router = useRouter(); const router = useRouter();
const dependenciesRef = useRef({ openConfirmModal, router, t });
useEffect(() => {
dependenciesRef.current = { openConfirmModal, router, t };
}, [openConfirmModal, router, t]);
useEffect(() => { useEffect(() => {
if (!isDirty) return; if (!isDirty) return;
const guardStateKey = "__homarrBoardEditGuard"; const handleClick = (event: Event) => {
const guardId = `${Date.now()}-${Math.random()}`; const target = (event.target as HTMLElement).closest("a");
let guardedUrl = window.location.href;
let isLeaving = false;
let isConfirming = false;
let isActionPending = false;
let shouldRemoveGuardEntry = true;
let didPageHide = false;
let departureFallbackTimer: number | undefined;
const pushGuardEntry = () => { if (!target) {
window.history.pushState( console.warn("No anchor element found for click event", event);
{ return;
...(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();
} }
};
const scheduleDepartureFallback = () => { event.preventDefault();
window.clearTimeout(departureFallbackTimer);
departureFallbackTimer = window.setTimeout(() => {
departureFallbackTimer = undefined;
if (!didPageHide) {
guardedUrl = window.location.href;
rearmGuard();
}
}, 1_000);
};
const openLeaveConfirmation = (action: BoardEditAction) => { openConfirmModal({
if (isConfirming) return; title: t("board.action.edit.confirmLeave.title"),
isConfirming = true; children: t("board.action.edit.confirmLeave.message"),
onConfirm() {
const dependencies = dependenciesRef.current; router.push(target.href);
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: { confirmProps: {
children: dependencies.t("common.action.discard"), children: t("common.action.discard"),
}, },
}); });
}; };
pushGuardEntry(); const handlePopState = (event: Event) => {
window.history.pushState(null, document.title, window.location.href);
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(); 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) => { const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (isLeaving || env.NODE_ENV === "development") return; if (env.NODE_ENV === "development") return;
event.preventDefault(); event.preventDefault();
event.returnValue = true; event.returnValue = true;
}; };
document.addEventListener("click", handleClick, true); const anchors = document.querySelectorAll(anchorSelector);
document.addEventListener(boardEditActionEventName, handleBoardEditAction); anchors.forEach((link) => {
link.addEventListener("click", handleClick);
});
window.addEventListener("popstate", handlePopState); window.addEventListener("popstate", handlePopState);
window.addEventListener("pagehide", handlePageHide);
window.addEventListener("pageshow", handlePageShow);
window.addEventListener("beforeunload", handleBeforeUnload); window.addEventListener("beforeunload", handleBeforeUnload);
return () => { return () => {
document.removeEventListener("click", handleClick, true); anchors.forEach((link) => {
document.removeEventListener(boardEditActionEventName, handleBoardEditAction); link.removeEventListener("click", handleClick);
});
window.removeEventListener("popstate", handlePopState); window.removeEventListener("popstate", handlePopState);
window.removeEventListener("pagehide", handlePageHide);
window.removeEventListener("pageshow", handlePageShow);
window.removeEventListener("beforeunload", handleBeforeUnload); 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]); }, [isDirty]);
}; };
@@ -4,18 +4,14 @@ import { shouldPrefetchWidgetForRequest } from "./_prefetch-policy";
describe("shouldPrefetchWidgetForRequest", () => { describe("shouldPrefetchWidgetForRequest", () => {
test.each(["mobile", "tablet"])("defers downloads for %s requests", (deviceType) => { test.each(["mobile", "tablet"])("defers downloads for %s requests", (deviceType) => {
expect(shouldPrefetchWidgetForRequest("downloads", deviceType, true)).toBe(false); expect(shouldPrefetchWidgetForRequest("downloads", deviceType)).toBe(false);
}); });
test("keeps downloads prefetched for desktop requests", () => { test("keeps downloads prefetched for desktop requests", () => {
expect(shouldPrefetchWidgetForRequest("downloads", undefined, true)).toBe(true); expect(shouldPrefetchWidgetForRequest("downloads", undefined)).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) => { test.each(["app", "bookmarks"] as const)("keeps eager %s data prefetched on mobile", (kind) => {
expect(shouldPrefetchWidgetForRequest(kind, "mobile", true)).toBe(true); expect(shouldPrefetchWidgetForRequest(kind, "mobile")).toBe(true);
}); });
}); });
@@ -1,11 +1,7 @@
import type { WidgetKind } from "@homarr/definitions"; import type { WidgetKind } from "@homarr/definitions";
export const shouldPrefetchWidgetForRequest = ( export const shouldPrefetchWidgetForRequest = (kind: WidgetKind, deviceType: string | undefined) => {
kind: WidgetKind,
deviceType: string | undefined,
enableAutomaticMobileLayout: boolean,
) => {
const isMobileDevice = deviceType === "mobile" || deviceType === "tablet"; const isMobileDevice = deviceType === "mobile" || deviceType === "tablet";
return kind !== "downloads" || !isMobileDevice || !enableAutomaticMobileLayout; return kind !== "downloads" || !isMobileDevice;
}; };
@@ -1,42 +1,19 @@
"use client"; "use client";
import { Button, Fieldset, Grid, Group, Input, NumberInput, Slider, Stack, Text, TextInput } from "@mantine/core"; import { Button, Fieldset, Group, Input, Slider, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { getDesktopLayout } from "@homarr/boards/context"; import { getDesktopLayout } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client"; import { useI18n } from "@homarr/translation/client";
import { boardSaveLayoutSchema, boardSaveLayoutsSchema } from "@homarr/validation/board"; import { boardSaveLayoutSchema } from "@homarr/validation/board";
import type { Board } from "../../_types"; import type { Board } from "../../_types";
interface Props { interface Props {
board: Board; 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 t = useI18n();
const utils = clientApi.useUtils(); const utils = clientApi.useUtils();
const desktopLayout = getDesktopLayout(board); const desktopLayout = getDesktopLayout(board);
@@ -68,20 +45,13 @@ const AutomaticLayoutSettingsContent = ({ board }: Pick<Props, "board">) => {
{t("board.setting.section.layout.desktop.description")} {t("board.setting.section.layout.desktop.description")}
</Text> </Text>
<Input.Wrapper label={t("layout.field.columnCount.label")}> <Input.Wrapper label={t("layout.field.columnCount.label")}>
<Slider <Slider mt="xs" min={1} max={24} step={1} {...form.getInputProps("columnCount")} />
mt="xs"
min={1}
max={24}
step={1}
thumbLabel={t("layout.field.columnCount.label")}
{...form.getInputProps("columnCount")}
/>
</Input.Wrapper> </Input.Wrapper>
</Stack> </Stack>
</Fieldset> </Fieldset>
<Text c="dimmed" size="sm"> <Text c="dimmed" size="sm">
{t("board.setting.section.layout.mobile.automaticDescription")} {t("board.setting.section.layout.mobile.description")}
</Text> </Text>
<Group justify="end"> <Group justify="end">
@@ -93,124 +63,3 @@ const AutomaticLayoutSettingsContent = ({ board }: Pick<Props, "board">) => {
</form> </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,10 +90,7 @@ export default async function BoardSettingsPage(props: Props) {
<GeneralSettingsContent board={board} /> <GeneralSettingsContent board={board} />
</AccordionItemFor> </AccordionItemFor>
<AccordionItemFor value="layout" icon={IconLayout}> <AccordionItemFor value="layout" icon={IconLayout}>
<LayoutSettingsContent <LayoutSettingsContent board={board} />
board={board}
enableAutomaticMobileLayout={boardSettings.enableAutomaticMobileLayout}
/>
</AccordionItemFor> </AccordionItemFor>
<AccordionItemFor value="background" icon={IconPhoto}> <AccordionItemFor value="background" icon={IconPhoto}>
<BackgroundSettingsContent board={board} /> <BackgroundSettingsContent board={board} />
@@ -48,22 +48,13 @@ export const BoardSwitcherLogo = () => {
<ScrollArea.Autosize mah={320}> <ScrollArea.Autosize mah={320}>
{boards.map((availableBoard) => { {boards.map((availableBoard) => {
const isCurrent = availableBoard.id === board.id; 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 ( return (
<Menu.Item <Menu.Item
key={availableBoard.id} key={availableBoard.id}
component={Link} component={Link}
href={`/boards/${availableBoard.name}`} href={`/boards/${availableBoard.name}`}
leftSection={<IconLayoutBoard size={20} />} leftSection={isCurrent ? <IconCheck size={20} /> : <IconLayoutBoard size={20} />}
aria-current={isCurrent ? "page" : undefined}
> >
<Text truncate title={availableBoard.name}> <Text truncate title={availableBoard.name}>
{availableBoard.name} {availableBoard.name}
-1
View File
@@ -107,7 +107,6 @@ export default async function Layout(props: {
board: { board: {
homeBoardId: serverSettings.board.homeBoardId, homeBoardId: serverSettings.board.homeBoardId,
mobileHomeBoardId: serverSettings.board.mobileHomeBoardId, mobileHomeBoardId: serverSettings.board.mobileHomeBoardId,
enableAutomaticMobileLayout: serverSettings.board.enableAutomaticMobileLayout,
enableStatusByDefault: serverSettings.board.enableStatusByDefault, enableStatusByDefault: serverSettings.board.enableStatusByDefault,
forceDisableStatus: serverSettings.board.forceDisableStatus, forceDisableStatus: serverSettings.board.forceDisableStatus,
}, },
@@ -33,13 +33,6 @@ export const BoardSettingsForm = ({ defaultValues }: { defaultValues: ServerSett
{...form.getInputProps("mobileHomeBoardId")} {...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> <Text fw={500}>{tBoard("status.title")}</Text>
<Switch <Switch
{...form.getInputProps("enableStatusByDefault", { type: "checkbox" })} {...form.getInputProps("enableStatusByDefault", { type: "checkbox" })}
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Button, Group, Stack } from "@mantine/core"; import { Button, Group, Stack } from "@mantine/core";
import { useRouter } from "next/navigation";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useForm } from "@homarr/form"; import { useForm } from "@homarr/form";
@@ -18,7 +17,6 @@ export const CommonSettingsForm = <TKey extends keyof ServerSettings>({
defaultValues: ServerSettings[TKey]; defaultValues: ServerSettings[TKey];
children: (form: ReturnType<typeof useForm<ServerSettings[TKey]>>) => React.ReactNode; children: (form: ReturnType<typeof useForm<ServerSettings[TKey]>>) => React.ReactNode;
}) => { }) => {
const router = useRouter();
const t = useI18n(); const t = useI18n();
const tSettings = useScopedI18n("management.page.settings"); const tSettings = useScopedI18n("management.page.settings");
const { mutateAsync, isPending } = clientApi.serverSettings.saveSettings.useMutation({ const { mutateAsync, isPending } = clientApi.serverSettings.saveSettings.useMutation({
@@ -26,7 +24,6 @@ export const CommonSettingsForm = <TKey extends keyof ServerSettings>({
showSuccessNotification({ showSuccessNotification({
message: tSettings("notification.success.message"), message: tSettings("notification.success.message"),
}); });
router.refresh();
}, },
onError() { onError() {
showErrorNotification({ showErrorNotification({
@@ -60,15 +60,9 @@ const createItemLayouts = (board: Board, currentSection: EmptySection, kind: Wid
return layouts.map((layoutId) => { return layouts.map((layoutId) => {
const boardLayout = board.layouts.find((layout) => layout.id === layoutId); const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId }); const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
const layoutItemSize = boardLayout
? {
...itemSize,
width: Math.min(itemSize.width, boardLayout.columnCount),
}
: itemSize;
const emptyPosition = boardLayout const emptyPosition = boardLayout
? getFirstEmptyPosition(elements, boardLayout.columnCount, 9999, layoutItemSize) ? getFirstEmptyPosition(elements, boardLayout.columnCount, 9999, itemSize)
: { xOffset: 0, yOffset: 0 }; : { xOffset: 0, yOffset: 0 };
if (!emptyPosition) { if (!emptyPosition) {
@@ -76,8 +70,8 @@ const createItemLayouts = (board: Board, currentSection: EmptySection, kind: Wid
} }
return { return {
width: layoutItemSize.width, width: itemSize.width,
height: layoutItemSize.height, height: itemSize.height,
...emptyPosition, ...emptyPosition,
sectionId: currentSection.id, sectionId: currentSection.id,
layoutId, layoutId,
@@ -7,7 +7,7 @@ export const getFirstEmptyPosition = (
size: { width: number; height: number } = { width: 1, height: 1 }, size: { width: number; height: number } = { width: 1, height: 1 },
) => { ) => {
for (let yOffset = 0; yOffset < rowCount + 1 - size.height; yOffset++) { for (let yOffset = 0; yOffset < rowCount + 1 - size.height; yOffset++) {
for (let xOffset = 0; xOffset < columnCount + 1 - size.width; xOffset++) { for (let xOffset = 0; xOffset < columnCount; xOffset++) {
const isOccupied = elements.some( const isOccupied = elements.some(
(element) => (element) =>
element.yOffset < yOffset + size.height && element.yOffset < yOffset + size.height &&
@@ -1,8 +1,9 @@
import { getCurrentLayout } from "@homarr/boards/context";
import type { Board } from "~/app/[locale]/boards/_types"; import type { Board } from "~/app/[locale]/boards/_types";
export interface MoveAndResizeItemInput { export interface MoveAndResizeItemInput {
itemId: string; itemId: string;
layoutId: string;
xOffset: number; xOffset: number;
yOffset: number; yOffset: number;
width: number; width: number;
@@ -10,8 +11,10 @@ export interface MoveAndResizeItemInput {
} }
export const moveAndResizeItemCallback = export const moveAndResizeItemCallback =
({ itemId, layoutId, ...layoutInput }: MoveAndResizeItemInput) => ({ itemId, ...layoutInput }: MoveAndResizeItemInput) =>
(previous: Board): Board => { (previous: Board): Board => {
const currentLayout = getCurrentLayout(previous);
return { return {
...previous, ...previous,
items: previous.items.map((item) => items: previous.items.map((item) =>
@@ -20,7 +23,7 @@ export const moveAndResizeItemCallback =
: { : {
...item, ...item,
layouts: item.layouts.map((layout) => layouts: item.layouts.map((layout) =>
layout.layoutId !== layoutId layout.layoutId !== currentLayout
? layout ? layout
: { : {
...layout, ...layout,
@@ -1,8 +1,9 @@
import { getCurrentLayout } from "@homarr/boards/context";
import type { Board } from "~/app/[locale]/boards/_types"; import type { Board } from "~/app/[locale]/boards/_types";
export interface MoveItemToSectionInput { export interface MoveItemToSectionInput {
itemId: string; itemId: string;
layoutId: string;
sectionId: string; sectionId: string;
xOffset: number; xOffset: number;
yOffset: number; yOffset: number;
@@ -11,8 +12,10 @@ export interface MoveItemToSectionInput {
} }
export const moveItemToSectionCallback = export const moveItemToSectionCallback =
({ itemId, layoutId, ...layoutInput }: MoveItemToSectionInput) => ({ itemId, ...layoutInput }: MoveItemToSectionInput) =>
(board: Board): Board => { (board: Board): Board => {
const currentLayout = getCurrentLayout(board);
return { return {
...board, ...board,
items: board.items.map((item) => items: board.items.map((item) =>
@@ -21,7 +24,7 @@ export const moveItemToSectionCallback =
: { : {
...item, ...item,
layouts: item.layouts.map((layout) => layouts: item.layouts.map((layout) =>
layout.layoutId !== layoutId layout.layoutId !== currentLayout
? layout ? layout
: { : {
...layout, ...layout,
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, test, vi } from "vitest"; import { describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context"; import * as boardContext from "@homarr/boards/context";
@@ -10,10 +10,6 @@ import { ItemMockBuilder } from "./mocks/item-mock";
import { LayoutMockBuilder } from "./mocks/layout-mock"; import { LayoutMockBuilder } from "./mocks/layout-mock";
describe("item actions create-item", () => { describe("item actions create-item", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("should add it to first section", () => { test("should add it to first section", () => {
// Arrange // Arrange
const itemKind = "clock"; const itemKind = "clock";
@@ -112,24 +108,4 @@ describe("item actions create-item", () => {
{ height: 1, width: 1 }, { height: 1, width: 1 },
); );
}); });
test("clamps wide widgets to each retained layout", () => {
const desktopLayout = new LayoutMockBuilder({ id: "desktop", columnCount: 12 }).build();
const mobileLayout = new LayoutMockBuilder({ id: "mobile", columnCount: 1 }).build();
const board = new BoardMockBuilder()
.addLayout(desktopLayout)
.addLayout(mobileLayout)
.addEmptySection({ id: "root", yOffset: 0 })
.build();
const result = createItemCallback({ kind: "mediaMissing" })(board);
const item = result.items.at(0);
expect(item?.layouts).toEqual(
expect.arrayContaining([
expect.objectContaining({ layoutId: desktopLayout.id, width: 4 }),
expect.objectContaining({ layoutId: mobileLayout.id, width: 1 }),
]),
);
});
}); });
@@ -106,10 +106,6 @@ describe("get first empty position", () => {
expect(result).toEqual(expectedX !== undefined ? { xOffset: expectedX, yOffset: expectedY } : undefined); expect(result).toEqual(expectedX !== undefined ? { xOffset: expectedX, yOffset: expectedY } : undefined);
}); });
test("does not place an item wider than the layout", () => {
expect(getFirstEmptyPosition([], 1, undefined, { width: 2, height: 1 })).toBeUndefined();
});
}); });
const createElementsFromLayout = (layout: string[][]) => { const createElementsFromLayout = (layout: string[][]) => {
@@ -1,4 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
import { moveAndResizeItemCallback } from "../move-and-resize-item"; import { moveAndResizeItemCallback } from "../move-and-resize-item";
import { BoardMockBuilder } from "./mocks/board-mock"; import { BoardMockBuilder } from "./mocks/board-mock";
@@ -9,6 +11,8 @@ describe("moveItemToSectionCallback should move item in section", () => {
// Arrange // Arrange
const itemToMove = "2"; const itemToMove = "2";
const layoutId = "1"; const layoutId = "1";
const spy = vi.spyOn(boardContext, "getCurrentLayout");
spy.mockReturnValue(layoutId);
const newPosition = { const newPosition = {
xOffset: 20, xOffset: 20,
yOffset: 30, yOffset: 30,
@@ -21,7 +25,7 @@ describe("moveItemToSectionCallback should move item in section", () => {
const board = new BoardMockBuilder().addItem(itemA).addItem(itemB).addItem(itemC).build(); const board = new BoardMockBuilder().addItem(itemA).addItem(itemB).addItem(itemC).build();
// Act // Act
const updatedBoard = moveAndResizeItemCallback({ itemId: itemToMove, layoutId, ...newPosition })(board); const updatedBoard = moveAndResizeItemCallback({ itemId: itemToMove, ...newPosition })(board);
// Assert // Assert
expect(updatedBoard.items).toHaveLength(3); expect(updatedBoard.items).toHaveLength(3);
@@ -39,6 +43,8 @@ describe("moveItemToSectionCallback should move item in section", () => {
// Arrange // Arrange
const itemToMove = "2"; const itemToMove = "2";
const layoutId = "1"; const layoutId = "1";
const spy = vi.spyOn(boardContext, "getCurrentLayout");
spy.mockReturnValue(layoutId);
const newPosition = { const newPosition = {
xOffset: 20, xOffset: 20,
yOffset: 30, yOffset: 30,
@@ -50,7 +56,7 @@ describe("moveItemToSectionCallback should move item in section", () => {
const board = new BoardMockBuilder().addItem(itemA).addItem(itemC).build(); const board = new BoardMockBuilder().addItem(itemA).addItem(itemC).build();
// Act // Act
const updatedBoard = moveAndResizeItemCallback({ itemId: itemToMove, layoutId, ...newPosition })(board); const updatedBoard = moveAndResizeItemCallback({ itemId: itemToMove, ...newPosition })(board);
// Assert // Assert
expect(updatedBoard.items).toHaveLength(2); expect(updatedBoard.items).toHaveLength(2);
@@ -1,4 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
import { moveItemToSectionCallback } from "../move-item-to-section"; import { moveItemToSectionCallback } from "../move-item-to-section";
import { BoardMockBuilder } from "./mocks/board-mock"; import { BoardMockBuilder } from "./mocks/board-mock";
@@ -9,6 +11,8 @@ describe("moveItemToSectionCallback should move item to section", () => {
// Arrange // Arrange
const itemToMove = "2"; const itemToMove = "2";
const layoutId = "1"; const layoutId = "1";
const spy = vi.spyOn(boardContext, "getCurrentLayout");
spy.mockReturnValue(layoutId);
const newPosition = { const newPosition = {
sectionId: "3", sectionId: "3",
xOffset: 20, xOffset: 20,
@@ -22,7 +26,7 @@ describe("moveItemToSectionCallback should move item to section", () => {
const board = new BoardMockBuilder().addItem(itemA).addItem(itemB).addItem(itemC).build(); const board = new BoardMockBuilder().addItem(itemA).addItem(itemB).addItem(itemC).build();
// Act // Act
const updatedBoard = moveItemToSectionCallback({ itemId: itemToMove, layoutId, ...newPosition })(board); const updatedBoard = moveItemToSectionCallback({ itemId: itemToMove, ...newPosition })(board);
// Assert // Assert
expect(updatedBoard.items).toHaveLength(3); expect(updatedBoard.items).toHaveLength(3);
@@ -40,6 +44,8 @@ describe("moveItemToSectionCallback should move item to section", () => {
// Arrange // Arrange
const itemToMove = "2"; const itemToMove = "2";
const layoutId = "1"; const layoutId = "1";
const spy = vi.spyOn(boardContext, "getCurrentLayout");
spy.mockReturnValue(layoutId);
const newPosition = { const newPosition = {
sectionId: "3", sectionId: "3",
xOffset: 20, xOffset: 20,
@@ -52,7 +58,7 @@ describe("moveItemToSectionCallback should move item to section", () => {
const board = new BoardMockBuilder().addItem(itemA).addItem(itemC).build(); const board = new BoardMockBuilder().addItem(itemA).addItem(itemC).build();
// Act // Act
const updatedBoard = moveItemToSectionCallback({ itemId: itemToMove, layoutId, ...newPosition })(board); const updatedBoard = moveItemToSectionCallback({ itemId: itemToMove, ...newPosition })(board);
// Assert // Assert
expect(updatedBoard.items).toHaveLength(2); expect(updatedBoard.items).toHaveLength(2);
@@ -1,6 +1,6 @@
import type { MutableRefObject } from "react"; import type { MutableRefObject } from "react";
import { useRef } from "react"; import { useRef } from "react";
import { Badge, Card, Center, Stack, Text, ThemeIcon, UnstyledButton } from "@mantine/core"; import { Badge, Card } from "@mantine/core";
import { useElementSize } from "@mantine/hooks"; import { useElementSize } from "@mantine/hooks";
import { QueryErrorResetBoundary, useQueryClient } from "@tanstack/react-query"; import { QueryErrorResetBoundary, useQueryClient } from "@tanstack/react-query";
import combineClasses from "clsx"; import combineClasses from "clsx";
@@ -10,8 +10,6 @@ import { ErrorBoundary } from "react-error-boundary";
import { useRequiredBoard } from "@homarr/boards/context"; import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode"; import { useEditMode } from "@homarr/boards/edit-mode";
import { useSettings } from "@homarr/settings"; import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import { loadWidgetDynamic, reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/widgets"; import { loadWidgetDynamic, reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/widgets";
import type { WidgetDisplayMode } from "@homarr/widgets"; import type { WidgetDisplayMode } from "@homarr/widgets";
import { WidgetError } from "@homarr/widgets/errors"; import { WidgetError } from "@homarr/widgets/errors";
@@ -29,9 +27,7 @@ interface BoardItemContentProps {
displayMode?: WidgetDisplayMode; displayMode?: WidgetDisplayMode;
disableContextMenu?: boolean; disableContextMenu?: boolean;
isReadOnly?: boolean; isReadOnly?: boolean;
disableItemConfiguration?: boolean;
widgetStateRef?: MutableRefObject<Record<string, unknown> | null>; widgetStateRef?: MutableRefObject<Record<string, unknown> | null>;
onOpenDetails?: () => void;
} }
const getOverflowFromKind = (kind: SectionItem["kind"]) => { const getOverflowFromKind = (kind: SectionItem["kind"]) => {
@@ -45,9 +41,7 @@ export const BoardItemContent = ({
displayMode = "default", displayMode = "default",
disableContextMenu = false, disableContextMenu = false,
isReadOnly = false, isReadOnly = false,
disableItemConfiguration = false,
widgetStateRef: externalWidgetStateRef, widgetStateRef: externalWidgetStateRef,
onOpenDetails,
}: BoardItemContentProps) => { }: BoardItemContentProps) => {
const { ref, width, height } = useElementSize<HTMLDivElement>(); const { ref, width, height } = useElementSize<HTMLDivElement>();
const board = useRequiredBoard(); const board = useRequiredBoard();
@@ -79,9 +73,7 @@ export const BoardItemContent = ({
height={height} height={height}
displayMode={displayMode} displayMode={displayMode}
isReadOnly={isReadOnly} isReadOnly={isReadOnly}
disableItemConfiguration={disableItemConfiguration}
widgetStateRef={widgetStateRef} widgetStateRef={widgetStateRef}
onOpenDetails={onOpenDetails}
/> />
</Card> </Card>
); );
@@ -125,23 +117,13 @@ interface InnerContentProps {
height: number; height: number;
displayMode: WidgetDisplayMode; displayMode: WidgetDisplayMode;
isReadOnly: boolean; isReadOnly: boolean;
disableItemConfiguration: boolean;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>; widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
onOpenDetails?: () => void;
} }
const InnerContent = ({ const InnerContent = ({ item, displayMode, isReadOnly, ...dimensions }: InnerContentProps) => {
item,
displayMode,
isReadOnly,
disableItemConfiguration,
onOpenDetails,
...dimensions
}: InnerContentProps) => {
const settings = useSettings(); const settings = useSettings();
const board = useRequiredBoard(); const board = useRequiredBoard();
const [isEditMode] = useEditMode(); const [isEditMode] = useEditMode();
const t = useI18n();
const Comp = loadWidgetDynamic(item.kind); const Comp = loadWidgetDynamic(item.kind);
const { definition } = widgetImports[item.kind]; const { definition } = widgetImports[item.kind];
const options = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options); const options = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
@@ -151,14 +133,6 @@ const InnerContent = ({
updateItemOptions({ itemId: item.id, newOptions }); updateItemOptions({ itemId: item.id, newOptions });
const widgetSupportsIntegrations = const widgetSupportsIntegrations =
"supportedIntegrations" in definition && definition.supportedIntegrations.length >= 1; "supportedIntegrations" in definition && definition.supportedIntegrations.length >= 1;
const hasNativeMobileSummary =
"mobile" in definition &&
definition.mobile !== undefined &&
"supportsCompactSummary" in definition.mobile &&
definition.mobile.supportsCompactSummary === true;
const useGenericMobileSummary = displayMode === "mobileSummary" && !hasNativeMobileSummary;
const title = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`);
const showItemMenu = !isReadOnly && !disableItemConfiguration;
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return ( return (
@@ -171,7 +145,7 @@ const InnerContent = ({
}} }}
fallbackRender={({ resetErrorBoundary, error }) => ( fallbackRender={({ resetErrorBoundary, error }) => (
<> <>
{showItemMenu && <BoardItemMenu offset={4} item={newItem} resetErrorBoundary={resetErrorBoundary} />} {!isReadOnly && <BoardItemMenu offset={4} item={newItem} resetErrorBoundary={resetErrorBoundary} />}
<WidgetError kind={item.kind} error={error} resetErrorBoundary={resetErrorBoundary} /> <WidgetError kind={item.kind} error={error} resetErrorBoundary={resetErrorBoundary} />
</> </>
)} )}
@@ -184,79 +158,32 @@ const InnerContent = ({
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false) (!("integrationsRequired" in definition) || definition.integrationsRequired !== false)
} }
/> />
{showItemMenu && <BoardItemMenu offset={4} item={newItem} />} {!isReadOnly && <BoardItemMenu offset={4} item={newItem} />}
{useGenericMobileSummary ? ( <Comp
<GenericMobileSummary options={options as never}
icon={definition.icon} integrationIds={item.integrationIds}
title={title} isEditMode={isEditMode}
widgetName={t(`widget.${item.kind}.name`)} boardId={board.id}
detailsLabel={t("board.mobile.details")} itemId={item.id}
onOpenDetails={onOpenDetails} isReadOnly={isReadOnly}
/> setOptions={(partialNewOptions) => {
) : ( if (isReadOnly) return;
<Comp updateOptions({
options={options as never} newOptions: {
integrationIds={item.integrationIds} ...options,
isEditMode={isEditMode} ...partialNewOptions.newOptions,
boardId={board.id} },
itemId={item.id} });
isReadOnly={isReadOnly} }}
setOptions={(partialNewOptions) => { displayMode={displayMode}
if (isReadOnly) return; {...dimensions}
updateOptions({ />
newOptions: {
...options,
...partialNewOptions.newOptions,
},
});
}}
displayMode={displayMode}
{...dimensions}
/>
)}
</ErrorBoundary> </ErrorBoundary>
)} )}
</QueryErrorResetBoundary> </QueryErrorResetBoundary>
); );
}; };
const GenericMobileSummary = ({
icon: Icon,
title,
widgetName,
detailsLabel,
onOpenDetails,
}: {
icon: TablerIcon;
title: string;
widgetName: string;
detailsLabel: string;
onOpenDetails?: () => void;
}) => (
<UnstyledButton
h="100%"
w="100%"
p="sm"
onClick={onOpenDetails}
aria-label={`${detailsLabel}: ${title}`}
data-mobile-generic-summary
>
<Center h="100%">
<Stack align="center" gap={4} maw="100%">
<ThemeIcon variant="light" size={36} radius="xl">
<Icon size={20} aria-hidden />
</ThemeIcon>
<Text fw={600} size="sm" ta="center" lineClamp={1} w="100%">
{widgetName}
</Text>
<Text c="dimmed" size="xs" ta="center" lineClamp={1} w="100%">
{detailsLabel}
</Text>
</Stack>
</Center>
</UnstyledButton>
);
const Throw = ({ when, error }: { when: boolean; error: Error }) => { const Throw = ({ when, error }: { when: boolean; error: Error }) => {
if (when) throw error; if (when) throw error;
return null; return null;
@@ -5,56 +5,66 @@ import { useEffect, useRef, useState } from "react";
import { Skeleton } from "@mantine/core"; import { Skeleton } from "@mantine/core";
import classes from "./mobile-board.module.css"; import classes from "./mobile-board.module.css";
import { observeMobileViewportProximity } from "./mobile-viewport-observer";
interface DeferredMobileItemProps extends PropsWithChildren { interface DeferredMobileItemProps extends PropsWithChildren {
eager: boolean; eager: boolean;
unmountWhenOffscreen: boolean; unmountWhenOffscreen: boolean;
onNearViewportChange?: (isNearViewport: boolean) => void;
} }
export { getMobilePreloadRootMargin, mobilePreloadViewportMultiplier } from "./mobile-viewport-observer"; export const mobilePreloadViewportMultiplier = 2;
export const DeferredMobileItem = ({ export const getMobilePreloadRootMargin = (viewportHeight: number) =>
eager, `${Math.max(0, Math.round(viewportHeight * mobilePreloadViewportMultiplier))}px 0px`;
unmountWhenOffscreen,
onNearViewportChange, export const DeferredMobileItem = ({ eager, unmountWhenOffscreen, children }: DeferredMobileItemProps) => {
children,
}: DeferredMobileItemProps) => {
const [hasMounted, setHasMounted] = useState(eager); const [hasMounted, setHasMounted] = useState(eager);
const wrapperRef = useRef<HTMLDivElement | null>(null); const wrapperRef = useRef<HTMLDivElement | null>(null);
const hasMountedOnceRef = useRef(eager);
useEffect(() => { useEffect(() => {
if (eager) { if (eager) {
hasMountedOnceRef.current = true;
setHasMounted(true); setHasMounted(true);
onNearViewportChange?.(true);
return; return;
} }
const element = wrapperRef.current; const element = wrapperRef.current;
if (!element) { if (!element || typeof IntersectionObserver === "undefined") {
setHasMounted(true); setHasMounted(true);
onNearViewportChange?.(true);
return; return;
} }
return observeMobileViewportProximity( let observer: IntersectionObserver | null = null;
element, const observe = () => {
(isNearViewport) => { if (hasMountedOnceRef.current && !unmountWhenOffscreen) return;
onNearViewportChange?.(isNearViewport); observer?.disconnect();
observer = new IntersectionObserver(
([entry]) => {
const isNearViewport = entry?.isIntersecting ?? false;
if (isNearViewport) { if (isNearViewport) {
setHasMounted(true); hasMountedOnceRef.current = true;
return; setHasMounted(true);
} if (!unmountWhenOffscreen) observer?.disconnect();
return;
}
if (unmountWhenOffscreen && !element.contains(document.activeElement)) { if (unmountWhenOffscreen && !element.contains(document.activeElement)) {
setHasMounted(false); setHasMounted(false);
} }
}, },
{ once: !unmountWhenOffscreen }, { rootMargin: getMobilePreloadRootMargin(window.innerHeight) },
); );
}, [eager, onNearViewportChange, unmountWhenOffscreen]); observer.observe(element);
};
observe();
window.addEventListener("resize", observe);
return () => {
window.removeEventListener("resize", observe);
observer?.disconnect();
};
}, [eager, unmountWhenOffscreen]);
return ( return (
<div ref={wrapperRef} className={classes.deferredItem} aria-busy={!hasMounted}> <div ref={wrapperRef} className={classes.deferredItem} aria-busy={!hasMounted}>
@@ -1,9 +1,8 @@
"use client"; "use client";
import type { CSSProperties, RefObject } from "react"; import type { CSSProperties, RefObject } from "react";
import { useMemo, useRef, useState } from "react"; import { useMemo, useRef } from "react";
import { Box, Center, Stack, Text, ThemeIcon, Title } from "@mantine/core"; import { Box, Center, Stack, Text, ThemeIcon, Title } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconLayoutBoard } from "@tabler/icons-react"; import { IconLayoutBoard } from "@tabler/icons-react";
import { getDesktopLayout, useRequiredBoard } from "@homarr/boards/context"; import { getDesktopLayout, useRequiredBoard } from "@homarr/boards/context";
@@ -64,8 +63,6 @@ const getMobilePresentation = (item: SectionItem) => {
const MobileBoardItem = ({ item }: { item: SectionItem }) => { const MobileBoardItem = ({ item }: { item: SectionItem }) => {
const widgetStateRef = useRef<Record<string, unknown> | null>(null); const widgetStateRef = useRef<Record<string, unknown> | null>(null);
const presentation = getMobilePresentation(item); const presentation = getMobilePresentation(item);
const [isNearViewport, setIsNearViewport] = useState(presentation.eager);
const [detailsOpened, detailsDisclosure] = useDisclosure(false);
return ( return (
<Box <Box
@@ -74,30 +71,16 @@ const MobileBoardItem = ({ item }: { item: SectionItem }) => {
data-mobile-board-item={item.id} data-mobile-board-item={item.id}
data-mobile-display-mode={presentation.displayMode} data-mobile-display-mode={presentation.displayMode}
> >
<DeferredMobileItem <DeferredMobileItem eager={presentation.eager} unmountWhenOffscreen={presentation.unmountWhenOffscreen}>
eager={presentation.eager}
unmountWhenOffscreen={presentation.unmountWhenOffscreen}
onNearViewportChange={setIsNearViewport}
>
<BoardItemContent <BoardItemContent
item={item} item={item}
displayMode={presentation.displayMode} displayMode={presentation.displayMode}
disableContextMenu disableContextMenu
isReadOnly isReadOnly
widgetStateRef={widgetStateRef} widgetStateRef={widgetStateRef}
onOpenDetails={presentation.usesGenericSummary ? detailsDisclosure.open : undefined}
/> />
</DeferredMobileItem> </DeferredMobileItem>
<MobileWidgetActions <MobileWidgetActions item={item} supportsDetails={presentation.supportsDetails} widgetStateRef={widgetStateRef} />
item={item}
supportsDetails={presentation.supportsDetails}
detailsFromCard={presentation.usesGenericSummary}
detailsOpened={detailsOpened}
openDetails={detailsDisclosure.open}
closeDetails={detailsDisclosure.close}
widgetStateRef={widgetStateRef}
isNearViewport={isNearViewport}
/>
</Box> </Box>
); );
}; };
@@ -3,7 +3,6 @@ import { describe, expect, test } from "vitest";
import { import {
isMobileContextActionVisible, isMobileContextActionVisible,
resolveMobileItemPresentation, resolveMobileItemPresentation,
shouldKeepMobileWidgetActionsMounted,
shouldRenderMobileWidgetActions, shouldRenderMobileWidgetActions,
} from "./mobile-presentation"; } from "./mobile-presentation";
@@ -43,7 +42,7 @@ describe("resolveMobileItemPresentation", () => {
}); });
}); });
test("uses a compact one-row fallback when only details are configured", () => { test("keeps automatic footprint defaults when only details are configured", () => {
expect( expect(
resolveMobileItemPresentation( resolveMobileItemPresentation(
{ kind: "calendar", height: 7 }, { kind: "calendar", height: 7 },
@@ -53,10 +52,8 @@ describe("resolveMobileItemPresentation", () => {
), ),
).toMatchObject({ ).toMatchObject({
width: 2, width: 2,
height: 1, height: 3,
displayMode: "mobileSummary",
supportsDetails: true, supportsDetails: true,
usesGenericSummary: true,
}); });
}); });
@@ -78,7 +75,6 @@ describe("resolveMobileItemPresentation", () => {
height: 1, height: 1,
displayMode: "mobileSummary", displayMode: "mobileSummary",
supportsDetails: false, supportsDetails: false,
usesGenericSummary: false,
eager: true, eager: true,
unmountWhenOffscreen: false, unmountWhenOffscreen: false,
}); });
@@ -105,42 +101,6 @@ describe("shouldRenderMobileWidgetActions", () => {
}); });
}); });
describe("shouldKeepMobileWidgetActionsMounted", () => {
test("does not expose actions before a deferred widget is near the viewport", () => {
expect(
shouldKeepMobileWidgetActionsMounted({
isNearViewport: false,
actionsOpened: false,
detailsOpened: false,
isOpeningDetails: false,
isCompletingAction: false,
actionTriggerHasFocus: false,
}),
).toBe(false);
});
test.each([
["near the viewport", { isNearViewport: true }],
["showing its action drawer", { actionsOpened: true }],
["showing its detail view", { detailsOpened: true }],
["transitioning to details", { isOpeningDetails: true }],
["completing an action", { isCompletingAction: true }],
["retaining keyboard focus", { actionTriggerHasFocus: true }],
])("keeps actions mounted while %s", (_label, activeState) => {
expect(
shouldKeepMobileWidgetActionsMounted({
isNearViewport: false,
actionsOpened: false,
detailsOpened: false,
isOpeningDetails: false,
isCompletingAction: false,
actionTriggerHasFocus: false,
...activeState,
}),
).toBe(true);
});
});
describe("isMobileContextActionVisible", () => { describe("isMobileContextActionVisible", () => {
test("requires actions to opt into the read-only mobile surface", () => { test("requires actions to opt into the read-only mobile surface", () => {
const action = { key: "configure", label: "Configure", onClick: () => undefined }; const action = { key: "configure", label: "Configure", onClick: () => undefined };
@@ -4,21 +4,14 @@ import type { WidgetContextMenuAction, WidgetMobilePresentation } from "@homarr/
export const resolveMobileItemPresentation = ( export const resolveMobileItemPresentation = (
item: { kind: WidgetKind; height: number }, item: { kind: WidgetKind; height: number },
mobile: WidgetMobilePresentation | undefined, mobile: WidgetMobilePresentation | undefined,
) => { ) => ({
const supportsCompactSummary = mobile?.supportsCompactSummary === true; width: mobile?.width ?? (item.kind === "app" ? 1 : 2),
const supportsDetails = mobile?.supportsDetailView === true; height: mobile?.height ?? (item.kind === "app" ? 1 : Math.max(1, Math.min(item.height, 3))),
const usesGenericSummary = supportsDetails && !supportsCompactSummary; displayMode: mobile?.supportsCompactSummary ? ("mobileSummary" as const) : ("default" as const),
supportsDetails: mobile?.supportsDetailView === true,
return { eager: mobile?.eager ?? (item.kind === "app" || item.kind === "bookmarks"),
width: mobile?.width ?? (item.kind === "app" ? 1 : 2), unmountWhenOffscreen: mobile?.eager === true ? false : (mobile?.unmountWhenOffscreen ?? false),
height: mobile?.height ?? (item.kind === "app" || usesGenericSummary ? 1 : Math.max(1, Math.min(item.height, 3))), });
displayMode: supportsCompactSummary || usesGenericSummary ? ("mobileSummary" as const) : ("default" as const),
supportsDetails,
usesGenericSummary,
eager: mobile?.eager ?? (item.kind === "app" || item.kind === "bookmarks"),
unmountWhenOffscreen: mobile?.eager === true ? false : (mobile?.unmountWhenOffscreen ?? false),
};
};
export const shouldRenderMobileWidgetActions = ({ export const shouldRenderMobileWidgetActions = ({
supportsDetails, supportsDetails,
@@ -30,24 +23,5 @@ export const shouldRenderMobileWidgetActions = ({
visibleContextActionCount: number; visibleContextActionCount: number;
}) => supportsDetails || supportsRefresh || visibleContextActionCount > 0; }) => supportsDetails || supportsRefresh || visibleContextActionCount > 0;
interface ShouldKeepMobileWidgetActionsMountedInput {
isNearViewport: boolean;
actionsOpened: boolean;
detailsOpened: boolean;
isOpeningDetails: boolean;
isCompletingAction: boolean;
actionTriggerHasFocus: boolean;
}
export const shouldKeepMobileWidgetActionsMounted = ({
isNearViewport,
actionsOpened,
detailsOpened,
isOpeningDetails,
isCompletingAction,
actionTriggerHasFocus,
}: ShouldKeepMobileWidgetActionsMountedInput) =>
isNearViewport || actionsOpened || detailsOpened || isOpeningDetails || isCompletingAction || actionTriggerHasFocus;
export const isMobileContextActionVisible = (action: WidgetContextMenuAction) => export const isMobileContextActionVisible = (action: WidgetContextMenuAction) =>
action.mobileVisible === true && !action.hidden; action.mobileVisible === true && !action.hidden;
@@ -1,103 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { getMobilePreloadRootMargin, observeMobileViewportProximity } from "./mobile-viewport-observer";
class IntersectionObserverMock {
static instances: IntersectionObserverMock[] = [];
readonly observedElements = new Set<Element>();
readonly rootMargin: string;
disconnected = false;
constructor(
private readonly callback: IntersectionObserverCallback,
options?: IntersectionObserverInit,
) {
this.rootMargin = options?.rootMargin ?? "0px";
IntersectionObserverMock.instances.push(this);
}
observe(element: Element) {
this.observedElements.add(element);
}
unobserve(element: Element) {
this.observedElements.delete(element);
}
disconnect() {
this.disconnected = true;
this.observedElements.clear();
}
emit(element: Element, isIntersecting: boolean) {
this.callback([{ target: element, isIntersecting } as IntersectionObserverEntry], this as never);
}
}
describe("observeMobileViewportProximity", () => {
beforeEach(() => {
IntersectionObserverMock.instances = [];
vi.stubGlobal("IntersectionObserver", IntersectionObserverMock);
Object.defineProperty(window, "innerHeight", { configurable: true, value: 600, writable: true });
});
afterEach(() => {
vi.unstubAllGlobals();
});
test("shares one observer across cards and recreates it once when the viewport margin changes", () => {
const firstElement = document.createElement("div");
const secondElement = document.createElement("div");
const firstListener = vi.fn();
const secondListener = vi.fn();
const stopObservingFirst = observeMobileViewportProximity(firstElement, firstListener);
const stopObservingSecond = observeMobileViewportProximity(secondElement, secondListener);
expect(IntersectionObserverMock.instances).toHaveLength(1);
expect(IntersectionObserverMock.instances[0]?.observedElements).toEqual(new Set([firstElement, secondElement]));
expect(IntersectionObserverMock.instances[0]?.rootMargin).toBe(getMobilePreloadRootMargin(600));
IntersectionObserverMock.instances[0]?.emit(firstElement, true);
expect(firstListener).toHaveBeenCalledWith(true);
expect(secondListener).not.toHaveBeenCalled();
window.dispatchEvent(new Event("resize"));
expect(IntersectionObserverMock.instances).toHaveLength(1);
window.innerHeight = 700;
window.dispatchEvent(new Event("resize"));
expect(IntersectionObserverMock.instances).toHaveLength(2);
expect(IntersectionObserverMock.instances[0]?.disconnected).toBe(true);
expect(IntersectionObserverMock.instances[1]?.observedElements).toEqual(new Set([firstElement, secondElement]));
expect(IntersectionObserverMock.instances[1]?.rootMargin).toBe(getMobilePreloadRootMargin(700));
stopObservingFirst();
stopObservingSecond();
expect(IntersectionObserverMock.instances[1]?.disconnected).toBe(true);
});
test("removes one-time subscriptions after their card first becomes near", () => {
const element = document.createElement("div");
const listener = vi.fn();
const stopObserving = observeMobileViewportProximity(element, listener, { once: true });
IntersectionObserverMock.instances[0]?.emit(element, true);
expect(listener).toHaveBeenCalledOnce();
expect(IntersectionObserverMock.instances[0]?.disconnected).toBe(true);
stopObserving();
});
test("mounts content immediately when IntersectionObserver is unavailable", () => {
vi.stubGlobal("IntersectionObserver", undefined);
const listener = vi.fn();
const stopObserving = observeMobileViewportProximity(document.createElement("div"), listener);
expect(listener).toHaveBeenCalledWith(true);
stopObserving();
});
});
@@ -1,116 +0,0 @@
export const mobilePreloadViewportMultiplier = 2;
export const getMobilePreloadRootMargin = (viewportHeight: number) =>
`${Math.max(0, Math.round(viewportHeight * mobilePreloadViewportMultiplier))}px 0px`;
interface MobileViewportSubscription {
listener: (isNearViewport: boolean) => void;
once: boolean;
}
interface ObserveMobileViewportOptions {
once?: boolean;
}
const subscriptions = new Map<Element, Set<MobileViewportSubscription>>();
let observer: IntersectionObserver | null = null;
let observedRootMargin: string | null = null;
let isListeningForResize = false;
const stopObservingIfIdle = () => {
if (subscriptions.size > 0) return;
observer?.disconnect();
observer = null;
observedRootMargin = null;
if (isListeningForResize) {
window.removeEventListener("resize", handleViewportResize);
isListeningForResize = false;
}
};
const removeSubscription = (element: Element, subscription: MobileViewportSubscription) => {
const elementSubscriptions = subscriptions.get(element);
if (!elementSubscriptions) return;
elementSubscriptions.delete(subscription);
if (elementSubscriptions.size > 0) return;
subscriptions.delete(element);
observer?.unobserve(element);
stopObservingIfIdle();
};
const handleIntersections: IntersectionObserverCallback = (entries) => {
for (const entry of entries) {
const elementSubscriptions = subscriptions.get(entry.target);
if (!elementSubscriptions) continue;
for (const subscription of elementSubscriptions) {
subscription.listener(entry.isIntersecting);
if (entry.isIntersecting && subscription.once) {
removeSubscription(entry.target, subscription);
}
}
}
};
const createObserver = (rootMargin: string) => {
observer?.disconnect();
observer = new IntersectionObserver(handleIntersections, { rootMargin });
observedRootMargin = rootMargin;
for (const element of subscriptions.keys()) {
observer.observe(element);
}
};
function handleViewportResize() {
const rootMargin = getMobilePreloadRootMargin(window.innerHeight);
if (rootMargin === observedRootMargin) return;
createObserver(rootMargin);
}
const ensureObserver = () => {
if (observer) return;
createObserver(getMobilePreloadRootMargin(window.innerHeight));
window.addEventListener("resize", handleViewportResize);
isListeningForResize = true;
};
export const observeMobileViewportProximity = (
element: Element,
listener: (isNearViewport: boolean) => void,
options: ObserveMobileViewportOptions = {},
) => {
if (typeof window === "undefined" || typeof IntersectionObserver === "undefined") {
listener(true);
return () => undefined;
}
const subscription: MobileViewportSubscription = {
listener,
once: options.once ?? false,
};
const elementSubscriptions = subscriptions.get(element);
if (elementSubscriptions) {
elementSubscriptions.add(subscription);
} else {
subscriptions.set(element, new Set([subscription]));
}
if (observer) {
observer.observe(element);
} else {
ensureObserver();
}
return () => {
removeSubscription(element, subscription);
};
};
@@ -1,7 +1,7 @@
"use client"; "use client";
import type { MutableRefObject } from "react"; import type { MutableRefObject } from "react";
import { useMemo, useRef, useState } from "react"; import { useMemo, useRef } from "react";
import { ActionIcon, Box, Button, Drawer, Loader, Modal, Stack } from "@mantine/core"; import { ActionIcon, Box, Button, Drawer, Loader, Modal, Stack } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks"; import { useDisclosure } from "@mantine/hooks";
import { IconDotsVertical, IconMaximize, IconRefresh } from "@tabler/icons-react"; import { IconDotsVertical, IconMaximize, IconRefresh } from "@tabler/icons-react";
@@ -20,40 +20,20 @@ import type { SectionItem } from "~/app/[locale]/boards/_types";
import { BoardItemContent } from "../items/item-content"; import { BoardItemContent } from "../items/item-content";
import { useHasNestedDialog } from "./mobile-dialog-stack"; import { useHasNestedDialog } from "./mobile-dialog-stack";
import classes from "./mobile-board.module.css"; import classes from "./mobile-board.module.css";
import { import { isMobileContextActionVisible, shouldRenderMobileWidgetActions } from "./mobile-presentation";
isMobileContextActionVisible,
shouldKeepMobileWidgetActionsMounted,
shouldRenderMobileWidgetActions,
} from "./mobile-presentation";
interface MobileWidgetActionsProps { interface MobileWidgetActionsProps {
item: SectionItem; item: SectionItem;
supportsDetails: boolean; supportsDetails: boolean;
detailsFromCard: boolean;
detailsOpened: boolean;
openDetails: () => void;
closeDetails: () => void;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>; widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
isNearViewport: boolean;
} }
export const MobileWidgetActions = ({ export const MobileWidgetActions = ({ item, supportsDetails, widgetStateRef }: MobileWidgetActionsProps) => {
item,
supportsDetails,
detailsFromCard,
detailsOpened,
openDetails,
closeDetails,
widgetStateRef,
isNearViewport,
}: MobileWidgetActionsProps) => {
const [actionsOpened, actionsDisclosure] = useDisclosure(false); const [actionsOpened, actionsDisclosure] = useDisclosure(false);
const [isOpeningDetails, setIsOpeningDetails] = useState(false); const [detailsOpened, detailsDisclosure] = useDisclosure(false);
const [isCompletingAction, setIsCompletingAction] = useState(false);
const [actionTriggerHasFocus, setActionTriggerHasFocus] = useState(false);
const actionTriggerRef = useRef<HTMLButtonElement | null>(null); const actionTriggerRef = useRef<HTMLButtonElement | null>(null);
const detailsDialogRef = useRef<HTMLDivElement | null>(null); const detailsDialogRef = useRef<HTMLDivElement | null>(null);
const pendingContextActionRef = useRef<(() => void) | null>(null); const openDetailsAfterActionsRef = useRef(false);
const hasNestedDialog = useHasNestedDialog(detailsOpened, detailsDialogRef); const hasNestedDialog = useHasNestedDialog(detailsOpened, detailsDialogRef);
const t = useI18n(); const t = useI18n();
const settings = useSettings(); const settings = useSettings();
@@ -79,169 +59,133 @@ export const MobileWidgetActions = ({
const visibleContextActions = contextActions.filter(isMobileContextActionVisible); const visibleContextActions = contextActions.filter(isMobileContextActionVisible);
const title = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`); const title = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`);
const hasActions = shouldRenderMobileWidgetActions({ const hasActions = shouldRenderMobileWidgetActions({
supportsDetails: supportsDetails && !detailsFromCard, supportsDetails,
supportsRefresh: queryKey !== undefined, supportsRefresh: queryKey !== undefined,
visibleContextActionCount: visibleContextActions.length, visibleContextActionCount: visibleContextActions.length,
}); });
const shouldKeepMounted = shouldKeepMobileWidgetActionsMounted({
isNearViewport,
actionsOpened,
detailsOpened,
isOpeningDetails,
isCompletingAction,
actionTriggerHasFocus,
});
if ((!hasActions && !detailsOpened) || !shouldKeepMounted) return null; if (!hasActions) return null;
return ( return (
<> <>
{hasActions && ( <ActionIcon
<> ref={actionTriggerRef}
<ActionIcon className={classes.widgetAction}
ref={actionTriggerRef} variant="filled"
className={classes.widgetAction} color="dark"
variant="filled" radius="xl"
color="dark" size={44}
radius="xl" aria-label={t("board.mobile.actions", { title })}
size={44} onClick={actionsDisclosure.open}
aria-label={t("board.mobile.actions", { title })} >
onClick={actionsDisclosure.open} <IconDotsVertical size={20} />
onFocus={() => setActionTriggerHasFocus(true)} </ActionIcon>
onBlur={() => setActionTriggerHasFocus(false)}
>
<IconDotsVertical size={20} />
</ActionIcon>
<Drawer <Drawer
opened={actionsOpened} opened={actionsOpened}
onClose={actionsDisclosure.close} onClose={actionsDisclosure.close}
title={title} title={title}
position="bottom" position="bottom"
size="auto" size="auto"
padding="md" padding="md"
overlayProps={{ backgroundOpacity: 0.45, blur: 2 }} overlayProps={{ backgroundOpacity: 0.45, blur: 2 }}
returnFocus={false} styles={{
styles={{ content: {
content: { paddingLeft: "env(safe-area-inset-left)",
paddingLeft: "env(safe-area-inset-left)", paddingRight: "env(safe-area-inset-right)",
paddingRight: "env(safe-area-inset-right)", },
}, }}
}} onExitTransitionEnd={() => {
onExitTransitionEnd={() => { if (!openDetailsAfterActionsRef.current) return;
if (isOpeningDetails) { openDetailsAfterActionsRef.current = false;
setIsOpeningDetails(false); detailsDisclosure.open();
openDetails(); }}
return; closeButtonProps={{
} "aria-label": t("common.action.close"),
size: 44,
}}
>
<Stack gap="xs" pb="calc(var(--mantine-spacing-sm) + env(safe-area-inset-bottom))">
{supportsDetails && (
<Button
variant="subtle"
justify="flex-start"
size="lg"
leftSection={<IconMaximize size={20} />}
onClick={() => {
openDetailsAfterActionsRef.current = true;
actionsDisclosure.close();
}}
>
{t("board.mobile.details")}
</Button>
)}
{visibleContextActions.map((action) => {
const Icon = action.icon;
return (
<Button
key={action.key}
variant="subtle"
color={action.color}
justify="flex-start"
size="lg"
disabled={action.disabled}
leftSection={Icon ? <Icon size={20} /> : undefined}
onClick={() => {
action.onClick();
actionsDisclosure.close();
}}
>
{String(translateIfNecessary(t, action.label))}
</Button>
);
})}
{queryKey && <MobileWidgetRefreshAction queryKey={queryKey} onComplete={actionsDisclosure.close} />}
</Stack>
</Drawer>
const pendingContextAction = pendingContextActionRef.current; <Modal
if (pendingContextAction) { ref={detailsDialogRef}
pendingContextActionRef.current = null; opened={detailsOpened}
setIsCompletingAction(false); onClose={detailsDisclosure.close}
pendingContextAction(); title={title}
return; fullScreen
} padding="md"
returnFocus={false}
actionTriggerRef.current?.focus(); trapFocus={!hasNestedDialog}
}} closeOnEscape={!hasNestedDialog}
closeButtonProps={{ onExitTransitionEnd={() => actionTriggerRef.current?.focus()}
"aria-label": t("common.action.close"), closeButtonProps={{
size: 44, "aria-label": t("common.action.close"),
}} size: 44,
> }}
<Stack gap="xs" pb="calc(var(--mantine-spacing-sm) + env(safe-area-inset-bottom))"> styles={{
{supportsDetails && !detailsFromCard && ( content: {
<Button display: "flex",
variant="subtle" flexDirection: "column",
justify="flex-start" height: "100dvh",
size="lg" paddingTop: "env(safe-area-inset-top)",
leftSection={<IconMaximize size={20} />} paddingLeft: "env(safe-area-inset-left)",
onClick={() => { paddingRight: "env(safe-area-inset-right)",
setIsOpeningDetails(true); },
actionsDisclosure.close(); body: {
}} flex: "1 1 auto",
> minHeight: 0,
{t("board.mobile.details")} overflowY: "auto",
</Button> paddingBottom: "calc(var(--mantine-spacing-md) + env(safe-area-inset-bottom))",
)} },
{visibleContextActions.map((action) => { }}
const Icon = action.icon; >
return ( <Box className={classes.detailContent}>
<Button <BoardItemContent
key={action.key} item={item}
variant="subtle" displayMode="mobileDetail"
color={action.color} disableContextMenu
justify="flex-start" isReadOnly
size="lg" widgetStateRef={widgetStateRef}
disabled={action.disabled} />
leftSection={Icon ? <Icon size={20} /> : undefined} </Box>
onClick={() => { </Modal>
pendingContextActionRef.current = action.onClick;
setIsCompletingAction(true);
actionsDisclosure.close();
}}
>
{String(translateIfNecessary(t, action.label))}
</Button>
);
})}
{queryKey && <MobileWidgetRefreshAction queryKey={queryKey} onComplete={actionsDisclosure.close} />}
</Stack>
</Drawer>
</>
)}
{supportsDetails && (
<Modal
ref={detailsDialogRef}
opened={detailsOpened}
onClose={closeDetails}
title={title}
fullScreen
padding="md"
returnFocus={detailsFromCard}
trapFocus={!hasNestedDialog}
closeOnEscape={!hasNestedDialog}
aria-hidden={hasNestedDialog || undefined}
inert={hasNestedDialog || undefined}
onExitTransitionEnd={() => {
if (!detailsFromCard) {
actionTriggerRef.current?.focus();
}
}}
closeButtonProps={{
"aria-label": t("common.action.close"),
size: 44,
}}
styles={{
content: {
display: "flex",
flexDirection: "column",
height: "100dvh",
paddingTop: "env(safe-area-inset-top)",
paddingLeft: "env(safe-area-inset-left)",
paddingRight: "env(safe-area-inset-right)",
},
body: {
flex: "1 1 auto",
minHeight: 0,
overflowY: "auto",
paddingBottom: "calc(var(--mantine-spacing-md) + env(safe-area-inset-bottom))",
},
}}
>
<Box className={classes.detailContent}>
<BoardItemContent
item={item}
displayMode="mobileDetail"
disableContextMenu
disableItemConfiguration
widgetStateRef={widgetStateRef}
/>
</Box>
</Modal>
)}
</> </>
); );
}; };
@@ -1,7 +1,7 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { fetchApi } from "@homarr/api/client"; import { fetchApi } from "@homarr/api/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context"; import { getCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { createId } from "@homarr/common"; import { createId } from "@homarr/common";
import { useConfirmModal, useModalAction } from "@homarr/modals"; import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useSettings } from "@homarr/settings"; import { useSettings } from "@homarr/settings";
@@ -18,7 +18,6 @@ export const useCategoryMenuActions = (category: CategorySection) => {
const { addCategory, moveCategory, removeCategory, renameCategory } = useCategoryActions(); const { addCategory, moveCategory, removeCategory, renameCategory } = useCategoryActions();
const t = useI18n(); const t = useI18n();
const board = useRequiredBoard(); const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const createCategoryAtYOffset = useCallback( const createCategoryAtYOffset = useCallback(
(position: number) => { (position: number) => {
@@ -105,6 +104,7 @@ export const useCategoryMenuActions = (category: CategorySection) => {
const settings = useSettings(); const settings = useSettings();
const openAllInNewTabs = useCallback(async () => { const openAllInNewTabs = useCallback(async () => {
const currentLayoutId = getCurrentLayout(board);
const appIds = filterByItemKind( const appIds = filterByItemKind(
board.items.filter( board.items.filter(
(item) => item.layouts.find((layout) => layout.layoutId === currentLayoutId)?.sectionId === category.id, (item) => item.layouts.find((layout) => layout.layoutId === currentLayoutId)?.sectionId === category.id,
@@ -130,7 +130,7 @@ export const useCategoryMenuActions = (category: CategorySection) => {
}); });
break; break;
} }
}, [category, board, currentLayoutId, t, openConfirmModal, settings]); }, [category, board, t, openConfirmModal, settings]);
return { return {
addCategoryAbove, addCategoryAbove,
@@ -1,7 +1,7 @@
import { Badge, Box, Card } from "@mantine/core"; import { Badge, Box, Card } from "@mantine/core";
import combineClasses from "clsx"; import combineClasses from "clsx";
import { useRequiredBoard } from "@homarr/boards/context"; import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import type { DynamicSectionItem } from "~/app/[locale]/boards/_types"; import type { DynamicSectionItem } from "~/app/[locale]/boards/_types";
import { BoardDynamicSectionMenu } from "./dynamic/dynamic-menu"; import { BoardDynamicSectionMenu } from "./dynamic/dynamic-menu";
@@ -14,6 +14,7 @@ interface Props {
export const BoardDynamicSection = ({ section }: Props) => { export const BoardDynamicSection = ({ section }: Props) => {
const board = useRequiredBoard(); const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const options = section.options; const options = section.options;
return ( return (
@@ -51,7 +52,8 @@ export const BoardDynamicSection = ({ section }: Props) => {
{options.title} {options.title}
</Badge> </Badge>
)} )}
<GridStack section={section} className="min-row" /> {/* Use unique key by layout to reinitialize gridstack */}
<GridStack key={`${currentLayoutId}-${section.id}`} section={section} className="min-row" />
</Card> </Card>
<BoardDynamicSectionMenu section={section} /> <BoardDynamicSectionMenu section={section} />
</Box> </Box>
@@ -4,8 +4,6 @@ import type { BoxProps } from "@mantine/core";
import { Box } from "@mantine/core"; import { Box } from "@mantine/core";
import combineClasses from "clsx"; import combineClasses from "clsx";
import { useCurrentLayout } from "@homarr/boards/context";
import type { DynamicSectionItem, Section } from "~/app/[locale]/boards/_types"; import type { DynamicSectionItem, Section } from "~/app/[locale]/boards/_types";
import { SectionContent } from "../content"; import { SectionContent } from "../content";
import { SectionProvider } from "../section-context"; import { SectionProvider } from "../section-context";
@@ -17,12 +15,6 @@ interface Props extends BoxProps {
} }
export const GridStack = ({ section, ...props }: Props) => { export const GridStack = ({ section, ...props }: Props) => {
const currentLayoutId = useCurrentLayout();
return <GridStackForLayout key={currentLayoutId} section={section} {...props} />;
};
const GridStackForLayout = ({ section, ...props }: Props) => {
const { items, innerSections } = useSectionItems(section.id); const { items, innerSections } = useSectionItems(section.id);
const itemIds = [...items, ...innerSections].map((item) => item.id); const itemIds = [...items, ...innerSections].map((item) => item.id);
@@ -103,7 +103,6 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
// Updates the react-query state // Updates the react-query state
moveAndResizeItem({ moveAndResizeItem({
itemId: id, itemId: id,
layoutId: currentLayoutId,
// We want the following properties to be null by default // We want the following properties to be null by default
// so the next free position is used from the gridstack // so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -121,7 +120,6 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
if (type === "section") { if (type === "section") {
moveAndResizeInnerSection({ moveAndResizeInnerSection({
innerSectionId: id, innerSectionId: id,
layoutId: currentLayoutId,
// We want the following properties to be null by default // We want the following properties to be null by default
// so the next free position is used from the gridstack // so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -138,7 +136,7 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
console.error(`Unknown grid-stack-item type to move. type='${type}' id='${id}'`); console.error(`Unknown grid-stack-item type to move. type='${type}' id='${id}'`);
}, },
[currentLayoutId, moveAndResizeItem, moveAndResizeInnerSection], [moveAndResizeItem, moveAndResizeInnerSection],
); );
const onAdd = useCallback( const onAdd = useCallback(
(addedNode: GridStackNode) => { (addedNode: GridStackNode) => {
@@ -151,7 +149,6 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
// Updates the react-query state // Updates the react-query state
moveItemToSection({ moveItemToSection({
itemId: id, itemId: id,
layoutId: currentLayoutId,
sectionId: section.id, sectionId: section.id,
// We want the following properties to be null by default // We want the following properties to be null by default
// so the next free position is used from the gridstack // so the next free position is used from the gridstack
@@ -170,7 +167,6 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
if (type === "section") { if (type === "section") {
moveInnerSectionToSection({ moveInnerSectionToSection({
innerSectionId: id, innerSectionId: id,
layoutId: currentLayoutId,
sectionId: section.id, sectionId: section.id,
// We want the following properties to be null by default // We want the following properties to be null by default
// so the next free position is used from the gridstack // so the next free position is used from the gridstack
@@ -188,7 +184,7 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
console.error(`Unknown grid-stack-item type to add. type='${type}' id='${id}'`); console.error(`Unknown grid-stack-item type to add. type='${type}' id='${id}'`);
}, },
[currentLayoutId, moveItemToSection, moveInnerSectionToSection, section.id], [moveItemToSection, moveInnerSectionToSection, section.id],
); );
// initialize the gridstack // initialize the gridstack
@@ -1,10 +1,10 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { getCurrentLayout } from "@homarr/boards/context";
import { useUpdateBoard } from "@homarr/boards/updater"; import { useUpdateBoard } from "@homarr/boards/updater";
interface MoveAndResizeInnerSection { interface MoveAndResizeInnerSection {
innerSectionId: string; innerSectionId: string;
layoutId: string;
xOffset: number; xOffset: number;
yOffset: number; yOffset: number;
width: number; width: number;
@@ -12,7 +12,6 @@ interface MoveAndResizeInnerSection {
} }
interface MoveInnerSectionToSection { interface MoveInnerSectionToSection {
innerSectionId: string; innerSectionId: string;
layoutId: string;
sectionId: string; sectionId: string;
xOffset: number; xOffset: number;
yOffset: number; yOffset: number;
@@ -24,7 +23,7 @@ export const useSectionActions = () => {
const { updateBoard } = useUpdateBoard(); const { updateBoard } = useUpdateBoard();
const moveAndResizeInnerSection = useCallback( const moveAndResizeInnerSection = useCallback(
({ innerSectionId, layoutId, ...positionProps }: MoveAndResizeInnerSection) => { ({ innerSectionId, ...positionProps }: MoveAndResizeInnerSection) => {
updateBoard((previous) => ({ updateBoard((previous) => ({
...previous, ...previous,
sections: previous.sections.map((section) => { sections: previous.sections.map((section) => {
@@ -32,10 +31,12 @@ export const useSectionActions = () => {
if (section.id !== innerSectionId) return section; if (section.id !== innerSectionId) return section;
if (section.kind !== "dynamic") return section; if (section.kind !== "dynamic") return section;
const currentLayout = getCurrentLayout(previous);
return { return {
...section, ...section,
layouts: section.layouts.map((layout) => { layouts: section.layouts.map((layout) => {
if (layout.layoutId !== layoutId) return layout; if (layout.layoutId !== currentLayout) return layout;
return { return {
...layout, ...layout,
...positionProps, ...positionProps,
@@ -49,7 +50,7 @@ export const useSectionActions = () => {
); );
const moveInnerSectionToSection = useCallback( const moveInnerSectionToSection = useCallback(
({ innerSectionId, layoutId, sectionId, ...positionProps }: MoveInnerSectionToSection) => { ({ innerSectionId, sectionId, ...positionProps }: MoveInnerSectionToSection) => {
updateBoard((previous) => { updateBoard((previous) => {
return { return {
...previous, ...previous,
@@ -58,10 +59,12 @@ export const useSectionActions = () => {
if (section.id !== innerSectionId) return section; if (section.id !== innerSectionId) return section;
if (section.kind !== "dynamic") return section; if (section.kind !== "dynamic") return section;
const currentLayout = getCurrentLayout(previous);
return { return {
...section, ...section,
layouts: section.layouts.map((layout) => { layouts: section.layouts.map((layout) => {
if (layout.layoutId !== layoutId) return layout; if (layout.layoutId !== currentLayout) return layout;
return { return {
...layout, ...layout,
...positionProps, ...positionProps,
@@ -1,10 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { import { resolveMobileBoardViewport } from "./use-mobile-board";
resolveIsAutomaticMobileBoard,
resolveMobileBoardViewport,
shouldShowMobileBoardViewportSkeleton,
} from "./use-mobile-board";
describe("resolveMobileBoardViewport", () => { describe("resolveMobileBoardViewport", () => {
test("keeps phones mobile regardless of their viewport width", () => { test("keeps phones mobile regardless of their viewport width", () => {
@@ -60,26 +56,3 @@ describe("resolveMobileBoardViewport", () => {
}); });
}); });
}); });
describe("resolveIsAutomaticMobileBoard", () => {
test.each([
[true, true, true],
[true, false, false],
[false, true, false],
[false, false, false],
])(
"requires both a mobile viewport and the server setting (viewport: %s, setting: %s)",
(isMobileViewport, enableAutomaticMobileLayout, expected) => {
expect(resolveIsAutomaticMobileBoard({ isMobileViewport, enableAutomaticMobileLayout })).toBe(expected);
},
);
test("does not show the tablet resolution skeleton in legacy mode", () => {
expect(
shouldShowMobileBoardViewportSkeleton({
enableAutomaticMobileLayout: false,
isResolved: false,
}),
).toBe(false);
});
});
@@ -5,8 +5,6 @@ import { createContext, useContext, useEffect, useState } from "react";
import { Box, Group, Skeleton, Stack } from "@mantine/core"; import { Box, Group, Skeleton, Stack } from "@mantine/core";
import { useMediaQuery } from "@mantine/hooks"; import { useMediaQuery } from "@mantine/hooks";
import { useSettings } from "@homarr/settings";
export const mobileBoardMediaQuery = "(max-width: 48em)"; export const mobileBoardMediaQuery = "(max-width: 48em)";
export type MobileBoardDeviceClass = "phone" | "tablet" | "desktop"; export type MobileBoardDeviceClass = "phone" | "tablet" | "desktop";
@@ -72,7 +70,6 @@ export const MobileBoardViewportProvider = ({
initialDeviceClass, initialDeviceClass,
children, children,
}: PropsWithChildren<{ initialDeviceClass: MobileBoardDeviceClass }>) => { }: PropsWithChildren<{ initialDeviceClass: MobileBoardDeviceClass }>) => {
const { enableAutomaticMobileLayout } = useSettings();
const [hasResolvedClientWidth, setHasResolvedClientWidth] = useState(false); const [hasResolvedClientWidth, setHasResolvedClientWidth] = useState(false);
const matchesMobileWidth = useMediaQuery(mobileBoardMediaQuery, initialDeviceClass === "phone", { const matchesMobileWidth = useMediaQuery(mobileBoardMediaQuery, initialDeviceClass === "phone", {
getInitialValueInEffect: true, getInitialValueInEffect: true,
@@ -90,42 +87,11 @@ export const MobileBoardViewportProvider = ({
return ( return (
<MobileBoardViewportContext.Provider value={viewport}> <MobileBoardViewportContext.Provider value={viewport}>
{shouldShowMobileBoardViewportSkeleton({ {viewport.isResolved ? children : <MobileBoardViewportSkeleton />}
enableAutomaticMobileLayout,
isResolved: viewport.isResolved,
}) ? (
<MobileBoardViewportSkeleton />
) : (
children
)}
</MobileBoardViewportContext.Provider> </MobileBoardViewportContext.Provider>
); );
}; };
export const useMobileBoardViewport = () => useContext(MobileBoardViewportContext); export const useMobileBoardViewport = () => useContext(MobileBoardViewportContext);
export const resolveIsAutomaticMobileBoard = ({ export const useIsMobileBoard = () => useMobileBoardViewport().isMobile;
isMobileViewport,
enableAutomaticMobileLayout,
}: {
isMobileViewport: boolean;
enableAutomaticMobileLayout: boolean;
}) => isMobileViewport && enableAutomaticMobileLayout;
export const shouldShowMobileBoardViewportSkeleton = ({
enableAutomaticMobileLayout,
isResolved,
}: {
enableAutomaticMobileLayout: boolean;
isResolved: boolean;
}) => enableAutomaticMobileLayout && !isResolved;
export const useIsMobileBoard = () => {
const viewport = useMobileBoardViewport();
const { enableAutomaticMobileLayout } = useSettings();
return resolveIsAutomaticMobileBoard({
isMobileViewport: viewport.isMobile,
enableAutomaticMobileLayout,
});
};
@@ -1,6 +1,5 @@
"use client"; "use client";
import { requestBoardEditAction } from "@homarr/boards/edit-mode";
import { useChangeLocale, useCurrentLocale } from "@homarr/translation/client"; import { useChangeLocale, useCurrentLocale } from "@homarr/translation/client";
import { LanguageCombobox } from "./language-combobox"; import { LanguageCombobox } from "./language-combobox";
@@ -17,7 +16,7 @@ export const CurrentLanguageCombobox = ({ width, withinPortal }: CurrentLanguage
return ( return (
<LanguageCombobox <LanguageCombobox
value={currentLocale} value={currentLocale}
onChange={(locale) => requestBoardEditAction(() => changeLocale(locale))} onChange={changeLocale}
isPending={isPending} isPending={isPending}
width={width} width={width}
withinPortal={withinPortal} withinPortal={withinPortal}
+15 -35
View File
@@ -17,10 +17,8 @@ import {
import type { RouterOutputs } from "@homarr/api"; import type { RouterOutputs } from "@homarr/api";
import { signOut, useSession } from "@homarr/auth/client"; import { signOut, useSession } from "@homarr/auth/client";
import { requestBoardEditAction } from "@homarr/boards/edit-mode";
import { hotkeys } from "@homarr/definitions"; import { hotkeys } from "@homarr/definitions";
import { createModal, useModalAction } from "@homarr/modals"; import { createModal, useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui"; import { Link } from "@homarr/ui";
@@ -49,36 +47,22 @@ export const UserAvatarMenu = ({ children, availableUpdatesPromise, isDockerEnab
const { openModal: openDockerModal } = useModalAction(DockerQuickAccessModal); const { openModal: openDockerModal } = useModalAction(DockerQuickAccessModal);
const handleSignout = useCallback(async () => { const handleSignout = useCallback(async () => {
try { await signOut({
const response = await signOut({ redirect: false,
redirect: false, });
}); openModal({
if (typeof response.url !== "string" || response.url.length === 0) { onTimeout: () => {
throw new Error("Sign out did not return a success URL"); if (logoutUrl) {
} window.location.assign(logoutUrl);
return;
return await new Promise<boolean>((resolve) => { }
openModal({ router.push("/auth/login");
onTimeout: () => { },
resolve(true); });
if (logoutUrl) { }, [logoutUrl, openModal, router]);
window.location.replace(logoutUrl);
return;
}
router.replace("/auth/login");
},
});
});
} catch {
showErrorNotification({
title: t("logoutError.title"),
message: t("logoutError.message"),
});
return false;
}
}, [logoutUrl, openModal, router, t]);
return ( return (
// We use keepMounted so we can add event listeners to prevent navigating away without saving the board
<Menu width={300} withinPortal keepMounted> <Menu width={300} withinPortal keepMounted>
<Menu.Dropdown> <Menu.Dropdown>
<AvailableUpdatesMenuItem availableUpdatesPromise={availableUpdatesPromise} /> <AvailableUpdatesMenuItem availableUpdatesPromise={availableUpdatesPromise} />
@@ -116,11 +100,7 @@ export const UserAvatarMenu = ({ children, availableUpdatesPromise, isDockerEnab
)} )}
<Menu.Divider /> <Menu.Divider />
{session.status === "authenticated" ? ( {session.status === "authenticated" ? (
<Menu.Item <Menu.Item onClick={handleSignout} leftSection={<IconLogout size="1rem" />} color="red">
onClick={() => requestBoardEditAction(handleSignout)}
leftSection={<IconLogout size="1rem" />}
color="red"
>
{t("logout")} {t("logout")}
</Menu.Item> </Menu.Item>
) : ( ) : (
+22 -131
View File
@@ -1,7 +1,6 @@
import type { Page } from "@playwright/test";
import { chromium, devices, expect } from "@playwright/test"; import { chromium, devices, expect } from "@playwright/test";
import { createId } from "@paralleldrive/cuid2"; import { createId } from "@paralleldrive/cuid2";
import { stringify } from "superjson"; import SuperJSON from "superjson";
import { describe, test } from "vitest"; import { describe, test } from "vitest";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
@@ -19,34 +18,9 @@ const adminCredentials = {
const boardName = "mobile-e2e"; const boardName = "mobile-e2e";
const setAutomaticMobileLayoutAsync = async (page: Page, enabled: boolean) => {
await page.goto(new URL("/manage/settings", page.url()).toString());
const toggle = page.getByRole("switch", { name: "Use automatic mobile layout" });
await expect(toggle).toBeVisible();
if ((await toggle.isChecked()) !== enabled) {
if (enabled) {
await toggle.check();
} else {
await toggle.uncheck();
}
await toggle.locator("xpath=ancestor::form").getByRole("button", { name: "Save", exact: true }).click();
await expect(page.getByText("Settings saved successfully")).toBeVisible();
}
await page.reload();
if (enabled) {
await expect(page.getByRole("switch", { name: "Use automatic mobile layout" })).toBeChecked();
} else {
await expect(page.getByRole("switch", { name: "Use automatic mobile layout" })).not.toBeChecked();
}
};
const seedMobileBoardAsync = async (db: SqliteDatabase, userId: string) => { const seedMobileBoardAsync = async (db: SqliteDatabase, userId: string) => {
const boardId = createId(); const boardId = createId();
const desktopLayoutId = createId(); const layoutId = createId();
const mobileLayoutId = createId();
const firstSectionId = createId(); const firstSectionId = createId();
const secondSectionId = createId(); const secondSectionId = createId();
@@ -55,22 +29,13 @@ const seedMobileBoardAsync = async (db: SqliteDatabase, userId: string) => {
name: boardName, name: boardName,
creatorId: userId, creatorId: userId,
}); });
await db.insert(sqliteSchema.layouts).values([ await db.insert(sqliteSchema.layouts).values({
{ id: layoutId,
id: desktopLayoutId, name: "Desktop",
name: "Desktop", boardId,
boardId, columnCount: 12,
columnCount: 12, breakpoint: 0,
breakpoint: 1200, });
},
{
id: mobileLayoutId,
name: "Mobile",
boardId,
columnCount: 4,
breakpoint: 0,
},
]);
await db.insert(sqliteSchema.sections).values([ await db.insert(sqliteSchema.sections).values([
{ {
id: firstSectionId, id: firstSectionId,
@@ -95,33 +60,22 @@ const seedMobileBoardAsync = async (db: SqliteDatabase, userId: string) => {
return { return {
id, id,
boardId, boardId,
kind: index === 0 ? ("notebook" as const) : index === 1 ? ("rssFeed" as const) : ("clock" as const), kind: index === 0 ? ("notebook" as const) : ("clock" as const),
options: stringify(index === 0 ? { content: "<p>Mobile notes</p>" } : {}), options: SuperJSON.stringify(index === 0 ? { content: "<p>Mobile notes</p>" } : {}),
advancedOptions: stringify({}), advancedOptions: SuperJSON.stringify({}),
}; };
}); });
await db.insert(sqliteSchema.items).values(itemRows); await db.insert(sqliteSchema.items).values(itemRows);
await db.insert(sqliteSchema.itemLayouts).values( await db.insert(sqliteSchema.itemLayouts).values(
itemRows.flatMap((item, index) => [ itemRows.map((item, index) => ({
{ itemId: item.id,
itemId: item.id, layoutId,
layoutId: desktopLayoutId, sectionId: index < 18 ? firstSectionId : secondSectionId,
sectionId: index < 18 ? firstSectionId : secondSectionId, xOffset: (index % 6) * 2,
xOffset: (index % 6) * 2, yOffset: Math.floor((index % 18) / 6) * 2,
yOffset: Math.floor((index % 18) / 6) * 2, width: 2,
width: 2, height: 2,
height: 2, })),
},
{
itemId: item.id,
layoutId: mobileLayoutId,
sectionId: index < 18 ? firstSectionId : secondSectionId,
xOffset: (index % 2) * 2,
yOffset: Math.floor((index % 18) / 2) * 2,
width: 2,
height: 2,
},
]),
); );
await db await db
.update(sqliteSchema.users) .update(sqliteSchema.users)
@@ -158,7 +112,6 @@ describe("Automatic mobile board", () => {
await loginPage.locator("#password").fill(adminCredentials.password); await loginPage.locator("#password").fill(adminCredentials.password);
await loginPage.locator("button[type='submit']").click(); await loginPage.locator("button[type='submit']").click();
await loginPage.waitForURL((url) => !url.pathname.includes("/auth/login"), { timeout: 15_000 }); await loginPage.waitForURL((url) => !url.pathname.includes("/auth/login"), { timeout: 15_000 });
await setAutomaticMobileLayoutAsync(loginPage, true);
const storageState = await loginContext.storageState(); const storageState = await loginContext.storageState();
const mobileViewports = [ const mobileViewports = [
@@ -197,7 +150,6 @@ describe("Automatic mobile board", () => {
await expect(page.locator("[data-mobile-board-item]"), viewport.name).toHaveCount(36); await expect(page.locator("[data-mobile-board-item]"), viewport.name).toHaveCount(36);
await expect(page.locator(".grid-stack-item"), viewport.name).toHaveCount(0); await expect(page.locator(".grid-stack-item"), viewport.name).toHaveCount(0);
await expect(page.getByRole("button", { name: /search/i }), viewport.name).toBeVisible(); await expect(page.getByRole("button", { name: /search/i }), viewport.name).toBeVisible();
await expect(page.getByRole("button", { name: "Edit item", exact: true }), viewport.name).toHaveCount(0);
const layoutMetrics = await page.evaluate(() => { const layoutMetrics = await page.evaluate(() => {
const grids = Array.from(document.querySelectorAll<HTMLElement>("[data-mobile-board] > div")); const grids = Array.from(document.querySelectorAll<HTMLElement>("[data-mobile-board] > div"));
@@ -249,10 +201,6 @@ describe("Automatic mobile board", () => {
} }
if (viewport.width === 390) { if (viewport.width === 390) {
await page.getByRole("button", { name: `Current board: ${boardName}` }).click();
await expect(page.getByRole("menuitem", { name: boardName })).toBeDisabled();
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "More" }).click(); await page.getByRole("button", { name: "More" }).click();
const moreDrawer = page.getByRole("dialog", { name: "More" }); const moreDrawer = page.getByRole("dialog", { name: "More" });
await expect(moreDrawer.getByRole("button", { name: "Second section" })).toBeVisible(); await expect(moreDrawer.getByRole("button", { name: "Second section" })).toBeVisible();
@@ -261,20 +209,12 @@ describe("Automatic mobile board", () => {
const notebookActions = page.getByRole("button", { name: /Actions for Notebook/i }); const notebookActions = page.getByRole("button", { name: /Actions for Notebook/i });
await notebookActions.click(); await notebookActions.click();
await page.getByRole("button", { name: "Open widget details", exact: true }).click(); await page.getByRole("button", { name: "Open widget details" }).click();
const details = page.getByRole("dialog", { name: "Notebook" }); const details = page.getByRole("dialog", { name: "Notebook" });
await expect(details).toBeVisible(); await expect(details).toBeVisible();
await expect(details.getByRole("button", { name: "Edit" })).toBeVisible();
await details.getByRole("button", { name: "Close" }).click(); await details.getByRole("button", { name: "Close" }).click();
await expect(notebookActions).toBeFocused(); await expect(notebookActions).toBeFocused();
const rssSummary = page.getByRole("button", { name: "Open widget details: RSS feeds" });
await rssSummary.click();
const rssDetails = page.getByRole("dialog", { name: "RSS feeds" });
await expect(rssDetails).toBeVisible();
await rssDetails.getByRole("button", { name: "Close" }).click();
await expect(rssSummary).toBeFocused();
const rtlOverflow = await page.evaluate(() => { const rtlOverflow = await page.evaluate(() => {
document.documentElement.dir = "rtl"; document.documentElement.dir = "rtl";
return document.documentElement.scrollWidth - document.documentElement.clientWidth; return document.documentElement.scrollWidth - document.documentElement.clientWidth;
@@ -293,56 +233,7 @@ describe("Automatic mobile board", () => {
await desktopPage.goto(`${baseUrl}/boards/${boardName}`); await desktopPage.goto(`${baseUrl}/boards/${boardName}`);
await expect(desktopPage.locator("[data-mobile-board]")).toHaveCount(0); await expect(desktopPage.locator("[data-mobile-board]")).toHaveCount(0);
await expect(desktopPage.locator(".grid-stack-item")).toHaveCount(36); await expect(desktopPage.locator(".grid-stack-item")).toHaveCount(36);
await desktopPage.getByRole("button", { name: "Edit item", exact: true }).click();
await desktopPage.setViewportSize({ width: 390, height: 844 });
await expect(desktopPage.locator("[data-mobile-board]")).toBeVisible();
await desktopPage.getByRole("button", { name: "More" }).click();
await desktopPage.getByRole("dialog", { name: "More" }).getByRole("link", { name: "Settings" }).click();
const unsavedChangesDialog = desktopPage.getByRole("dialog", { name: "Unsaved changes" });
await expect(unsavedChangesDialog).toBeVisible();
await desktopPage.keyboard.press("Escape");
await expect(unsavedChangesDialog).toBeHidden();
await desktopPage.goBack();
await expect(unsavedChangesDialog).toBeVisible();
await desktopPage.goBack();
await expect(desktopPage.getByRole("dialog", { name: "Unsaved changes" })).toHaveCount(1);
await desktopPage.keyboard.press("Escape");
await expect(unsavedChangesDialog).toBeHidden();
await desktopPage.setViewportSize({ width: 800, height: 900 });
await desktopPage.getByRole("button", { name: "Edit item", exact: true }).click();
await expect(desktopPage.getByText("The board was successfully saved")).toBeVisible();
await expect
.poll(() => desktopPage.evaluate(() => window.history.state?.["__homarrBoardEditGuard"] ?? null))
.toBeNull();
await setAutomaticMobileLayoutAsync(desktopPage, false);
await desktopContext.close(); await desktopContext.close();
const legacyMobileContext = await browser.newContext({
storageState,
viewport: { width: 390, height: 844 },
userAgent: devices["iPhone 13"].userAgent,
hasTouch: true,
isMobile: true,
});
const legacyMobilePage = await legacyMobileContext.newPage();
await legacyMobilePage.goto(`${baseUrl}/boards/${boardName}`);
await expect(legacyMobilePage.locator("[data-mobile-board]")).toHaveCount(0);
await expect(legacyMobilePage.locator(".grid-stack-item")).toHaveCount(36);
await expect(legacyMobilePage.getByRole("button", { name: "Edit item" })).toBeVisible();
await expect(legacyMobilePage.getByRole("button", { name: "More" })).toHaveCount(0);
await legacyMobilePage.getByRole("button", { name: "First section" }).click();
await legacyMobilePage.getByRole("button", { name: "Second section" }).click();
await expect
.poll(async () =>
legacyMobilePage
.locator(".grid-stack")
.first()
.evaluate((element) => getComputedStyle(element).getPropertyValue("--gridstack-column-count").trim()),
)
.toBe("4");
await legacyMobileContext.close();
} finally { } finally {
await loginContext.close(); await loginContext.close();
await browser.close(); await browser.close();
+29 -258
View File
@@ -49,7 +49,6 @@ import {
boardDuplicateSchema, boardDuplicateSchema,
boardRenameSchema, boardRenameSchema,
boardSaveLayoutSchema, boardSaveLayoutSchema,
boardSaveLayoutsSchema,
boardSavePartialSettingsSchema, boardSavePartialSettingsSchema,
boardSavePermissionsSchema, boardSavePermissionsSchema,
boardSaveSchema, boardSaveSchema,
@@ -688,7 +687,7 @@ export const boardRouter = createTRPCRouter({
mcp: { mcp: {
enabled: true, enabled: true,
description: description:
"Set a board's desktop column count while preserving saved responsive layouts. Requires modify permission. REQUIRED: id (board ID), columnCount (1-24)", "Set a board's desktop column count and remove legacy responsive layouts. Requires modify permission. REQUIRED: id (board ID), columnCount (1-24)",
}, },
}) })
.input(boardSaveLayoutSchema) .input(boardSaveLayoutSchema)
@@ -762,8 +761,12 @@ export const boardRouter = createTRPCRouter({
await transaction await transaction
.update(schema.layouts) .update(schema.layouts)
.set({ columnCount: input.columnCount }) .set({ name: "Base", columnCount: input.columnCount, breakpoint: 0 })
.where(eq(schema.layouts.id, desktopLayout.id)); .where(eq(schema.layouts.id, desktopLayout.id));
await transaction
.delete(schema.layouts)
.where(and(eq(schema.layouts.boardId, board.id), not(eq(schema.layouts.id, desktopLayout.id))));
}); });
}, },
handleSync(db) { handleSync(db) {
@@ -808,230 +811,18 @@ export const boardRouter = createTRPCRouter({
transaction transaction
.update(layouts) .update(layouts)
.set({ columnCount: input.columnCount }) .set({ name: "Base", columnCount: input.columnCount, breakpoint: 0 })
.where(eq(layouts.id, desktopLayout.id)) .where(eq(layouts.id, desktopLayout.id))
.run(); .run();
transaction
.delete(layouts)
.where(and(eq(layouts.boardId, board.id), not(eq(layouts.id, desktopLayout.id))))
.run();
}); });
}, },
}); });
}), }),
saveLayouts: protectedProcedure
.input(boardSaveLayoutsSchema)
.output(boardSaveLayoutsSchema.shape.layouts)
.mutation(async ({ ctx, input }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
const board = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id);
const addedLayouts = filterAddedItems(input.layouts, board.layouts);
const layoutsToInsert: InferInsertModel<typeof layouts>[] = [];
const itemSectionLayoutsToInsert: InferInsertModel<typeof itemLayouts>[] = [];
const sectionLayoutsToInsert: InferInsertModel<typeof sectionLayouts>[] = [];
const savedLayoutIds = new Map<string, string>();
for (const addedLayout of addedLayouts) {
const layoutId = createId();
savedLayoutIds.set(addedLayout.id, layoutId);
layoutsToInsert.push({
id: layoutId,
name: addedLayout.name,
columnCount: addedLayout.columnCount,
breakpoint: addedLayout.breakpoint,
boardId: board.id,
});
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutA.columnCount - layoutB.columnCount);
const layoutToClone =
sortedLayouts.find((layout) => layout.columnCount >= addedLayout.columnCount) ?? sortedLayouts.at(-1);
if (!layoutToClone) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Board must have a layout" });
}
const updatedBoardLayout = getUpdatedBoardLayout(board, {
previous: {
layoutId: layoutToClone.id,
columnCount: layoutToClone.columnCount,
},
current: {
layoutId,
columnCount: addedLayout.columnCount,
},
});
itemSectionLayoutsToInsert.push(...updatedBoardLayout.itemSectionLayouts);
sectionLayoutsToInsert.push(...updatedBoardLayout.sectionLayouts);
}
const updatedLayouts = filterUpdatedItems(input.layouts, board.layouts);
const itemSectionLayoutsToUpdate: InferInsertModel<typeof itemLayouts>[] = [];
const sectionLayoutsToUpdate: InferInsertModel<typeof sectionLayouts>[] = [];
const layoutsToUpdate: typeof input.layouts = [];
for (const updatedLayout of updatedLayouts) {
const dbLayout = board.layouts.find((layout) => layout.id === updatedLayout.id);
if (!dbLayout) continue;
if (dbLayout.columnCount !== updatedLayout.columnCount) {
const updatedBoardLayout = getUpdatedBoardLayout(board, {
previous: {
layoutId: dbLayout.id,
columnCount: dbLayout.columnCount,
},
current: {
layoutId: dbLayout.id,
columnCount: updatedLayout.columnCount,
},
});
itemSectionLayoutsToUpdate.push(...updatedBoardLayout.itemSectionLayouts);
sectionLayoutsToUpdate.push(...updatedBoardLayout.sectionLayouts);
}
layoutsToUpdate.push(updatedLayout);
}
const removedLayoutIds = filterRemovedItems(input.layouts, board.layouts).map((layout) => layout.id);
await handleTransactionsAsync(ctx.db, {
async handleAsync(db, schema) {
await db.transaction(async (transaction) => {
if (layoutsToInsert.length > 0) {
await transaction.insert(schema.layouts).values(layoutsToInsert);
}
if (itemSectionLayoutsToInsert.length > 0) {
await transaction.insert(schema.itemLayouts).values(itemSectionLayoutsToInsert);
}
if (sectionLayoutsToInsert.length > 0) {
await transaction.insert(schema.sectionLayouts).values(sectionLayoutsToInsert);
}
for (const itemSectionLayout of itemSectionLayoutsToUpdate) {
await transaction
.update(schema.itemLayouts)
.set({
height: itemSectionLayout.height,
width: itemSectionLayout.width,
xOffset: itemSectionLayout.xOffset,
yOffset: itemSectionLayout.yOffset,
sectionId: itemSectionLayout.sectionId,
})
.where(
and(
eq(schema.itemLayouts.itemId, itemSectionLayout.itemId),
eq(schema.itemLayouts.layoutId, itemSectionLayout.layoutId),
),
);
}
for (const sectionLayout of sectionLayoutsToUpdate) {
await transaction
.update(schema.sectionLayouts)
.set({
height: sectionLayout.height,
width: sectionLayout.width,
xOffset: sectionLayout.xOffset,
yOffset: sectionLayout.yOffset,
parentSectionId: sectionLayout.parentSectionId,
})
.where(
and(
eq(schema.sectionLayouts.sectionId, sectionLayout.sectionId),
eq(schema.sectionLayouts.layoutId, sectionLayout.layoutId),
),
);
}
for (const layout of layoutsToUpdate) {
await transaction
.update(schema.layouts)
.set({
name: layout.name,
columnCount: layout.columnCount,
breakpoint: layout.breakpoint,
})
.where(eq(schema.layouts.id, layout.id));
}
if (removedLayoutIds.length > 0) {
await transaction.delete(schema.layouts).where(inArray(schema.layouts.id, removedLayoutIds));
}
});
},
handleSync(db) {
db.transaction((transaction) => {
if (layoutsToInsert.length > 0) {
transaction.insert(layouts).values(layoutsToInsert).run();
}
if (itemSectionLayoutsToInsert.length > 0) {
transaction.insert(itemLayouts).values(itemSectionLayoutsToInsert).run();
}
if (sectionLayoutsToInsert.length > 0) {
transaction.insert(sectionLayouts).values(sectionLayoutsToInsert).run();
}
for (const itemSectionLayout of itemSectionLayoutsToUpdate) {
transaction
.update(itemLayouts)
.set({
height: itemSectionLayout.height,
width: itemSectionLayout.width,
xOffset: itemSectionLayout.xOffset,
yOffset: itemSectionLayout.yOffset,
sectionId: itemSectionLayout.sectionId,
})
.where(
and(
eq(itemLayouts.itemId, itemSectionLayout.itemId),
eq(itemLayouts.layoutId, itemSectionLayout.layoutId),
),
)
.run();
}
for (const sectionLayout of sectionLayoutsToUpdate) {
transaction
.update(sectionLayouts)
.set({
height: sectionLayout.height,
width: sectionLayout.width,
xOffset: sectionLayout.xOffset,
yOffset: sectionLayout.yOffset,
parentSectionId: sectionLayout.parentSectionId,
})
.where(
and(
eq(sectionLayouts.sectionId, sectionLayout.sectionId),
eq(sectionLayouts.layoutId, sectionLayout.layoutId),
),
)
.run();
}
for (const layout of layoutsToUpdate) {
transaction
.update(layouts)
.set({
name: layout.name,
columnCount: layout.columnCount,
breakpoint: layout.breakpoint,
})
.where(eq(layouts.id, layout.id))
.run();
}
if (removedLayoutIds.length > 0) {
transaction.delete(layouts).where(inArray(layouts.id, removedLayoutIds)).run();
}
});
},
});
return input.layouts.map((layout) => ({
...layout,
id: savedLayoutIds.get(layout.id) ?? layout.id,
}));
}),
savePartialBoardSettings: protectedProcedure savePartialBoardSettings: protectedProcedure
.meta({ .meta({
openapi: { method: "PATCH", path: "/api/boards/{id}/settings", tags: ["boards"], protect: true }, openapi: { method: "PATCH", path: "/api/boards/{id}/settings", tags: ["boards"], protect: true },
@@ -1700,16 +1491,16 @@ export const boardRouter = createTRPCRouter({
} }
const itemId = createId(); const itemId = createId();
const itemRow = {
await ctx.db.insert(items).values({
id: itemId, id: itemId,
boardId: input.boardId, boardId: input.boardId,
kind: input.kind, kind: input.kind,
options: superjson.stringify(input.options), options: superjson.stringify(input.options),
advancedOptions: emptySuperJSON, advancedOptions: emptySuperJSON,
}; });
const layoutRows: (typeof itemLayouts.$inferInsert)[] = []; const layoutRows: (typeof itemLayouts.$inferInsert)[] = [];
const defaultSize = widgetDefaultSizes[input.kind as WidgetKind] ?? { width: 1, height: 1 };
for (const layout of board.layouts) { for (const layout of board.layouts) {
const existingInSection = board.items const existingInSection = board.items
@@ -1728,17 +1519,14 @@ export const boardRouter = createTRPCRouter({
} }
} }
const layoutItemSize = { const defaultSize = widgetDefaultSizes[input.kind as WidgetKind] ?? { width: 1, height: 1 };
...defaultSize,
width: Math.min(defaultSize.width, layout.columnCount),
};
const fitsAt = (x: number, y: number) => { const fitsAt = (x: number, y: number) => {
if (x + layoutItemSize.width > layout.columnCount) return false; if (x + defaultSize.width > layout.columnCount) return false;
for (let dy = 0; dy < layoutItemSize.height; dy++) { for (let dy = 0; dy < defaultSize.height; dy++) {
const row = occupied[y + dy]; const row = occupied[y + dy];
if (!row) continue; if (!row) continue;
for (let dx = 0; dx < layoutItemSize.width; dx++) { for (let dx = 0; dx < defaultSize.width; dx++) {
if (row[x + dx]) return false; if (row[x + dx]) return false;
} }
} }
@@ -1756,8 +1544,8 @@ export const boardRouter = createTRPCRouter({
layoutId: layout.id, layoutId: layout.id,
xOffset: x, xOffset: x,
yOffset: y, yOffset: y,
width: layoutItemSize.width, width: defaultSize.width,
height: layoutItemSize.height, height: defaultSize.height,
}); });
placed = true; placed = true;
} }
@@ -1772,32 +1560,15 @@ export const boardRouter = createTRPCRouter({
} }
} }
const integrationRows = input.integrationIds.map((integrationId) => ({ itemId, integrationId })); if (layoutRows.length > 0) {
await ctx.db.insert(itemLayouts).values(layoutRows);
}
await handleTransactionsAsync(ctx.db, { if (input.integrationIds.length > 0) {
async handleAsync(db, schema) { await ctx.db
await db.transaction(async (transaction) => { .insert(integrationItems)
await transaction.insert(schema.items).values(itemRow); .values(input.integrationIds.map((integrationId) => ({ itemId, integrationId })));
if (layoutRows.length > 0) { }
await transaction.insert(schema.itemLayouts).values(layoutRows);
}
if (integrationRows.length > 0) {
await transaction.insert(schema.integrationItems).values(integrationRows);
}
});
},
handleSync(db) {
db.transaction((transaction) => {
transaction.insert(items).values(itemRow).run();
if (layoutRows.length > 0) {
transaction.insert(itemLayouts).values(layoutRows).run();
}
if (integrationRows.length > 0) {
transaction.insert(integrationItems).values(integrationRows).run();
}
});
},
});
return { itemId }; return { itemId };
}), }),
+4 -14
View File
@@ -19,7 +19,6 @@ import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
const boardServerSettingsSchema = z.object({ const boardServerSettingsSchema = z.object({
homeBoardId: z.string().nullable(), homeBoardId: z.string().nullable(),
mobileHomeBoardId: z.string().nullable(), mobileHomeBoardId: z.string().nullable(),
enableAutomaticMobileLayout: z.boolean(),
enableStatusByDefault: z.boolean(), enableStatusByDefault: z.boolean(),
forceDisableStatus: z.boolean(), forceDisableStatus: z.boolean(),
}) satisfies z.ZodType<ServerSettings["board"]>; }) satisfies z.ZodType<ServerSettings["board"]>;
@@ -40,7 +39,7 @@ export const serverSettingsRouter = createTRPCRouter({
mcp: { mcp: {
enabled: true, enabled: true,
description: description:
"Get global board defaults, including desktop/mobile home board IDs, automatic mobile layout mode, and status behavior. Requires admin permission", "Get global board defaults, including desktop/mobile home board IDs and status behavior. Requires admin permission",
}, },
}) })
.input(z.void()) .input(z.void())
@@ -55,7 +54,7 @@ export const serverSettingsRouter = createTRPCRouter({
mcp: { mcp: {
enabled: true, enabled: true,
description: description:
"Update global board defaults. Requires admin permission. Optional fields: homeBoardId, mobileHomeBoardId, enableAutomaticMobileLayout, enableStatusByDefault, forceDisableStatus. Home board IDs must reference public boards or be null", "Update global board defaults. Requires admin permission. Optional fields: homeBoardId, mobileHomeBoardId, enableStatusByDefault, forceDisableStatus. Home board IDs must reference public boards or be null",
}, },
}) })
.input(boardServerSettingsUpdateSchema) .input(boardServerSettingsUpdateSchema)
@@ -104,19 +103,10 @@ export const serverSettingsRouter = createTRPCRouter({
) )
.mutation(async ({ ctx, input }) => { .mutation(async ({ ctx, input }) => {
const current = await getServerSettingByKeyAsync(ctx.db, input.settingsKey); const current = await getServerSettingByKeyAsync(ctx.db, input.settingsKey);
const next = { await updateServerSettingByKeyAsync(ctx.db, input.settingsKey, {
...current, ...current,
...input.value, ...input.value,
} as ServerSettings[keyof ServerSettings]; } as ServerSettings[keyof ServerSettings]);
const existing = await ctx.db.query.serverSettings.findFirst({
where: eq(serverSettings.settingKey, input.settingsKey),
});
if (existing) {
await updateServerSettingByKeyAsync(ctx.db, input.settingsKey, next);
} else {
await insertServerSettingByKeyAsync(ctx.db, input.settingsKey, next);
}
}), }),
initSettings: onboardingProcedure initSettings: onboardingProcedure
.requiresStep("settings") .requiresStep("settings")
+7 -191
View File
@@ -4,7 +4,7 @@ import { describe, expect, it, test, vi } from "vitest";
import type { Session } from "@homarr/auth"; import type { Session } from "@homarr/auth";
import { createId } from "@homarr/common"; import { createId } from "@homarr/common";
import type { Database, InferInsertModel } from "@homarr/db"; import type { Database, InferInsertModel } from "@homarr/db";
import { and, eq, not } from "@homarr/db"; import { and, eq } from "@homarr/db";
import { import {
boardGroupPermissions, boardGroupPermissions,
boards, boards,
@@ -1382,187 +1382,6 @@ describe("saveGroupBoardPermissions should save group board permissions", () =>
); );
}); });
const createExistingLayout = (id: string) => ({
id,
name: "Base",
columnCount: 10,
breakpoint: 0,
});
const createNewLayout = (columnCount: number) => ({
id: createId(),
name: "New layout",
columnCount,
breakpoint: 1400,
});
describe("saveLayouts should preserve legacy responsive layout editing", () => {
test("should add a layout and clone item and dynamic-section placements", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId, sectionId, itemId } = await createFullBoardAsync(db, "default");
const assignments = await createItemsAndSectionsAsync(db, {
boardId,
layoutId,
sectionId,
});
const newLayout = createNewLayout(3);
const savedLayouts = await caller.saveLayouts({
id: boardId,
layouts: [createExistingLayout(layoutId), newLayout],
});
const layout = expectToBeDefined(
await db.query.layouts.findFirst({
where: not(eq(layouts.id, layoutId)),
}),
);
expect(layout).toMatchObject({
name: newLayout.name,
columnCount: newLayout.columnCount,
breakpoint: newLayout.breakpoint,
});
expect(savedLayouts).toEqual([createExistingLayout(layoutId), { ...newLayout, id: layout.id }]);
await expectLayoutForRootLayoutAsync(db, sectionId, layout.id, {
...assignments.inRoot,
a: itemId,
});
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layout.id, assignments.inDynamicSection);
await caller.saveLayouts({ id: boardId, layouts: savedLayouts });
await expect(db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) })).resolves.toHaveLength(2);
});
test("should update layout metadata and positions", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId, sectionId, itemId } = await createFullBoardAsync(db, "default");
const assignments = await createItemsAndSectionsAsync(db, {
boardId,
layoutId,
sectionId,
});
await caller.saveLayouts({
id: boardId,
layouts: [
{
id: layoutId,
name: "Phone",
columnCount: 3,
breakpoint: 480,
},
],
});
await expect(db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) })).resolves.toMatchObject({
name: "Phone",
columnCount: 3,
breakpoint: 480,
});
await expectLayoutForRootLayoutAsync(db, sectionId, layoutId, {
...assignments.inRoot,
a: itemId,
});
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection);
});
test("should remove layouts omitted from the saved responsive configuration", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
await caller.saveLayouts({
id: boardId,
layouts: [createNewLayout(12)],
});
await expect(db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) })).resolves.toBeUndefined();
});
test("should reject duplicate responsive breakpoints", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
await expect(
caller.saveLayouts({
id: boardId,
layouts: [
createExistingLayout(layoutId),
{
...createNewLayout(4),
breakpoint: 0,
},
],
}),
).rejects.toMatchObject({ code: "BAD_REQUEST" });
});
test("should reject duplicate responsive layout IDs", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
const existingLayout = createExistingLayout(layoutId);
await expect(
caller.saveLayouts({
id: boardId,
layouts: [existingLayout, { ...existingLayout, name: "Phone", breakpoint: 480 }],
}),
).rejects.toMatchObject({ code: "BAD_REQUEST" });
});
test("should reject fractional responsive layout values", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
await expect(
caller.saveLayouts({
id: boardId,
layouts: [{ ...createExistingLayout(layoutId), breakpoint: 480.5 }],
}),
).rejects.toMatchObject({ code: "BAD_REQUEST" });
await expect(
caller.saveLayouts({
id: boardId,
layouts: [{ ...createExistingLayout(layoutId), columnCount: 3.5 }],
}),
).rejects.toMatchObject({ code: "BAD_REQUEST" });
});
});
describe("addItem should preserve every saved layout", () => {
test("should clamp wide widgets to a retained narrow layout", async () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
const mobileLayoutId = createId();
await db.insert(layouts).values({
id: mobileLayoutId,
name: "Mobile",
columnCount: 1,
breakpoint: 480,
boardId,
});
const { itemId } = await caller.addItem({
boardId,
kind: "mediaMissing",
});
const savedItemLayouts = await db.query.itemLayouts.findMany({
where: eq(itemLayouts.itemId, itemId),
});
expect(savedItemLayouts).toHaveLength(2);
expect(savedItemLayouts).toContainEqual(expect.objectContaining({ layoutId, width: 4 }));
expect(savedItemLayouts).toContainEqual(expect.objectContaining({ layoutId: mobileLayoutId, width: 1 }));
});
});
describe("saveLayout should save the desktop layout", () => { describe("saveLayout should save the desktop layout", () => {
test("should update position of items when column count changes", async () => { test("should update position of items when column count changes", async () => {
// Arrange // Arrange
@@ -1588,7 +1407,7 @@ describe("saveLayout should save the desktop layout", () => {
}); });
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection); await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection);
}); });
test("should preserve legacy layouts and desktop metadata", async () => { test("should keep the desktop layout and remove legacy responsive layouts", async () => {
// Arrange // Arrange
const db = createDb(); const db = createDb();
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession }); const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
@@ -1615,18 +1434,15 @@ describe("saveLayout should save the desktop layout", () => {
// Act // Act
await caller.saveLayout({ await caller.saveLayout({
id: boardId, id: boardId,
columnCount: 14, columnCount: 16,
}); });
// Assert // Assert
const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) }); const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) });
expect(savedLayouts).toHaveLength(2); expect(savedLayouts).toEqual([
expect(savedLayouts).toContainEqual( expect.objectContaining({ id: desktopLayoutId, name: "Base", columnCount: 16, breakpoint: 0 }),
expect.objectContaining({ id: layoutId, name: "Base", columnCount: 10, breakpoint: 0 }), ]);
); expect(savedLayouts.some((layout) => layout.id === layoutId)).toBe(false);
expect(savedLayouts).toContainEqual(
expect.objectContaining({ id: desktopLayoutId, name: "Large", columnCount: 14, breakpoint: 1200 }),
);
}); });
test("should fail when board not found", async () => { test("should fail when board not found", async () => {
// Arrange // Arrange
@@ -56,33 +56,6 @@ describe("getAll server settings", () => {
}); });
describe("saveSettings", () => { describe("saveSettings", () => {
test("saveSettings should persist settings when defaults are not seeded", async () => {
const db = createDb();
const caller = serverSettingsRouter.createCaller({
db,
deviceType: undefined,
session: defaultSession,
});
await caller.saveSettings({
settingsKey: "board",
value: {
enableAutomaticMobileLayout: false,
},
});
const dbSettings = await db.select().from(serverSettings);
expect(dbSettings).toStrictEqual([
{
settingKey: "board",
value: stringify({
...defaultServerSettings.board,
enableAutomaticMobileLayout: false,
}),
},
]);
});
test("saveSettings should update settings and return true when it updated only one", async () => { test("saveSettings should update settings and return true when it updated only one", async () => {
const db = createDb(); const db = createDb();
const caller = serverSettingsRouter.createCaller({ const caller = serverSettingsRouter.createCaller({
@@ -130,27 +103,6 @@ describe("board settings API", () => {
await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board); await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board);
}); });
test("getBoardSettings should backfill the automatic layout default for legacy values", async () => {
const db = createDb();
const caller = serverSettingsRouter.createCaller({
db,
deviceType: undefined,
session: defaultSession,
});
const legacyBoardSettings = {
homeBoardId: defaultServerSettings.board.homeBoardId,
mobileHomeBoardId: defaultServerSettings.board.mobileHomeBoardId,
enableStatusByDefault: defaultServerSettings.board.enableStatusByDefault,
forceDisableStatus: defaultServerSettings.board.forceDisableStatus,
};
await db.insert(serverSettings).values({
settingKey: "board",
value: stringify(legacyBoardSettings),
});
await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board);
});
test("updateBoardSettings should insert settings when defaults are not persisted", async () => { test("updateBoardSettings should insert settings when defaults are not persisted", async () => {
const db = createDb(); const db = createDb();
const caller = serverSettingsRouter.createCaller({ const caller = serverSettingsRouter.createCaller({
@@ -193,7 +145,6 @@ describe("board settings API", () => {
await caller.updateBoardSettings({ homeBoardId: boardId }); await caller.updateBoardSettings({ homeBoardId: boardId });
const result = await caller.updateBoardSettings({ const result = await caller.updateBoardSettings({
mobileHomeBoardId: boardId, mobileHomeBoardId: boardId,
enableAutomaticMobileLayout: false,
enableStatusByDefault: false, enableStatusByDefault: false,
}); });
@@ -201,7 +152,6 @@ describe("board settings API", () => {
...defaultServerSettings.board, ...defaultServerSettings.board,
homeBoardId: boardId, homeBoardId: boardId,
mobileHomeBoardId: boardId, mobileHomeBoardId: boardId,
enableAutomaticMobileLayout: false,
enableStatusByDefault: false, enableStatusByDefault: false,
}); });
const dbSettings = await db.select().from(serverSettings); const dbSettings = await db.select().from(serverSettings);
@@ -2,53 +2,36 @@ import { getIntegrationKindsByCategory } from "@homarr/definitions";
import { mediaReleaseRequestHandler } from "@homarr/request-handler/media-release"; import { mediaReleaseRequestHandler } from "@homarr/request-handler/media-release";
import { createManyIntegrationMiddleware } from "../../middlewares/integration"; import { createManyIntegrationMiddleware } from "../../middlewares/integration";
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "../../settle-integrations"; import { settleIntegrationQueries } from "../../settle-integrations";
import { createTRPCRouter, publicProcedure } from "../../trpc"; import { createTRPCRouter, publicProcedure } from "../../trpc";
const mediaReleasesProcedure = publicProcedure.concat(
createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRelease")),
);
type MediaReleaseIntegration = Parameters<typeof mediaReleaseRequestHandler.handler>[0];
const getMediaReleasesWithProvenanceAsync = async (integrations: MediaReleaseIntegration[]) => {
const results = await settleIntegrationQueries(
integrations,
async (integration) => {
const innerHandler = mediaReleaseRequestHandler.handler(integration, {});
const { data, timestamp, isStale } = await innerHandler.getDataWithProvenanceAsync();
return {
integration: {
id: integration.id,
name: integration.name,
kind: integration.kind,
updatedAt: timestamp,
},
releases: data,
isStale,
};
},
{ throwOnAllFailure: true },
);
const items = results.flatMap((result) =>
result.releases.map((release) => ({
...release,
integration: result.integration,
})),
);
return {
items,
...getIntegrationQueryProvenance(integrations.length, results),
};
};
export const mediaReleaseRouter = createTRPCRouter({ export const mediaReleaseRouter = createTRPCRouter({
getMediaReleases: mediaReleasesProcedure.query(async ({ ctx }) => { getMediaReleases: publicProcedure
return (await getMediaReleasesWithProvenanceAsync(ctx.integrations)).items; .concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRelease")))
}), .query(async ({ ctx }) => {
getMediaReleasesWithProvenance: mediaReleasesProcedure.query(async ({ ctx }) => { const results = await settleIntegrationQueries(
return await getMediaReleasesWithProvenanceAsync(ctx.integrations); ctx.integrations,
}), async (integration) => {
const innerHandler = mediaReleaseRequestHandler.handler(integration, {});
const { data, timestamp } = await innerHandler.getDataAsync();
return {
integration: {
id: integration.id,
name: integration.name,
kind: integration.kind,
updatedAt: timestamp,
},
releases: data,
};
},
{ throwOnAllFailure: true },
);
return results.flatMap((result) =>
result.releases.map((release) => ({
...release,
integration: result.integration,
})),
);
}),
}); });
@@ -3,7 +3,6 @@ import { z } from "zod/v4";
import { getIntegrationKindsByCategory } from "@homarr/definitions"; import { getIntegrationKindsByCategory } from "@homarr/definitions";
import { createIntegrationAsync } from "@homarr/integrations"; import { createIntegrationAsync } from "@homarr/integrations";
import { mediaRequestStatusConfiguration } from "@homarr/integrations/types"; import { mediaRequestStatusConfiguration } from "@homarr/integrations/types";
import type { MediaRequestListInput } from "@homarr/request-handler/media-request-list";
import { import {
mediaRequestListInputSchema, mediaRequestListInputSchema,
mediaRequestListRequestHandler, mediaRequestListRequestHandler,
@@ -11,93 +10,11 @@ import {
import { mediaRequestStatsRequestHandler } from "@homarr/request-handler/media-request-stats"; import { mediaRequestStatsRequestHandler } from "@homarr/request-handler/media-request-stats";
import { createManyIntegrationMiddleware, createOneIntegrationMiddleware } from "../../middlewares/integration"; import { createManyIntegrationMiddleware, createOneIntegrationMiddleware } from "../../middlewares/integration";
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "../../settle-integrations"; import { settleIntegrationQueries } from "../../settle-integrations";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc"; import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
const latestRequestsProcedure = publicProcedure
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
.input(mediaRequestListInputSchema);
const requestStatsProcedure = publicProcedure.concat(
createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")),
);
type MediaRequestIntegration = Parameters<typeof mediaRequestListRequestHandler.handler>[0];
type MediaRequestStatsIntegration = Parameters<typeof mediaRequestStatsRequestHandler.handler>[0];
const getLatestRequestsWithProvenanceAsync = async (
integrations: MediaRequestIntegration[],
input: MediaRequestListInput,
) => {
const results = await settleIntegrationQueries(
integrations,
async (integration) => {
const { data, isStale } = await mediaRequestListRequestHandler
.handler(integration, input)
.getDataWithProvenanceAsync();
return {
integration: { id: integration.id, name: integration.name, kind: integration.kind },
data,
isStale,
};
},
{ throwOnAllFailure: true },
);
const items = results
.flatMap(({ data, integration }) =>
data.map((request) => ({
...request,
integrationId: integration.id,
})),
)
.toSorted((dataA, dataB) => {
if (dataA.status === dataB.status) {
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
}
return (
mediaRequestStatusConfiguration[dataA.status].position - mediaRequestStatusConfiguration[dataB.status].position
);
});
return {
items,
...getIntegrationQueryProvenance(integrations.length, results),
};
};
const getRequestStatsWithProvenanceAsync = async (integrations: MediaRequestStatsIntegration[]) => {
const results = await settleIntegrationQueries(
integrations,
async (integration) => {
const { data, isStale } = await mediaRequestStatsRequestHandler
.handler(integration, {})
.getDataWithProvenanceAsync();
return {
integration: { id: integration.id, name: integration.name, kind: integration.kind },
data,
isStale,
};
},
{ throwOnAllFailure: true },
);
return {
stats: results.flatMap((result) => result.data.stats),
users: results
.flatMap((result) =>
result.data.users.map((user) => ({
...user,
integration: result.integration,
})),
)
.toSorted(({ requestCount: countA }, { requestCount: countB }) => countB - countA),
integrations: results.map((result) => result.integration),
...getIntegrationQueryProvenance(integrations.length, results),
};
};
export const mediaRequestsRouter = createTRPCRouter({ export const mediaRequestsRouter = createTRPCRouter({
getLatestRequests: latestRequestsProcedure getLatestRequests: publicProcedure
.meta({ .meta({
mcp: { mcp: {
enabled: true, enabled: true,
@@ -105,13 +22,36 @@ export const mediaRequestsRouter = createTRPCRouter({
"Get latest media requests from Overseerr/Jellyseerr with their status (pending, approved, declined, failed, completed). REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all). OPTIONAL: statuses (array of statuses to include, must be non-empty) and recentDays (number 0-365; 0 disables the time filter).", "Get latest media requests from Overseerr/Jellyseerr with their status (pending, approved, declined, failed, completed). REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all). OPTIONAL: statuses (array of statuses to include, must be non-empty) and recentDays (number 0-365; 0 disables the time filter).",
}, },
}) })
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
.input(mediaRequestListInputSchema)
.query(async ({ ctx, input }) => { .query(async ({ ctx, input }) => {
return (await getLatestRequestsWithProvenanceAsync(ctx.integrations, input)).items; const results = await settleIntegrationQueries(
ctx.integrations,
async (integration) => {
const { data } = await mediaRequestListRequestHandler.handler(integration, input).getDataAsync();
return { integration: { id: integration.id, name: integration.name, kind: integration.kind }, data };
},
{ throwOnAllFailure: true },
);
return results
.flatMap(({ data, integration }) =>
data.map((request) => ({
...request,
integrationId: integration.id,
})),
)
.toSorted((dataA, dataB) => {
if (dataA.status === dataB.status) {
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
}
return (
mediaRequestStatusConfiguration[dataA.status].position -
mediaRequestStatusConfiguration[dataB.status].position
);
});
}), }),
getLatestRequestsWithProvenance: latestRequestsProcedure.query(async ({ ctx, input }) => { getStats: publicProcedure
return await getLatestRequestsWithProvenanceAsync(ctx.integrations, input);
}),
getStats: requestStatsProcedure
.meta({ .meta({
mcp: { mcp: {
enabled: true, enabled: true,
@@ -119,17 +59,30 @@ export const mediaRequestsRouter = createTRPCRouter({
"Get media request statistics including total counts and top requesters. REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all)", "Get media request statistics including total counts and top requesters. REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all)",
}, },
}) })
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
.query(async ({ ctx }) => { .query(async ({ ctx }) => {
const result = await getRequestStatsWithProvenanceAsync(ctx.integrations); const results = await settleIntegrationQueries(
ctx.integrations,
async (integration) => {
const { data } = await mediaRequestStatsRequestHandler.handler(integration, {}).getDataAsync();
return { integration: { id: integration.id, name: integration.name, kind: integration.kind }, data };
},
{ throwOnAllFailure: true },
);
return { return {
stats: result.stats, stats: results.flatMap((result) => result.data.stats),
users: result.users, users: results
integrations: result.integrations, .map((result) =>
result.data.users.map((user) => ({
...user,
integration: result.integration,
})),
)
.flat()
.toSorted(({ requestCount: countA }, { requestCount: countB }) => countB - countA),
integrations: results.map((result) => result.integration),
}; };
}), }),
getStatsWithProvenance: requestStatsProcedure.query(async ({ ctx }) => {
return await getRequestStatsWithProvenanceAsync(ctx.integrations);
}),
answerRequest: protectedProcedure answerRequest: protectedProcedure
.meta({ .meta({
mcp: { mcp: {
+1 -17
View File
@@ -2,7 +2,7 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "./settle-integrations"; import { settleIntegrationQueries } from "./settle-integrations";
const integrations = [ const integrations = [
{ id: "first", name: "First", kind: "mock" }, { id: "first", name: "First", kind: "mock" },
@@ -76,19 +76,3 @@ describe("settleIntegrationQueries", () => {
).resolves.toEqual([]); ).resolves.toEqual([]);
}); });
}); });
describe("getIntegrationQueryProvenance", () => {
it("counts dropped and stale integration results independently", () => {
expect(getIntegrationQueryProvenance(4, [{ isStale: false }, { isStale: true }, { isStale: true }])).toEqual({
failedIntegrationCount: 1,
staleIntegrationCount: 2,
});
});
it("does not report failures for complete current results", () => {
expect(getIntegrationQueryProvenance(2, [{ isStale: false }, {}])).toEqual({
failedIntegrationCount: 0,
staleIntegrationCount: 0,
});
});
});
-1
View File
@@ -33,7 +33,6 @@ test("MCP tools should contain expected procedures", () => {
expect(toolNames).toContain("app_byId"); expect(toolNames).toContain("app_byId");
expect(toolNames).toContain("app_create"); expect(toolNames).toContain("app_create");
expect(toolNames).toContain("board_savePartialBoardSettings"); expect(toolNames).toContain("board_savePartialBoardSettings");
expect(toolNames).toContain("board_saveLayout");
expect(toolNames).toContain("board_duplicateBoard"); expect(toolNames).toContain("board_duplicateBoard");
expect(toolNames).toContain("info_getInfo"); expect(toolNames).toContain("info_getInfo");
expect(toolNames).toContain("invite_getAll"); expect(toolNames).toContain("invite_getAll");
-1
View File
@@ -24,7 +24,6 @@
}, },
"dependencies": { "dependencies": {
"@homarr/api": "workspace:^0.1.0", "@homarr/api": "workspace:^0.1.0",
"@homarr/settings": "workspace:^0.1.0",
"react": "catalog:", "react": "catalog:",
"react-dom": "catalog:" "react-dom": "catalog:"
}, },
-36
View File
@@ -1,36 +0,0 @@
import { describe, expect, test } from "vitest";
import type { RouterOutputs } from "@homarr/api";
import { getBoardLayouts, getCurrentLayout, getDesktopLayout } from "./context";
const createBoard = () =>
({
layouts: [
{ id: "small", name: "Small", columnCount: 4, breakpoint: 0 },
{ id: "medium", name: "Medium", columnCount: 8, breakpoint: 768 },
{ id: "large", name: "Large", columnCount: 12, breakpoint: 1200 },
],
}) as RouterOutputs["board"]["getBoardByName"];
describe("board layout selection", () => {
test("automatic mode always uses the desktop layout", () => {
const board = createBoard();
expect(getDesktopLayout(board).id).toBe("large");
expect(getCurrentLayout(board, true, 390)).toBe("large");
});
test.each([
[390, "small"],
[768, "medium"],
[1024, "medium"],
[1440, "large"],
])("legacy mode selects the matching responsive layout at %spx", (viewportWidth, expectedLayoutId) => {
expect(getCurrentLayout(createBoard(), false, viewportWidth)).toBe(expectedLayoutId);
});
test("keeps every saved layout available for reversible mutations", () => {
expect(getBoardLayouts(createBoard())).toEqual(["small", "medium", "large"]);
});
});
+7 -52
View File
@@ -1,13 +1,12 @@
"use client"; "use client";
import type { PropsWithChildren } from "react"; import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useEffect, useState } from "react"; import { createContext, useContext, useEffect } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
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 { getActiveQueryCacheBoardId, setActiveQueryCacheBoardId } from "@homarr/api/query-cache"; import { getActiveQueryCacheBoardId, setActiveQueryCacheBoardId } from "@homarr/api/query-cache";
import { useSettings } from "@homarr/settings";
import { updateBoardName } from "./updater"; import { updateBoardName } from "./updater";
@@ -74,6 +73,10 @@ export const useOptionalBoard = () => {
return context?.board ?? null; return context?.board ?? null;
}; };
export const getCurrentLayout = (board: RouterOutputs["board"]["getBoardByName"]) => {
return getDesktopLayout(board).id;
};
export const getDesktopLayout = (board: RouterOutputs["board"]["getBoardByName"]) => { export const getDesktopLayout = (board: RouterOutputs["board"]["getBoardByName"]) => {
const layout = board.layouts const layout = board.layouts
.toSorted( .toSorted(
@@ -88,57 +91,9 @@ export const getDesktopLayout = (board: RouterOutputs["board"]["getBoardByName"]
return layout; return layout;
}; };
export const getCurrentLayout = ( export const useCurrentLayout = () => getCurrentLayout(useRequiredBoard());
board: RouterOutputs["board"]["getBoardByName"],
enableAutomaticMobileLayout: boolean,
viewportWidth?: number,
) => {
if (enableAutomaticMobileLayout || viewportWidth === undefined) {
return getDesktopLayout(board).id;
}
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutB.breakpoint - layoutA.breakpoint); export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) => [getCurrentLayout(board)];
const layout = sortedLayouts.find((candidate) => candidate.breakpoint <= viewportWidth) ?? sortedLayouts.at(-1);
if (!layout) {
throw new Error("Board must have a layout");
}
return layout.id;
};
export const useCurrentLayout = () => {
const board = useRequiredBoard();
const { enableAutomaticMobileLayout } = useSettings();
const [currentLayout, setCurrentLayout] = useState(() =>
getCurrentLayout(
board,
enableAutomaticMobileLayout,
!enableAutomaticMobileLayout && typeof window !== "undefined" ? window.innerWidth : undefined,
),
);
const updateCurrentLayout = useCallback(() => {
setCurrentLayout(getCurrentLayout(board, enableAutomaticMobileLayout, window.innerWidth));
}, [board, enableAutomaticMobileLayout]);
useEffect(() => {
updateCurrentLayout();
if (enableAutomaticMobileLayout) return;
window.addEventListener("resize", updateCurrentLayout);
return () => {
window.removeEventListener("resize", updateCurrentLayout);
};
}, [enableAutomaticMobileLayout, updateCurrentLayout]);
return currentLayout;
};
export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) =>
board.layouts.map((layout) => layout.id);
export const useLayouts = () => { export const useLayouts = () => {
const board = useRequiredBoard(); const board = useRequiredBoard();
-30
View File
@@ -1,30 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import type { BoardEditAction, BoardEditActionEvent } from "./edit-mode";
import { boardEditActionEventName, requestBoardEditAction } from "./edit-mode";
describe("requestBoardEditAction", () => {
test("runs the action immediately when no edit guard is mounted", () => {
const action = vi.fn();
requestBoardEditAction(action);
expect(action).toHaveBeenCalledOnce();
});
test("lets an edit guard defer the action until the user confirms", () => {
const action = vi.fn();
let deferredAction: BoardEditAction | undefined;
const listener = (event: Event) => {
event.preventDefault();
deferredAction = (event as BoardEditActionEvent).detail.action;
};
document.addEventListener(boardEditActionEventName, listener, { once: true });
requestBoardEditAction(action);
expect(action).not.toHaveBeenCalled();
void deferredAction?.();
expect(action).toHaveBeenCalledOnce();
});
});
-22
View File
@@ -6,28 +6,6 @@ import { useDisclosure } from "@mantine/hooks";
const EditModeContext = createContext<ReturnType<typeof useDisclosure> | null>(null); const EditModeContext = createContext<ReturnType<typeof useDisclosure> | null>(null);
export const boardEditActionEventName = "homarr:board-edit-action";
export type BoardEditActionResult = boolean | void;
export type BoardEditAction = () => BoardEditActionResult | Promise<BoardEditActionResult>;
export type BoardEditActionEvent = CustomEvent<{ action: BoardEditAction }>;
export const requestBoardEditAction = (action: BoardEditAction) => {
if (typeof document === "undefined") {
void action();
return;
}
const event: BoardEditActionEvent = new CustomEvent(boardEditActionEventName, {
cancelable: true,
detail: { action },
});
if (document.dispatchEvent(event)) {
void action();
}
};
const noop = () => undefined; const noop = () => undefined;
const readOnlyEditMode = [false, { open: noop, close: noop, toggle: noop, set: noop }] satisfies ReturnType< const readOnlyEditMode = [false, { open: noop, close: noop, toggle: noop, set: noop }] satisfies ReturnType<
typeof useDisclosure typeof useDisclosure
-106
View File
@@ -1,106 +0,0 @@
import { stringify } from "superjson";
import { describe, expect, test } from "vitest";
import { createId } from "@homarr/common";
import { eq } from "@homarr/db";
import {
getServerSettingByKeyAsync,
getServerSettingsAsync,
shouldEnableAutomaticMobileLayoutForUpgrade,
} from "@homarr/db/queries";
import { boards, layouts, serverSettings } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import { defaultServerSettings } from "@homarr/server-settings";
import { seedServerSettingsAsync } from "./seed";
describe("automatic mobile layout upgrade default", () => {
test("enables automatic mode for a new instance", () => {
expect(shouldEnableAutomaticMobileLayoutForUpgrade([])).toBe(true);
});
test("enables automatic mode when every existing board has only its canonical layout", () => {
expect(
shouldEnableAutomaticMobileLayoutForUpgrade([
{ boardId: "first", name: "Base", breakpoint: 0 },
{ boardId: "second", name: "Base", breakpoint: 0 },
]),
).toBe(true);
});
test("preserves legacy mode when a board has multiple responsive layouts", () => {
expect(
shouldEnableAutomaticMobileLayoutForUpgrade([
{ boardId: "board", name: "Base", breakpoint: 0 },
{ boardId: "board", name: "Mobile", breakpoint: 480 },
]),
).toBe(false);
});
test.each([
{ boardId: "board", name: "Phone", breakpoint: 0 },
{ boardId: "board", name: "Base", breakpoint: 480 },
])("preserves legacy mode for a noncanonical saved layout", (existingLayout) => {
expect(shouldEnableAutomaticMobileLayoutForUpgrade([existingLayout])).toBe(false);
});
test("uses the upgrade heuristic when migrations and seeding are skipped", async () => {
const db = createDb();
const boardId = createId();
await db.insert(boards).values({ id: boardId, name: "dashboard", isPublic: false });
await db.insert(layouts).values([
{ id: createId(), boardId, name: "Base", columnCount: 12, breakpoint: 0 },
{ id: createId(), boardId, name: "Phone", columnCount: 4, breakpoint: 480 },
]);
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toMatchObject({
enableAutomaticMobileLayout: false,
});
await expect(getServerSettingsAsync(db)).resolves.toMatchObject({
board: {
enableAutomaticMobileLayout: false,
},
});
});
test("backfills legacy responsive instances once without overriding an explicit choice", async () => {
const db = createDb();
const boardId = createId();
await db.insert(boards).values({ id: boardId, name: "dashboard", isPublic: false });
await db.insert(layouts).values([
{ id: createId(), boardId, name: "Base", columnCount: 12, breakpoint: 0 },
{ id: createId(), boardId, name: "Phone", columnCount: 4, breakpoint: 480 },
]);
await db.insert(serverSettings).values({
settingKey: "board",
value: stringify({
homeBoardId: null,
mobileHomeBoardId: null,
enableStatusByDefault: true,
forceDisableStatus: false,
}),
});
await seedServerSettingsAsync(db);
await seedServerSettingsAsync(db);
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toStrictEqual({
...defaultServerSettings.board,
enableAutomaticMobileLayout: false,
});
await db
.update(serverSettings)
.set({
value: stringify({
...defaultServerSettings.board,
enableAutomaticMobileLayout: true,
}),
})
.where(eq(serverSettings.settingKey, "board"));
await seedServerSettingsAsync(db);
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toStrictEqual(defaultServerSettings.board);
});
});
+4 -19
View File
@@ -21,7 +21,6 @@ import { getMaxGroupPositionAsync, placeAllWidgetsAsync } from "../queries";
import { import {
getServerSettingByKeyAsync, getServerSettingByKeyAsync,
insertServerSettingByKeyAsync, insertServerSettingByKeyAsync,
shouldEnableAutomaticMobileLayoutForUpgrade,
updateServerSettingByKeyAsync, updateServerSettingByKeyAsync,
} from "../queries/server-setting"; } from "../queries/server-setting";
@@ -246,33 +245,19 @@ const seedDefaultSearchEnginesAsync = async (db: Database) => {
console.log("Set Homarr docs as the default search engine"); console.log("Set Homarr docs as the default search engine");
}; };
export const seedServerSettingsAsync = async (db: Database) => { const seedServerSettingsAsync = async (db: Database) => {
const serverSettingsData = await db.query.serverSettings.findMany(); const serverSettingsData = await db.query.serverSettings.findMany();
const existingLayouts = await db.query.layouts.findMany({
columns: {
boardId: true,
name: true,
breakpoint: true,
},
});
const defaultsForThisInstance = {
...defaultServerSettings,
board: {
...defaultServerSettings.board,
enableAutomaticMobileLayout: shouldEnableAutomaticMobileLayoutForUpgrade(existingLayouts),
},
};
for (const settingsKey of defaultServerSettingsKeys) { for (const settingsKey of defaultServerSettingsKeys) {
const currentDbEntry = serverSettingsData.find((setting) => setting.settingKey === settingsKey); const currentDbEntry = serverSettingsData.find((setting) => setting.settingKey === settingsKey);
if (!currentDbEntry) { if (!currentDbEntry) {
await insertServerSettingByKeyAsync(db, settingsKey, defaultsForThisInstance[settingsKey]); await insertServerSettingByKeyAsync(db, settingsKey, defaultServerSettings[settingsKey]);
console.log(`Created serverSetting through seed key=${settingsKey}`); console.log(`Created serverSetting through seed key=${settingsKey}`);
continue; continue;
} }
const currentSettings = SuperJSON.parse<(typeof defaultServerSettings)[typeof settingsKey]>(currentDbEntry.value); const currentSettings = await getServerSettingByKeyAsync(db, settingsKey);
const defaultSettings = defaultsForThisInstance[settingsKey]; const defaultSettings = defaultServerSettings[settingsKey];
const missingKeys = objectKeys(defaultSettings).filter((key) => !(key in currentSettings)); const missingKeys = objectKeys(defaultSettings).filter((key) => !(key in currentSettings));
if (missingKeys.length === 0) { if (missingKeys.length === 0) {
+9 -78
View File
@@ -1,4 +1,4 @@
import { parse, stringify } from "superjson"; import SuperJSON from "superjson";
import type { ServerSettings } from "@homarr/server-settings"; import type { ServerSettings } from "@homarr/server-settings";
import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings"; import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
@@ -7,71 +7,23 @@ import type { Database } from "..";
import { eq } from ".."; import { eq } from "..";
import { serverSettings } from "../schema"; import { serverSettings } from "../schema";
interface ExistingBoardLayout {
boardId: string;
name: string;
breakpoint: number;
}
export const shouldEnableAutomaticMobileLayoutForUpgrade = (existingLayouts: ExistingBoardLayout[]) => {
const layoutCounts = new Map<string, number>();
for (const layout of existingLayouts) {
if (layout.name !== "Base" || layout.breakpoint !== 0) {
return false;
}
const nextCount = (layoutCounts.get(layout.boardId) ?? 0) + 1;
if (nextCount > 1) {
return false;
}
layoutCounts.set(layout.boardId, nextCount);
}
return true;
};
const getAutomaticMobileLayoutUpgradeDefaultAsync = async (db: Database) => {
const existingLayouts = await db.query.layouts.findMany({
columns: {
boardId: true,
name: true,
breakpoint: true,
},
});
return shouldEnableAutomaticMobileLayoutForUpgrade(existingLayouts);
};
export const getServerSettingsAsync = async (db: Database) => { export const getServerSettingsAsync = async (db: Database) => {
const settings = await db.query.serverSettings.findMany(); const settings = await db.query.serverSettings.findMany();
const mergedSettings = defaultServerSettingsKeys.reduce((acc, settingKey) => { return defaultServerSettingsKeys.reduce((acc, settingKey) => {
const setting = settings.find((candidate) => candidate.settingKey === settingKey); const setting = settings.find((setting) => setting.settingKey === settingKey);
if (!setting) { if (!setting) {
// Typescript is not happy because the key is a union and it does not know that they are the same // Typescript is not happy because the key is a union and it does not know that they are the same
acc[settingKey] = { ...defaultServerSettings[settingKey] } as never; acc[settingKey] = defaultServerSettings[settingKey] as never;
return acc; return acc;
} }
const persistedSettings = parse<Record<string, unknown>>(setting.value);
acc[settingKey] = { acc[settingKey] = {
...defaultServerSettings[settingKey], ...defaultServerSettings[settingKey],
...persistedSettings, ...SuperJSON.parse(setting.value),
} as never; };
return acc; return acc;
}, {} as ServerSettings); }, {} as ServerSettings);
const persistedBoardSettings = settings.find((setting) => setting.settingKey === "board");
const parsedBoardSettings = persistedBoardSettings
? parse<Partial<ServerSettings["board"]>>(persistedBoardSettings.value)
: {};
if (typeof parsedBoardSettings.enableAutomaticMobileLayout !== "boolean") {
mergedSettings.board.enableAutomaticMobileLayout = await getAutomaticMobileLayoutUpgradeDefaultAsync(db);
}
return mergedSettings;
}; };
export const getServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>(db: Database, key: TKey) => { export const getServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>(db: Database, key: TKey) => {
@@ -80,31 +32,10 @@ export const getServerSettingByKeyAsync = async <TKey extends keyof ServerSettin
}); });
if (!dbSettings) { if (!dbSettings) {
if (key === "board") {
return {
...defaultServerSettings.board,
enableAutomaticMobileLayout: await getAutomaticMobileLayoutUpgradeDefaultAsync(db),
} as ServerSettings[TKey];
}
return defaultServerSettings[key]; return defaultServerSettings[key];
} }
const persistedSettings = parse<Partial<ServerSettings[TKey]>>(dbSettings.value); return SuperJSON.parse<ServerSettings[TKey]>(dbSettings.value);
const mergedSettings = {
...defaultServerSettings[key],
...persistedSettings,
} as ServerSettings[TKey];
if (
key === "board" &&
typeof (persistedSettings as Partial<ServerSettings["board"]>).enableAutomaticMobileLayout !== "boolean"
) {
(mergedSettings as ServerSettings["board"]).enableAutomaticMobileLayout =
await getAutomaticMobileLayoutUpgradeDefaultAsync(db);
}
return mergedSettings;
}; };
export const updateServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>( export const updateServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>(
@@ -115,7 +46,7 @@ export const updateServerSettingByKeyAsync = async <TKey extends keyof ServerSet
await db await db
.update(serverSettings) .update(serverSettings)
.set({ .set({
value: stringify(value), value: SuperJSON.stringify(value),
}) })
.where(eq(serverSettings.settingKey, key)); .where(eq(serverSettings.settingKey, key));
}; };
@@ -127,6 +58,6 @@ export const insertServerSettingByKeyAsync = async <TKey extends keyof ServerSet
) => { ) => {
await db.insert(serverSettings).values({ await db.insert(serverSettings).values({
settingKey: key, settingKey: key,
value: stringify(value), value: SuperJSON.stringify(value),
}); });
}; };
-1
View File
@@ -16,7 +16,6 @@ export interface ConfirmModalProps {
children: ReactNode; children: ReactNode;
onConfirm?: () => MaybePromise<void>; onConfirm?: () => MaybePromise<void>;
onCancel?: () => MaybePromise<void>; onCancel?: () => MaybePromise<void>;
onClose?: () => void;
closeOnConfirm?: boolean; closeOnConfirm?: boolean;
closeOnCancel?: boolean; closeOnCancel?: boolean;
cancelProps?: ButtonProps & ComponentPropsWithoutRef<"button">; cancelProps?: ButtonProps & ComponentPropsWithoutRef<"button">;
+1 -6
View File
@@ -127,7 +127,6 @@ const ActiveModal = ({ modal, state, handleCloseModal }: ActiveModalProps) => {
interface OpenModalOptions { interface OpenModalOptions {
keepMounted?: boolean; keepMounted?: boolean;
title?: stringOrTranslation; title?: stringOrTranslation;
onClose?: () => void;
} }
export const useModalAction = <TModal extends ModalDefinition>(modal: TModal) => { export const useModalAction = <TModal extends ModalDefinition>(modal: TModal) => {
@@ -148,10 +147,6 @@ export const useConfirmModal = () => {
const { openModal } = useModalAction(ConfirmModal); const { openModal } = useModalAction(ConfirmModal);
return { return {
openConfirmModal: (props: ConfirmModalProps) => openConfirmModal: (props: ConfirmModalProps) => openModal(props, { title: props.title }),
openModal(props, {
title: props.title,
onClose: props.onClose,
}),
}; };
}; };
@@ -1,50 +0,0 @@
// @vitest-environment node
import { describe, expect, test, vi } from "vitest";
import { createRequestHandler } from "./request-handler";
describe("createRequestHandler", () => {
test("keeps the standard result contract free of cache provenance", async () => {
const requestHandler = createRequestHandler({
requestAsync: vi.fn().mockResolvedValue("current"),
});
const result = await requestHandler.handler({ integrationId: "first" }).getDataAsync();
expect(result).toMatchObject({ data: "current", timestamp: expect.any(Date) });
expect(result).not.toHaveProperty("isStale");
});
test("marks an expired cache fallback as stale while preserving its timestamp", async () => {
const requestAsync = vi.fn().mockResolvedValueOnce("cached").mockRejectedValueOnce(new Error("offline"));
const requestHandler = createRequestHandler({
requestAsync,
cacheTtlMs: 0,
fallbackToStaleOnError: true,
});
const handler = requestHandler.handler({ integrationId: "first" });
const fresh = await handler.getDataWithProvenanceAsync();
const fallback = await handler.getDataWithProvenanceAsync();
expect(fresh).toMatchObject({ data: "cached", isStale: false });
expect(fallback).toEqual({
data: "cached",
timestamp: fresh.timestamp,
isStale: true,
});
expect(requestAsync).toHaveBeenCalledTimes(2);
});
test("does not hide an initial error when no cache exists", async () => {
const requestHandler = createRequestHandler({
requestAsync: vi.fn().mockRejectedValue(new Error("offline")),
fallbackToStaleOnError: true,
});
await expect(requestHandler.handler({ integrationId: "first" }).getDataWithProvenanceAsync()).rejects.toThrow(
"offline",
);
});
});
@@ -5,7 +5,6 @@ interface Options<TData, TInput extends Record<string, unknown>> {
} }
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number }; type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
type RequestResult<TData> = Pick<CacheEntry<TData>, "data" | "timestamp"> & { isStale: boolean };
const MAX_CACHE_SIZE = 1000; const MAX_CACHE_SIZE = 1000;
const DEFAULT_TTL_MS = 10_000; const DEFAULT_TTL_MS = 10_000;
@@ -21,21 +20,21 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
options: Options<TData, TInput>, options: Options<TData, TInput>,
) => { ) => {
const cache = new Map<string, CacheEntry<TData>>(); const cache = new Map<string, CacheEntry<TData>>();
const inflight = new Map<string, Promise<RequestResult<TData>>>(); const inflight = new Map<string, Promise<CacheEntry<TData>>>();
return { return {
invalidateCache: () => { invalidateCache: () => {
cache.clear(); cache.clear();
inflight.clear(); inflight.clear();
}, },
handler: (input: TInput) => { handler: (input: TInput) => ({
const getDataWithProvenanceAsync = async (): Promise<RequestResult<TData>> => { async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS; const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
const key = JSON.stringify(input); const key = JSON.stringify(input);
const cached = cache.get(key); const cached = cache.get(key);
if (cached && Date.now() < cached.expiresAt) { if (cached && Date.now() < cached.expiresAt) {
return { data: cached.data, timestamp: cached.timestamp, isStale: false }; return { data: cached.data, timestamp: cached.timestamp };
} }
const existing = inflight.get(key); const existing = inflight.get(key);
@@ -52,27 +51,19 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl }; const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
cache.set(key, entry); cache.set(key, entry);
inflight.delete(key); inflight.delete(key);
return { data: entry.data, timestamp: entry.timestamp, isStale: false }; return entry;
}) })
.catch((err) => { .catch((err) => {
inflight.delete(key); inflight.delete(key);
if (options.fallbackToStaleOnError && cached) { if (options.fallbackToStaleOnError && cached) {
return { data: cached.data, timestamp: cached.timestamp, isStale: true }; return cached;
} }
throw err; throw err;
}); });
inflight.set(key, promise); inflight.set(key, promise);
return promise; return promise;
}; },
}),
return {
async getDataAsync(): Promise<Pick<RequestResult<TData>, "data" | "timestamp">> {
const { data, timestamp } = await getDataWithProvenanceAsync();
return { data, timestamp };
},
getDataWithProvenanceAsync,
};
},
}; };
}; };
-1
View File
@@ -27,7 +27,6 @@ export const defaultServerSettings = {
board: { board: {
homeBoardId: null as string | null, homeBoardId: null as string | null,
mobileHomeBoardId: null as string | null, mobileHomeBoardId: null as string | null,
enableAutomaticMobileLayout: true,
enableStatusByDefault: true, enableStatusByDefault: true,
forceDisableStatus: false, forceDisableStatus: false,
}, },
+2 -3
View File
@@ -12,14 +12,14 @@ export type SettingsContextProps = Pick<
| "pingIconsEnabled" | "pingIconsEnabled"
| "enableRightClickOnWidgets" | "enableRightClickOnWidgets"
> & > &
Pick<ServerSettings["board"], "enableAutomaticMobileLayout" | "enableStatusByDefault" | "forceDisableStatus"> & Pick<ServerSettings["board"], "enableStatusByDefault" | "forceDisableStatus"> &
Pick<ServerSettings["user"], "enableGravatar">; Pick<ServerSettings["user"], "enableGravatar">;
export interface PublicServerSettings { export interface PublicServerSettings {
search: Pick<ServerSettings["search"], "defaultSearchEngineId">; search: Pick<ServerSettings["search"], "defaultSearchEngineId">;
board: Pick< board: Pick<
ServerSettings["board"], ServerSettings["board"],
"homeBoardId" | "mobileHomeBoardId" | "enableAutomaticMobileLayout" | "enableStatusByDefault" | "forceDisableStatus" "homeBoardId" | "mobileHomeBoardId" | "enableStatusByDefault" | "forceDisableStatus"
>; >;
user: Pick<ServerSettings["user"], "enableGravatar">; user: Pick<ServerSettings["user"], "enableGravatar">;
} }
@@ -51,7 +51,6 @@ export const createSettings = ({
mobileHomeBoardId: user?.mobileHomeBoardId ?? serverSettings.board.mobileHomeBoardId, mobileHomeBoardId: user?.mobileHomeBoardId ?? serverSettings.board.mobileHomeBoardId,
pingIconsEnabled: user?.pingIconsEnabled ?? false, pingIconsEnabled: user?.pingIconsEnabled ?? false,
enableRightClickOnWidgets: user?.enableRightClickOnWidgets ?? true, enableRightClickOnWidgets: user?.enableRightClickOnWidgets ?? true,
enableAutomaticMobileLayout: serverSettings.board.enableAutomaticMobileLayout,
enableStatusByDefault: serverSettings.board.enableStatusByDefault, enableStatusByDefault: serverSettings.board.enableStatusByDefault,
forceDisableStatus: serverSettings.board.forceDisableStatus, forceDisableStatus: serverSettings.board.forceDisableStatus,
enableGravatar: serverSettings.user.enableGravatar, enableGravatar: serverSettings.user.enableGravatar,
-1
View File
@@ -24,7 +24,6 @@
"dependencies": { "dependencies": {
"@homarr/api": "workspace:^0.1.0", "@homarr/api": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0", "@homarr/auth": "workspace:^0.1.0",
"@homarr/boards": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0", "@homarr/definitions": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0", "@homarr/integrations": "workspace:^0.1.0",
@@ -7,7 +7,6 @@ import type { DayOfWeek } from "@mantine/dates";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client"; import { useSession } from "@homarr/auth/client";
import { requestBoardEditAction } from "@homarr/boards/edit-mode";
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";
@@ -161,7 +160,7 @@ export const useUserPreferences = () => {
const clientSetters: Partial<Record<UserPreferenceKey, (value: unknown) => void>> = { const clientSetters: Partial<Record<UserPreferenceKey, (value: unknown) => void>> = {
colorScheme: (value) => setColorScheme(value as ColorScheme), colorScheme: (value) => setColorScheme(value as ColorScheme),
locale: (value) => requestBoardEditAction(() => changeLocale(value as typeof currentLocale)), locale: (value) => changeLocale(value as typeof currentLocale),
fullPreferencesPage: () => undefined, fullPreferencesPage: () => undefined,
}; };
+1 -20
View File
@@ -1495,10 +1495,6 @@
"docker": "Docker", "docker": "Docker",
"preferences": "Your preferences", "preferences": "Your preferences",
"logout": "Logout", "logout": "Logout",
"logoutError": {
"title": "Logout failed",
"message": "Your session is still active. Please try again."
},
"login": "Login", "login": "Login",
"homeBoard": "Your home board", "homeBoard": "Your home board",
"loggedOut": "Logged out", "loggedOut": "Logged out",
@@ -4413,15 +4409,7 @@
"description": "Configure the layout used on desktop and larger screens." "description": "Configure the layout used on desktop and larger screens."
}, },
"mobile": { "mobile": {
"automaticDescription": "On mobile, items are automatically arranged in two columns and cannot be moved or resized. Named categories and dynamic sections appear as headings, never as layout containers." "description": "On mobile, items are automatically arranged in two columns and cannot be moved or resized. Named categories and dynamic sections appear as headings, never as layout containers."
},
"responsive": {
"title": "Responsive layouts",
"description": "Automatic mobile layout is disabled for this server. Configure the saved layouts selected at each viewport breakpoint; these layouts can also be edited directly on mobile.",
"defaultName": "New layout",
"action": {
"add": "Add layout"
}
} }
}, },
"background": { "background": {
@@ -4871,13 +4859,6 @@
"mobileLabel": "Global mobile board", "mobileLabel": "Global mobile board",
"description": "Only public boards are available for selection" "description": "Only public boards are available for selection"
}, },
"mobileLayout": {
"title": "Mobile layout",
"enable": {
"label": "Use automatic mobile layout",
"description": "Arrange every board into a read-only two-column layout on phones and small tablets. Turn this off to use saved responsive layouts and mobile layout editing. Saved responsive layouts are kept when this is enabled."
}
},
"status": { "status": {
"title": "App status", "title": "App status",
"enableStatusByDefault": { "enableStatusByDefault": {
+1 -41
View File
@@ -24,7 +24,7 @@ export const boardNameSchema = z
.min(1) .min(1)
.max(255) .max(255)
.regex(/^[A-Za-z0-9-_]*$/); .regex(/^[A-Za-z0-9-_]*$/);
export const boardColumnCountSchema = z.number().int().min(1).max(24); export const boardColumnCountSchema = z.number().min(1).max(24);
export const boardByNameSchema = z.object({ export const boardByNameSchema = z.object({
name: boardNameSchema, name: boardNameSchema,
@@ -75,46 +75,6 @@ export const boardSaveLayoutSchema = z.object({
columnCount: boardColumnCountSchema, columnCount: boardColumnCountSchema,
}); });
const responsiveBoardLayoutsSchema = z
.array(
z.object({
id: z.string(),
name: z.string().trim().nonempty().max(32),
columnCount: boardColumnCountSchema,
breakpoint: z.number().int().min(0).max(32767),
}),
)
.min(1)
.superRefine((layouts, context) => {
const seenBreakpoints = new Set<number>();
const seenIds = new Set<string>();
layouts.forEach((layout, index) => {
if (seenIds.has(layout.id)) {
context.addIssue({
code: "custom",
message: "Each responsive layout must have a unique ID",
path: [index, "id"],
});
}
seenIds.add(layout.id);
if (seenBreakpoints.has(layout.breakpoint)) {
context.addIssue({
code: "custom",
message: "Each responsive layout must have a unique breakpoint",
path: [index, "breakpoint"],
});
}
seenBreakpoints.add(layout.breakpoint);
});
});
export const boardSaveLayoutsSchema = z.object({
id: z.string(),
layouts: responsiveBoardLayoutsSchema,
});
export const boardSaveSchema = z.object({ export const boardSaveSchema = z.object({
id: z.string(), id: z.string(),
sections: z.array(sectionSchema), sections: z.array(sectionSchema),
+1 -19
View File
@@ -7,16 +7,13 @@ import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client"; import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context"; import { useRequiredBoard } from "@homarr/boards/context";
import { useRegisterSpotlightContextResults } from "@homarr/spotlight"; import { useRegisterSpotlightContextResults } from "@homarr/spotlight";
import { useI18n } from "@homarr/translation/client";
import { MaskedOrNormalImage } from "@homarr/ui"; import { MaskedOrNormalImage } from "@homarr/ui";
import { WidgetMobileSummary } from "../common/mobile-summary";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
import classes from "./bookmark.module.css"; import classes from "./bookmark.module.css";
export default function BookmarksWidget({ options, itemId, displayMode }: WidgetComponentProps<"bookmarks">) { export default function BookmarksWidget({ options, itemId }: WidgetComponentProps<"bookmarks">) {
const board = useRequiredBoard(); const board = useRequiredBoard();
const t = useI18n();
const { data = [] } = clientApi.app.byIds.useQuery(options.items, { const { data = [] } = clientApi.app.byIds.useQuery(options.items, {
select(data) { select(data) {
return data.toSorted((appA, appB) => options.items.indexOf(appA.id) - options.items.indexOf(appB.id)); return data.toSorted((appA, appB) => options.items.indexOf(appA.id) - options.items.indexOf(appB.id));
@@ -44,21 +41,6 @@ export default function BookmarksWidget({ options, itemId, displayMode }: Widget
[data], [data],
); );
if (displayMode === "mobileSummary") {
return (
<WidgetMobileSummary
value={data.length}
label={options.title || t("widget.bookmarks.name")}
description={
data
.map((app) => app.name)
.slice(0, 2)
.join(" · ") || t("board.mobile.details")
}
/>
);
}
return ( return (
<Stack h="100%" gap="sm" p="sm"> <Stack h="100%" gap="sm" p="sm">
{options.title.length > 0 && ( {options.title.length > 0 && (
+2 -7
View File
@@ -10,13 +10,8 @@ import { BookmarkAddButton } from "./add-button";
export const { definition, componentLoader } = createWidgetDefinition("bookmarks", { export const { definition, componentLoader } = createWidgetDefinition("bookmarks", {
icon: IconBookmark, icon: IconBookmark,
mobile: { mobile: { supportsDetailView: true },
width: 2, queryKey: [["app"]],
height: 1,
supportsCompactSummary: true,
supportsDetailView: true,
},
queryKey: [["app", "byIds"]],
createOptions() { createOptions() {
return optionsBuilder.from((factory) => ({ return optionsBuilder.from((factory) => ({
title: factory.text(), title: factory.text(),
+4 -10
View File
@@ -14,7 +14,6 @@ import { useSettings } from "@homarr/settings";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
import { CalendarDay } from "./calender-day"; import { CalendarDay } from "./calender-day";
import classes from "./component.module.css"; import classes from "./component.module.css";
@@ -45,8 +44,8 @@ const FetchCalendar = ({ month, setMonth, isEditMode, integrationIds, options, d
const { data, error, isPending } = clientApi.widget.calendar.findAllEvents.useQuery(input); const { data, error, isPending } = clientApi.widget.calendar.findAllEvents.useQuery(input);
const events = useMemo(() => data?.flatMap((item) => item.events) ?? [], [data]); const events = useMemo(() => data?.flatMap((item) => item.events) ?? [], [data]);
if (isPending) return <WidgetMobileLoading />; if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, data !== undefined); if (displayMode === "mobileSummary" && error && !data) throw error;
return ( return (
<CalendarBase <CalendarBase
@@ -56,11 +55,7 @@ const FetchCalendar = ({ month, setMonth, isEditMode, integrationIds, options, d
setMonth={setMonth} setMonth={setMonth}
options={options} options={options}
displayMode={displayMode} displayMode={displayMode}
isStale={hasWidgetDataWarning({ isStale={Boolean(error) || (data?.length ?? 0) < integrationIds.length}
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: data?.length,
})}
/> />
); );
}; };
@@ -130,7 +125,7 @@ const CalendarBase = ({
); );
} }
const calendar = ( return (
<Calendar <Calendar
defaultDate={new Date()} defaultDate={new Date()}
onPreviousMonth={(month) => setMonth(new Date(month))} onPreviousMonth={(month) => setMonth(new Date(month))}
@@ -210,7 +205,6 @@ const CalendarBase = ({
}} }}
/> />
); );
return <WidgetDataState hasWarning={isStale}>{calendar}</WidgetDataState>;
}; };
/** /**
@@ -1,34 +0,0 @@
import { describe, expect, test } from "vitest";
import { hasWidgetDataWarning, throwOnInitialQueryError } from "./query-state";
describe("widget query state", () => {
test.each([
{ error: new Error("refresh failed") },
{ failedIntegrationCount: 1 },
{ staleIntegrationCount: 1 },
{ expectedIntegrationCount: 2, receivedIntegrationCount: 1 },
])("warns when data provenance is incomplete or stale", (provenance) => {
expect(hasWidgetDataWarning(provenance)).toBe(true);
});
test("does not warn for complete current data", () => {
expect(
hasWidgetDataWarning({
failedIntegrationCount: 0,
staleIntegrationCount: 0,
expectedIntegrationCount: 2,
receivedIntegrationCount: 2,
}),
).toBe(false);
});
test("throws an initial query error", () => {
const error = new Error("initial request failed");
expect(() => throwOnInitialQueryError(error, false)).toThrow(error);
});
test("keeps cached data visible after a refresh error", () => {
expect(() => throwOnInitialQueryError(new Error("refresh failed"), true)).not.toThrow();
});
});
@@ -1,73 +0,0 @@
"use client";
import type { ReactNode } from "react";
import { Box, Center, Tooltip } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
interface WidgetQueryProvenance {
error?: unknown;
failedIntegrationCount?: number;
staleIntegrationCount?: number;
expectedIntegrationCount?: number;
receivedIntegrationCount?: number;
}
export const hasWidgetDataWarning = ({
error,
failedIntegrationCount = 0,
staleIntegrationCount = 0,
expectedIntegrationCount,
receivedIntegrationCount,
}: WidgetQueryProvenance) =>
Boolean(error) ||
failedIntegrationCount > 0 ||
staleIntegrationCount > 0 ||
(expectedIntegrationCount !== undefined &&
receivedIntegrationCount !== undefined &&
receivedIntegrationCount < expectedIntegrationCount);
export const throwOnInitialQueryError = (error: unknown, hasData: boolean) => {
if (error && !hasData) throw error;
};
interface WidgetDataStateProps {
children: ReactNode;
hasWarning: boolean;
}
export function WidgetDataState({ children, hasWarning }: WidgetDataStateProps) {
const t = useI18n();
const label = t("board.mobile.dataWarning");
return (
<Box pos="relative" h="100%" w="100%">
{hasWarning && (
<Tooltip label={label} position="left" withArrow>
<Center
component="output"
aria-label={label}
pos="absolute"
bottom={4}
w={28}
h={28}
style={{
insetInlineStart: 4,
zIndex: 4,
borderRadius: "var(--mantine-radius-sm)",
background: "light-dark(var(--mantine-color-yellow-1), var(--mantine-color-dark-6))",
}}
>
<IconAlertTriangle
size={16}
color="light-dark(var(--mantine-color-yellow-9), var(--mantine-color-yellow-3))"
aria-hidden
/>
</Center>
</Tooltip>
)}
{children}
</Box>
);
}
+1 -1
View File
@@ -6,7 +6,7 @@ import { optionsBuilder } from "../options";
export const { definition, componentLoader } = createWidgetDefinition("customApi", { export const { definition, componentLoader } = createWidgetDefinition("customApi", {
icon: IconApi, icon: IconApi,
mobile: { supportsDetailView: true, unmountWhenOffscreen: true }, mobile: { supportsDetailView: true },
queryKey: [["widget", "customApi"]], queryKey: [["widget", "customApi"]],
createOptions() { createOptions() {
return optionsBuilder.from((factory) => ({ return optionsBuilder.from((factory) => ({
@@ -9,7 +9,7 @@ export const widgetKind = "dnsHoleControls";
export const { definition, componentLoader } = createWidgetDefinition(widgetKind, { export const { definition, componentLoader } = createWidgetDefinition(widgetKind, {
icon: IconDeviceGamepad, icon: IconDeviceGamepad,
mobile: { supportsDetailView: true, unmountWhenOffscreen: true }, mobile: { supportsDetailView: true },
queryKey: [["widget", "dnsHole"]], queryKey: [["widget", "dnsHole"]],
refetchInterval: 5, refetchInterval: 5,
createOptions() { createOptions() {
@@ -9,7 +9,6 @@ export const widgetKind = "dnsHoleSummary";
export const { definition, componentLoader } = createWidgetDefinition(widgetKind, { export const { definition, componentLoader } = createWidgetDefinition(widgetKind, {
icon: IconAd, icon: IconAd,
mobile: { unmountWhenOffscreen: true },
queryKey: [["widget", "dnsHole"]], queryKey: [["widget", "dnsHole"]],
refetchInterval: 5, refetchInterval: 5,
createOptions() { createOptions() {
+1 -53
View File
@@ -51,8 +51,6 @@ import type { ExtendedClientStatus, ExtendedDownloadClientItem } from "@homarr/i
import { showErrorNotification } from "@homarr/notifications"; import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -280,57 +278,7 @@ function SpeedCell({
); );
} }
export default function DownloadsWidget(props: WidgetComponentProps<"downloads">) { export default function DownloadClientsWidget({
if (props.displayMode === "mobileSummary") {
return <DownloadsMobileSummary integrationIds={props.integrationIds} options={props.options} />;
}
return <DownloadClientsWidget {...props} />;
}
function DownloadsMobileSummary({
integrationIds,
options,
}: Pick<WidgetComponentProps<"downloads">, "integrationIds" | "options">) {
const t = useScopedI18n("widget.downloads");
const { data, error, isPending } = clientApi.widget.downloads.getJobsAndStatuses.useQuery({
integrationIds,
limitPerIntegration: options.limitPerIntegration,
});
if (isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, data !== undefined);
const currentItems = data ?? [];
const selectedClients = currentItems.filter(({ integration }) => integrationIds.includes(integration.id));
const visibleItemCount = selectedClients.reduce(
(total, { data: clientData }) =>
total +
clientData.items
.filter(({ category }) => matchesCategoryFilter(category, options.categoryFilter, options.filterIsWhitelist))
.filter((item) => showCompletedItem(item, options)).length,
0,
);
const totalDownloadSpeed = selectedClients.reduce(
(total, { data: clientData }) => total + (clientData.status.rates.down ?? 0),
0,
);
return (
<WidgetMobileSummary
value={visibleItemCount}
label={t("name")}
description={`${t("items.downSpeed.columnTitle")}: ${formatByteRate(totalDownloadSpeed)}`}
isStale={hasWidgetDataWarning({
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: currentItems.length,
})}
/>
);
}
function DownloadClientsWidget({
isEditMode, isEditMode,
integrationIds, integrationIds,
options, options,
+1 -1
View File
@@ -7,7 +7,7 @@ import { optionsBuilder } from "../options";
export const { definition, componentLoader } = createWidgetDefinition("firewall", { export const { definition, componentLoader } = createWidgetDefinition("firewall", {
icon: IconWall, icon: IconWall,
mobile: { supportsDetailView: true, unmountWhenOffscreen: true }, mobile: { supportsDetailView: true },
queryKey: [["widget", "firewall"]], queryKey: [["widget", "firewall"]],
refetchInterval: 5, refetchInterval: 5,
createOptions() { createOptions() {
@@ -16,7 +16,6 @@ import type { TablerIcon } from "@homarr/ui";
import { OverflowBadge } from "@homarr/ui"; import { OverflowBadge } from "@homarr/ui";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
export default function MediaReleasesWidget({ export default function MediaReleasesWidget({
@@ -24,33 +23,29 @@ export default function MediaReleasesWidget({
integrationIds, integrationIds,
displayMode, displayMode,
}: WidgetComponentProps<"mediaReleases">) { }: WidgetComponentProps<"mediaReleases">) {
const { data, error, isPending } = clientApi.widget.mediaRelease.getMediaReleasesWithProvenance.useQuery({ const { data, error, isPending } = clientApi.widget.mediaRelease.getMediaReleases.useQuery({
integrationIds, integrationIds,
}); });
const t = useI18n("widget.mediaReleases"); const t = useI18n("widget.mediaReleases");
if (isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, data !== undefined);
const releases = data?.items ?? [];
const hasWarning = hasWidgetDataWarning({
error,
failedIntegrationCount: data?.failedIntegrationCount,
staleIntegrationCount: data?.staleIntegrationCount,
});
if (displayMode === "mobileSummary") { if (displayMode === "mobileSummary") {
if (isPending) return <WidgetMobileLoading />;
if (error && !data) throw error;
const releases = data ?? [];
return ( return (
<WidgetMobileSummary <WidgetMobileSummary
value={releases.length} value={releases.length}
label={t("name")} label={t("name")}
description={releases[0]?.title} description={releases[0]?.title}
isStale={hasWarning} isStale={Boolean(error)}
/> />
); );
} }
const content = ( const releases = data ?? [];
return (
<Stack p="xs" gap="sm"> <Stack p="xs" gap="sm">
{releases.map((item, index) => ( {releases.map((item, index) => (
<Fragment key={item.id}> <Fragment key={item.id}>
@@ -60,11 +55,10 @@ export default function MediaReleasesWidget({
))} ))}
</Stack> </Stack>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
} }
interface ItemProps { interface ItemProps {
item: RouterOutputs["widget"]["mediaRelease"]["getMediaReleasesWithProvenance"]["items"][number]; item: RouterOutputs["widget"]["mediaRelease"]["getMediaReleases"][number];
options: WidgetComponentProps<"mediaReleases">["options"]; options: WidgetComponentProps<"mediaReleases">["options"];
} }
@@ -27,7 +27,6 @@ import { useScopedI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../../common/empty-state"; import { WidgetEmptyState } from "../../common/empty-state";
import { WidgetMobileLoading, WidgetMobileSummary } from "../../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../../common/query-state";
import type { WidgetComponentProps } from "../../definition"; import type { WidgetComponentProps } from "../../definition";
import { NoIntegrationDataError } from "../../errors/no-data-integration"; import { NoIntegrationDataError } from "../../errors/no-data-integration";
import classes from "../search-button.module.css"; import classes from "../search-button.module.css";
@@ -40,7 +39,11 @@ export default function MediaServerWidget({
displayMode, displayMode,
}: WidgetComponentProps<"mediaRequests-requestList">) { }: WidgetComponentProps<"mediaRequests-requestList">) {
const t = useScopedI18n("widget.mediaRequests-requestList"); const t = useScopedI18n("widget.mediaRequests-requestList");
const { data, error, isPending } = clientApi.widget.mediaRequests.getLatestRequestsWithProvenance.useQuery({ const {
data: mediaRequests,
error,
isPending,
} = clientApi.widget.mediaRequests.getLatestRequests.useQuery({
integrationIds, integrationIds,
statuses: statuses:
options.statusFilter.length > 0 options.statusFilter.length > 0
@@ -49,38 +52,23 @@ export default function MediaServerWidget({
recentDays: options.recentDays, recentDays: options.recentDays,
}); });
if (isPending) return <WidgetMobileLoading />; if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, data !== undefined); if (displayMode === "mobileSummary" && error && !mediaRequests) throw error;
if (!data) return <WidgetEmptyState />; if (!mediaRequests) return <WidgetEmptyState />;
if (mediaRequests.length === 0) throw new NoIntegrationDataError();
const hasWarning = hasWidgetDataWarning({
error,
failedIntegrationCount: data.failedIntegrationCount,
staleIntegrationCount: data.staleIntegrationCount,
});
if (data.items.length === 0 && !hasWarning) throw new NoIntegrationDataError();
if (displayMode === "mobileSummary") { if (displayMode === "mobileSummary") {
return ( return (
<WidgetMobileSummary <WidgetMobileSummary
value={data.items.length} value={mediaRequests.length}
label={t("name")} label={t("name")}
description={data.items[0]?.name} description={mediaRequests[0]?.name}
isStale={hasWarning} isStale={Boolean(error)}
/> />
); );
} }
if (data.items.length === 0) { return (
return (
<WidgetDataState hasWarning={hasWarning}>
<WidgetEmptyState />
</WidgetDataState>
);
}
const content = (
<Box className={classes.searchRoot}> <Box className={classes.searchRoot}>
{!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />} {!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />}
<ScrollArea <ScrollArea
@@ -89,7 +77,7 @@ export default function MediaServerWidget({
style={{ pointerEvents: isEditMode ? "none" : undefined }} style={{ pointerEvents: isEditMode ? "none" : undefined }}
> >
<Stack className="mediaRequests-list-list" gap="xs" p="sm"> <Stack className="mediaRequests-list-list" gap="xs" p="sm">
{data.items.map((mediaRequest) => ( {mediaRequests.map((mediaRequest) => (
<MediaRequestCard <MediaRequestCard
key={`${mediaRequest.integrationId}-${mediaRequest.id}`} key={`${mediaRequest.integrationId}-${mediaRequest.id}`}
request={mediaRequest} request={mediaRequest}
@@ -101,7 +89,6 @@ export default function MediaServerWidget({
</ScrollArea> </ScrollArea>
</Box> </Box>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
} }
const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => { const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => {
@@ -123,7 +110,7 @@ const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[]
}; };
interface MediaRequestCardProps { interface MediaRequestCardProps {
request: RouterOutputs["widget"]["mediaRequests"]["getLatestRequestsWithProvenance"]["items"][number]; request: RouterOutputs["widget"]["mediaRequests"]["getLatestRequests"][number];
isTiny: boolean; isTiny: boolean;
options: WidgetComponentProps<"mediaRequests-requestList">["options"]; options: WidgetComponentProps<"mediaRequests-requestList">["options"];
} }
@@ -22,8 +22,6 @@ import { openMediaRequestSearch } from "@homarr/spotlight";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../../common/empty-state"; import { WidgetEmptyState } from "../../common/empty-state";
import { WidgetMobileLoading, WidgetMobileSummary } from "../../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../../common/query-state";
import type { WidgetComponentProps } from "../../definition"; import type { WidgetComponentProps } from "../../definition";
import { NoIntegrationDataError } from "../../errors/no-data-integration"; import { NoIntegrationDataError } from "../../errors/no-data-integration";
import classes from "./component.module.css"; import classes from "./component.module.css";
@@ -36,30 +34,16 @@ export default function MediaServerWidget({
integrationIds, integrationIds,
isEditMode, isEditMode,
width, width,
displayMode,
}: WidgetComponentProps<"mediaRequests-requestStats">) { }: WidgetComponentProps<"mediaRequests-requestStats">) {
const t = useScopedI18n("widget.mediaRequests-requestStats"); const t = useScopedI18n("widget.mediaRequests-requestStats");
const { const { data: requestStats } = clientApi.widget.mediaRequests.getStats.useQuery({
data: requestStats,
error,
isPending,
} = clientApi.widget.mediaRequests.getStatsWithProvenance.useQuery({
integrationIds, integrationIds,
}); });
const board = useRequiredBoard(); const board = useRequiredBoard();
if (isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, requestStats !== undefined);
if (!requestStats) return <WidgetEmptyState />; if (!requestStats) return <WidgetEmptyState />;
const hasWarning = hasWidgetDataWarning({ if (requestStats.users.length === 0 && requestStats.stats.length === 0) throw new NoIntegrationDataError();
error,
failedIntegrationCount: requestStats.failedIntegrationCount,
staleIntegrationCount: requestStats.staleIntegrationCount,
});
if (requestStats.users.length === 0 && requestStats.stats.length === 0 && !hasWarning) {
throw new NoIntegrationDataError();
}
const data = [ const data = [
{ {
@@ -104,23 +88,9 @@ export default function MediaServerWidget({
}, },
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[]; ] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
if (displayMode === "mobileSummary") {
const total = data.find((stat) => stat.name === "total")?.number ?? 0;
const pending = data.find((stat) => stat.name === "pending")?.number ?? 0;
return (
<WidgetMobileSummary
value={total}
label={t("titles.stats.total")}
description={`${pending} ${t("titles.stats.pending")}`}
isStale={hasWarning}
/>
);
}
const isTiny = width < 256; const isTiny = width < 256;
const content = ( return (
<Box className={searchClasses.searchRoot}> <Box className={searchClasses.searchRoot}>
{!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />} {!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />}
<Stack <Stack
@@ -203,7 +173,6 @@ export default function MediaServerWidget({
</Stack> </Stack>
</Box> </Box>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
} }
const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => { const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => {
@@ -7,12 +7,7 @@ import { createWidgetDefinition } from "../../definition";
export const { componentLoader, definition } = createWidgetDefinition("mediaRequests-requestStats", { export const { componentLoader, definition } = createWidgetDefinition("mediaRequests-requestStats", {
icon: IconChartBar, icon: IconChartBar,
mobile: { mobile: { supportsDetailView: true },
width: 2,
height: 1,
supportsCompactSummary: true,
supportsDetailView: true,
},
queryKey: [["widget", "mediaRequests"]], queryKey: [["widget", "mediaRequests"]],
createOptions() { createOptions() {
return {}; return {};
@@ -25,7 +25,6 @@ import type { TablerIcon } from "@homarr/ui";
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks"; import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
export default function MediaServerWidget({ displayMode, ...props }: WidgetComponentProps<"mediaServer">) { export default function MediaServerWidget({ displayMode, ...props }: WidgetComponentProps<"mediaServer">) {
@@ -44,9 +43,10 @@ const MediaServerMobileSummary = ({
}); });
if (isPending) return <WidgetMobileLoading />; if (isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, data !== undefined); if (error && !data) throw error;
const currentStreams = data ?? []; const currentStreams = data ?? [];
const hasPartialFailure = currentStreams.length < integrationIds.length;
const playingSessions = currentStreams const playingSessions = currentStreams
.flatMap((stream) => stream.sessions) .flatMap((stream) => stream.sessions)
.filter((session) => session.currentlyPlaying !== null); .filter((session) => session.currentlyPlaying !== null);
@@ -56,11 +56,7 @@ const MediaServerMobileSummary = ({
value={playingSessions.length} value={playingSessions.length}
label={t("items.currentlyPlaying")} label={t("items.currentlyPlaying")}
description={playingSessions[0]?.currentlyPlaying?.name} description={playingSessions[0]?.currentlyPlaying?.name}
isStale={hasWidgetDataWarning({ isStale={Boolean(error) || hasPartialFailure}
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: currentStreams.length,
})}
/> />
); );
}; };
@@ -69,11 +65,10 @@ const MediaServerTable = ({
options, options,
integrationIds, integrationIds,
}: Pick<WidgetComponentProps<"mediaServer">, "options" | "integrationIds">) => { }: Pick<WidgetComponentProps<"mediaServer">, "options" | "integrationIds">) => {
const { data: queryData, error } = clientApi.widget.mediaServer.getCurrentStreams.useQuery({ const { data: currentStreams = [] } = clientApi.widget.mediaServer.getCurrentStreams.useQuery({
integrationIds, integrationIds,
showOnlyPlaying: options.showOnlyPlaying, showOnlyPlaying: options.showOnlyPlaying,
}); });
const currentStreams = queryData ?? [];
const t = useScopedI18n("widget.mediaServer"); const t = useScopedI18n("widget.mediaServer");
const columns = useMemo<MRT_ColumnDef<StreamSession>[]>( const columns = useMemo<MRT_ColumnDef<StreamSession>[]>(
@@ -297,14 +292,8 @@ const MediaServerTable = ({
integrationName: session?.integrationName, integrationName: session?.integrationName,
}; };
}); });
throwOnInitialQueryError(error, queryData !== undefined);
const hasWarning = hasWidgetDataWarning({
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: currentStreams.length,
});
const content = ( return (
<Stack gap={0} h="100%" display="flex"> <Stack gap={0} h="100%" display="flex">
<MantineReactTable table={table} /> <MantineReactTable table={table} />
<Group <Group
@@ -328,7 +317,6 @@ const MediaServerTable = ({
</Group> </Group>
</Stack> </Stack>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
}; };
const ItemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => { const ItemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => {
@@ -10,7 +10,6 @@ import { useTimeAgo } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
export default function NotificationsWidget({ export default function NotificationsWidget({
@@ -39,20 +38,17 @@ export default function NotificationsWidget({
[notificationIntegrations], [notificationIntegrations],
); );
if (isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, notificationIntegrations !== undefined);
const hasWarning = hasWidgetDataWarning({
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: notificationIntegrations?.length,
});
if (displayMode === "mobileSummary") { if (displayMode === "mobileSummary") {
if (isPending) return <WidgetMobileLoading />;
if (error && !notificationIntegrations) throw error;
const notifications = notificationIntegrations ?? [];
const latestNotification = sortedNotifications[0]; const latestNotification = sortedNotifications[0];
const isStale = Boolean(error) || notifications.length < integrationIds.length;
const summary = latestNotification ? ( const summary = latestNotification ? (
<NotificationMobileSummary notification={latestNotification} isStale={hasWarning} /> <NotificationMobileSummary notification={latestNotification} isStale={isStale} />
) : ( ) : (
<WidgetMobileSummary value={0} label={t("name")} description={t("noItems")} isStale={hasWarning} /> <WidgetMobileSummary value={0} label={t("name")} description={t("noItems")} isStale={isStale} />
); );
if (!latestNotification?.href) return summary; if (!latestNotification?.href) return summary;
@@ -72,7 +68,7 @@ export default function NotificationsWidget({
); );
} }
const content = ( return (
<ScrollArea className="scroll-area-w100" w="100%" p="sm"> <ScrollArea className="scroll-area-w100" w="100%" p="sm">
<Stack w={"100%"} gap="sm"> <Stack w={"100%"} gap="sm">
{sortedNotifications.length > 0 ? ( {sortedNotifications.length > 0 ? (
@@ -121,7 +117,6 @@ export default function NotificationsWidget({
</Stack> </Stack>
</ScrollArea> </ScrollArea>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
} }
const NotificationMobileSummary = ({ const NotificationMobileSummary = ({
+1 -1
View File
@@ -5,7 +5,7 @@ import { optionsBuilder } from "../options";
export const { definition, componentLoader } = createWidgetDefinition("tracearr", { export const { definition, componentLoader } = createWidgetDefinition("tracearr", {
icon: IconActivityHeartbeat, icon: IconActivityHeartbeat,
mobile: { supportsDetailView: true, unmountWhenOffscreen: true }, mobile: { supportsDetailView: true },
queryKey: [["widget", "tracearr"]], queryKey: [["widget", "tracearr"]],
refetchInterval: 5, refetchInterval: 5,
createOptions() { createOptions() {
+1 -1
View File
@@ -8,7 +8,7 @@ export const timeFrameValues = ["today", "24h", "7d", "30d", "month", "lastMonth
export const { definition, componentLoader } = createWidgetDefinition("umami", { export const { definition, componentLoader } = createWidgetDefinition("umami", {
icon: IconChartBar, icon: IconChartBar,
mobile: { supportsDetailView: true, unmountWhenOffscreen: true }, mobile: { supportsDetailView: true },
queryKey: [["widget", "umami"]], queryKey: [["widget", "umami"]],
refetchInterval: null, refetchInterval: null,
supportedIntegrations: ["umami"], supportedIntegrations: ["umami"],
+7 -13
View File
@@ -11,7 +11,6 @@ import { useScopedI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../common/empty-state"; import { WidgetEmptyState } from "../common/empty-state";
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary"; import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
import { NoIntegrationDataError } from "../errors/no-data-integration"; import { NoIntegrationDataError } from "../errors/no-data-integration";
import classes from "./component.module.css"; import classes from "./component.module.css";
@@ -118,15 +117,11 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
} = clientApi.widget.uptimeKuma.getDashboard.useQuery({ } = clientApi.widget.uptimeKuma.getDashboard.useQuery({
integrationIds, integrationIds,
}); });
const hasPartialFailure = (dashboardData?.length ?? 0) < integrationIds.length;
if (isPending) return <WidgetMobileLoading />; if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
throwOnInitialQueryError(error, dashboardData !== undefined); if (displayMode === "mobileSummary" && error && !dashboardData) throw error;
if (!dashboardData) return <WidgetEmptyState />; if (!dashboardData) return <WidgetEmptyState />;
const hasWarning = hasWidgetDataWarning({
error,
expectedIntegrationCount: integrationIds.length,
receivedIntegrationCount: dashboardData.length,
});
const combined = dashboardData.reduce<UptimeKumaDashboardData>( const combined = dashboardData.reduce<UptimeKumaDashboardData>(
(acc, item) => ({ (acc, item) => ({
@@ -168,13 +163,13 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
value={formatNumber(combined[primaryStat], 0)} value={formatNumber(combined[primaryStat], 0)}
label={t(`stats.${primaryStat}`)} label={t(`stats.${primaryStat}`)}
description={supportingDescription} description={supportingDescription}
isStale={hasWarning} isStale={Boolean(error) || hasPartialFailure}
/> />
); );
} }
if (!hasContent) { if (!hasContent) {
return <WidgetMobileSummary value="—" label={t("name")} isStale={hasWarning} />; return <WidgetMobileSummary value="—" label={t("name")} isStale={Boolean(error) || hasPartialFailure} />;
} }
return ( return (
@@ -182,7 +177,7 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
value={`${formatNumber(uptimeValue, 1)}%`} value={`${formatNumber(uptimeValue, 1)}%`}
label={t("averageUptime")} label={t("averageUptime")}
description={supportingDescription} description={supportingDescription}
isStale={hasWarning} isStale={Boolean(error) || hasPartialFailure}
/> />
); );
} }
@@ -191,7 +186,7 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats]; heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats];
const heroRingClass = heroVariantByRing[String(options.showUptimeRing) as keyof typeof heroVariantByRing]; const heroRingClass = heroVariantByRing[String(options.showUptimeRing) as keyof typeof heroVariantByRing];
const content = ( return (
<div className={classes.root}> <div className={classes.root}>
{showHero && ( {showHero && (
<div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}> <div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}>
@@ -246,7 +241,6 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
)} )}
</div> </div>
); );
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
} }
function clampPercent(value: number): number { function clampPercent(value: number): number {
-6
View File
@@ -1427,9 +1427,6 @@ importers:
'@homarr/api': '@homarr/api':
specifier: workspace:^0.1.0 specifier: workspace:^0.1.0
version: link:../api version: link:../api
'@homarr/settings':
specifier: workspace:^0.1.0
version: link:../settings
react: react:
specifier: 'catalog:' specifier: 'catalog:'
version: 19.2.7 version: 19.2.7
@@ -2331,9 +2328,6 @@ importers:
'@homarr/auth': '@homarr/auth':
specifier: workspace:^0.1.0 specifier: workspace:^0.1.0
version: link:../auth version: link:../auth
'@homarr/boards':
specifier: workspace:^0.1.0
version: link:../boards
'@homarr/common': '@homarr/common':
specifier: workspace:^0.1.0 specifier: workspace:^0.1.0
version: link:../common version: link:../common