Compare commits

..
Author SHA1 Message Date
Thomas Camlong 15feac9aaa fix(old-import): add missing withBorder mapping for bookmarks widget
Restores typecheck after dev merge added the bookmarks withBorder option.
2026-06-04 23:14:38 +02:00
Thomas Camlong 5b1e3ce80e Merge branch 'dev' into feat/board-cache
Resolve _creator.tsx conflict: keep React cache via getBoardForParams.
2026-06-04 22:59:28 +02:00
Thomas Camlong 884fde245b fix(boards): replace global cache with React cache() per-request dedup
The unstable_cache approach bypassed throwIfActionForbiddenAsync and
dropped user-specific data (permissions, collapse states). Use React
cache() to deduplicate getInitialBoard within a single request instead,
preserving auth checks and all user data while reducing DB calls from
9 to 3 per board page load.
2026-05-25 11:01:07 +02:00
Thomas Camlong 689da2fb91 fix: format files and fix revalidateTag signature for Next 16
- Run prettier on all modified files
- Add required cache profile arg to revalidateTag
- Suppress require-await for server action (must be async)
2026-05-18 15:01:01 +02:00
Thomas Camlong 22af9e2c3e feat(boards): cache named board data with tag-based invalidation
Named boards are now served from Next.js unstable_cache (1h TTL,
tag `board-{name}`). A new `getSharedBoardWithWhereAsync` helper
fetches the board without per-user data so the result is safe to
share across requests.

Cache is busted via `invalidateBoardCacheAsync` (revalidateTag +
revalidatePath) from board save, layout save, and partial settings
mutations.
2026-05-18 14:51:44 +02:00
Thomas Camlong 2c388bd449 perf(boards): parallelize board page data fetching
Board fetch + auth() now run concurrently via Promise.all instead of
sequentially. Widget prefetches for all kinds also run in parallel
alongside integration permission loading.
2026-05-18 14:49:07 +02:00
20 changed files with 76 additions and 1010 deletions

No files matched your search

