feat!: release v2 (#6545)

Co-authored-by: Artur <145776561+arturict@users.noreply.github.com>
Co-authored-by: arturict <arturict@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Co-authored-by: ajnart <thomas@ajnart.fr>
Co-authored-by: ajnart <thomas@ajnart.dev>
Co-authored-by: chenjun <chenjun@foxmail.com>
Co-authored-by: Wikibear <wikibear@users.noreply.github.com>
Co-authored-by: Bergasha <bergasha@gmail.com>
Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com>
Co-authored-by: Lucas Araujo <lucas.lra@gmail.com>
Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com>
Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social>
Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com>
Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com>
Co-authored-by: thrawnx <tight.bulb9384@fastmail.com>
Co-authored-by: Chris <58918656+nordada@users.noreply.github.com>
Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Co-authored-by: Yanis <naamaneyanis@gmail.com>
Co-authored-by: Wikibear <me@sej.de>
Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386 -139176

No files matched your search

+104 -25
View File
@@ -1,25 +1,90 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { createContext, useContext, useEffect, useSyncExternalStore } from "react";
import { usePathname } from "next/navigation";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { boardViewportWidthCookieName, getLayoutIdForViewportWidth } from "./layout-selection";
import { updateBoardName } from "./updater";
const BoardContext = createContext<{
board: RouterOutputs["board"]["getBoardByName"];
} | null>(null);
type Board = RouterOutputs["board"]["getBoardByName"];
interface BoardContextValue {
board: Board;
layoutOverrideId: string | null;
currentLayout: string;
initialViewportWidth: number;
}
const BoardContext = createContext<BoardContextValue | null>(null);
const subscribeToViewport = (onStoreChange: () => void) => {
if (typeof window === "undefined") return () => undefined;
let animationFrame = 0;
const handleResize = () => {
if (animationFrame !== 0) return;
animationFrame = window.requestAnimationFrame(() => {
animationFrame = 0;
persistViewportWidth(getViewportWidth());
onStoreChange();
});
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
window.cancelAnimationFrame(animationFrame);
};
};
export const BoardPreviewProvider = ({ children, board }: PropsWithChildren<{ board: Board }>) => {
const currentLayout = board.layouts[0]?.id ?? "";
return (
<BoardContext.Provider
value={{
board,
layoutOverrideId: null,
currentLayout,
initialViewportWidth: 0,
}}
>
{children}
</BoardContext.Provider>
);
};
export const BoardProvider = ({
children,
initialBoard,
initialLayoutId,
initialViewportWidth,
layoutOverrideId = null,
}: PropsWithChildren<{
initialBoard: RouterOutputs["board"]["getBoardByName"];
initialLayoutId: string;
initialViewportWidth: number;
layoutOverrideId?: string | null;
}>) => {
const { data } = clientApi.board.getBoardByName.useQuery({ name: initialBoard.name }, { initialData: initialBoard });
const { data } = clientApi.board.getBoardByName.useQuery(
{ name: initialBoard.name },
{
initialData: initialBoard,
// The route already fetched this board, so keep it fresh long enough to
// avoid an immediate duplicate request while still surfacing remote edits
// when a user later returns to the board.
staleTime: 30_000,
},
);
const currentLayout = useSyncExternalStore(
subscribeToViewport,
() => getCurrentLayout(data, layoutOverrideId),
() => layoutOverrideId ?? initialLayoutId,
);
// Update the board name so it can be used within updateBoard method
updateBoardName(initialBoard.name);
@@ -35,10 +100,16 @@ export const BoardProvider = ({
};
}, [pathname, utils, initialBoard.name]);
useEffect(() => {
persistViewportWidth(getViewportWidth());
}, []);
return (
<BoardContext.Provider
value={{
board: data,
layoutOverrideId,
currentLayout,
initialViewportWidth,
}}
>
{children}
@@ -62,35 +133,37 @@ export const useOptionalBoard = () => {
return context?.board ?? null;
};
export const getCurrentLayout = (board: RouterOutputs["board"]["getBoardByName"]) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (typeof window === "undefined") return board.layouts.at(0)!.id;
export const useLayoutOverride = () => useContext(BoardContext)?.layoutOverrideId ?? null;
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutB.breakpoint - layoutA.breakpoint);
export const getCurrentLayout = (
board: RouterOutputs["board"]["getBoardByName"],
layoutOverrideId: string | null = null,
) => {
const layouts = board.layouts;
if (layoutOverrideId && layouts.some((layout) => layout.id === layoutOverrideId)) return layoutOverrideId;
// Fallback to smallest if none exists with breakpoint smaller than window width
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return sortedLayouts.find((layout) => layout.breakpoint <= window.innerWidth)?.id ?? sortedLayouts.at(0)!.id;
const viewportWidth = typeof window === "undefined" ? 0 : getViewportWidth();
return getLayoutIdForViewportWidth(layouts, viewportWidth);
};
export const useCurrentLayout = () => {
const board = useRequiredBoard();
const [currentLayout, setCurrentLayout] = useState(getCurrentLayout(board));
const context = useContext(BoardContext);
const onResize = useCallback(() => {
setCurrentLayout(getCurrentLayout(board));
}, [board]);
if (!context) {
throw new Error("Board is required");
}
useEffect(() => {
if (typeof window === "undefined") return;
window.addEventListener("resize", onResize);
return context.currentLayout;
};
return () => {
window.removeEventListener("resize", onResize);
};
}, [onResize]);
export const useInitialViewportWidth = () => {
const context = useContext(BoardContext);
return currentLayout;
if (!context) {
throw new Error("Board is required");
}
return context.initialViewportWidth;
};
export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) =>
@@ -101,3 +174,9 @@ export const useLayouts = () => {
return getBoardLayouts(board);
};
const persistViewportWidth = (viewportWidth: number) => {
document.cookie = `${boardViewportWidthCookieName}=${Math.round(viewportWidth)}; Path=/; Max-Age=31536000; SameSite=Lax`;
};
const getViewportWidth = () => document.documentElement.clientWidth || window.innerWidth;
+8 -3
View File
@@ -1,13 +1,18 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useContext } from "react";
import { createContext, useContext, useEffect } from "react";
import { useDisclosure } from "@mantine/hooks";
const EditModeContext = createContext<ReturnType<typeof useDisclosure> | null>(null);
export const EditModeProvider = ({ children }: PropsWithChildren) => {
const editModeDisclosure = useDisclosure(false);
export const EditModeProvider = ({ children, initialOpen = false }: PropsWithChildren<{ initialOpen?: boolean }>) => {
const editModeDisclosure = useDisclosure(initialOpen);
const [, { open }] = editModeDisclosure;
useEffect(() => {
if (initialOpen) open();
}, [initialOpen, open]);
return <EditModeContext.Provider value={editModeDisclosure}>{children}</EditModeContext.Provider>;
};
+215
View File
@@ -0,0 +1,215 @@
import { describe, expect, test } from "vitest";
import type { BoardPreviewData, BoardPreviewLayout } from "./layout-preview";
import { getRepresentativeLayoutWidth, projectBoardLayout } from "./layout-preview";
const mobile = {
id: "mobile",
columnCount: 3,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 0,
role: "mobile",
} satisfies BoardPreviewLayout;
const custom = {
id: "tablet",
columnCount: 6,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 480,
role: "custom",
} satisfies BoardPreviewLayout;
const base = {
id: "base",
columnCount: 12,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 768,
role: "base",
} satisfies BoardPreviewLayout;
const root = { id: "root", kind: "empty" as const, xOffset: 0, layouts: [] };
describe("layout representative widths", () => {
test("uses phone, activation midpoint, and desktop widths", () => {
const layouts = [mobile, custom, base];
expect(getRepresentativeLayoutWidth(mobile, layouts)).toBe(390);
expect(getRepresentativeLayoutWidth(custom, layouts)).toBe(624);
expect(getRepresentativeLayoutWidth(base, layouts)).toBe(1280);
});
});
describe("projectBoardLayout", () => {
test("keeps exact saved positions for the active layout", () => {
const board = {
layouts: [mobile],
sections: [
root,
{
id: "container",
kind: "container",
xOffset: null,
layouts: [
{
layoutId: mobile.id,
parentSectionId: root.id,
width: 3,
height: 2,
xOffset: 0,
yOffset: 0,
},
],
},
],
items: [],
} satisfies BoardPreviewData;
expect(projectBoardLayout(board, mobile, mobile)).toEqual([
expect.objectContaining({ id: "container", sectionId: root.id, width: 3, height: 2 }),
]);
});
test("reflows root items and containers while retaining nested items", () => {
const board = {
layouts: [mobile, base],
sections: [
root,
{
id: "container",
kind: "container",
xOffset: null,
layouts: [
{
layoutId: base.id,
parentSectionId: root.id,
width: 6,
height: 3,
xOffset: 6,
yOffset: 0,
},
],
},
],
items: [
{
id: "root-item",
layouts: [
{
layoutId: base.id,
sectionId: root.id,
width: 5,
height: 2,
xOffset: 0,
yOffset: 0,
},
],
},
{
id: "nested-item",
layouts: [
{
layoutId: base.id,
sectionId: "container",
width: 4,
height: 1,
xOffset: 0,
yOffset: 0,
},
],
},
],
} satisfies BoardPreviewData;
const projected = projectBoardLayout(board, base, mobile);
expect(projected.find((element) => element.id === "root-item")).toMatchObject({
type: "item",
width: 3,
height: 2,
xOffset: 0,
yOffset: 0,
sectionId: root.id,
});
expect(projected.find((element) => element.id === "container")).toMatchObject({
type: "section",
width: 3,
xOffset: 0,
yOffset: 2,
sectionId: root.id,
});
expect(projected.find((element) => element.id === "nested-item")).toMatchObject({
type: "item",
width: 3,
sectionId: "container",
});
});
test("ignores missing positions and supports empty boards", () => {
const board = {
layouts: [mobile],
sections: [root],
items: [{ id: "missing", layouts: [] }],
} satisfies BoardPreviewData;
expect(projectBoardLayout(board, base, mobile)).toEqual([]);
});
test("moves fixed-rail items into the mobile canvas without overlap", () => {
const baseWithRails = {
...base,
leftGutterColumnCount: 2,
rightGutterColumnCount: 2,
};
const roots = [
{ id: "left", kind: "empty" as const, xOffset: -1, layouts: [] },
root,
{ id: "right", kind: "empty" as const, xOffset: 1, layouts: [] },
];
const board = {
layouts: [mobile, baseWithRails],
sections: roots,
items: roots.map((section, index) => ({
id: `item-${section.id}`,
layouts: [
{
layoutId: base.id,
sectionId: section.id,
width: 2,
height: 1,
xOffset: 0,
yOffset: index,
},
],
})),
} satisfies BoardPreviewData;
const projected = projectBoardLayout(board, baseWithRails, mobile);
expect(projected).toHaveLength(3);
expect(projected.every((element) => element.sectionId === root.id)).toBe(true);
expect(projected.every((element) => element.xOffset >= 0 && element.xOffset + element.width <= 3)).toBe(true);
for (const [index, element] of projected.entries()) {
expect(
projected
.slice(index + 1)
.some(
(other) =>
element.xOffset < other.xOffset + other.width &&
element.xOffset + element.width > other.xOffset &&
element.yOffset < other.yOffset + other.height &&
element.yOffset + element.height > other.yOffset,
),
).toBe(false);
}
});
test("returns an empty preview when malformed data has no main root", () => {
const board = {
layouts: [mobile, base],
sections: [{ id: "left", kind: "empty", xOffset: -1, layouts: [] }],
items: [],
} satisfies BoardPreviewData;
expect(projectBoardLayout(board, base, mobile)).toEqual([]);
});
});
+178
View File
@@ -0,0 +1,178 @@
import { generateResponsiveGridFor } from "@homarr/common";
import type { GridAlgorithmItem } from "@homarr/common";
import type { BoardLane, LayoutRole, WidgetKind } from "@homarr/definitions";
import { boardLanes, getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
export interface BoardPreviewLayout {
id: string;
columnCount: number;
leftGutterColumnCount: number;
rightGutterColumnCount: number;
breakpoint: number;
role: LayoutRole;
}
interface BoardPreviewItemLayout {
layoutId: string;
sectionId: string;
xOffset: number;
yOffset: number;
width: number;
height: number;
}
interface BoardPreviewSectionLayout {
layoutId: string;
parentSectionId: string | null;
xOffset: number;
yOffset: number;
width: number;
height: number;
}
export interface BoardPreviewData {
layouts: readonly BoardPreviewLayout[];
sections: readonly BoardPreviewSection[];
items: readonly {
id: string;
kind?: WidgetKind;
iconUrl?: string | null;
layouts: readonly BoardPreviewItemLayout[];
}[];
}
type BoardPreviewSection =
| {
id: string;
kind: "empty";
xOffset: number | null;
layouts?: readonly BoardPreviewSectionLayout[];
}
| {
id: string;
kind: "container";
xOffset?: number | null;
layouts: readonly BoardPreviewSectionLayout[];
};
type LayoutGeometry = Pick<
BoardPreviewLayout,
"id" | "columnCount" | "leftGutterColumnCount" | "rightGutterColumnCount"
>;
export const getRepresentativeLayoutWidth = (layout: BoardPreviewLayout, allLayouts: readonly BoardPreviewLayout[]) => {
if (layout.role === "mobile") return 390;
if (layout.role === "base") return Math.max(1280, layout.breakpoint);
const nextLayout = allLayouts
.filter((candidate) => candidate.breakpoint > layout.breakpoint)
.toSorted((layoutA, layoutB) => layoutA.breakpoint - layoutB.breakpoint)
.at(0);
return nextLayout ? Math.round((layout.breakpoint + nextLayout.breakpoint) / 2) : Math.max(1280, layout.breakpoint);
};
export const projectBoardLayout = (
board: BoardPreviewData,
sourceLayout: LayoutGeometry,
targetLayout: LayoutGeometry,
) => {
const elements = getElementsForLayout(board, sourceLayout.id);
if (
sourceLayout.id === targetLayout.id &&
sourceLayout.columnCount === targetLayout.columnCount &&
sourceLayout.leftGutterColumnCount === targetLayout.leftGutterColumnCount &&
sourceLayout.rightGutterColumnCount === targetLayout.rightGutterColumnCount
) {
return elements;
}
const emptyRoots = board.sections
.filter((section) => section.kind === "empty")
.toSorted((first, second) => (first.xOffset ?? 0) - (second.xOffset ?? 0) || first.id.localeCompare(second.id));
const rootByLane = new Map<BoardLane, (typeof emptyRoots)[number]>();
for (const root of emptyRoots) {
const lane = getRootSectionLane(root.xOffset);
if (!rootByLane.has(lane)) rootByLane.set(lane, root);
}
const mainRoot = rootByLane.get("main");
if (!mainRoot) return [];
const sourceRootById = new Map(
emptyRoots.map((section) => [section.id, getRootSectionLane(section.xOffset)] as const),
);
const targetLaneBySourceLane = new Map<BoardLane, BoardLane>(
boardLanes.map((lane) => [
lane,
lane !== "main" && getBoardLaneColumnCount(targetLayout, lane) === 0 ? "main" : lane,
]),
);
const remappedElements = elements.map((element) => {
const sourceLane = sourceRootById.get(element.sectionId);
if (!sourceLane) return element;
const targetLane = targetLaneBySourceLane.get(sourceLane) ?? "main";
return { ...element, sectionId: (rootByLane.get(targetLane) ?? mainRoot).id };
});
return boardLanes.flatMap((lane) => {
const root = rootByLane.get(lane);
const width = getBoardLaneColumnCount(targetLayout, lane);
if (!root || width === 0) return [];
const sourceLanes = boardLanes.filter(
(sourceLane) =>
rootByLane.has(sourceLane) &&
getBoardLaneColumnCount(sourceLayout, sourceLane) > 0 &&
targetLaneBySourceLane.get(sourceLane) === lane,
);
const previousWidth =
sourceLanes.length === 1
? getBoardLaneColumnCount(sourceLayout, sourceLanes[0] ?? "main")
: Number.MAX_SAFE_INTEGER;
return generateResponsiveGridFor({
items: remappedElements,
previousWidth,
width,
sectionId: root.id,
}).items;
});
};
const getElementsForLayout = (board: BoardPreviewData, layoutId: string): GridAlgorithmItem[] => [
...board.items.flatMap((item) => {
const layout = item.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout
? [
{
id: item.id,
type: "item" as const,
height: layout.height,
width: layout.width,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
sectionId: layout.sectionId,
},
]
: [];
}),
...board.sections.flatMap((section) => {
if (section.kind !== "container") return [];
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.parentSectionId
? [
{
id: section.id,
type: "section" as const,
height: layout.height,
width: layout.width,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
sectionId: layout.parentSectionId,
},
]
: [];
}),
];
@@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import { getLayoutIdForViewportWidth } from "./layout-selection";
const layouts = [
{ id: "mobile", breakpoint: 0 },
{ id: "tablet", breakpoint: 768 },
{ id: "desktop", breakpoint: 1280 },
];
describe("getLayoutIdForViewportWidth", () => {
test.each([
[390, "mobile"],
[768, "tablet"],
[1279, "tablet"],
[1920, "desktop"],
])("selects the responsive layout for %ipx", (width, expected) => {
expect(getLayoutIdForViewportWidth(layouts, width)).toBe(expected);
});
test("falls back to the smallest layout for invalid widths", () => {
expect(getLayoutIdForViewportWidth(layouts, Number.NaN)).toBe("mobile");
});
test("rejects boards without layouts", () => {
expect(() => getLayoutIdForViewportWidth([], 1280)).toThrow("Expected the board to contain a layout");
});
});
+21
View File
@@ -0,0 +1,21 @@
export const boardViewportWidthCookieName = "homarr-viewport-width";
interface ResponsiveLayout {
id: string;
breakpoint: number;
}
export const getLayoutIdForViewportWidth = (layouts: readonly ResponsiveLayout[], viewportWidth: number): string => {
if (layouts.length === 0) {
throw new Error("Expected the board to contain a layout");
}
const normalizedWidth = Number.isFinite(viewportWidth) ? Math.max(0, viewportWidth) : 0;
const sortedLayouts = layouts.toSorted((layoutA, layoutB) => layoutB.breakpoint - layoutA.breakpoint);
const selected = sortedLayouts.find((layout) => layout.breakpoint <= normalizedWidth) ?? sortedLayouts.at(-1);
if (!selected) {
throw new Error("Expected the board to contain a layout");
}
return selected.id;
};
+42 -5
View File
@@ -5,14 +5,15 @@ import { useCallback } from "react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
type Board = RouterOutputs["board"]["getHomeBoard"];
type UpdateCallback = (previous: Board) => Board;
let boardName: string | null = null;
export const updateBoardName = (name: string | null) => {
boardName = name;
};
type UpdateCallback = (prev: RouterOutputs["board"]["getHomeBoard"]) => RouterOutputs["board"]["getHomeBoard"];
export const useUpdateBoard = () => {
const utils = clientApi.useUtils();
@@ -21,9 +22,13 @@ export const useUpdateBoard = () => {
if (!boardName) {
throw new Error("Board name is not set");
}
utils.board.getBoardByName.setData({ name: boardName }, (previous) =>
previous ? updaterWithoutUndefined(previous) : previous,
);
let updatedBoard: Board | undefined;
utils.board.getBoardByName.setData({ name: boardName }, (previous) => {
if (!previous) return previous;
updatedBoard = updaterWithoutUndefined(previous);
return updatedBoard;
});
return updatedBoard;
},
[utils],
);
@@ -32,3 +37,35 @@ export const useUpdateBoard = () => {
updateBoard,
};
};
interface PersistBoardOptions {
onError?: (error: unknown) => void;
}
export const usePersistBoard = ({ id, name }: Pick<Board, "id" | "name">) => {
const utils = clientApi.useUtils();
const { updateBoard } = useUpdateBoard();
const { mutateAsync: saveBoardAsync } = clientApi.board.saveBoard.useMutation({
scope: { id: `board-save:${id}` },
});
const updateAndPersistBoard = useCallback(
(updater: UpdateCallback, options?: PersistBoardOptions) => {
const persistedBoard = updateBoard(updater);
if (!persistedBoard) return undefined;
void saveBoardAsync(persistedBoard).catch((error: unknown) => {
const currentBoard = utils.board.getBoardByName.getData({ name });
if (currentBoard === persistedBoard) {
void utils.board.getBoardByName.invalidate({ name });
}
options?.onError?.(error);
});
return persistedBoard;
},
[name, saveBoardAsync, updateBoard, utils],
);
return { updateAndPersistBoard };
};