feat: rebuild board grid experience

This commit is contained in:
ajnart committed 2026-08-01 00:43:28 +02:00
1 parent fcc5130068
commit 25c9955cc6
127 files changed
+14934 -2342

No files matched your search

@@ -0,0 +1,201 @@
"use client";
import type { FocusEvent, KeyboardEvent, PropsWithChildren } from "react";
import { useId, useState } from "react";
import { Box } from "@mantine/core";
import combineClasses from "clsx";
import { useCurrentLayout } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useI18n } from "@homarr/translation/client";
import type { DynamicSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import {
getEditableGridCellAttributes,
getLayoutRowCount,
getLogicalItemStyle,
getReadonlyGridItemAttributes,
placeGridItem,
} from "~/components/board/layout";
import type { GridPlacement } from "~/components/board/layout";
import { useSectionContext } from "../section-context";
import classes from "./section-grid.module.css";
import type { SectionGridPlacement } from "./use-grid-layout-actions";
import { useGridLayoutActions } from "./use-grid-layout-actions";
interface FixedGridItemProps {
item: DynamicSectionItem | SectionItem;
minWidth?: number;
minHeight?: number;
}
export const FixedGridItem = ({
item,
minWidth = 1,
minHeight = 1,
children,
}: PropsWithChildren<FixedGridItemProps>) => {
const [isEditMode] = useEditMode();
const currentLayoutId = useCurrentLayout();
const t = useI18n();
const { section, items, innerSections, columnCount, maxRowCount, announce } = useSectionContext();
const { commitSectionGrid } = useGridLayoutActions();
const [isKeyboardEditing, setIsKeyboardEditing] = useState(false);
const instructionsId = useId();
const placement = toPlacement(item);
const displayName =
item.type === "item"
? item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`)
: item.options.title.trim() || t("section.dynamic.untitled");
const accessibleLabel = t("item.moveResize.entryLabel", {
name: displayName,
column: String(placement.x + 1),
row: String(placement.y + 1),
});
const setKeyboardEditing = (next: boolean) => {
setIsKeyboardEditing(next);
announce(
`${accessibleLabel}: ${t(next ? "item.moveResize.keyboard.started" : "item.moveResize.keyboard.stopped")}`,
);
};
const handleKeyboard = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.target !== event.currentTarget || !isEditMode || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setKeyboardEditing(!isKeyboardEditing);
return;
}
if (event.key === "Escape" && isKeyboardEditing) {
event.preventDefault();
setKeyboardEditing(false);
return;
}
if (!isKeyboardEditing || !isArrowKey(event.key)) return;
event.preventDefault();
const allPlacements = [...items, ...innerSections].map(toPlacement);
const current = allPlacements.find((candidate) => candidate.id === item.id);
if (!current) return;
const next = getKeyboardPlacement(current, event.key, event.shiftKey, {
columnCount,
minWidth,
minHeight,
maxRowCount,
});
if (next.x === current.x && next.y === current.y && next.w === current.w && next.h === current.h) {
announce(`${accessibleLabel}: ${t("item.moveResize.keyboard.boundary")}`);
return;
}
const resolved = placeGridItem(allPlacements, next, columnCount) as SectionGridPlacement[];
if (maxRowCount !== null && getLayoutRowCount(resolved) > maxRowCount) {
announce(`${accessibleLabel}: ${t("item.moveResize.keyboard.boundary")}`);
return;
}
commitSectionGrid({ layoutId: currentLayoutId, sectionId: section.id, placements: resolved });
announce(
`${displayName}: ${t("item.moveResize.field.xOffset.label")} ${next.x + 1}, ${t(
"item.moveResize.field.yOffset.label",
)} ${next.y + 1}, ${t("item.moveResize.field.width.label")} ${next.w}, ${t(
"item.moveResize.field.height.label",
)} ${next.h}`,
);
};
const handleBlur = (event: FocusEvent<HTMLDivElement>) => {
if (isKeyboardEditing && !event.currentTarget.contains(event.relatedTarget)) {
setIsKeyboardEditing(false);
}
};
const semantics = isEditMode
? getEditableGridCellAttributes({ label: accessibleLabel, placement })
: getReadonlyGridItemAttributes(placement);
return (
<Box
{...semantics}
className={combineClasses(isEditMode ? classes.editorEntry : classes.staticItem)}
style={isEditMode ? { position: "relative", width: "100%", height: "100%" } : getLogicalItemStyle(placement)}
data-grid-item-id={isEditMode ? undefined : item.id}
data-grid-item-type={isEditMode ? undefined : item.type}
data-editor-grid-entry={isEditMode ? "true" : undefined}
data-type={item.type}
data-kind={item.kind}
data-keyboard-editing={isEditMode ? String(isKeyboardEditing) : undefined}
aria-describedby={isEditMode ? instructionsId : undefined}
aria-keyshortcuts={
isEditMode
? "Enter Space Escape ArrowLeft ArrowRight ArrowUp ArrowDown Shift+ArrowLeft Shift+ArrowRight Shift+ArrowUp Shift+ArrowDown"
: undefined
}
onBlur={isEditMode ? handleBlur : undefined}
onKeyDown={isEditMode ? handleKeyboard : undefined}
>
{children}
{isEditMode && (
<span id={instructionsId} className={classes.liveRegion}>
{t("item.moveResize.keyboard.instructions")}
</span>
)}
</Box>
);
};
const toPlacement = (item: DynamicSectionItem | SectionItem): SectionGridPlacement => ({
id: item.id,
type: item.type,
x: item.xOffset,
y: item.yOffset,
w: item.width,
h: item.height,
});
const isArrowKey = (key: string): key is "ArrowLeft" | "ArrowRight" | "ArrowUp" | "ArrowDown" =>
key === "ArrowLeft" || key === "ArrowRight" || key === "ArrowUp" || key === "ArrowDown";
const getKeyboardPlacement = (
current: SectionGridPlacement,
key: "ArrowLeft" | "ArrowRight" | "ArrowUp" | "ArrowDown",
resize: boolean,
{
columnCount,
minWidth,
minHeight,
maxRowCount,
}: {
columnCount: number;
minWidth: number;
minHeight: number;
maxRowCount: number | null;
},
): GridPlacement & Pick<SectionGridPlacement, "type"> => {
if (resize) {
const widthDelta = key === "ArrowLeft" ? -1 : key === "ArrowRight" ? 1 : 0;
const heightDelta = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
return {
...current,
w: Math.max(minWidth, Math.min(columnCount - current.x, current.w + widthDelta)),
h: Math.max(
minHeight,
Math.min(maxRowCount === null ? Number.MAX_SAFE_INTEGER : maxRowCount - current.y, current.h + heightDelta),
),
};
}
const xDelta = key === "ArrowLeft" ? -1 : key === "ArrowRight" ? 1 : 0;
const yDelta = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
return {
...current,
x: Math.max(0, Math.min(columnCount - current.w, current.x + xDelta)),
y: Math.max(
0,
Math.min(maxRowCount === null ? Number.MAX_SAFE_INTEGER : maxRowCount - current.h, current.y + yDelta),
),
};
};
@@ -0,0 +1,76 @@
"use client";
import type * as GridEditorModule from "./grid-editor";
let editorModulePromise: Promise<typeof GridEditorModule> | undefined;
export const loadGridEditorAsync = () => {
editorModulePromise ??= import("./grid-editor").catch((error: unknown) => {
editorModulePromise = undefined;
throw error;
});
return editorModulePromise;
};
export const scheduleGridEditorWarmup = (loadAsync: () => Promise<unknown>) => {
let animationFrameId: number | undefined;
let idleCallbackId: number | undefined;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let hydrationObserver: MutationObserver | undefined;
let cancelled = false;
const load = () => {
if (!cancelled) void loadAsync().catch(() => undefined);
};
const scheduleAfterPaint = () => {
animationFrameId = window.requestAnimationFrame(() => {
if ("requestIdleCallback" in window) {
idleCallbackId = window.requestIdleCallback(load, { timeout: 2_000 });
} else {
timeoutId = setTimeout(load, 1_000);
}
});
};
const scheduleWhenInteractive = () => {
if (document.querySelector('[data-board-hydrated="true"]')) {
scheduleAfterPaint();
return;
}
hydrationObserver = new MutationObserver(() => {
if (!document.querySelector('[data-board-hydrated="true"]')) return;
hydrationObserver?.disconnect();
hydrationObserver = undefined;
scheduleAfterPaint();
});
hydrationObserver.observe(document.documentElement, {
attributeFilter: ["data-board-hydrated"],
attributes: true,
childList: true,
subtree: true,
});
};
const handleVisibilityChange = () => {
if (document.visibilityState !== "visible") return;
document.removeEventListener("visibilitychange", handleVisibilityChange);
scheduleWhenInteractive();
};
if (document.visibilityState === "visible") {
scheduleWhenInteractive();
} else {
document.addEventListener("visibilitychange", handleVisibilityChange);
}
return () => {
cancelled = true;
document.removeEventListener("visibilitychange", handleVisibilityChange);
hydrationObserver?.disconnect();
if (animationFrameId !== undefined) window.cancelAnimationFrame(animationFrameId);
if (idleCallbackId !== undefined && "cancelIdleCallback" in window) {
window.cancelIdleCallback(idleCallbackId);
}
if (timeoutId !== undefined) clearTimeout(timeoutId);
};
};
@@ -0,0 +1,36 @@
.grid-stack.grid-stack-editing > .grid-stack-placeholder > .placeholder-content {
background: color-mix(in srgb, var(--mantine-primary-color-filled) 20%, transparent);
border: 2px dashed var(--mantine-primary-color-filled);
border-radius: var(--mantine-radius-md);
}
.grid-stack.grid-stack-editing > .grid-stack-item.ui-draggable-dragging {
filter: drop-shadow(var(--mantine-shadow-lg));
}
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-handle {
z-index: 8;
}
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-e,
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-w {
width: 28px;
}
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-s {
height: 28px;
}
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-se,
.grid-stack.grid-stack-editing > .grid-stack-item > .ui-resizable-sw {
width: 28px;
height: 28px;
background-size: 12px 12px;
}
@media (prefers-reduced-motion: reduce) {
.grid-stack.grid-stack-editing,
.grid-stack.grid-stack-editing .grid-stack-item {
transition: none !important;
}
}
@@ -0,0 +1,421 @@
"use client";
import type { CSSProperties } from "react";
import { useCallback, useLayoutEffect, useMemo, useRef } from "react";
import "gridstack/dist/gridstack.min.css"; // oxlint-disable-line import/no-unassigned-import
import "./grid-editor.css"; // oxlint-disable-line import/no-unassigned-import
import type { AddRemoveFcn, GridItemHTMLElement, GridStackNode, GridStackWidget } from "gridstack";
import { GridStack } from "gridstack";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useI18n } from "@homarr/translation/client";
import { getLogicalTrackSize, LOGICAL_GRID_GAP, LOGICAL_GRID_PITCH } from "~/components/board/layout";
import { useSectionContext } from "../section-context";
import { useBoardGridPortalHost } from "./grid-portal-host";
import { decorateGridResizeHandles } from "./grid-resize-handles";
import type { SectionGridPlacement } from "./use-grid-layout-actions";
import { useGridLayoutActions } from "./use-grid-layout-actions";
const AUTO_EXPAND_ROW_BUFFER = 8;
interface GridEditorProps {
sectionId: string;
columnCount: number;
rowCount: number;
fixedRowCount: boolean;
placements: readonly SectionGridPlacement[];
className: string;
}
/**
* The only board module that imports GridStack. The library owns every
* positioned shell, while one board-level portal host owns React content.
* Moving a shell between independent grids therefore never reparents a
* React-owned element.
*/
export default function GridEditor({
sectionId,
columnCount,
rowCount,
fixedRowCount,
placements,
className,
}: GridEditorProps) {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const t = useI18n();
const { announce, innerSections, items } = useSectionContext();
const { acquireContainer, releaseContainer } = useBoardGridPortalHost();
const { commitSectionGrid, commitSectionGrids } = useGridLayoutActions();
const wrapperRef = useRef<HTMLDivElement>(null);
const gridRef = useRef<GridStack | null>(null);
const applyingControlledLayoutRef = useRef(false);
const placementsRef = useRef(placements);
const entriesRef = useRef([...items, ...innerSections]);
const acceptWidgetRef = useRef<(element: Element) => boolean>(() => false);
const dimensionsRef = useRef({ columnCount, fixedRowCount, rowCount });
placementsRef.current = placements;
entriesRef.current = [...items, ...innerSections];
dimensionsRef.current = { columnCount, fixedRowCount, rowCount };
const forbiddenDynamicSectionIds = useMemo(
() => getTargetAncestorSectionIds(board.sections, currentLayoutId, sectionId),
[board.sections, currentLayoutId, sectionId],
);
acceptWidgetRef.current = (element) => {
const node = (element as GridItemHTMLElement).gridstackNode;
const id = element.getAttribute("data-grid-item-id") ?? node?.id;
if (!id) return false;
if ((node?.minW ?? 1) > columnCount) return false;
if (fixedRowCount && (node?.minH ?? 1) > rowCount) return false;
return element.getAttribute("data-grid-item-type") !== "section" || !forbiddenDynamicSectionIds.has(String(id));
};
const shellCallback = useCallback<AddRemoveFcn>(
(_parent, widget, add, isGrid) => {
if (isGrid) return undefined;
const id = widget.id ? String(widget.id) : null;
if (!id) return undefined;
if (!add) {
const element = (widget as GridStackNode).el;
const container = element?.querySelector<HTMLElement>(":scope > .grid-stack-item-content");
if (container) releaseContainer(id, container);
element?.remove();
return undefined;
}
const element = document.createElement("div") as GridItemHTMLElement;
element.className = "grid-stack-item";
element.appendChild(acquireContainer(id));
return element;
},
[acquireContainer, releaseContainer],
);
const snapshotGrid = useCallback(
(grid: GridStack | undefined) => {
if (!grid?.el) return null;
const snapshotSectionId = grid.el.getAttribute("data-grid-section-id");
if (!snapshotSectionId) return null;
return {
layoutId: currentLayoutId,
sectionId: snapshotSectionId,
placements: getGridPlacements(grid),
};
},
[currentLayoutId],
);
const commitGrid = useCallback(
(grid: GridStack | undefined) => {
if (applyingControlledLayoutRef.current) return;
const snapshot = snapshotGrid(grid);
if (snapshot) commitSectionGrid(snapshot);
},
[commitSectionGrid, snapshotGrid],
);
const announceNode = useCallback(
(node: GridStackNode | undefined) => {
if (!node?.id) return;
const entry = entriesRef.current.find((candidate) => candidate.id === String(node.id));
const displayName =
entry?.type === "item"
? entry.advancedOptions.title?.trim() || t(`widget.${entry.kind}.name`)
: entry?.type === "section"
? entry.options.title.trim() || t("section.dynamic.untitled")
: t("item.action.moveResize");
const label = t("item.moveResize.entryLabel", {
name: displayName,
column: String((node.x ?? 0) + 1),
row: String((node.y ?? 0) + 1),
});
announce(
`${label}: ${t("item.moveResize.field.width.label")} ${node.w ?? 1}, ${t(
"item.moveResize.field.height.label",
)} ${node.h ?? 1}`,
);
},
[announce, t],
);
const eventHandlersRef = useRef({
announceNode,
commitGrid,
commitSectionGrids,
snapshotGrid,
});
eventHandlersRef.current = {
announceNode,
commitGrid,
commitSectionGrids,
snapshotGrid,
};
useLayoutEffect(() => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
const dimensions = dimensionsRef.current;
const grid = GridStack.init(
{
acceptWidgets: (element) => acceptWidgetRef.current(element),
alwaysShowResizeHandle: true,
animate: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
cellHeight: LOGICAL_GRID_PITCH,
column: dimensions.columnCount,
draggable: {
cancel:
'a,button,input,textarea,select,option,[contenteditable="true"],[role="button"],[data-grid-no-drag],.ui-resizable-handle',
handle: "[data-editor-grid-entry]",
scroll: true,
},
float: true,
margin: `0 ${LOGICAL_GRID_GAP}px ${LOGICAL_GRID_GAP}px 0`,
maxRow: dimensions.fixedRowCount ? dimensions.rowCount : 0,
minRow: dimensions.fixedRowCount ? dimensions.rowCount : 1,
resizable: {
autoHide: false,
handles: "e, se, s, sw, w",
},
},
wrapper,
);
if (!grid) return;
// GridStack infers a native sub-grid from DOM nesting. Homarr owns nested
// grids independently so content can move between them without remounting;
// keeping the inferred link makes parent/child teardown order unsafe.
const inferredParentNode = grid.parentGridNode;
if (inferredParentNode) {
if (inferredParentNode.subGrid === grid) delete inferredParentNode.subGrid;
delete grid.parentGridNode;
wrapper.classList.remove("grid-stack-nested");
inferredParentNode.el?.classList.remove("grid-stack-sub-grid");
}
gridRef.current = grid;
wrapper.setAttribute("data-grid-section-id", sectionId);
wrapper.classList.add("grid-stack-editing");
const handleStop = (_event: Event, element: GridItemHTMLElement) => {
eventHandlersRef.current.commitGrid(element.gridstackNode?.grid ?? grid);
eventHandlersRef.current.announceNode(element.gridstackNode);
decorateGrid(element.gridstackNode?.grid ?? grid, placementsRef.current);
restoreContentHeight(grid);
};
const handleDragStart = () => {
const currentDimensions = dimensionsRef.current;
if (currentDimensions.fixedRowCount) return;
grid.updateOptions({
minRow: currentDimensions.rowCount + AUTO_EXPAND_ROW_BUFFER,
});
setViewportRowCount(grid, currentDimensions.rowCount + AUTO_EXPAND_ROW_BUFFER);
};
const handleDropped = (
_event: Event,
previousNode: GridStackNode | undefined,
newNode: GridStackNode | undefined,
) => {
queueMicrotask(() => {
if (applyingControlledLayoutRef.current) return;
const snapshots = uniqueGrids([previousNode?.grid, newNode?.grid ?? grid])
.map((changedGrid) => eventHandlersRef.current.snapshotGrid(changedGrid))
.filter((snapshot) => snapshot !== null);
if (snapshots.length > 0) eventHandlersRef.current.commitSectionGrids(snapshots);
eventHandlersRef.current.announceNode(newNode);
for (const changedGrid of uniqueGrids([previousNode?.grid, newNode?.grid])) {
decorateGrid(changedGrid, placementsRef.current);
restoreContentHeight(changedGrid);
}
});
};
grid.on("dragstart", handleDragStart);
grid.on("dragstop", handleStop);
grid.on("resizestop", handleStop);
grid.on("dropped", handleDropped);
return () => {
grid.offAll();
const elements = grid.getGridItems();
for (const element of elements) {
const id = element.getAttribute("data-grid-item-id") ?? element.gridstackNode?.id;
const container = element.querySelector<HTMLElement>(":scope > .grid-stack-item-content");
if (id && container) releaseContainer(String(id), container);
}
grid.destroy(false);
for (const element of elements) element.remove();
if (gridRef.current === grid) gridRef.current = null;
};
}, [releaseContainer, sectionId, shellCallback]);
useLayoutEffect(() => {
const grid = gridRef.current;
if (!grid) return;
grid.updateOptions({
column: columnCount,
maxRow: fixedRowCount ? rowCount : 0,
minRow: fixedRowCount ? rowCount : 1,
});
}, [columnCount, fixedRowCount, rowCount]);
useLayoutEffect(() => {
const grid = gridRef.current;
if (!grid) return;
applyingControlledLayoutRef.current = true;
grid.load(placements.map(toGridStackWidget), shellCallback);
applyingControlledLayoutRef.current = false;
decorateGrid(grid, placements);
restoreContentHeight(grid);
const actual = getGridPlacements(grid);
if (!arePlacementsEqual(actual, placements)) {
commitSectionGrid({ layoutId: currentLayoutId, sectionId, placements: actual });
}
}, [commitSectionGrid, currentLayoutId, placements, sectionId, shellCallback]);
return (
<>
<div
ref={wrapperRef}
className={className}
data-grid-section-id={sectionId}
style={
{
width: columnCount * LOGICAL_GRID_PITCH,
minHeight: rowCount * LOGICAL_GRID_PITCH,
} as CSSProperties
}
/>
<span
data-grid-runtime="homarr-edit-grid-v1"
data-editor-section-id={sectionId}
aria-hidden="true"
style={{ position: "absolute", width: 1, height: 1, pointerEvents: "none" }}
/>
</>
);
}
const toGridStackWidget = (placement: SectionGridPlacement): GridStackWidget => ({
id: placement.id,
x: placement.x,
y: placement.y,
w: placement.w,
h: placement.h,
minW: placement.minW ?? 1,
minH: placement.minH ?? 1,
});
const getGridPlacements = (grid: GridStack): SectionGridPlacement[] =>
grid.getGridItems().flatMap((element) => {
const node = element.gridstackNode;
const id = element.getAttribute("data-grid-item-id") ?? node?.id;
const type = element.getAttribute("data-grid-item-type");
if (!node || !id || (type !== "item" && type !== "section")) return [];
return [
{
id: String(id),
type,
x: node.x ?? 0,
y: node.y ?? 0,
w: node.w ?? 1,
h: node.h ?? 1,
minW: node.minW,
minH: node.minH,
},
];
});
const decorateGrid = (grid: GridStack | undefined, placements: readonly SectionGridPlacement[]) => {
if (!grid?.el) return;
const placementById = new Map(placements.map((placement) => [placement.id, placement]));
grid.el.classList.add("grid-stack-editing");
for (const item of grid.getGridItems()) {
const id = item.getAttribute("data-grid-item-id") ?? item.gridstackNode?.id;
const placement = id ? placementById.get(String(id)) : undefined;
decorateItem(item, placement?.type ?? getElementItemType(item));
}
};
const decorateItem = (element: GridItemHTMLElement, type: SectionGridPlacement["type"] | undefined) => {
const node = element.gridstackNode;
if (!node?.id) return;
element.setAttribute("data-grid-item-id", String(node.id));
if (type) element.setAttribute("data-grid-item-type", type);
element.setAttribute("data-grid-x", String(node.x ?? 0));
element.setAttribute("data-grid-y", String(node.y ?? 0));
element.setAttribute("data-grid-w", String(node.w ?? 1));
element.setAttribute("data-grid-h", String(node.h ?? 1));
decorateGridResizeHandles(element);
};
const getElementItemType = (element: Element): SectionGridPlacement["type"] | undefined => {
const type = element.getAttribute("data-grid-item-type");
return type === "item" || type === "section" ? type : undefined;
};
const arePlacementsEqual = (first: readonly SectionGridPlacement[], second: readonly SectionGridPlacement[]) => {
if (first.length !== second.length) return false;
const secondById = new Map(second.map((placement) => [placement.id, placement]));
return first.every((placement) => {
const other = secondById.get(placement.id);
return (
other !== undefined &&
placement.type === other.type &&
placement.x === other.x &&
placement.y === other.y &&
placement.w === other.w &&
placement.h === other.h
);
});
};
const uniqueGrids = (grids: Array<GridStack | undefined>) =>
Array.from(new Set(grids.filter((grid): grid is GridStack => grid !== undefined)));
const restoreContentHeight = (grid: GridStack | undefined) => {
if (!grid || (grid.opts.maxRow ?? 0) > 0) return;
const contentRowCount = Math.max(1, ...getGridPlacements(grid).map((placement) => placement.y + placement.h));
grid.updateOptions({ minRow: contentRowCount });
setViewportRowCount(grid, contentRowCount);
};
const setViewportRowCount = (grid: GridStack, rowCount: number) => {
const viewport = grid.el.parentElement;
if (!viewport?.hasAttribute("data-section-id")) return;
viewport.style.setProperty("--board-grid-drag-height", `${getLogicalTrackSize(rowCount)}px`);
};
const getTargetAncestorSectionIds = (
sections: ReturnType<typeof useRequiredBoard>["sections"],
layoutId: string,
targetSectionId: string,
) => {
const parentById = new Map(
sections
.filter((section) => section.kind === "dynamic")
.flatMap((section) => {
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout ? ([[section.id, layout.parentSectionId]] as const) : [];
}),
);
const ancestors = new Set<string>();
let current: string | undefined = targetSectionId;
while (current && !ancestors.has(current)) {
ancestors.add(current);
current = parentById.get(current);
}
return ancestors;
};
@@ -0,0 +1,194 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { GridItemHTMLElement } from "gridstack";
import type { RouterOutputs } from "@homarr/api";
import { useIntegrations } from "@homarr/auth/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { getRootSectionLane } from "@homarr/definitions";
import type { DynamicSectionItem, Section } from "~/app/[locale]/boards/_types";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { SectionContentItem } from "../content";
import { SectionProvider } from "../section-context";
import { useSectionItems } from "../use-section-items";
import { decorateGridResizeHandles } from "./grid-resize-handles";
import classes from "./section-grid.module.css";
interface GridPortalHostContextValue {
announce: (message: string) => void;
integrations: RouterOutputs["integration"]["all"] | undefined;
acquireContainer: (id: string) => HTMLElement;
releaseContainer: (id: string, container: HTMLElement) => void;
}
const GridPortalHostContext = createContext<GridPortalHostContextValue | null>(null);
/**
* One portal registry owns every edit-mode item on the board. Its content
* containers are stable even when GridStack replaces or transfers the outer
* positioning shell, so moving between grids does not remount widget content.
*/
export const BoardGridPortalHost = ({ children }: PropsWithChildren) => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const integrations = useIntegrations();
const containersRef = useRef<Map<string, HTMLElement>>(new Map());
const [containers, setContainers] = useState<Map<string, HTMLElement>>(() => new Map());
const [announcement, setAnnouncement] = useState({ id: 0, message: "" });
const announce = useCallback((message: string) => {
setAnnouncement((previous) => ({ id: previous.id + 1, message }));
}, []);
const acquireContainer = useCallback((id: string) => {
const existing = containersRef.current.get(id);
if (existing) return existing;
const container = document.createElement("div");
container.className = "grid-stack-item-content";
container.style.overflow = "visible";
containersRef.current.set(id, container);
setContainers(new Map(containersRef.current));
return container;
}, []);
const releaseContainer = useCallback((id: string, container: HTMLElement) => {
// Controlled cross-grid moves remove the source shell before the target
// adopts this container. Wait until all grid effects in the commit ran.
queueMicrotask(() => {
if (container.isConnected || containersRef.current.get(id) !== container) return;
containersRef.current.delete(id);
setContainers(new Map(containersRef.current));
});
}, []);
const value = useMemo<GridPortalHostContextValue>(
() => ({
announce,
integrations,
acquireContainer,
releaseContainer,
}),
[acquireContainer, announce, integrations, releaseContainer],
);
return (
<GridPortalHostContext.Provider value={value}>
{children}
{Array.from(containers, ([id, container]) => {
const ownerSectionId = getOwnerSectionId(board, currentLayoutId, id);
return ownerSectionId
? createPortal(
<GridPortalContent
itemId={id}
ownerSectionId={ownerSectionId}
container={container}
integrations={integrations}
announce={announce}
/>,
container,
id,
)
: null;
})}
<div className={classes.liveRegion} aria-live="polite" aria-atomic="true">
<span key={announcement.id}>{announcement.message}</span>
</div>
</GridPortalHostContext.Provider>
);
};
export const useBoardGridPortalHost = () => {
const context = useContext(GridPortalHostContext);
if (!context) throw new Error("BoardGridPortalHost is required");
return context;
};
interface GridPortalContentProps {
itemId: string;
ownerSectionId: string;
container: HTMLElement;
integrations: RouterOutputs["integration"]["all"] | undefined;
announce: (message: string) => void;
}
const GridPortalContent = ({ itemId, ownerSectionId, container, integrations, announce }: GridPortalContentProps) => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { items, innerSections } = useSectionItems(ownerSectionId);
const entry = [...items, ...innerSections].find((candidate) => candidate.id === itemId);
const rawSection = board.sections.find((section) => section.id === ownerSectionId);
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId);
const section = toGridSection(rawSection, currentLayoutId);
useLayoutEffect(() => {
const itemElement = container.parentElement as GridItemHTMLElement | null;
if (!itemElement) return;
itemElement.gridstackNode?.grid?.refreshDragHandles(itemElement);
decorateGridResizeHandles(itemElement);
}, [container, ownerSectionId]);
if (!entry || !section || !currentLayout) return null;
const columnCount =
section.kind === "dynamic"
? section.width
: section.kind === "empty"
? getBoardLaneColumnCount(currentLayout, getRootSectionLane(section.xOffset))
: currentLayout.columnCount;
const configuredMaxRowCount = section.kind === "dynamic" ? section.height : null;
const contentRowCount = Math.max(
1,
...items.map((item) => item.yOffset + item.height),
...innerSections.map((innerSection) => innerSection.yOffset + innerSection.height),
);
const maxRowCount = configuredMaxRowCount === null ? null : Math.max(configuredMaxRowCount, contentRowCount);
return (
<SectionProvider
value={{
section,
items,
innerSections,
integrations,
columnCount,
maxRowCount,
announce,
}}
>
<SectionContentItem item={entry} integrations={integrations} />
</SectionProvider>
);
};
const toGridSection = (
section: Section | undefined,
layoutId: string,
): Exclude<Section, { kind: "dynamic" }> | DynamicSectionItem | null => {
if (!section) return null;
if (section.kind !== "dynamic") return section;
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
if (!layout) return null;
return {
...section,
...layout,
type: "section",
};
};
const getOwnerSectionId = (board: ReturnType<typeof useRequiredBoard>, layoutId: string, entryId: string) => {
const item = board.items.find((candidate) => candidate.id === entryId);
if (item) {
return item.layouts.find((layout) => layout.layoutId === layoutId)?.sectionId ?? null;
}
const section = board.sections.find((candidate) => candidate.kind === "dynamic" && candidate.id === entryId);
if (!section || section.kind !== "dynamic") return null;
return section.layouts.find((layout) => layout.layoutId === layoutId)?.parentSectionId ?? null;
};
@@ -0,0 +1,16 @@
export const decorateGridResizeHandles = (element: Element) => {
for (const handle of element.querySelectorAll<HTMLElement>(".ui-resizable-handle")) {
const direction = Array.from(handle.classList).find((className) =>
/^ui-resizable-(?:n|ne|e|se|s|sw|w|nw)$/.test(className),
);
if (!direction) continue;
const directionName = direction.replace("ui-resizable-", "");
handle.setAttribute(
"data-testid",
directionName === "se" ? "board-grid-resize-handle" : `board-grid-resize-handle-${directionName}`,
);
handle.setAttribute("data-grid-resize-direction", directionName);
handle.setAttribute("aria-hidden", "true");
}
};
@@ -0,0 +1,77 @@
.viewport {
position: relative;
overflow: visible;
}
.staticGrid,
.editorGrid {
position: relative;
overflow: visible;
}
.editorGrid {
position: absolute;
inset: 0 auto auto 0;
}
.editorGrid:not(:global(.grid-stack-editing)) {
visibility: hidden;
}
.staticItem {
overflow: visible;
transition:
left 220ms ease,
top 220ms ease,
width 220ms ease,
height 220ms ease;
}
.editorEntry {
width: 100%;
height: 100%;
overflow: visible;
cursor: grab;
}
.editorEntry:active {
cursor: grabbing;
}
.editorEntry:focus-visible,
.editorEntry[data-keyboard-editing="true"] {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: 2px;
border-radius: var(--mantine-radius-md);
}
.editorLoading {
position: absolute;
inset: 0;
z-index: 20;
overflow: hidden;
}
.editorLoadingItem {
background-color: var(--mantine-color-default);
border: 1px solid var(--mantine-color-default-border);
border-radius: var(--mantine-radius-md);
}
.liveRegion {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
@media (prefers-reduced-motion: reduce) {
.staticItem {
transition: none;
}
}
@@ -0,0 +1,241 @@
"use client";
import { useMemo } from "react";
import dynamic from "next/dynamic";
import { Box, LoadingOverlay } from "@mantine/core";
import combineClasses from "clsx";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useI18n } from "@homarr/translation/client";
import type { DynamicSectionItem, Section } from "~/app/[locale]/boards/_types";
import {
getCollapsedDisplayLayout,
getEditableCanvasAttributes,
getLayoutRowCount,
getLogicalItemStyle,
getLogicalTrackSize,
getReadonlyCanvasAttributes,
normalizeGridPlacement,
} from "~/components/board/layout";
import { loadGridEditorAsync } from "./grid-editor-loader";
import type { SectionGridPlacement } from "./use-grid-layout-actions";
import { SectionContent } from "../content";
import { useCollapsedSectionIds } from "../section-collapse";
import { SectionProvider, useSectionContext } from "../section-context";
import { useSectionItems } from "../use-section-items";
import { useBoardGridPortalHost } from "./grid-portal-host";
import classes from "./section-grid.module.css";
const GridEditor = dynamic(loadGridEditorAsync, {
loading: GridEditorLoading,
ssr: false,
});
function GridEditorLoading() {
const t = useI18n();
const { items, innerSections } = useSectionContext();
return (
<Box
component="output"
className={classes.editorLoading}
data-testid="board-grid-editor-loading"
aria-label={t("common.action.loading")}
>
{[...items, ...innerSections].map((item) => (
<Box
key={item.id}
className={classes.editorLoadingItem}
style={getLogicalItemStyle({
x: item.xOffset,
y: item.yOffset,
w: item.width,
h: item.height,
})}
aria-hidden="true"
/>
))}
<LoadingOverlay visible />
</Box>
);
}
interface SectionGridProps {
section: Exclude<Section, { kind: "dynamic" }> | DynamicSectionItem;
columnCount: number;
requestedRowCount?: number;
label: string;
railPlacement?: "main" | "left" | "right";
className?: string;
}
export const SectionGrid = ({
section,
columnCount,
requestedRowCount = 0,
label,
railPlacement = "main",
className,
}: SectionGridProps) => {
const [isEditMode] = useEditMode();
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { items, innerSections } = useSectionItems(section.id);
const { announce, integrations } = useBoardGridPortalHost();
const collapsedSectionIds = useCollapsedSectionIds();
const minimumBySectionId = useMemo(
() =>
new Map(
innerSections.map((innerSection) => [
innerSection.id,
getDynamicSectionMinimumSize(board, currentLayoutId, innerSection.id),
]),
),
[board, currentLayoutId, innerSections],
);
const placements = useMemo(
() =>
[...items, ...innerSections].map((item): SectionGridPlacement => {
const minimum = item.type === "section" ? minimumBySectionId.get(item.id) : undefined;
return normalizeGridPlacement(
{
id: item.id,
type: item.type,
x: item.xOffset,
y: item.yOffset,
w: item.width,
h: item.height,
minW: minimum?.width,
minH: minimum?.height,
},
columnCount,
);
}),
[columnCount, innerSections, items, minimumBySectionId],
);
const displayPlacements = useMemo(() => {
const directCollapsedIds = new Set(
placements
.filter(
(placement) =>
placement.type === "section" &&
collapsedSectionIds.has(placement.id) &&
innerSections.find((innerSection) => innerSection.id === placement.id)?.options.collapsible,
)
.map((placement) => placement.id),
);
if (directCollapsedIds.size === 0) return placements;
return getCollapsedDisplayLayout(placements, {
columnCount,
collapsedItemIds: directCollapsedIds,
});
}, [collapsedSectionIds, columnCount, innerSections, placements]);
const placementById = useMemo(
() => new Map(displayPlacements.map((placement) => [placement.id, placement])),
[displayPlacements],
);
const displayedItems = items.map((item) => withPlacement(item, placementById.get(item.id)));
const displayedInnerSections = innerSections.map((item) => withPlacement(item, placementById.get(item.id)));
const contentRowCount = Math.max(1, getLayoutRowCount(displayPlacements));
const rowCount = Math.max(contentRowCount, requestedRowCount);
const fixedRowCount = section.kind === "dynamic";
const logicalWidth = getLogicalTrackSize(columnCount);
const logicalHeight = getLogicalTrackSize(rowCount);
const canvasAttributes = isEditMode
? getEditableCanvasAttributes({ label, columnCount, rowCount })
: getReadonlyCanvasAttributes({ label });
return (
<SectionProvider
value={{
section,
items: displayedItems,
innerSections: displayedInnerSections,
integrations,
columnCount,
maxRowCount: fixedRowCount ? rowCount : null,
announce,
}}
>
<Box
{...canvasAttributes}
className={combineClasses(classes.viewport, className)}
w={logicalWidth}
h={`var(--board-grid-drag-height, ${logicalHeight}px)`}
data-section-id={section.id}
data-section-kind={section.kind}
data-rail-placement={railPlacement}
>
{isEditMode ? (
<GridEditor
sectionId={section.id}
columnCount={columnCount}
rowCount={rowCount}
fixedRowCount={fixedRowCount}
placements={displayPlacements}
className={combineClasses("grid-stack", classes.editorGrid)}
/>
) : (
<Box
className={classes.staticGrid}
style={{ width: logicalWidth, height: logicalHeight }}
data-grid-section-id={section.id}
data-kind={section.kind}
>
<SectionContent />
</Box>
)}
</Box>
</SectionProvider>
);
};
const getDynamicSectionMinimumSize = (
board: ReturnType<typeof useRequiredBoard>,
layoutId: string,
sectionId: string,
) => {
const directItems = board.items.flatMap((item) => {
const layout = item.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.sectionId === sectionId ? [layout] : [];
});
const directSections = board.sections.flatMap((candidate) => {
if (candidate.kind !== "dynamic") return [];
const layout = candidate.layouts.find((candidateLayout) => candidateLayout.layoutId === layoutId);
return layout?.parentSectionId === sectionId ? [layout] : [];
});
const children = [...directItems, ...directSections];
return {
width: Math.max(1, ...children.map((child) => child.xOffset + child.width)),
height: Math.max(1, ...children.map((child) => child.yOffset + child.height)),
};
};
const withPlacement = <
TItem extends {
id: string;
xOffset: number;
yOffset: number;
width: number;
height: number;
},
>(
item: TItem,
placement: SectionGridPlacement | undefined,
): TItem => {
if (!placement) return item;
return {
...item,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
};
};
@@ -0,0 +1,254 @@
import { act, createElement } from "react";
import type { ReactNode } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { getCollapsedDisplayLayout, LOGICAL_GRID_CELL_SIZE } from "../../../layout";
import { FixedGridItem } from "../fixed-grid-item";
const mocks = vi.hoisted(() => ({
announce: vi.fn(),
commitSectionGrid: vi.fn(),
editMode: true,
maxRowCount: null as number | null,
items: [
{
id: "weather",
type: "item" as const,
kind: "weather" as const,
xOffset: 0,
yOffset: 0,
width: 1,
height: 1,
advancedOptions: {
title: null as string | null,
},
},
{
id: "clock",
type: "item" as const,
kind: "clock" as const,
xOffset: 1,
yOffset: 0,
width: 1,
height: 1,
advancedOptions: {
title: null as string | null,
},
},
],
}));
vi.mock("@homarr/boards/edit-mode", () => ({
useEditMode: () => [mocks.editMode],
}));
vi.mock("@homarr/boards/context", () => ({
useCurrentLayout: () => "layout",
}));
vi.mock("@homarr/translation/client", () => ({
useI18n: () => (key: string, values?: Record<string, string>) =>
key === "item.moveResize.entryLabel" ? `${values?.name}, column ${values?.column}, row ${values?.row}` : key,
}));
vi.mock("../use-grid-layout-actions", () => ({
useGridLayoutActions: () => ({
commitSectionGrid: mocks.commitSectionGrid,
}),
}));
vi.mock("../../section-context", () => ({
useSectionContext: () => ({
section: { id: "root", kind: "empty", options: {} },
items: mocks.items,
innerSections: [],
columnCount: 3,
maxRowCount: mocks.maxRowCount,
announce: mocks.announce,
}),
}));
vi.mock("@mantine/core", async () => {
const React = await import("react");
return {
Box: ({ children, ...props }: { children?: ReactNode }) => React.createElement("div", props, children),
};
});
describe("fixed grid item behavior", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
mocks.announce.mockReset();
mocks.commitSectionGrid.mockReset();
mocks.editMode = true;
mocks.maxRowCount = null;
getWeatherMock().advancedOptions.title = null;
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
test("moves with the keyboard and deterministically pushes a collision down", () => {
renderWeather(root);
const entry = getEditorEntry(container);
startKeyboardEditing(entry);
act(() => entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
expect(mocks.commitSectionGrid).toHaveBeenCalledWith({
layoutId: "layout",
sectionId: "root",
placements: [
{ id: "weather", type: "item", x: 1, y: 0, w: 1, h: 1 },
{ id: "clock", type: "item", x: 1, y: 1, w: 1, h: 1 },
],
});
expect(mocks.announce).toHaveBeenCalledTimes(2);
});
test("uses shift plus an arrow to resize while honoring grid bounds", () => {
renderWeather(root);
const entry = getEditorEntry(container);
startKeyboardEditing(entry);
act(() =>
entry.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowRight",
shiftKey: true,
bubbles: true,
}),
),
);
expect(mocks.commitSectionGrid).toHaveBeenCalledWith({
layoutId: "layout",
sectionId: "root",
placements: [
{ id: "weather", type: "item", x: 0, y: 0, w: 2, h: 1 },
{ id: "clock", type: "item", x: 1, y: 1, w: 1, h: 1 },
],
});
mocks.commitSectionGrid.mockReset();
act(() =>
entry.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowLeft",
shiftKey: true,
bubbles: true,
}),
),
);
expect(mocks.commitSectionGrid).not.toHaveBeenCalled();
expect(mocks.announce).toHaveBeenLastCalledWith(
"widget.weather.name, column 1, row 1: item.moveResize.keyboard.boundary",
);
});
test("uses the whole tile as the focusable move surface without a grab button", () => {
getWeatherMock().advancedOptions.title = " Balcony forecast ";
renderWeather(root);
const entry = getEditorEntry(container);
expect(entry.getAttribute("aria-label")).toBe("Balcony forecast, column 1, row 1");
expect(entry.tabIndex).toBe(0);
expect(entry.getAttribute("aria-describedby")).not.toBeNull();
expect(container.querySelector('[data-testid="board-grid-drag-handle"]')).toBeNull();
});
test("renders a view-only 1x1 card at the fixed 200px logical size", () => {
mocks.editMode = false;
renderWeather(root);
const item = container.querySelector<HTMLElement>('[data-grid-id="weather"]');
expect(item).not.toBeNull();
expect(item?.style.width).toBe(`${LOGICAL_GRID_CELL_SIZE}px`);
expect(item?.style.height).toBe(`${LOGICAL_GRID_CELL_SIZE}px`);
expect(item?.getAttribute("role")).toBeNull();
act(() => item?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
expect(mocks.commitSectionGrid).not.toHaveBeenCalled();
});
test("does not move or resize beyond a fixed section row boundary", () => {
mocks.maxRowCount = 1;
renderWeather(root);
const entry = getEditorEntry(container);
startKeyboardEditing(entry);
act(() => entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
act(() => entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", shiftKey: true, bubbles: true })));
expect(mocks.commitSectionGrid).not.toHaveBeenCalled();
expect(mocks.announce).toHaveBeenNthCalledWith(
2,
"widget.weather.name, column 1, row 1: item.moveResize.keyboard.boundary",
);
expect(mocks.announce).toHaveBeenNthCalledWith(
3,
"widget.weather.name, column 1, row 1: item.moveResize.keyboard.boundary",
);
});
test("collapsing an expanded box changes display geometry without mutating persisted placement", () => {
const persisted = [
{ id: "box", type: "section" as const, x: 0, y: 0, w: 2, h: 4 },
{ id: "app", type: "item" as const, x: 0, y: 4, w: 1, h: 1 },
];
const displayed = getCollapsedDisplayLayout(persisted, {
columnCount: 2,
collapsedItemIds: new Set(["box"]),
});
expect(displayed).toEqual([
{ ...persisted[0], h: 1 },
{ ...persisted[1], y: 1 },
]);
expect(persisted[0]?.h).toBe(4);
expect(persisted[1]?.y).toBe(4);
});
});
const renderWeather = (root: Root) => {
act(() => {
root.render(
createElement(
FixedGridItem,
{
item: getWeatherMock() as never,
},
createElement("span", null, "Weather"),
),
);
});
};
const getWeatherMock = () => {
const item = mocks.items[0];
if (!item) throw new Error("Expected the weather item mock to exist");
return item;
};
const getEditorEntry = (container: HTMLElement) => {
const entry = container.querySelector<HTMLDivElement>("[data-editor-grid-entry]");
if (!entry) throw new Error("Expected the fixed grid item to render an editor entry");
return entry;
};
const startKeyboardEditing = (entry: HTMLDivElement) => {
act(() => entry.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
};
@@ -0,0 +1,106 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { scheduleGridEditorWarmup } from "../grid-editor-loader";
describe("grid editor warm-up", () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
document.body.replaceChildren();
});
test("waits for board hydration, a paint, and browser idle time", async () => {
let animationFrameCallback: FrameRequestCallback | undefined;
let idleCallback: IdleRequestCallback | undefined;
vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
animationFrameCallback = callback;
return 1;
});
vi.stubGlobal("requestIdleCallback", (callback: IdleRequestCallback) => {
idleCallback = callback;
return 2;
});
vi.stubGlobal("cancelIdleCallback", vi.fn());
const loadAsync = vi.fn().mockResolvedValue(undefined);
const cancel = scheduleGridEditorWarmup(loadAsync);
expect(animationFrameCallback).toBeUndefined();
const canvas = document.createElement("section");
canvas.dataset.boardHydrated = "true";
document.body.append(canvas);
await vi.waitFor(() => expect(animationFrameCallback).toBeDefined());
expect(loadAsync).not.toHaveBeenCalled();
animationFrameCallback?.(0);
expect(idleCallback).toBeDefined();
expect(loadAsync).not.toHaveBeenCalled();
idleCallback?.({
didTimeout: false,
timeRemaining: () => 10,
});
expect(loadAsync).toHaveBeenCalledOnce();
cancel();
});
test("does not load after cancellation", () => {
let idleCallback: IdleRequestCallback | undefined;
vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
callback(0);
return 1;
});
vi.stubGlobal("requestIdleCallback", (callback: IdleRequestCallback) => {
idleCallback = callback;
return 2;
});
vi.stubGlobal("cancelIdleCallback", vi.fn());
document.body.innerHTML = '<section data-board-hydrated="true"></section>';
const loadAsync = vi.fn().mockResolvedValue(undefined);
const cancel = scheduleGridEditorWarmup(loadAsync);
cancel();
idleCallback?.({ didTimeout: false, timeRemaining: () => 10 });
expect(loadAsync).not.toHaveBeenCalled();
});
test("falls back to a timeout when requestIdleCallback is unavailable", async () => {
vi.useFakeTimers();
const requestIdleCallbackDescriptor = Object.getOwnPropertyDescriptor(window, "requestIdleCallback");
Reflect.deleteProperty(window, "requestIdleCallback");
vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
callback(0);
return 1;
});
document.body.innerHTML = '<section data-board-hydrated="true"></section>';
const loadAsync = vi.fn().mockResolvedValue(undefined);
const cancel = scheduleGridEditorWarmup(loadAsync);
await vi.advanceTimersByTimeAsync(1_000);
expect(loadAsync).toHaveBeenCalledOnce();
cancel();
vi.useRealTimers();
if (requestIdleCallbackDescriptor) {
Object.defineProperty(window, "requestIdleCallback", requestIdleCallbackDescriptor);
}
});
test("waits until the document becomes visible", () => {
let visibilityState: DocumentVisibilityState = "hidden";
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibilityState);
const animationFrame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const loadAsync = vi.fn().mockResolvedValue(undefined);
document.body.innerHTML = '<section data-board-hydrated="true"></section>';
const cancel = scheduleGridEditorWarmup(loadAsync);
expect(animationFrame).not.toHaveBeenCalled();
visibilityState = "visible";
document.dispatchEvent(new Event("visibilitychange"));
expect(animationFrame).toHaveBeenCalledOnce();
cancel();
});
});
@@ -0,0 +1,236 @@
import { readdirSync, readFileSync } from "node:fs";
import { relative, resolve } from "node:path";
import ts from "typescript";
import { describe, expect, test } from "vitest";
const gridDirectory = resolve(import.meta.dirname, "..");
const nextjsSourceDirectory = resolve(gridDirectory, "../../../../");
const sectionGridPath = resolve(gridDirectory, "section-grid.tsx");
const editorLoaderPath = resolve(gridDirectory, "grid-editor-loader.ts");
describe("board grid import boundary", () => {
test("keeps every GridStack runtime import inside the edit-only module", () => {
const runtimeImports = getSourceFiles(nextjsSourceDirectory)
.flatMap(getRuntimeImports)
.filter(({ specifier }) => specifier === "gridstack" || specifier.startsWith("gridstack/"))
.map(({ filePath, kind, specifier }) => ({
file: toSourceRelativePath(filePath),
kind,
specifier,
}))
.toSorted((first, second) =>
`${first.file}:${first.specifier}:${first.kind}`.localeCompare(
`${second.file}:${second.specifier}:${second.kind}`,
),
);
expect(runtimeImports).toEqual([
{
file: "components/board/sections/grid/grid-editor.tsx",
kind: "static",
specifier: "gridstack",
},
{
file: "components/board/sections/grid/grid-editor.tsx",
kind: "static",
specifier: "gridstack/dist/gridstack.min.css",
},
]);
});
test("loads the editor through next/dynamic only in the edit branch", () => {
const sourceFile = parseSourceFile(sectionGridPath);
const dynamicImport = sourceFile.statements.find(
(statement): statement is ts.ImportDeclaration =>
ts.isImportDeclaration(statement) &&
ts.isStringLiteral(statement.moduleSpecifier) &&
statement.moduleSpecifier.text === "next/dynamic",
);
expect(dynamicImport?.importClause?.name?.text).toBe("dynamic");
const gridEditorDeclaration = findNode(
sourceFile,
(node): node is ts.VariableDeclaration =>
ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === "GridEditor",
);
expect(gridEditorDeclaration).toBeDefined();
expect(gridEditorDeclaration?.initializer && ts.isCallExpression(gridEditorDeclaration.initializer)).toBe(true);
const dynamicCall = gridEditorDeclaration?.initializer;
if (!dynamicCall || !ts.isCallExpression(dynamicCall)) {
throw new Error("GridEditor must be initialized with next/dynamic");
}
expect(ts.isIdentifier(dynamicCall.expression) && dynamicCall.expression.text === "dynamic").toBe(true);
expect(
dynamicCall.arguments.some((argument) => ts.isIdentifier(argument) && argument.text === "loadGridEditorAsync"),
).toBe(true);
expect(dynamicCall.arguments.some(hasDisabledSsrOption)).toBe(true);
expect(dynamicCall.arguments.some(hasEditorLoadingOption)).toBe(true);
expect(getRuntimeImports(sectionGridPath).filter(({ specifier }) => specifier === "./grid-editor")).toEqual([]);
expect(
getRuntimeImports(editorLoaderPath)
.filter(({ specifier }) => specifier === "./grid-editor")
.map(({ kind }) => kind),
).toEqual(["dynamic"]);
const usages = findNodes(
sourceFile,
(node): node is ts.JsxSelfClosingElement =>
ts.isJsxSelfClosingElement(node) && ts.isIdentifier(node.tagName) && node.tagName.text === "GridEditor",
);
expect(usages).toHaveLength(1);
const gridEditorUsage = usages[0];
if (!gridEditorUsage) {
throw new Error("GridEditor must be rendered once");
}
const editConditional = findAncestor(gridEditorUsage, ts.isConditionalExpression);
expect(
editConditional !== undefined &&
ts.isIdentifier(editConditional.condition) &&
editConditional.condition.text === "isEditMode" &&
isDescendantOf(gridEditorUsage, editConditional.whenTrue),
).toBe(true);
});
});
interface RuntimeImport {
filePath: string;
kind: "dynamic" | "require" | "static";
specifier: string;
}
const getSourceFiles = (directory: string): string[] =>
readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const path = resolve(directory, entry.name);
if (entry.isDirectory()) return getSourceFiles(path);
return /\.[cm]?[jt]sx?$/.test(entry.name) ? [path] : [];
});
const getRuntimeImports = (filePath: string): RuntimeImport[] => {
const sourceFile = parseSourceFile(filePath);
const imports: RuntimeImport[] = [];
const visit = (node: ts.Node) => {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && isRuntimeImportDeclaration(node)) {
imports.push({ filePath, kind: "static", specifier: node.moduleSpecifier.text });
} else if (
ts.isExportDeclaration(node) &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier) &&
isRuntimeExportDeclaration(node)
) {
imports.push({ filePath, kind: "static", specifier: node.moduleSpecifier.text });
} else if (
ts.isCallExpression(node) &&
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
(ts.isIdentifier(node.expression) && node.expression.text === "require"))
) {
const [argument] = node.arguments;
if (node.arguments.length === 1 && argument && ts.isStringLiteral(argument)) {
imports.push({
filePath,
kind: node.expression.kind === ts.SyntaxKind.ImportKeyword ? "dynamic" : "require",
specifier: argument.text,
});
}
} else if (
ts.isImportEqualsDeclaration(node) &&
!node.isTypeOnly &&
ts.isExternalModuleReference(node.moduleReference) &&
node.moduleReference.expression &&
ts.isStringLiteral(node.moduleReference.expression)
) {
imports.push({ filePath, kind: "static", specifier: node.moduleReference.expression.text });
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
return imports;
};
const isRuntimeImportDeclaration = (declaration: ts.ImportDeclaration) => {
const clause = declaration.importClause;
if (!clause) return true;
if (clause.isTypeOnly) return false;
if (clause.name) return true;
if (!clause.namedBindings || ts.isNamespaceImport(clause.namedBindings)) return true;
if (clause.namedBindings.elements.length === 0) return true;
return clause.namedBindings.elements.some((element) => !element.isTypeOnly);
};
const isRuntimeExportDeclaration = (declaration: ts.ExportDeclaration) => {
if (declaration.isTypeOnly) return false;
if (!declaration.exportClause || ts.isNamespaceExport(declaration.exportClause)) return true;
if (declaration.exportClause.elements.length === 0) return true;
return declaration.exportClause.elements.some((element) => !element.isTypeOnly);
};
const parseSourceFile = (filePath: string) =>
ts.createSourceFile(filePath, readFileSync(filePath, "utf8"), ts.ScriptTarget.Latest, true, getScriptKind(filePath));
const getScriptKind = (filePath: string) => {
if (filePath.endsWith(".tsx")) return ts.ScriptKind.TSX;
if (filePath.endsWith(".jsx")) return ts.ScriptKind.JSX;
if (filePath.endsWith(".js") || filePath.endsWith(".mjs") || filePath.endsWith(".cjs")) return ts.ScriptKind.JS;
return ts.ScriptKind.TS;
};
const hasDisabledSsrOption = (node: ts.Node) => {
if (!ts.isObjectLiteralExpression(node)) return false;
return node.properties.some(
(property) =>
ts.isPropertyAssignment(property) &&
ts.isIdentifier(property.name) &&
property.name.text === "ssr" &&
property.initializer.kind === ts.SyntaxKind.FalseKeyword,
);
};
const hasEditorLoadingOption = (node: ts.Node) => {
if (!ts.isObjectLiteralExpression(node)) return false;
return node.properties.some(
(property) =>
ts.isPropertyAssignment(property) &&
ts.isIdentifier(property.name) &&
property.name.text === "loading" &&
ts.isIdentifier(property.initializer) &&
property.initializer.text === "GridEditorLoading",
);
};
const findNode = <TNode extends ts.Node>(
root: ts.Node,
predicate: (node: ts.Node) => node is TNode,
): TNode | undefined => findNodes(root, predicate)[0];
const findNodes = <TNode extends ts.Node>(root: ts.Node, predicate: (node: ts.Node) => node is TNode) => {
const matches: TNode[] = [];
const visit = (node: ts.Node) => {
if (predicate(node)) matches.push(node);
ts.forEachChild(node, visit);
};
visit(root);
return matches;
};
const findAncestor = <TNode extends ts.Node>(
node: ts.Node,
predicate: (candidate: ts.Node) => candidate is TNode,
): TNode | undefined => {
let current = node.parent;
while (current) {
if (predicate(current)) return current;
current = current.parent;
}
return undefined;
};
const isDescendantOf = (node: ts.Node, ancestor: ts.Node) => node.pos >= ancestor.pos && node.end <= ancestor.end;
const toSourceRelativePath = (filePath: string) => relative(nextjsSourceDirectory, filePath).replaceAll("\\", "/");
@@ -0,0 +1,24 @@
import { describe, expect, test } from "vitest";
import { decorateGridResizeHandles } from "../grid-resize-handles";
describe("grid resize handle decoration", () => {
test("restores accessible hit-target markers after GridStack refreshes its handles", () => {
const item = document.createElement("div");
item.innerHTML = `
<div class="ui-resizable-handle ui-resizable-e"></div>
<div class="ui-resizable-handle ui-resizable-se"></div>
`;
decorateGridResizeHandles(item);
const east = item.querySelector<HTMLElement>(".ui-resizable-e");
const southeast = item.querySelector<HTMLElement>(".ui-resizable-se");
expect(east?.dataset.testid).toBe("board-grid-resize-handle-e");
expect(east?.dataset.gridResizeDirection).toBe("e");
expect(east?.getAttribute("aria-hidden")).toBe("true");
expect(southeast?.dataset.testid).toBe("board-grid-resize-handle");
expect(southeast?.dataset.gridResizeDirection).toBe("se");
expect(southeast?.getAttribute("aria-hidden")).toBe("true");
});
});
@@ -0,0 +1,92 @@
"use client";
import { useCallback } from "react";
import { useUpdateBoard } from "@homarr/boards/updater";
import type { GridPlacement } from "~/components/board/layout";
export interface SectionGridPlacement extends GridPlacement {
type: "item" | "section";
minW?: number;
minH?: number;
}
export interface CommitSectionGridInput {
layoutId: string;
sectionId: string;
placements: readonly SectionGridPlacement[];
}
/**
* Commits a complete section snapshot in one cache update. GridStack can move
* several neighbours for one gesture, so persisting only the active item would
* lose its collision result.
*/
export const useGridLayoutActions = () => {
const { updateBoard } = useUpdateBoard();
const commitSectionGrids = useCallback(
(snapshots: readonly CommitSectionGridInput[]) => {
const byId = new Map(
snapshots.flatMap(({ layoutId, sectionId, placements }) =>
placements.map((placement) => [`${layoutId}:${placement.id}`, { layoutId, sectionId, placement }] as const),
),
);
updateBoard((previous) => {
return {
...previous,
items: previous.items.map((item) => {
const layouts = item.layouts.map((layout) => {
const resolved = byId.get(`${layout.layoutId}:${item.id}`);
if (!resolved || resolved.placement.type !== "item") return layout;
const { placement, sectionId } = resolved;
return {
...layout,
sectionId,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
};
});
return layouts.some((layout, index) => layout !== item.layouts[index]) ? { ...item, layouts } : item;
}),
sections: previous.sections.map((innerSection) => {
if (innerSection.kind !== "dynamic") return innerSection;
const layouts = innerSection.layouts.map((layout) => {
const resolved = byId.get(`${layout.layoutId}:${innerSection.id}`);
if (!resolved || resolved.placement.type !== "section") return layout;
const { placement, sectionId } = resolved;
return {
...layout,
parentSectionId: sectionId,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
};
});
return layouts.some((layout, index) => layout !== innerSection.layouts[index])
? { ...innerSection, layouts }
: innerSection;
}),
};
});
},
[updateBoard],
);
const commitSectionGrid = useCallback(
(snapshot: CommitSectionGridInput) => {
commitSectionGrids([snapshot]);
},
[commitSectionGrids],
);
return { commitSectionGrid, commitSectionGrids };
};