@@ -1,11 +1,9 @@
import { cache } from "react";
import { api } from "@homarr/api/server";
import { createBoardContentPage } from "../_creator";
const getHomeBoardAsync = cache(() => api.board.getHomeBoard());
export default createBoardContentPage<{ locale: string }>({
getInitialBoardAsync: getHomeBoardAsync,
async getInitialBoardAsync() {
return await api.board.getHomeBoard();
},
});
@@ -1,11 +1,9 @@
import { cache } from "react";
import { api } from "@homarr/api/server";
import { createBoardContentPage } from "../../_creator";
const getBoardByNameAsync = cache((name: string) => api.board.getBoardByName({ name }));
export default createBoardContentPage<{ locale: string; name: string }>({
getInitialBoardAsync: async ({ name }) => getBoardByNameAsync(name),
async getInitialBoardAsync({ name }) {
return await api.board.getBoardByName({ name });
},
});
@@ -1,24 +1,33 @@
"use client";
import dynamic from "next/dynamic";
import { Box } from "@mantine/core";
import { Box, Stack } from "@mantine/core";
import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { StaticBoardGrid } from "~/components/board/sections/static-grid";
import { BoardCategorySection } from "~/components/board/sections/category-section";
import { BoardEmptySection } from "~/components/board/sections/empty-section";
import { BoardBackgroundVideo } from "~/components/layout/background";
const EditModeBoard = dynamic(() => import("./_edit-board"), { ssr: false });
export const ClientBoard = () => {
const board = useRequiredBoard();
const [isEditMode] = useEditMode();
const currentLayoutId = useCurrentLayout();
const fullWidthSortedSections = board.sections
.filter((section) => section.kind === "empty" || section.kind === "category")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
return (
<Box h="100%" pos="relative">
<BoardBackgroundVideo />
{isEditMode ? <EditModeBoard /> : <StaticBoardGrid board={board} />}
<Stack h="100%">
{fullWidthSortedSections.map((section) =>
section.kind === "empty" ? (
<BoardEmptySection key={`${currentLayoutId}-${section.id}`} section={section} />
) : (
<BoardCategorySection key={`${currentLayoutId}-${section.id}`} section={section} />
),
)}
</Stack>
</Box>
);
};
@@ -1,3 +1,4 @@
import { cache } from "react";
import type { Metadata } from "next";
import { TRPCError } from "@trpc/server";
@@ -34,17 +35,20 @@ interface Props<TParams extends Params> {
export const createBoardContentPage = <TParams extends Record<string, unknown>>({
getInitialBoardAsync: getInitialBoard,
}: Props<TParams>) => {
const getCachedBoard = cache((_paramsKey: string, params: TParams) => getInitialBoard(params));
const getBoardForParams = (params: TParams) => getCachedBoard(JSON.stringify(params), params);
return {
layout: createBoardLayout({
headerActions: <BoardContentHeaderActions />,
getInitialBoardAsync: getInitialBoard,
getInitialBoardAsync: getBoardForParams,
}),
// eslint-disable-next-line no-restricted-syntax
page: async ({ params }: { params: Promise<TParams> }) => {
const resolvedParams = await params;
const queryClient = getQueryClient();
const [board, session] = await Promise.all([getInitialBoard(resolvedParams), auth()]);
const [board, session] = await Promise.all([getBoardForParams(resolvedParams), auth()]);
const itemsMap = board.items.reduce((acc, item) => {
const existing = acc.get(item.kind);
@@ -81,7 +85,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
},
generateMetadataAsync: async ({ params }: { params: Promise<TParams> }): Promise<Metadata> => {
try {
const board = await getInitialBoard(await params);
const board = await getBoardForParams(await params);
const t = await getI18n();
return {
@@ -97,7 +101,6 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
},
};
} catch (error) {
// Ignore not found errors and return empty metadata
if (error instanceof TRPCError && error.code === "NOT_FOUND") {
return {};
}
@@ -1,3 +1,7 @@
"use client";
export { ClientBoard as DynamicClientBoard } from "./_client";
import dynamic from "next/dynamic";
export const DynamicClientBoard = dynamic(() => import("./_client").then((mod) => mod.ClientBoard), {
ssr: false,
});
@@ -1,31 +0,0 @@
"use client";
import { Stack } from "@mantine/core";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { BoardCategorySection } from "~/components/board/sections/category-section";
import { BoardEmptySection } from "~/components/board/sections/empty-section";
const EditModeBoard = () => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const fullWidthSortedSections = board.sections
.filter((section) => section.kind === "empty" || section.kind === "category")
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
return (
<Stack h="100%">
{fullWidthSortedSections.map((section) =>
section.kind === "empty" ? (
<BoardEmptySection key={`${currentLayoutId}-${section.id}`} section={section} />
) : (
<BoardCategorySection key={`${currentLayoutId}-${section.id}`} section={section} />
),
)}
</Stack>
);
};
export default EditModeBoard;
@@ -19,10 +19,6 @@ import { BoardItemMenu } from "./item-menu";
interface BoardItemContentProps {
item: SectionItem;
fallbackDimensions?: {
width: number;
height: number;
};
}
const getOverflowFromKind = (kind: SectionItem["kind"]) => {
@@ -31,11 +27,9 @@ const getOverflowFromKind = (kind: SectionItem["kind"]) => {
return undefined;
};
export const BoardItemContent = ({ item, fallbackDimensions }: BoardItemContentProps) => {
export const BoardItemContent = ({ item }: BoardItemContentProps) => {
const { ref, width, height } = useElementSize<HTMLDivElement>();
const board = useRequiredBoard();
const fallbackWidth = fallbackDimensions?.width ?? 0;
const fallbackHeight = fallbackDimensions?.height ?? 0;
return (
<>
@@ -58,7 +52,7 @@ export const BoardItemContent = ({ item, fallbackDimensions }: BoardItemContentP
}}
p={0}
>
<InnerContent item={item} width={width || fallbackWidth} height={height || fallbackHeight} />
<InnerContent item={item} width={width} height={height} />
</Card>
{item.advancedOptions.title?.trim() && (
<Badge
@@ -12,7 +12,7 @@ import { widgetImports } from "@homarr/widgets";
import { WidgetEditModal } from "@homarr/widgets/modals";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import { useOptionalSectionContext } from "../sections/section-context";
import { useSectionContext } from "../sections/section-context";
import { useItemActions } from "./item-actions";
import { ItemMoveModal } from "./item-move-modal";
@@ -41,8 +41,7 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
useItemActions();
const { data: integrationData, isPending } = clientApi.integration.all.useQuery();
const currentDefinition = useMemo(() => widgetImports[item.kind].definition, [item.kind]);
const sectionContext = useOptionalSectionContext();
const gridstack = sectionContext?.refs.gridstack;
const { gridstack } = useSectionContext().refs;
const settings = useSettings();
// Reset error boundary on next render if item has been edited
@@ -128,7 +127,7 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
<Menu.Item
leftSection={<IconLayoutKanban size={16} />}
onClick={() => {
if (!gridstack?.current) return;
if (!gridstack.current) return;
openMoveModal({ item, columnCount: gridstack.current.getColumn(), gridStack: gridstack.current });
}}
>
@@ -1,21 +1,48 @@
import { Card, Collapse, Group, Stack, Title, UnstyledButton } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconChevronDown, IconChevronUp } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useRequiredBoard } from "@homarr/boards/context";
import type { CategorySection } from "~/app/[locale]/boards/_types";
import { CategoryMenu } from "./category/category-menu";
import { GridStack } from "./gridstack/gridstack";
import classes from "./item.module.css";
import { useCategoryCollapse } from "./use-category-collapse";
const localStorageKey = (sectionId: string) => `homarr-section-collapsed-${sectionId}`;
interface Props {
section: CategorySection;
}
export const BoardCategorySection = ({ section }: Props) => {
const { status } = useSession();
const { mutate } = clientApi.section.changeCollapsed.useMutation();
const board = useRequiredBoard();
const [opened, { toggle }] = useCategoryCollapse(section);
const initialCollapsed =
typeof window !== "undefined"
? (localStorage.getItem(localStorageKey(section.id)) ?? String(section.collapsed)) === "true"
: section.collapsed;
const [opened, { toggle }] = useDisclosure(initialCollapsed, {
onOpen() {
if (status === "authenticated") {
mutate({ sectionId: section.id, collapsed: true });
} else if (status === "unauthenticated") {
localStorage.setItem(localStorageKey(section.id), "true");
}
},
onClose() {
if (status === "authenticated") {
mutate({ sectionId: section.id, collapsed: false });
} else if (status === "unauthenticated") {
localStorage.setItem(localStorageKey(section.id), "false");
}
},
});
return (
<Card style={{ "--opacity": board.opacity / 100 }} radius={board.itemRadius} p={0} className={classes.itemCard}>
@@ -20,8 +20,4 @@ export const useSectionContext = () => {
return context;
};
export const useOptionalSectionContext = () => {
return useContext(SectionContext);
};
export const SectionProvider = SectionContext.Provider;
@@ -1,93 +0,0 @@
import { describe, expect, test } from "vitest";
import { BoardMockBuilder } from "../items/actions/test/mocks/board-mock";
import { DynamicSectionMockBuilder } from "../items/actions/test/mocks/dynamic-section-mock";
import { ItemMockBuilder } from "../items/actions/test/mocks/item-mock";
import { LayoutMockBuilder } from "../items/actions/test/mocks/layout-mock";
import {
getEstimatedGridWidth,
getFallbackDimensions,
getFullWidthSortedSections,
getStaticGridElements,
getStaticGridLayouts,
getStaticGridRowCount,
getStaticLayoutSelectionCss,
} from "./static-grid-layout";
describe("static grid layout", () => {
test("sorts layouts and creates breakpoint CSS in mobile-first order", () => {
const mobile = new LayoutMockBuilder({ id: "mobile", breakpoint: 0, columnCount: 4 }).build();
const tablet = new LayoutMockBuilder({ id: "tablet", breakpoint: 768, columnCount: 8 }).build();
const desktop = new LayoutMockBuilder({ id: "desktop", breakpoint: 1024, columnCount: 12 }).build();
const sortedLayouts = getStaticGridLayouts([desktop, mobile, tablet]);
const css = getStaticLayoutSelectionCss("board-1", sortedLayouts);
expect(sortedLayouts.map((layout) => layout.id)).toEqual(["mobile", "tablet", "desktop"]);
expect(css).toContain('[data-static-layout="mobile"] { display: block; }');
expect(css).toContain("@media (min-width: 768px)");
expect(css).toContain('[data-static-layout="tablet"] { display: block; }');
expect(css).toContain("@media (min-width: 1024px)");
expect(css).toContain('[data-static-layout="desktop"] { display: block; }');
});
test("selects and sorts layout-specific section elements", () => {
const rootSectionId = "root";
const mobileLayoutId = "mobile";
const desktopLayoutId = "desktop";
const mobile = new LayoutMockBuilder({ id: mobileLayoutId, breakpoint: 0, columnCount: 4 }).build();
const desktop = new LayoutMockBuilder({ id: desktopLayoutId, breakpoint: 1024, columnCount: 12 }).build();
const item = new ItemMockBuilder({ id: "item" })
.addLayout({ layoutId: mobileLayoutId, sectionId: rootSectionId, xOffset: 2, yOffset: 1, width: 1, height: 1 })
.addLayout({ layoutId: desktopLayoutId, sectionId: rootSectionId, xOffset: 0, yOffset: 1, width: 4, height: 2 })
.build();
const dynamicSection = new DynamicSectionMockBuilder({ id: "dynamic" })
.addLayout({
layoutId: mobileLayoutId,
parentSectionId: rootSectionId,
xOffset: 0,
yOffset: 0,
width: 2,
height: 2,
})
.addLayout({
layoutId: desktopLayoutId,
parentSectionId: rootSectionId,
xOffset: 4,
yOffset: 1,
width: 4,
height: 2,
})
.build();
const board = new BoardMockBuilder()
.addEmptySection({ id: rootSectionId, yOffset: 2 })
.addEmptySection({ id: "first", yOffset: 0 })
.addSection(dynamicSection)
.addItem(item)
.build();
board.layouts = [desktop, mobile];
const mobileElements = getStaticGridElements(board, rootSectionId, mobileLayoutId);
const desktopElements = getStaticGridElements(board, rootSectionId, desktopLayoutId);
const fullWidthSections = getFullWidthSortedSections(board);
expect(mobileElements.map((element) => element.id)).toEqual(["dynamic", "item"]);
expect(desktopElements.map((element) => ({ id: element.id, width: element.width }))).toEqual([
{ id: "item", width: 4 },
{ id: "dynamic", width: 4 },
]);
expect(getStaticGridRowCount(mobileElements)).toBe(2);
expect(fullWidthSections.map((section) => section.id)).toEqual(["first", rootSectionId]);
});
test("estimates grid and item dimensions per layout range", () => {
const mobile = new LayoutMockBuilder({ id: "mobile", breakpoint: 0, columnCount: 4 }).build();
const tablet = new LayoutMockBuilder({ id: "tablet", breakpoint: 768, columnCount: 8 }).build();
const desktop = new LayoutMockBuilder({ id: "desktop", breakpoint: 1024, columnCount: 12 }).build();
expect(getEstimatedGridWidth(mobile, tablet)).toBe(384);
expect(getEstimatedGridWidth(tablet, desktop)).toBe(896);
expect(getEstimatedGridWidth(desktop)).toBe(1280);
expect(getFallbackDimensions({ width: 2, height: 3 }, 400, 4)).toEqual({ width: 180, height: 280 });
});
});
@@ -1,103 +0,0 @@
import type { Board, DynamicSectionItem, EmptySection, SectionItem } from "~/app/[locale]/boards/_types";
type BoardLayout = Board["layouts"][number];
type StaticGridElement = SectionItem | DynamicSectionItem;
const STATIC_GRID_ITEM_INSET = 20;
const DEFAULT_SMALL_VIEWPORT_WIDTH = 360;
const DEFAULT_LARGE_VIEWPORT_WIDTH = 1280;
export const getStaticGridLayouts = (layouts: Board["layouts"]) =>
[...layouts].toSorted((layoutA, layoutB) => layoutA.breakpoint - layoutB.breakpoint);
const escapeCssString = (value: string) => value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
export const getStaticLayoutSelectionCss = (boardId: string, layouts: Board["layouts"]) => {
const sortedLayouts = getStaticGridLayouts(layouts);
const initialLayout = sortedLayouts.at(0);
if (!initialLayout) return "";
const scope = `[data-static-board="${escapeCssString(boardId)}"]`;
const css = [
`${scope} .static-board-layout { display: none; }`,
`${scope} .static-board-layout[data-static-layout="${escapeCssString(initialLayout.id)}"] { display: block; }`,
];
for (const layout of sortedLayouts.slice(1)) {
css.push(
`@media (min-width: ${layout.breakpoint}px) { ${scope} .static-board-layout { display: none; } ${scope} .static-board-layout[data-static-layout="${escapeCssString(layout.id)}"] { display: block; } }`,
);
}
return css.join("\n");
};
export const getFullWidthSortedSections = (board: Board) =>
board.sections
.filter(
(section): section is EmptySection | Extract<Board["sections"][number], { kind: "category" }> =>
section.kind === "empty" || section.kind === "category",
)
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
export const getSectionItemsForLayout = (board: Board, sectionId: string, layoutId: string): SectionItem[] => {
return board.items
.map(({ layouts, ...item }) => {
const layout = layouts.find((candidate) => candidate.layoutId === layoutId);
if (!layout) return null;
return { ...layout, ...item, type: "item" as const };
})
.filter((item): item is SectionItem => item !== null && item.sectionId === sectionId);
};
export const getDynamicSectionsForLayout = (
board: Board,
sectionId: string,
layoutId: string,
): DynamicSectionItem[] => {
return board.sections
.filter((section) => section.kind === "dynamic")
.map(({ layouts, ...section }) => {
const layout = layouts.find((candidate) => candidate.layoutId === layoutId);
if (!layout) return null;
return { ...layout, ...section, type: "section" as const };
})
.filter((entry): entry is DynamicSectionItem => entry !== null && entry.parentSectionId === sectionId);
};
export const getStaticGridElements = (board: Board, sectionId: string, layoutId: string): StaticGridElement[] => {
return [
...getSectionItemsForLayout(board, sectionId, layoutId),
...getDynamicSectionsForLayout(board, sectionId, layoutId),
].toSorted((itemA, itemB) => {
if (itemA.yOffset === itemB.yOffset) return itemA.xOffset - itemB.xOffset;
return itemA.yOffset - itemB.yOffset;
});
};
export const getStaticGridRowCount = (items: StaticGridElement[], fixedRowCount?: number) => {
return fixedRowCount ?? Math.max(...items.map((item) => item.yOffset + item.height));
};
export const getEstimatedGridWidth = (layout: BoardLayout, nextLayout?: BoardLayout) => {
if (nextLayout) {
const upperBound = Math.max(nextLayout.breakpoint - 1, DEFAULT_SMALL_VIEWPORT_WIDTH);
return Math.max(DEFAULT_SMALL_VIEWPORT_WIDTH, Math.round((layout.breakpoint + upperBound) / 2));
}
return Math.max(layout.breakpoint, DEFAULT_LARGE_VIEWPORT_WIDTH);
};
export const getFallbackDimensions = (
item: Pick<StaticGridElement, "width" | "height">,
estimatedGridWidth: number,
columnCount: number,
) => {
const cellSize = estimatedGridWidth / columnCount;
return {
width: Math.max(0, item.width * cellSize - STATIC_GRID_ITEM_INSET),
height: Math.max(0, item.height * cellSize - STATIC_GRID_ITEM_INSET),
};
};
@@ -1,289 +0,0 @@
"use client";
import { Badge, Card, Collapse, Group, Stack, Title, UnstyledButton } from "@mantine/core";
import { IconChevronDown, IconChevronUp } from "@tabler/icons-react";
import { useRequiredBoard } from "@homarr/boards/context";
import type {
Board,
CategorySection,
DynamicSectionItem,
EmptySection,
SectionItem,
} from "~/app/[locale]/boards/_types";
import { BoardItemContent } from "../items/item-content";
import { CategoryMenu } from "./category/category-menu";
import classes from "./item.module.css";
import {
getEstimatedGridWidth,
getFallbackDimensions,
getFullWidthSortedSections,
getStaticGridElements,
getStaticGridLayouts,
getStaticGridRowCount,
getStaticLayoutSelectionCss,
} from "./static-grid-layout";
import { useCategoryCollapse } from "./use-category-collapse";
interface StaticBoardGridProps {
board: Board;
}
export const StaticBoardGrid = ({ board }: StaticBoardGridProps) => {
const boardId = `board-${board.id}`;
const layouts = getStaticGridLayouts(board.layouts);
const layoutSelectionCss = getStaticLayoutSelectionCss(boardId, layouts);
const fullWidthSortedSections = getFullWidthSortedSections(board);
if (layouts.length === 0) return null;
return (
<>
<style>{layoutSelectionCss}</style>
<div data-static-board={boardId}>
{layouts.map((layout, index) => (
<div key={layout.id} className="static-board-layout" data-static-layout={layout.id}>
<Stack h="100%">
{fullWidthSortedSections.map((section) =>
section.kind === "empty" ? (
<StaticEmptySection
key={section.id}
section={section}
board={board}
layoutId={layout.id}
columnCount={layout.columnCount}
estimatedGridWidth={getEstimatedGridWidth(layout, layouts.at(index + 1))}
/>
) : (
<StaticCategorySection
key={section.id}
section={section}
board={board}
layoutId={layout.id}
columnCount={layout.columnCount}
estimatedGridWidth={getEstimatedGridWidth(layout, layouts.at(index + 1))}
/>
),
)}
</Stack>
</div>
))}
</div>
</>
);
};
interface StaticSectionGridProps {
sectionId: string;
board: Board;
layoutId: string;
columnCount: number;
estimatedGridWidth: number;
isDynamic?: boolean;
fixedRowCount?: number;
}
const StaticSectionGrid = ({
sectionId,
board,
layoutId,
columnCount,
estimatedGridWidth,
isDynamic,
fixedRowCount,
}: StaticSectionGridProps) => {
const allItems = getStaticGridElements(board, sectionId, layoutId);
if (allItems.length === 0) return null;
const rowCount = getStaticGridRowCount(allItems, fixedRowCount);
return (
<div className="static-grid-container" style={{ height: isDynamic ? "100%" : undefined }}>
<div
className="static-grid"
style={{
display: "grid",
gridTemplateColumns: `repeat(${columnCount}, 1fr)`,
gridTemplateRows: isDynamic
? `repeat(${rowCount}, 1fr)`
: `repeat(${rowCount}, calc(100cqi / ${columnCount}))`,
height: isDynamic ? "100%" : undefined,
}}
>
{allItems.map((item) => (
<StaticGridItem
key={item.id}
item={item}
board={board}
layoutId={layoutId}
estimatedGridWidth={estimatedGridWidth}
columnCount={columnCount}
/>
))}
</div>
</div>
);
};
interface StaticGridItemProps {
item: SectionItem | DynamicSectionItem;
board: Board;
layoutId: string;
estimatedGridWidth: number;
columnCount: number;
}
const StaticGridItem = ({ item, board, layoutId, estimatedGridWidth, columnCount }: StaticGridItemProps) => {
const fallbackDimensions = getFallbackDimensions(item, estimatedGridWidth, columnCount);
return (
<div
style={{
gridColumn: `${item.xOffset + 1} / span ${item.width}`,
gridRow: `${item.yOffset + 1} / span ${item.height}`,
position: "relative",
}}
>
<div className="static-grid-item-content">
{item.type === "item" ? (
<BoardItemContent item={item} fallbackDimensions={fallbackDimensions} />
) : (
<StaticDynamicSection
section={item}
board={board}
layoutId={layoutId}
estimatedGridWidth={fallbackDimensions.width}
/>
)}
</div>
</div>
);
};
interface StaticEmptySectionProps {
section: EmptySection;
board: Board;
layoutId: string;
columnCount: number;
estimatedGridWidth: number;
}
const StaticEmptySection = ({ section, board, layoutId, columnCount, estimatedGridWidth }: StaticEmptySectionProps) => {
const items = getStaticGridElements(board, section.id, layoutId);
if (items.length === 0) return null;
return (
<StaticSectionGrid
sectionId={section.id}
board={board}
layoutId={layoutId}
columnCount={columnCount}
estimatedGridWidth={estimatedGridWidth}
/>
);
};
interface StaticCategorySectionProps {
section: CategorySection;
board: Board;
layoutId: string;
columnCount: number;
estimatedGridWidth: number;
}
const StaticCategorySection = ({
section,
board,
layoutId,
columnCount,
estimatedGridWidth,
}: StaticCategorySectionProps) => {
const boardData = useRequiredBoard();
const [opened, { toggle }] = useCategoryCollapse(section);
return (
<Card
style={{ "--opacity": boardData.opacity / 100 }}
radius={boardData.itemRadius}
p={0}
className={classes.itemCard}
>
<Stack>
<Group wrap="nowrap" gap="sm">
<UnstyledButton w="100%" p="sm" onClick={toggle}>
<Group wrap="nowrap">
{opened ? <IconChevronUp size={20} /> : <IconChevronDown size={20} />}
<Title order={3}>{section.name}</Title>
</Group>
</UnstyledButton>
<CategoryMenu category={section} />
</Group>
<Collapse expanded={opened} p="sm" pt={0}>
<StaticSectionGrid
sectionId={section.id}
board={board}
layoutId={layoutId}
columnCount={columnCount}
estimatedGridWidth={estimatedGridWidth}
/>
</Collapse>
</Stack>
</Card>
);
};
interface StaticDynamicSectionProps {
section: DynamicSectionItem;
board: Board;
layoutId: string;
estimatedGridWidth: number;
}
const StaticDynamicSection = ({ section, board, layoutId, estimatedGridWidth }: StaticDynamicSectionProps) => {
const boardData = useRequiredBoard();
const options = section.options;
return (
<Card
className={classes.itemCard}
w="100%"
h="100%"
styles={{
root: {
overflow: "visible",
"--opacity": boardData.opacity / 100,
"--border-color": options.borderColor || undefined,
},
}}
radius={boardData.itemRadius}
p={0}
>
{options.title && (
<Badge
pos="absolute"
top={-15}
left={10}
size="md"
radius={boardData.itemRadius}
color="var(--background-color)"
c="var(--mantine-color-text)"
bd="1px solid var(--border-color)"
>
{options.title}
</Badge>
)}
<StaticSectionGrid
sectionId={section.id}
board={board}
layoutId={layoutId}
columnCount={section.width}
estimatedGridWidth={estimatedGridWidth}
isDynamic
fixedRowCount={section.height}
/>
</Card>
);
};
@@ -1,77 +0,0 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import type { CategorySection } from "~/app/[locale]/boards/_types";
export const getCategoryCollapseStorageKey = (sectionId: string) => `homarr-section-collapsed-${sectionId}`;
const categoryCollapseChangeEventName = "homarr-section-collapse-change";
interface CategoryExpandedChangeEventDetail {
sectionId: string;
expanded: boolean;
}
const getInitialExpanded = (section: CategorySection) => {
if (typeof window === "undefined") return section.collapsed;
return (localStorage.getItem(getCategoryCollapseStorageKey(section.id)) ?? String(section.collapsed)) === "true";
};
export const useCategoryCollapse = (section: CategorySection) => {
const { status } = useSession();
const { mutate } = clientApi.section.changeCollapsed.useMutation();
const [opened, setOpened] = useState(() => getInitialExpanded(section));
const persistExpanded = useCallback(
(expanded: boolean) => {
if (status === "authenticated") {
mutate({ sectionId: section.id, collapsed: expanded });
} else if (status === "unauthenticated") {
localStorage.setItem(getCategoryCollapseStorageKey(section.id), String(expanded));
}
},
[mutate, section.id, status],
);
useEffect(() => {
const handleCollapseChange = (event: Event) => {
const { sectionId, expanded } = (event as CustomEvent<CategoryExpandedChangeEventDetail>).detail;
if (sectionId === section.id) {
setOpened(expanded);
}
};
window.addEventListener(categoryCollapseChangeEventName, handleCollapseChange);
return () => {
window.removeEventListener(categoryCollapseChangeEventName, handleCollapseChange);
};
}, [section.id]);
const toggle = useCallback(() => {
setOpened((current) => {
const expanded = !current;
persistExpanded(expanded);
if (typeof window !== "undefined") {
window.dispatchEvent(
new CustomEvent<CategoryExpandedChangeEventDetail>(categoryCollapseChangeEventName, {
detail: {
sectionId: section.id,
expanded,
},
}),
);
}
return expanded;
});
}, [persistExpanded, section.id]);
return [opened, { toggle }] as const;
};
-14
View File
@@ -112,17 +112,3 @@
.grid-stack-empty-wrapper {
display: none !important;
}
.static-grid-container {
container-type: inline-size;
}
.static-grid-item-content {
position: absolute;
inset: 10px;
> .grid-stack-item-content {
width: 100%;
height: 100%;
}
}
-304
View File
@@ -1,304 +0,0 @@
import { chromium } from "@playwright/test";
import { createId } from "@paralleldrive/cuid2";
import SuperJSON from "superjson";
import { describe, expect, test } from "vitest";
import * as sqliteSchema from "../packages/db/schema/sqlite";
import { hashPasswordAsync } from "../packages/auth/security";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import type { SqliteDatabase } from "./shared/e2e-db";
const boardName = "responsive-board";
const credentials = {
username: "responsive-admin",
password: "Comp(exP4sswOrd",
};
const viewports = [
{ width: 320, height: 568 },
{ width: 375, height: 667 },
{ width: 768, height: 1024 },
{ width: 1024, height: 768 },
{ width: 1366, height: 768 },
{ width: 1920, height: 1080 },
];
describe("Board responsive layout", () => {
test("renders static board layouts across common viewports and loads edit mode", async () => {
const { db, localMountPath } = await createSqliteDbFileAsync();
const { categorySectionId } = await seedResponsiveBoardAsync(db);
const homarrContainer = await createHomarrContainer({
mounts: {
"/appdata": localMountPath,
},
}).start();
const browser = await chromium.launch();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
try {
for (const viewport of viewports) {
const context = await browser.newContext({ viewport });
await context.addInitScript(() => {
window.__homarrLayoutShiftScore = 0;
new PerformanceObserver((entries) => {
for (const entry of entries.getEntries()) {
const layoutShift = entry as PerformanceEntry & { value: number; hadRecentInput: boolean };
if (!layoutShift.hadRecentInput) {
window.__homarrLayoutShiftScore += layoutShift.value;
}
}
}).observe({ type: "layout-shift", buffered: true });
});
await context.addInitScript(
({ sectionId }) => {
localStorage.setItem(`homarr-section-collapsed-${sectionId}`, "true");
},
{ sectionId: categorySectionId },
);
const page = await context.newPage();
await page.goto(`${baseUrl}/boards/${boardName}`);
await page.waitForSelector(".static-grid-item-content", { state: "visible" });
await page.waitForTimeout(500);
const result = await page.evaluate(() => {
const visibleLayout = Array.from(document.querySelectorAll<HTMLElement>(".static-board-layout")).find(
(element) => getComputedStyle(element).display !== "none",
);
const grids = Array.from(visibleLayout?.querySelectorAll<HTMLElement>(".static-grid") ?? []);
const hasOverlappingItems = grids.some((grid) => {
const rects = Array.from(grid.children)
.map((element) => element.getBoundingClientRect())
.filter((rect) => rect.width > 0 && rect.height > 0);
return rects.some((rect, index) =>
rects.slice(index + 1).some((otherRect) => {
const horizontalOverlap = Math.min(rect.right, otherRect.right) - Math.max(rect.left, otherRect.left);
const verticalOverlap = Math.min(rect.bottom, otherRect.bottom) - Math.max(rect.top, otherRect.top);
return horizontalOverlap > 1 && verticalOverlap > 1;
}),
);
});
const visibleItems = Array.from(
visibleLayout?.querySelectorAll<HTMLElement>(".static-grid-item-content") ?? [],
).filter((element) => {
const rect = element.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
return {
hasVisibleLayout: Boolean(visibleLayout),
visibleItemCount: visibleItems.length,
hasHorizontalOverflow: document.documentElement.scrollWidth > window.innerWidth + 1,
hasOverlappingItems,
layoutShiftScore: window.__homarrLayoutShiftScore,
};
});
expect(result.hasVisibleLayout).toBe(true);
expect(result.visibleItemCount).toBe(4);
expect(result.hasHorizontalOverflow).toBe(false);
expect(result.hasOverlappingItems).toBe(false);
expect(result.layoutShiftScore).toBeLessThanOrEqual(0.01);
await context.close();
}
const context = await browser.newContext({ viewport: { width: 1366, height: 768 } });
const page = await context.newPage();
await page.goto(`${baseUrl}/auth/login`);
await page.getByLabel("Username").fill(credentials.username);
await page.getByLabel("Password").fill(credentials.password);
await page.locator("css=button[type='submit']").click();
await page.waitForURL(baseUrl);
await page.goto(`${baseUrl}/boards/${boardName}`);
await page.waitForSelector(".static-grid-item-content", { state: "visible" });
await page.keyboard.press("ControlOrMeta+E");
await page.waitForSelector(".grid-stack", { state: "visible" });
await expect.poll(() => page.locator(".grid-stack-item").count()).toBeGreaterThan(0);
await context.close();
} finally {
await browser.close();
await homarrContainer.stop();
}
}, 120_000);
});
const seedResponsiveBoardAsync = async (db: SqliteDatabase) => {
const userId = createId();
const boardId = createId();
const mobileLayoutId = createId();
const tabletLayoutId = createId();
const desktopLayoutId = createId();
const rootSectionId = createId();
const categorySectionId = createId();
const dynamicSectionId = createId();
await db.update(sqliteSchema.onboarding).set({ step: "finish" });
await db.insert(sqliteSchema.users).values({
id: userId,
name: credentials.username,
password: await hashPasswordAsync(credentials.password),
});
await db.insert(sqliteSchema.boards).values({
id: boardId,
name: boardName,
isPublic: true,
creatorId: userId,
});
await db.insert(sqliteSchema.layouts).values([
{ id: mobileLayoutId, name: "Mobile", boardId, columnCount: 4, breakpoint: 0 },
{ id: tabletLayoutId, name: "Tablet", boardId, columnCount: 8, breakpoint: 768 },
{ id: desktopLayoutId, name: "Desktop", boardId, columnCount: 12, breakpoint: 1024 },
]);
await db.insert(sqliteSchema.sections).values([
{ id: rootSectionId, boardId, kind: "empty", xOffset: 0, yOffset: 0 },
{ id: categorySectionId, boardId, kind: "category", xOffset: 0, yOffset: 1, name: "Systems" },
{
id: dynamicSectionId,
boardId,
kind: "dynamic",
options: SuperJSON.stringify({ title: "Nested", borderColor: "", customCssClasses: [] }),
},
]);
await db.insert(sqliteSchema.sectionLayouts).values([
{
sectionId: dynamicSectionId,
layoutId: mobileLayoutId,
parentSectionId: categorySectionId,
xOffset: 0,
yOffset: 0,
width: 4,
height: 2,
},
{
sectionId: dynamicSectionId,
layoutId: tabletLayoutId,
parentSectionId: categorySectionId,
xOffset: 0,
yOffset: 0,
width: 4,
height: 2,
},
{
sectionId: dynamicSectionId,
layoutId: desktopLayoutId,
parentSectionId: categorySectionId,
xOffset: 0,
yOffset: 0,
width: 6,
height: 2,
},
]);
const rootItemId = await insertClockItemAsync(db, boardId);
const categoryItemId = await insertClockItemAsync(db, boardId);
const dynamicItemId = await insertClockItemAsync(db, boardId);
await db.insert(sqliteSchema.itemLayouts).values([
{
itemId: rootItemId,
sectionId: rootSectionId,
layoutId: mobileLayoutId,
xOffset: 0,
yOffset: 0,
width: 2,
height: 1,
},
{
itemId: rootItemId,
sectionId: rootSectionId,
layoutId: tabletLayoutId,
xOffset: 0,
yOffset: 0,
width: 3,
height: 1,
},
{
itemId: rootItemId,
sectionId: rootSectionId,
layoutId: desktopLayoutId,
xOffset: 0,
yOffset: 0,
width: 4,
height: 1,
},
{
itemId: categoryItemId,
sectionId: categorySectionId,
layoutId: mobileLayoutId,
xOffset: 0,
yOffset: 2,
width: 4,
height: 1,
},
{
itemId: categoryItemId,
sectionId: categorySectionId,
layoutId: tabletLayoutId,
xOffset: 4,
yOffset: 0,
width: 4,
height: 2,
},
{
itemId: categoryItemId,
sectionId: categorySectionId,
layoutId: desktopLayoutId,
xOffset: 6,
yOffset: 0,
width: 6,
height: 2,
},
{
itemId: dynamicItemId,
sectionId: dynamicSectionId,
layoutId: mobileLayoutId,
xOffset: 0,
yOffset: 0,
width: 2,
height: 1,
},
{
itemId: dynamicItemId,
sectionId: dynamicSectionId,
layoutId: tabletLayoutId,
xOffset: 0,
yOffset: 0,
width: 2,
height: 1,
},
{
itemId: dynamicItemId,
sectionId: dynamicSectionId,
layoutId: desktopLayoutId,
xOffset: 0,
yOffset: 0,
width: 3,
height: 1,
},
]);
return {
categorySectionId,
};
};
const insertClockItemAsync = async (db: SqliteDatabase, boardId: string) => {
const itemId = createId();
await db.insert(sqliteSchema.items).values({
id: itemId,
boardId,
kind: "clock",
options: SuperJSON.stringify({ is24HourFormat: true }),
advancedOptions: SuperJSON.stringify({ title: null, customCssClasses: [], borderColor: "" }),
});
return itemId;
};
declare global {
interface Window {
__homarrLayoutShiftScore: number;
}
}
+6 -2
View File
@@ -1,7 +1,7 @@
import type { ComponentType } from "react";
import type { Loader } from "next/dynamic";
import dynamic from "next/dynamic";
import { Skeleton } from "@mantine/core";
import { Center, Loader as UiLoader } from "@mantine/core";
import { objectEntries } from "@homarr/common";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
@@ -107,7 +107,11 @@ export const loadWidgetDynamic = <TKind extends WidgetKind>(kind: TKind) => {
const newlyLoadedComponent = dynamic<WidgetComponentProps<TKind>>(
widgetImports[kind].componentLoader as Loader<WidgetComponentProps<TKind>>,
{
loading: () => <Skeleton w="100%" h="100%" radius="md" animate />,
loading: () => (
<Center w="100%" h="100%">
<UiLoader />
</Center>
),
},
);
-4
View File
@@ -11,8 +11,6 @@ import prefetchForApps from "./app/prefetch";
import prefetchForBookmarks from "./bookmarks/prefetch";
import type { Prefetch, WidgetOptionsRecordOf } from "./definition";
import type { inferOptionsFromCreator } from "./options";
import prefetchRssFeedsAsync from "./rssFeed/prefetch";
import prefetchWeatherAsync from "./weather/prefetch";
const cachedGetServerSettingsAsync = cache(getServerSettingsAsync);
@@ -21,8 +19,6 @@ const prefetchCallbacks: Partial<{
}> = {
bookmarks: prefetchForBookmarks,
app: prefetchForApps,
weather: prefetchWeatherAsync,
rssFeed: prefetchRssFeedsAsync,
};
export const prefetchForKindAsync = async <TKind extends WidgetKind>(
-22
View File
@@ -1,22 +0,0 @@
import { api, trpc } from "@homarr/api/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import type { Prefetch } from "../definition";
const logger = createLogger({ module: "rssFeedWidgetPrefetch" });
const prefetchRssFeedsAsync: Prefetch<"rssFeed"> = async (queryClient, items) => {
for (const item of items) {
const input = {
urls: item.options.feedUrls,
maximumAmountPosts: item.options.maximumAmountPosts,
};
const data = await api.widget.rssFeed.getFeeds(input);
queryClient.setQueryData(trpc.widget.rssFeed.getFeeds.queryKey(input), data);
}
logger.info("Successfully prefetched RSS feeds", { count: items.length });
};
export default prefetchRssFeedsAsync;
-29
View File
@@ -1,29 +0,0 @@
import { api, trpc } from "@homarr/api/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import type { Prefetch } from "../definition";
const logger = createLogger({ module: "weatherWidgetPrefetch" });
const prefetchWeatherAsync: Prefetch<"weather"> = async (queryClient, items) => {
const locations = items.map((item) => ({
latitude: item.options.location.latitude,
longitude: item.options.location.longitude,
}));
const uniqueLocations = locations.filter(
(loc, idx, arr) =>
arr.findIndex((other) => other.latitude === loc.latitude && other.longitude === loc.longitude) === idx,
);
await Promise.all(
uniqueLocations.map(async (input) => {
const data = await api.widget.weather.atLocation(input);
queryClient.setQueryData(trpc.widget.weather.atLocation.queryKey(input), data);
}),
);
logger.info("Successfully prefetched weather data", { count: uniqueLocations.length });
};
export default prefetchWeatherAsync;