merge: stack auto mobile boards
This commit is contained in:
1155 files changed
+110206
-33634
No files matched your search
@@ -1,28 +1,69 @@
|
||||
"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"];
|
||||
layoutOverrideId: string | null;
|
||||
currentLayout: string;
|
||||
initialViewportWidth: number;
|
||||
} | 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 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);
|
||||
@@ -38,11 +79,16 @@ export const BoardProvider = ({
|
||||
};
|
||||
}, [pathname, utils, initialBoard.name]);
|
||||
|
||||
useEffect(() => {
|
||||
persistViewportWidth(getViewportWidth());
|
||||
}, []);
|
||||
return (
|
||||
<BoardContext.Provider
|
||||
value={{
|
||||
board: data,
|
||||
layoutOverrideId,
|
||||
currentLayout,
|
||||
initialViewportWidth,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
@@ -71,46 +117,32 @@ export const useLayoutOverride = () => useContext(BoardContext)?.layoutOverrideI
|
||||
export const getCurrentLayout = (
|
||||
board: RouterOutputs["board"]["getBoardByName"],
|
||||
layoutOverrideId: string | null = null,
|
||||
) => getCurrentLayoutFromLayouts(board.layouts, layoutOverrideId);
|
||||
|
||||
const getCurrentLayoutFromLayouts = (
|
||||
layouts: RouterOutputs["board"]["getBoardByName"]["layouts"],
|
||||
layoutOverrideId: string | null,
|
||||
) => {
|
||||
const layouts = board.layouts;
|
||||
if (layoutOverrideId && layouts.some((layout) => layout.id === layoutOverrideId)) return layoutOverrideId;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
if (typeof window === "undefined") return layouts.at(0)!.id;
|
||||
|
||||
const sortedLayouts = layouts.toSorted((layoutA, layoutB) => layoutB.breakpoint - layoutA.breakpoint);
|
||||
|
||||
// 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 layoutOverrideId = useLayoutOverride();
|
||||
const [currentLayout, setCurrentLayout] = useState(getCurrentLayout(board, layoutOverrideId));
|
||||
const layouts = board.layouts;
|
||||
const context = useContext(BoardContext);
|
||||
|
||||
const onResize = useCallback(() => {
|
||||
setCurrentLayout(getCurrentLayoutFromLayouts(layouts, layoutOverrideId));
|
||||
}, [layoutOverrideId, layouts]);
|
||||
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);
|
||||
|
||||
useEffect(() => onResize(), [onResize]);
|
||||
if (!context) {
|
||||
throw new Error("Board is required");
|
||||
}
|
||||
|
||||
return currentLayout;
|
||||
return context.initialViewportWidth;
|
||||
};
|
||||
|
||||
export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) =>
|
||||
@@ -121,3 +153,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;
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
Reference in new issue
Block a user