feat: rebuild board grid experience

This commit is contained in:
ajnart committed 2026-08-14 11:07:06 +02:00
1 parent e41d938a5f
commit d6b114e423
121 files changed
+7384 -2292

No files matched your search

@@ -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");
});
});