merge: stack auto mobile boards

This commit is contained in:
Thomas Camlong committed 2026-08-08 20:59:56 +02:00
commit a039049084
1155 files changed
+110206 -33634

No files matched your search

@@ -1,65 +0,0 @@
import { Card, Collapse, Group, Stack, Title, UnstyledButton } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconChevronDown, IconChevronUp } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useRequiredBoard } from "@homarr/boards/context";
import type { CategorySection } from "~/app/[locale]/boards/_types";
import { CategoryMenu } from "./category/category-menu";
import { GridStack } from "./gridstack/gridstack";
import classes from "./item.module.css";
const localStorageKey = (sectionId: string) => `homarr-section-collapsed-${sectionId}`;
interface Props {
section: CategorySection;
}
export const BoardCategorySection = ({ section }: Props) => {
const { status } = useSession();
const { mutate } = clientApi.section.changeCollapsed.useMutation();
const board = useRequiredBoard();
const initialCollapsed =
typeof window !== "undefined"
? (localStorage.getItem(localStorageKey(section.id)) ?? String(section.collapsed)) === "true"
: section.collapsed;
const [opened, { toggle }] = useDisclosure(initialCollapsed, {
onOpen() {
if (status === "authenticated") {
mutate({ sectionId: section.id, collapsed: true });
} else if (status === "unauthenticated") {
localStorage.setItem(localStorageKey(section.id), "true");
}
},
onClose() {
if (status === "authenticated") {
mutate({ sectionId: section.id, collapsed: false });
} else if (status === "unauthenticated") {
localStorage.setItem(localStorageKey(section.id), "false");
}
},
});
return (
<Card style={{ "--opacity": board.opacity / 100 }} radius={board.itemRadius} p={0} className={classes.itemCard}>
<Stack>
<Group wrap="nowrap" gap="sm">
<UnstyledButton w="100%" p="sm" onClick={toggle}>
<Group wrap="nowrap">
{opened ? <IconChevronUp size={20} /> : <IconChevronDown size={20} />}
<Title order={3}>{section.name}</Title>
</Group>
</UnstyledButton>
<CategoryMenu category={section} />
</Group>
<Collapse expanded={opened} p="sm" pt={0}>
<GridStack section={section} />
</Collapse>
</Stack>
</Card>
);
};
@@ -1,54 +0,0 @@
import type { RouterOutputs } from "@homarr/api";
import type { CategorySection } from "~/app/[locale]/boards/_types";
export interface MoveCategoryInput {
id: string;
direction: "up" | "down";
}
export const moveCategoryCallback =
(input: MoveCategoryInput) =>
(previous: RouterOutputs["board"]["getHomeBoard"]): RouterOutputs["board"]["getHomeBoard"] => {
const currentCategory = previous.sections.find(
(section): section is CategorySection => section.kind === "category" && section.id === input.id,
);
if (!currentCategory) {
return previous;
}
if (currentCategory.yOffset === 1 && input.direction === "up") {
return previous;
}
if (currentCategory.yOffset === previous.sections.length - 2 && input.direction === "down") {
return previous;
}
return {
...previous,
sections: previous.sections.map((section) => {
if (section.kind !== "category" && section.kind !== "empty") {
return section;
}
const offset = input.direction === "up" ? -2 : 2;
// Move category and empty section
if (section.yOffset === currentCategory.yOffset || section.yOffset === currentCategory.yOffset + 1) {
return {
...section,
yOffset: section.yOffset + offset,
};
}
if (
section.yOffset === currentCategory.yOffset + offset ||
section.yOffset === currentCategory.yOffset + offset + 1
) {
return {
...section,
yOffset: section.yOffset - offset,
};
}
return section;
}),
};
};
@@ -1,150 +0,0 @@
import { getBoardLayouts } from "@homarr/boards/context";
import type { Board, CategorySection, EmptySection, Section } from "~/app/[locale]/boards/_types";
export interface RemoveCategoryInput {
id: string;
}
export const removeCategoryCallback =
(input: RemoveCategoryInput) =>
(previous: Board): Board => {
const currentCategory = previous.sections.find(
(section): section is CategorySection => section.kind === "category" && section.id === input.id,
);
if (!currentCategory) {
return previous;
}
const emptySectionsAbove = previous.sections.filter(
(section): section is EmptySection => section.kind === "empty" && section.yOffset < currentCategory.yOffset,
);
const aboveSection = emptySectionsAbove.sort((sectionA, sectionB) => sectionB.yOffset - sectionA.yOffset).at(0);
const emptySectionsBelow = previous.sections.filter(
(section): section is EmptySection => section.kind === "empty" && section.yOffset > currentCategory.yOffset,
);
const removedSection = emptySectionsBelow.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset).at(0);
if (!aboveSection || !removedSection) {
return previous;
}
const aboveYOffsets = getBoardLayouts(previous).map((layoutId) => {
return {
layoutId,
yOffset: Math.max(
calculateYHeightWithOffsetForItemLayouts(previous, { sectionId: aboveSection.id, layoutId }),
calculateYHeightWithOffsetForDynamicSectionLayouts(previous.sections, {
sectionId: aboveSection.id,
layoutId,
}),
),
};
});
const categoryYOffsets = getBoardLayouts(previous).map((layoutId) => {
return {
layoutId,
yOffset: Math.max(
calculateYHeightWithOffsetForItemLayouts(previous, { sectionId: currentCategory.id, layoutId }),
calculateYHeightWithOffsetForDynamicSectionLayouts(previous.sections, {
sectionId: currentCategory.id,
layoutId,
}),
),
};
});
return {
...previous,
sections: previous.sections
.filter((section) => section.id !== currentCategory.id && section.id !== removedSection.id)
.map((section) =>
section.kind === "dynamic"
? {
...section,
layouts: section.layouts.map((layout) => {
const aboveYOffset = aboveYOffsets.find(({ layoutId }) => layout.layoutId === layoutId)?.yOffset ?? 0;
const categoryYOffset =
categoryYOffsets.find(({ layoutId }) => layout.layoutId === layoutId)?.yOffset ?? 0;
if (layout.parentSectionId === currentCategory.id) {
return {
...layout,
yOffset: layout.yOffset + aboveYOffset,
parentSectionId: aboveSection.id,
};
}
if (layout.parentSectionId === removedSection.id) {
return {
...layout,
yOffset: layout.yOffset + aboveYOffset + categoryYOffset,
parentSectionId: aboveSection.id,
};
}
return layout;
}),
}
: section,
),
items: previous.items.map((item) => ({
...item,
layouts: item.layouts.map((layout) => {
const aboveYOffset = aboveYOffsets.find(({ layoutId }) => layout.layoutId === layoutId)?.yOffset ?? 0;
const categoryYOffset = categoryYOffsets.find(({ layoutId }) => layout.layoutId === layoutId)?.yOffset ?? 0;
if (layout.sectionId === currentCategory.id) {
return {
...layout,
yOffset: layout.yOffset + aboveYOffset,
sectionId: aboveSection.id,
};
}
if (layout.sectionId === removedSection.id) {
return {
...layout,
yOffset: layout.yOffset + aboveYOffset + categoryYOffset,
sectionId: aboveSection.id,
};
}
return layout;
}),
})),
};
};
const calculateYHeightWithOffsetForDynamicSectionLayouts = (
sections: Section[],
{ sectionId, layoutId }: { sectionId: string; layoutId: string },
) => {
return sections
.filter((section) => section.kind === "dynamic")
.map((section) => section.layouts.find((layout) => layout.layoutId === layoutId))
.filter((layout) => layout !== undefined)
.filter((layout) => layout.parentSectionId === sectionId)
.reduce((acc, layout) => {
const yHeightWithOffset = layout.yOffset + layout.height;
if (yHeightWithOffset > acc) return yHeightWithOffset;
return acc;
}, 0);
};
const calculateYHeightWithOffsetForItemLayouts = (
board: Board,
{ sectionId, layoutId }: { sectionId: string; layoutId: string },
) =>
board.items
.map((item) => item.layouts.find((layout) => layout.layoutId === layoutId))
.filter((layout) => layout !== undefined)
.filter((layout) => layout.sectionId === sectionId)
.reduce((acc, layout) => {
const yHeightWithOffset = layout.yOffset + layout.height;
if (yHeightWithOffset > acc) return yHeightWithOffset;
return acc;
}, 0);
@@ -1,79 +0,0 @@
import { describe, expect, test } from "vitest";
import type { Section } from "~/app/[locale]/boards/_types";
import { moveCategoryCallback } from "../move-category";
describe("Move Category", () => {
test.each([
[3, [0, 3, 4, 1, 2, 5, 6]],
[5, [0, 1, 2, 5, 6, 3, 4]],
])("should move category up", (moveId, expectedOrder) => {
const sections = createSections(3);
const input = {
id: moveId.toString(),
direction: "up" as const,
};
const result = moveCategoryCallback(input)({ sections } as never);
expect(sortSections(result.sections).map((section) => parseInt(section.id, 10))).toEqual(expectedOrder);
});
test.each([
[1, [0, 3, 4, 1, 2, 5, 6]],
[3, [0, 1, 2, 5, 6, 3, 4]],
])("should move category down", (moveId, expectedOrder) => {
const sections = createSections(3);
const input = {
id: moveId.toString(),
direction: "down" as const,
};
const result = moveCategoryCallback(input)({ sections } as never);
expect(sortSections(result.sections).map((section) => parseInt(section.id, 10))).toEqual(expectedOrder);
});
test("should not move category up if it is at the top", () => {
const sections = createSections(3);
const input = {
id: "1",
direction: "up" as const,
};
const result = moveCategoryCallback(input)({ sections } as never);
expect(sortSections(result.sections).map((section) => parseInt(section.id, 10))).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
test("should not move category down if it is at the bottom", () => {
const sections = createSections(3);
const input = {
id: "5",
direction: "down" as const,
};
const result = moveCategoryCallback(input)({ sections } as never);
expect(sortSections(result.sections).map((section) => parseInt(section.id, 10))).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
});
const createSections = (categoryCount: number) => {
return Array.from({ length: categoryCount * 2 + 1 }, (_, index) => ({
id: index.toString(),
kind: index % 2 === 1 ? ("category" as const) : ("empty" as const),
name: `Category ${index}`,
yOffset: index,
xOffset: 0,
collapsed: false,
items: [],
})) satisfies Section[];
};
const sortSections = (sections: Section[]) => {
return sections
.filter((section) => section.kind !== "dynamic")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
};
@@ -1,145 +0,0 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
import type { DynamicSection, Section } from "~/app/[locale]/boards/_types";
import { BoardMockBuilder } from "~/components/board/items/actions/test/mocks/board-mock";
import { CategorySectionMockBuilder } from "~/components/board/items/actions/test/mocks/category-section-mock";
import { DynamicSectionMockBuilder } from "~/components/board/items/actions/test/mocks/dynamic-section-mock";
import { EmptySectionMockBuilder } from "~/components/board/items/actions/test/mocks/empty-section-mock";
import { ItemMockBuilder } from "~/components/board/items/actions/test/mocks/item-mock";
import { removeCategoryCallback } from "../remove-category";
describe("Remove Category", () => {
test.each([
[3, [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 5, 6], [3, 4], 2],
[5, [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4], [5, 6], 4],
[1, [0, 1, 2, 3, 4, 5, 6], [0, 3, 4, 5, 6], [1, 2], 0],
[3, [0, 3, 6, 7, 8], [0, 7, 8], [3, 6], 0],
])(
"should remove category",
(removeId, initialYOffsets, expectedYOffsets, expectedRemovals, expectedLocationOfItems) => {
// Arrange
const layoutId = "1";
const input = removeId.toString();
const board = new BoardMockBuilder()
.addLayout({ id: layoutId })
.addSections(createSections(initialYOffsets))
.addItems(createSectionItems(initialYOffsets, layoutId))
.build();
vi.spyOn(boardContext, "getBoardLayouts").mockReturnValue([layoutId]);
// Act
const result = removeCategoryCallback({ id: input })(board);
// Assert
expect(result.sections.map((section) => parseInt(section.id, 10))).toEqual(expectedYOffsets);
expectedRemovals.forEach((expectedRemoval) => {
expect(result.sections.find((section) => section.id === expectedRemoval.toString())).toBeUndefined();
});
const aboveSectionItems = result.items.filter(
(item) => item.layouts[0]?.sectionId === expectedLocationOfItems.toString(),
);
expect(aboveSectionItems.map((item) => parseInt(item.id, 10))).toEqual(expect.arrayContaining(expectedRemovals));
},
);
test("should correctly move items to above empty section", () => {
// Arrange
const layoutId = "1";
const sectionIds = {
above: "2",
category: "3",
below: "4",
dynamic: "7",
};
const initialYOffsets = [0, 1, 2, 3, 4, 5, 6];
const board = new BoardMockBuilder()
.addLayout({ id: layoutId })
.addSections(createSections(initialYOffsets))
.addItems(createSectionItems([0, 1, 5, 6], layoutId)) // Only add items to other sections
.addDynamicSection(
new DynamicSectionMockBuilder({ id: sectionIds.dynamic })
.addLayout({ layoutId, parentSectionId: sectionIds.category, yOffset: 7, height: 3 })
.build(),
)
.addItem(new ItemMockBuilder({ id: "above-1" }).addLayout({ layoutId, sectionId: sectionIds.above }).build())
.addItem(
new ItemMockBuilder({ id: "above-2" })
.addLayout({ layoutId, sectionId: sectionIds.above, yOffset: 3, xOffset: 2, height: 2 })
.build(),
)
.addItem(
new ItemMockBuilder({ id: "category-1" }).addLayout({ layoutId, sectionId: sectionIds.category }).build(),
)
.addItem(
new ItemMockBuilder({ id: "category-2" })
.addLayout({ layoutId, sectionId: sectionIds.category, yOffset: 2, xOffset: 4, width: 4 })
.build(),
)
.addItem(
new ItemMockBuilder({ id: "below-1" }).addLayout({ layoutId, sectionId: sectionIds.below, xOffset: 5 }).build(),
)
.addItem(
new ItemMockBuilder({ id: "below-2" })
.addLayout({ layoutId, sectionId: sectionIds.below, yOffset: 1, xOffset: 1, height: 2 })
.build(),
)
.addItem(new ItemMockBuilder({ id: "dynamic-1" }).addLayout({ layoutId, sectionId: sectionIds.dynamic }).build())
.build();
vi.spyOn(boardContext, "getBoardLayouts").mockReturnValue([layoutId]);
// Act
const result = removeCategoryCallback({ id: sectionIds.category })(board);
// Assert
expect(result.sections.map((section) => parseInt(section.id, 10))).toEqual([0, 1, 2, 5, 6, 7]);
const aboveSectionItems = result.items.filter((item) => item.layouts[0]?.sectionId === sectionIds.above);
expect(aboveSectionItems.length).toBe(6);
expect(
aboveSectionItems
.map((item) => ({
...item,
...item.layouts[0]!,
}))
.sort((itemA, itemB) => itemA.yOffset - itemB.yOffset),
).toEqual([
expect.objectContaining({ id: "above-1", yOffset: 0, xOffset: 0 }),
expect.objectContaining({ id: "above-2", yOffset: 3, xOffset: 2, height: 2 }),
expect.objectContaining({ id: "category-1", yOffset: 5, xOffset: 0 }),
expect.objectContaining({ id: "category-2", yOffset: 7, xOffset: 4, width: 4 }),
expect.objectContaining({ id: "below-1", yOffset: 15, xOffset: 5 }),
expect.objectContaining({ id: "below-2", yOffset: 16, xOffset: 1, height: 2 }),
]);
const dynamicSection = result.sections.find((section): section is DynamicSection => section.id === "7")!;
expect(dynamicSection.layouts.at(0)?.yOffset).toBe(12);
expect(dynamicSection.layouts[0]?.parentSectionId).toBe("2");
});
});
const createSections = (initialYOffsets: number[]) => {
return initialYOffsets.map((yOffset, index) =>
index % 2 === 0
? new EmptySectionMockBuilder({
id: yOffset.toString(),
yOffset,
}).build()
: new CategorySectionMockBuilder({
id: yOffset.toString(),
yOffset,
}).build(),
) satisfies Section[];
};
const createSectionItems = (initialYOffsets: number[], layoutId: string) => {
return initialYOffsets.map((yOffset) =>
new ItemMockBuilder({ id: yOffset.toString() }).addLayout({ layoutId, sectionId: yOffset.toString() }).build(),
);
};
@@ -1,145 +0,0 @@
import { useCallback } from "react";
import { useUpdateBoard } from "@homarr/boards/updater";
import { createId } from "@homarr/common";
import type { CategorySection, EmptySection, Section } from "~/app/[locale]/boards/_types";
import type { MoveCategoryInput } from "./actions/move-category";
import { moveCategoryCallback } from "./actions/move-category";
import type { RemoveCategoryInput } from "./actions/remove-category";
import { removeCategoryCallback } from "./actions/remove-category";
interface AddCategory {
name: string;
yOffset: number;
}
interface RenameCategory {
id: string;
name: string;
}
export const useCategoryActions = () => {
const { updateBoard } = useUpdateBoard();
const addCategory = useCallback(
({ name, yOffset }: AddCategory) => {
if (yOffset <= -1) {
return;
}
updateBoard((previous) => ({
...previous,
sections: [
// Place sections before the new category
...previous.sections.filter(
(section) => (section.kind === "category" || section.kind === "empty") && section.yOffset < yOffset,
),
{
id: createId(),
name,
kind: "category",
yOffset,
xOffset: 0,
collapsed: false,
},
{
id: createId(),
kind: "empty",
yOffset: yOffset + 1,
xOffset: 0,
},
// Place sections after the new category
...previous.sections
.filter(
(section): section is CategorySection | EmptySection =>
(section.kind === "category" || section.kind === "empty") && section.yOffset >= yOffset,
)
.map((section) => ({
...section,
yOffset: section.yOffset + 2,
})),
...previous.sections.filter((section) => section.kind !== "category" && section.kind !== "empty"),
] satisfies Section[],
}));
},
[updateBoard],
);
const addCategoryToEnd = useCallback(
({ name }: { name: string }) => {
updateBoard((previous) => {
const lastSection = previous.sections
.filter(
(section): section is CategorySection | EmptySection =>
section.kind === "empty" || section.kind === "category",
)
.sort((sectionA, sectionB) => sectionB.yOffset - sectionA.yOffset)
.at(0);
if (!lastSection) return previous;
const lastYOffset = lastSection.yOffset;
return {
...previous,
sections: [
...previous.sections,
{
id: createId(),
name,
kind: "category",
yOffset: lastYOffset + 1,
xOffset: 0,
collapsed: false,
},
{
id: createId(),
kind: "empty",
yOffset: lastYOffset + 2,
xOffset: 0,
},
] satisfies Section[],
};
});
},
[updateBoard],
);
const renameCategory = useCallback(
({ id: categoryId, name }: RenameCategory) => {
updateBoard((previous) => ({
...previous,
sections: previous.sections.map((section) => {
if (section.kind !== "category") return section;
if (section.id !== categoryId) return section;
return {
...section,
name,
};
}),
}));
},
[updateBoard],
);
const moveCategory = useCallback(
(input: MoveCategoryInput) => {
updateBoard(moveCategoryCallback(input));
},
[updateBoard],
);
const removeCategory = useCallback(
(input: RemoveCategoryInput) => {
updateBoard(removeCategoryCallback(input));
},
[updateBoard],
);
return {
addCategory,
addCategoryToEnd,
renameCategory,
moveCategory,
removeCategory,
};
};
@@ -1,45 +0,0 @@
import { Stack, TextInput } from "@mantine/core";
import { z } from "zod/v4";
import { useZodForm } from "@homarr/form";
import { createModal, ModalFormFooter, modalSizeForm } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
interface Category {
id: string;
name: string;
}
interface InnerProps {
submitLabel: string;
category: Category;
onSuccess: (category: Category) => void;
}
export const CategoryEditModal = createModal<InnerProps>(({ actions, innerProps }) => {
const t = useI18n();
const form = useZodForm(z.object({ name: z.string().min(1) }), {
initialValues: {
name: innerProps.category.name,
},
});
return (
<form
onSubmit={form.onSubmit((values) => {
void innerProps.onSuccess({
...innerProps.category,
name: values.name,
});
actions.closeModal();
})}
>
<Stack>
<TextInput label={t("section.category.field.name.label")} data-autofocus {...form.getInputProps("name")} />
<ModalFormFooter onCancel={actions.closeModal} submitLabel={innerProps.submitLabel} />
</Stack>
</form>
);
}).withOptions({
size: modalSizeForm,
});
@@ -1,146 +0,0 @@
import { useCallback } from "react";
import { fetchApi } from "@homarr/api/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import type { CategorySection } from "~/app/[locale]/boards/_types";
import { useCategoryActions } from "./category-actions";
import { CategoryEditModal } from "./category-edit-modal";
import { filterByItemKind } from "./filter";
export const useCategoryMenuActions = (category: CategorySection) => {
const { openModal } = useModalAction(CategoryEditModal);
const { openConfirmModal } = useConfirmModal();
const { addCategory, moveCategory, removeCategory, renameCategory } = useCategoryActions();
const t = useI18n();
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const createCategoryAtYOffset = useCallback(
(position: number) => {
openModal(
{
category: {
id: createId(),
name: t("section.category.create.title"),
},
onSuccess: (category) => {
addCategory({
name: category.name,
yOffset: position,
});
},
submitLabel: t("section.category.create.submit"),
},
{
title: (t) => t("section.category.create.title"),
},
);
},
[addCategory, t, openModal],
);
// creates a new category above the current
const addCategoryAbove = useCallback(() => {
const aboveYOffset = category.yOffset;
createCategoryAtYOffset(aboveYOffset);
}, [category.yOffset, createCategoryAtYOffset]);
// creates a new category below the current
const addCategoryBelow = useCallback(() => {
const belowYOffset = category.yOffset + 2;
createCategoryAtYOffset(belowYOffset);
}, [category.yOffset, createCategoryAtYOffset]);
const moveCategoryUp = useCallback(() => {
moveCategory({
id: category.id,
direction: "up",
});
}, [category.id, moveCategory]);
const moveCategoryDown = useCallback(() => {
moveCategory({
id: category.id,
direction: "down",
});
}, [category.id, moveCategory]);
// Removes the current category
const remove = useCallback(() => {
openConfirmModal({
title: t("section.category.remove.title"),
children: t("section.category.remove.message", {
name: category.name,
}),
onConfirm: () => {
removeCategory({
id: category.id,
});
},
});
}, [category.id, category.name, removeCategory, t, openConfirmModal]);
const edit = useCallback(() => {
openModal(
{
category,
submitLabel: t("section.category.edit.submit"),
onSuccess: (category) => {
renameCategory({
id: category.id,
name: category.name,
});
},
},
{
title: (t) => t("section.category.edit.title"),
},
);
}, [category, openModal, renameCategory, t]);
const settings = useSettings();
const openAllInNewTabs = useCallback(async () => {
const appIds = (
await filterByItemKind(
board.items.filter(
(item) => item.layouts.find((layout) => layout.layoutId === currentLayoutId)?.sectionId === category.id,
),
settings,
"app",
)
).map((item) => {
return item.options.appId;
});
const apps = await fetchApi.app.byIds.query(appIds);
const appsWithUrls = apps.filter((app) => app.href && app.href.length > 0);
for (const app of appsWithUrls) {
const openedWindow = window.open(app.href ?? undefined);
if (openedWindow) {
continue;
}
openConfirmModal({
title: t("section.category.openAllInNewTabs.title"),
children: t("section.category.openAllInNewTabs.text"),
});
break;
}
}, [category, board, currentLayoutId, t, openConfirmModal, settings]);
return {
addCategoryAbove,
addCategoryBelow,
moveCategoryUp,
moveCategoryDown,
remove,
edit,
openAllInNewTabs,
};
};
@@ -1,128 +0,0 @@
"use client";
import React, { useMemo } from "react";
import { ActionIcon, Menu } from "@mantine/core";
import {
IconDotsVertical,
IconEdit,
IconExternalLink,
IconRowInsertBottom,
IconRowInsertTop,
IconTransitionBottom,
IconTransitionTop,
IconTrash,
} from "@tabler/icons-react";
import { useEditMode } from "@homarr/boards/edit-mode";
import type { MaybePromise } from "@homarr/common/types";
import { useScopedI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
import type { CategorySection } from "~/app/[locale]/boards/_types";
import { useCategoryMenuActions } from "./category-menu-actions";
interface Props {
category: CategorySection;
}
export const CategoryMenu = ({ category }: Props) => {
const actions = useActions(category);
const t = useScopedI18n("section.category");
return (
<Menu>
<Menu.Target>
<ActionIcon mr="sm" variant="transparent" aria-label={t("menu.label.settings")}>
<IconDotsVertical size={20} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
{actions.map((action) => {
return (
<React.Fragment key={action.label}>
{"group" in action && <Menu.Label>{t(action.group)}</Menu.Label>}
<Menu.Item
leftSection={<action.icon size="1rem" />}
onClick={action.onClick}
color={"color" in action ? action.color : undefined}
>
{t(action.label)}
</Menu.Item>
</React.Fragment>
);
})}
</Menu.Dropdown>
</Menu>
);
};
const useActions = (category: CategorySection) => {
const [isEditMode] = useEditMode();
const editModeActions = useEditModeActions(category);
const nonEditModeActions = useNonEditModeActions(category);
return useMemo(
() => (isEditMode ? editModeActions : nonEditModeActions),
[isEditMode, editModeActions, nonEditModeActions],
);
};
const useEditModeActions = (category: CategorySection) => {
const { addCategoryAbove, addCategoryBelow, moveCategoryUp, moveCategoryDown, edit, remove } =
useCategoryMenuActions(category);
return [
{
icon: IconEdit,
label: "action.edit",
onClick: edit,
},
{
icon: IconTrash,
color: "red",
label: "action.remove",
onClick: remove,
},
{
group: "menu.label.changePosition",
icon: IconTransitionTop,
label: "action.moveUp",
onClick: moveCategoryUp,
},
{
icon: IconTransitionBottom,
label: "action.moveDown",
onClick: moveCategoryDown,
},
{
group: "menu.label.create",
icon: IconRowInsertTop,
label: "action.createAbove",
onClick: addCategoryAbove,
},
{
icon: IconRowInsertBottom,
label: "action.createBelow",
onClick: addCategoryBelow,
},
] as const satisfies ActionDefinition[];
};
const useNonEditModeActions = (category: CategorySection) => {
const { openAllInNewTabs } = useCategoryMenuActions(category);
return [
{
icon: IconExternalLink,
label: "action.openAllInNewTabs",
onClick: openAllInNewTabs,
},
] as const satisfies ActionDefinition[];
};
interface ActionDefinition {
icon: TablerIcon;
label: string;
onClick: () => MaybePromise<void>;
color?: string;
group?: string;
}
@@ -1,25 +0,0 @@
import type { WidgetKind } from "@homarr/definitions";
import type { SettingsContextProps } from "@homarr/settings/creator";
import type { WidgetComponentProps } from "@homarr/widgets/definition";
import { loadWidgetDefinition, reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import type { Item } from "~/app/[locale]/boards/_types";
export const filterByItemKind = async <TKind extends WidgetKind>(
items: Item[],
settings: SettingsContextProps,
kind: TKind,
) => {
const definition = await loadWidgetDefinition(kind);
return items
.filter((item) => item.kind === kind)
.map((item) => ({
...item,
options: reduceWidgetOptionsWithDefinition(
definition,
settings,
item.options,
) as WidgetComponentProps<TKind>["options"],
}));
};
@@ -0,0 +1,175 @@
import dynamic from "next/dynamic";
import { ActionIcon, Badge, Box, Button, Card } from "@mantine/core";
import { IconChevronDown, IconChevronUp, IconExternalLink, IconGripVertical } from "@tabler/icons-react";
import combineClasses from "clsx";
import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { ContainerSectionItem } from "~/app/[locale]/boards/_types";
import { SectionGrid } from "./grid/section-grid";
import { useSectionCollapse } from "./section-collapse";
import { useOpenSectionApps } from "./use-open-section-apps";
import classes from "./item.module.css";
const BoardContainerMenu = dynamic(
() => import("./container/container-menu").then((module) => module.BoardContainerMenu),
{ ssr: false },
);
interface Props {
section: ContainerSectionItem;
}
export const BoardContainerSection = ({ section }: Props) => {
const board = useRequiredBoard();
const [isEditMode] = useEditMode();
const t = useScopedI18n("section.container");
const tAll = useI18n();
const options = section.options;
const { open: openAllInNewTabs, isLoading: areAppsLoading } = useOpenSectionApps(
section.id,
options.showOpenAll && !isEditMode,
);
const { isVisuallyCollapsed, toggle } = useSectionCollapse({
sectionId: section.id,
collapsible: options.collapsible,
});
const label = options.title.trim() || t("untitled");
const contentId = `board-container-${section.id}-content`;
const labelLeft = isEditMode ? 40 : 8;
const labelRight = isEditMode ? 48 : options.showOpenAll ? 40 : 8;
return (
<Box className="board-grid-item-content" data-grid-item-content w="100%" h="100%" style={{ overflow: "visible" }}>
<Card
className={combineClasses(
classes.itemCard,
options.customCssClasses.join(" "),
isVisuallyCollapsed && classes.collapsedContainerCard,
)}
w="100%"
h="100%"
data-board-container-collapsed={isVisuallyCollapsed ? "true" : "false"}
styles={{
root: {
overflow: "visible",
"--opacity": board.opacity / 100,
"--border-color": options.borderColor || undefined,
},
}}
radius={board.itemRadius}
p={0}
>
{options.collapsible && !isEditMode && (
<Button
className={classes.containerToggle}
pos="absolute"
top={isVisuallyCollapsed ? 0 : -24}
left={0}
w="100%"
h={isVisuallyCollapsed ? "100%" : 24}
px={12}
pe={options.showOpenAll ? 40 : 12}
radius="sm"
variant="default"
justify={options.showLabel ? "flex-start" : "center"}
leftSection={
options.showLabel ? (
isVisuallyCollapsed ? (
<IconChevronDown size={16} />
) : (
<IconChevronUp size={16} />
)
) : undefined
}
onClick={toggle}
aria-expanded={!isVisuallyCollapsed}
aria-controls={contentId}
aria-label={`${t(isVisuallyCollapsed ? "action.expand" : "action.collapse")}: ${label}`}
data-board-container-collapsed-control={isVisuallyCollapsed ? "true" : undefined}
data-board-container-label
title={options.showLabel ? label : undefined}
>
{options.showLabel ? (
label
) : isVisuallyCollapsed ? (
<IconChevronDown size={16} />
) : (
<IconChevronUp size={16} />
)}
</Button>
)}
{isEditMode && (
<ActionIcon
component="span"
pos="absolute"
top={4}
left={4}
style={{ zIndex: 10, cursor: "grab", touchAction: "none" }}
variant="default"
size={24}
radius="sm"
data-grid-container-drag-handle
aria-hidden="true"
>
<IconGripVertical size={16} />
</ActionIcon>
)}
{!isVisuallyCollapsed && (!options.collapsible || isEditMode) && options.showLabel && options.title && (
<Badge
pos="absolute"
top={-24}
left={labelLeft}
maw={`calc(100% - ${labelLeft + labelRight}px)`}
size="md"
radius="sm"
variant="default"
c="var(--mantine-color-text)"
style={{
zIndex: 9,
overflow: "hidden",
pointerEvents: "none",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
backgroundColor: "var(--background-color)",
borderColor: "var(--border-color)",
}}
title={options.title}
data-board-container-label
>
{options.title}
</Badge>
)}
{options.showOpenAll && !isEditMode && (
<ActionIcon
pos="absolute"
top={isVisuallyCollapsed ? "50%" : -24}
right={8}
style={{ zIndex: 10, transform: isVisuallyCollapsed ? "translateY(-50%)" : undefined }}
variant={options.collapsible ? "subtle" : "default"}
size={24}
radius="sm"
loading={areAppsLoading}
onClick={openAllInNewTabs}
aria-label={tAll("section.action.openAllInNewTabsFor", { name: label })}
>
<IconExternalLink size={16} />
</ActionIcon>
)}
<Box
id={contentId}
className={classes.containerBody}
h="100%"
data-collapsed={isVisuallyCollapsed ? "true" : "false"}
aria-hidden={isVisuallyCollapsed}
inert={isVisuallyCollapsed}
>
<SectionGrid section={section} columnCount={section.width} requestedRowCount={section.height} label={label} />
</Box>
</Card>
{isEditMode && <BoardContainerMenu section={section} />}
</Box>
);
};
@@ -0,0 +1,61 @@
import { getBoardLayouts } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import { getRootSectionLane } from "@homarr/definitions";
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
import type { Board, ContainerSection, ContainerSectionLayout, EmptySection } from "~/app/[locale]/boards/_types";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { getFirstEmptyPosition } from "~/components/board/items/actions/empty-position";
import { getSectionElements } from "~/components/board/items/actions/section-elements";
export const addContainerCallback = () => (board: Board) => {
const firstSection = board.sections
.filter(
(section): section is EmptySection => section.kind === "empty" && getRootSectionLane(section.xOffset) === "main",
)
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) return board;
const sectionLayouts = createContainerLayouts(board, firstSection);
const newSection = {
id: createId(),
kind: "container",
collapsed: false,
options: containerSectionOptionsSchema.parse(undefined),
layouts: sectionLayouts,
} satisfies ContainerSection;
return {
...board,
sections: board.sections.concat(newSection),
};
};
const createContainerLayouts = (board: Board, currentSection: EmptySection): ContainerSectionLayout[] => {
const layouts = getBoardLayouts(board);
return layouts.map((layoutId) => {
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
const columnCount = boardLayout ? getBoardLaneColumnCount(boardLayout, "main") : 1;
const size = {
width: Math.min(4, columnCount),
height: 3,
};
const emptyPosition = boardLayout
? getFirstEmptyPosition(elements, columnCount, undefined, size)
: { xOffset: 0, yOffset: 0 };
if (!emptyPosition) throw new Error("Your board is full");
return {
...size,
...emptyPosition,
parentSectionId: currentSection.id,
layoutId,
};
});
};
@@ -0,0 +1,185 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
import type { ContainerSection } from "~/app/[locale]/boards/_types";
import * as emptyPositionModule from "~/components/board/items/actions/empty-position";
import { BoardMockBuilder } from "~/components/board/items/actions/test/mocks/board-mock";
import { ContainerSectionMockBuilder } from "~/components/board/items/actions/test/mocks/container-section-mock";
import { ItemMockBuilder } from "~/components/board/items/actions/test/mocks/item-mock";
import { addContainerCallback } from "./add-container";
import { removeContainerCallback } from "./remove-container";
describe("container actions", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("creates a container in the first main root for every responsive layout", () => {
const board = new BoardMockBuilder().addEmptySection({ id: "root", yOffset: 0 }).build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 2;
vi.spyOn(boardContext, "getBoardLayouts").mockReturnValue([layout.id]);
vi.spyOn(emptyPositionModule, "getFirstEmptyPosition").mockReturnValue({ xOffset: 0, yOffset: 4 });
const result = addContainerCallback()(board);
const created = result.sections.find((section) => section.kind === "container");
expect(created).toMatchObject({
kind: "container",
collapsed: false,
options: {
showLabel: true,
collapsible: false,
showOpenAll: false,
},
layouts: [
{
layoutId: "layout",
parentSectionId: "root",
xOffset: 0,
yOffset: 4,
width: 2,
height: 3,
},
],
});
});
test("removes a container and flattens its direct children into the parent", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "layout", parentSectionId: "root", xOffset: 3, yOffset: 4, width: 6, height: 5 })
.build();
const child = new ContainerSectionMockBuilder({ id: "child" })
.addLayout({ layoutId: "layout", parentSectionId: removed.id, xOffset: 1, yOffset: 2, width: 2, height: 2 })
.build();
const nestedItem = new ItemMockBuilder({ id: "nested-item" })
.addLayout({ layoutId: "layout", sectionId: removed.id, xOffset: 2, yOffset: 1, width: 1, height: 1 })
.build();
const board = new BoardMockBuilder()
.addEmptySection({ id: "root" })
.addSection(removed)
.addSection(child)
.addItem(nestedItem)
.build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
const result = removeContainerCallback({ id: removed.id })(board);
const flattenedChild = result.sections.find(
(section): section is ContainerSection => section.kind === "container" && section.id === child.id,
);
expect(result.sections.some((section) => section.id === removed.id)).toBe(false);
expect(flattenedChild?.layouts[0]).toMatchObject({
parentSectionId: "root",
xOffset: 4,
yOffset: 6,
});
expect(result.items.find((item) => item.id === nestedItem.id)?.layouts[0]).toMatchObject({
sectionId: "root",
xOffset: 5,
yOffset: 5,
});
});
test("normalizes, pins the top-left child, and resolves collisions while flattening malformed geometry", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "layout", parentSectionId: "root", xOffset: 2, yOffset: 0, width: 2, height: 2 })
.build();
const existing = new ItemMockBuilder({ id: "existing" })
.addLayout({ layoutId: "layout", sectionId: "root", xOffset: 0, yOffset: 0, width: 2, height: 1 })
.build();
const childA = new ItemMockBuilder({ id: "a" })
.addLayout({ layoutId: "layout", sectionId: removed.id, xOffset: 1, yOffset: 0, width: 2, height: 1 })
.build();
const childB = new ItemMockBuilder({ id: "b" })
.addLayout({ layoutId: "layout", sectionId: removed.id, xOffset: 0, yOffset: 0, width: 2, height: 1 })
.build();
const board = new BoardMockBuilder()
.addEmptySection({ id: "root" })
.addSection(removed)
.addItems([existing, childA, childB])
.build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 4;
const result = removeContainerCallback({ id: removed.id })(board);
const layouts = Object.fromEntries(
result.items.map((item) => {
const itemLayout = item.layouts[0];
if (!itemLayout) throw new Error("Expected an item layout");
return [item.id, itemLayout];
}),
);
expect(layouts.existing).toMatchObject({ xOffset: 0, yOffset: 0, width: 2, height: 1 });
expect(layouts.a).toMatchObject({ sectionId: "root", xOffset: 2, yOffset: 1, width: 2, height: 1 });
expect(layouts.b).toMatchObject({ sectionId: "root", xOffset: 2, yOffset: 0, width: 2, height: 1 });
});
test("keeps the container when a child container has layout geometry that cannot be flattened", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "other-layout", parentSectionId: "root", xOffset: 3, yOffset: 4 })
.build();
const child = new ContainerSectionMockBuilder({ id: "child" })
.addLayout({ layoutId: "layout", parentSectionId: removed.id, xOffset: 1, yOffset: 2 })
.build();
const board = new BoardMockBuilder().addSection(removed).addSection(child).build();
const result = removeContainerCallback({ id: removed.id })(board);
expect(result).toBe(board);
expect(result.sections).toContainEqual(removed);
});
test("keeps the container when a child item has layout geometry that cannot be flattened", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "other-layout", parentSectionId: "root", xOffset: 3, yOffset: 4 })
.build();
const item = new ItemMockBuilder({ id: "item" })
.addLayout({ layoutId: "layout", sectionId: removed.id, xOffset: 2, yOffset: 1 })
.build();
const board = new BoardMockBuilder().addSection(removed).addItem(item).build();
const result = removeContainerCallback({ id: removed.id })(board);
expect(result).toBe(board);
expect(result.sections).toContainEqual(removed);
});
test("keeps the container when flattening would move a child back into the removed container", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "layout", parentSectionId: "removed", xOffset: 3, yOffset: 4 })
.build();
const item = new ItemMockBuilder({ id: "item" })
.addLayout({ layoutId: "layout", sectionId: removed.id, xOffset: 2, yOffset: 1 })
.build();
const board = new BoardMockBuilder().addSection(removed).addItem(item).build();
const result = removeContainerCallback({ id: removed.id })(board);
expect(result).toBe(board);
expect(result.sections).toContainEqual(removed);
});
test("keeps the container when its destination is a child container", () => {
const removed = new ContainerSectionMockBuilder({ id: "removed" })
.addLayout({ layoutId: "layout", parentSectionId: "child", xOffset: 3, yOffset: 4 })
.build();
const child = new ContainerSectionMockBuilder({ id: "child" })
.addLayout({ layoutId: "layout", parentSectionId: removed.id, xOffset: 1, yOffset: 2 })
.build();
const board = new BoardMockBuilder().addSection(removed).addSection(child).build();
const result = removeContainerCallback({ id: removed.id })(board);
expect(result).toBe(board);
expect(result.sections).toContainEqual(removed);
});
});
@@ -0,0 +1,181 @@
import type { Board, ContainerSection } from "~/app/[locale]/boards/_types";
import { resolvePinnedGridCollisions } from "~/components/board/sections/grid/dnd";
import {
getSectionGridColumnCount,
getSectionGridPlacements,
} from "~/components/board/sections/grid/section-grid-placements";
import type { SectionGridPlacement } from "~/components/board/sections/grid/use-grid-layout-actions";
export interface RemoveContainerInput {
id: string;
}
export const removeContainerCallback =
({ id }: RemoveContainerInput) =>
(board: Board): Board => {
const sectionToRemove = board.sections.find(
(section): section is ContainerSection => section.id === id && section.kind === "container",
);
if (!sectionToRemove) return board;
const removedLayoutsById = new Map(sectionToRemove.layouts.map((layout) => [layout.layoutId, layout]));
const childLayoutIds = [
...board.sections.flatMap((section) =>
section.kind === "container"
? section.layouts.flatMap((layout) =>
layout.parentSectionId === sectionToRemove.id ? [layout.layoutId] : [],
)
: [],
),
...board.items.flatMap((item) =>
item.layouts.flatMap((layout) => (layout.sectionId === sectionToRemove.id ? [layout.layoutId] : [])),
),
];
const hasUnresolvableChildLayout = childLayoutIds.some((layoutId) => {
const removedLayout = removedLayoutsById.get(layoutId);
return (
!removedLayout || !isValidFlattenDestination(board, sectionToRemove.id, layoutId, removedLayout.parentSectionId)
);
});
if (hasUnresolvableChildLayout) return board;
const flattened = {
...board,
sections: board.sections
.filter((section) => section.id !== id)
.map((section) => {
if (section.kind !== "container") return section;
return {
...section,
layouts: section.layouts.map((layout) => {
if (layout.parentSectionId !== sectionToRemove.id) return layout;
const removedSectionLayout = sectionToRemove.layouts.find(
(layoutToRemove) => layoutToRemove.layoutId === layout.layoutId,
);
if (!removedSectionLayout) return layout;
return {
...layout,
xOffset: layout.xOffset + removedSectionLayout.xOffset,
yOffset: layout.yOffset + removedSectionLayout.yOffset,
parentSectionId: removedSectionLayout.parentSectionId,
};
}),
};
}),
items: board.items.map((item) => ({
...item,
layouts: item.layouts.map((layout) => {
if (layout.sectionId !== sectionToRemove.id) return layout;
const removedSectionLayout = sectionToRemove.layouts.find(
(layoutToRemove) => layoutToRemove.layoutId === layout.layoutId,
);
if (!removedSectionLayout) return layout;
return {
...layout,
xOffset: layout.xOffset + removedSectionLayout.xOffset,
yOffset: layout.yOffset + removedSectionLayout.yOffset,
sectionId: removedSectionLayout.parentSectionId,
};
}),
})),
};
return resolveFlattenedLayouts(flattened, sectionToRemove, board);
};
const isValidFlattenDestination = (
board: Board,
removedSectionId: string,
layoutId: string,
destinationSectionId: string,
) => {
const visited = new Set<string>();
let sectionId = destinationSectionId;
while (true) {
if (sectionId === removedSectionId || visited.has(sectionId)) return false;
visited.add(sectionId);
const section = board.sections.find((candidate) => candidate.id === sectionId);
if (!section) return false;
if (section.kind !== "container") return true;
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
if (!layout) return false;
sectionId = layout.parentSectionId;
}
};
const resolveFlattenedLayouts = (board: Board, removed: ContainerSection, original: Board): Board => {
const resolvedByLayoutAndId = new Map<string, SectionGridPlacement>();
for (const removedLayout of removed.layouts) {
const movedIds = [
...original.items.flatMap((item) => {
const layout = item.layouts.find((candidate) => candidate.layoutId === removedLayout.layoutId);
return layout?.sectionId === removed.id ? [item.id] : [];
}),
...original.sections.flatMap((section) => {
if (section.kind !== "container") return [];
const layout = section.layouts.find((candidate) => candidate.layoutId === removedLayout.layoutId);
return layout?.parentSectionId === removed.id ? [section.id] : [];
}),
];
const columnCount = getSectionGridColumnCount(board, removedLayout.layoutId, removedLayout.parentSectionId);
if (!columnCount) continue;
const placements = getSectionGridPlacements(board, removedLayout.layoutId, removedLayout.parentSectionId);
const movedIdSet = new Set(movedIds);
const pinned = placements
.filter((placement) => movedIdSet.has(placement.id))
.toSorted((first, second) => first.y - second.y || first.x - second.x || first.id.localeCompare(second.id))[0];
if (!pinned) continue;
for (const placement of resolvePinnedGridCollisions(placements, pinned, columnCount)) {
resolvedByLayoutAndId.set(`${removedLayout.layoutId}:${placement.id}`, placement);
}
}
if (resolvedByLayoutAndId.size === 0) return board;
return {
...board,
items: board.items.map((item) => ({
...item,
layouts: item.layouts.map((layout) => {
const placement = resolvedByLayoutAndId.get(`${layout.layoutId}:${item.id}`);
return placement?.type === "item"
? {
...layout,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
}
: layout;
}),
})),
sections: board.sections.map((section) =>
section.kind !== "container"
? section
: {
...section,
layouts: section.layouts.map((layout) => {
const placement = resolvedByLayoutAndId.get(`${layout.layoutId}:${section.id}`);
return placement?.type === "section"
? {
...layout,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
}
: layout;
}),
},
),
};
};
@@ -0,0 +1,42 @@
import { useCallback } from "react";
import { useUpdateBoard } from "@homarr/boards/updater";
import type { ContainerSectionOptions } from "@homarr/validation/shared";
import { addContainerCallback } from "./actions/add-container";
import type { RemoveContainerInput } from "./actions/remove-container";
import { removeContainerCallback } from "./actions/remove-container";
interface UpdateContainerOptions {
containerId: string;
newOptions: ContainerSectionOptions;
}
export const useContainerActions = () => {
const { updateBoard } = useUpdateBoard();
const addContainer = useCallback(() => {
updateBoard(addContainerCallback());
}, [updateBoard]);
const updateContainer = useCallback(
({ containerId, newOptions }: UpdateContainerOptions) => {
updateBoard((previous) => ({
...previous,
sections: previous.sections.map((item) =>
item.id !== containerId || item.kind !== "container" ? item : { ...item, options: newOptions },
),
}));
},
[updateBoard],
);
const removeContainer = useCallback(
(input: RemoveContainerInput) => {
updateBoard(removeContainerCallback(input));
},
[updateBoard],
);
return { addContainer, updateContainer, removeContainer };
};
@@ -0,0 +1,74 @@
"use client";
import { CloseButton, ColorInput, Stack, Switch, TextInput, useMantineTheme } from "@mantine/core";
import type { z } from "zod/v4";
import { useZodForm } from "@homarr/form";
import { createModal, ModalFormFooter, modalSizeForm } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
import { TextMultiSelect } from "@homarr/ui";
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
interface ModalProps {
value: z.infer<typeof containerSectionOptionsSchema>;
onSuccessfulEdit: (value: z.infer<typeof containerSectionOptionsSchema>) => void;
}
export const ContainerEditModal = createModal<ModalProps>(({ actions, innerProps }) => {
const t = useI18n();
const theme = useMantineTheme();
const form = useZodForm(containerSectionOptionsSchema.unwrap(), {
mode: "controlled",
initialValues: { ...innerProps.value },
});
return (
<form
onSubmit={form.onSubmit((values) => {
innerProps.onSuccessfulEdit(values);
actions.closeModal();
})}
>
<Stack>
<TextInput label={t("section.container.option.title.label")} data-autofocus {...form.getInputProps("title")} />
<Switch
label={t("section.option.showLabel.label")}
description={t("section.option.showLabel.description")}
{...form.getInputProps("showLabel", { type: "checkbox" })}
/>
<Switch
label={t("section.option.collapsible.label")}
description={t("section.option.collapsible.description")}
{...form.getInputProps("collapsible", { type: "checkbox" })}
/>
<Switch
label={t("section.option.showOpenAll.label")}
description={t("section.option.showOpenAll.description")}
{...form.getInputProps("showOpenAll", { type: "checkbox" })}
/>
<TextMultiSelect
label={t("section.container.option.customCssClasses.label")}
{...form.getInputProps("customCssClasses")}
/>
<ColorInput
label={t("section.container.option.borderColor.label")}
format="hex"
swatches={Object.values(theme.colors).map((color) => color[6])}
rightSection={
<CloseButton
onClick={() => form.setFieldValue("borderColor", "")}
style={{ display: form.getInputProps("borderColor").value ? undefined : "none" }}
/>
}
{...form.getInputProps("borderColor")}
/>
<ModalFormFooter onCancel={actions.closeModal} />
</Stack>
</form>
);
}).withOptions({
defaultTitle(t) {
return t("item.edit.title");
},
size: modalSizeForm,
});
@@ -0,0 +1,79 @@
import { ActionIcon, Menu } from "@mantine/core";
import { IconArrowsMove, IconLayoutKanban, IconPencil, IconTrash } from "@tabler/icons-react";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { ContainerSectionItem } from "~/app/[locale]/boards/_types";
import { useOpenItemMoveModal } from "../../items/item-move-modal";
import { useSectionContext } from "../section-context";
import { useContainerActions } from "./container-actions";
import { ContainerEditModal } from "./container-edit-modal";
export const BoardContainerMenu = ({ section }: { section: ContainerSectionItem }) => {
const t = useI18n();
const tContainer = useScopedI18n("section.container");
const tItem = useScopedI18n("item");
const { openModal } = useModalAction(ContainerEditModal);
const openMoveModal = useOpenItemMoveModal();
const { updateContainer, removeContainer } = useContainerActions();
const { openConfirmModal } = useConfirmModal();
const [isEditMode] = useEditMode();
const { section: parentSection } = useSectionContext();
const label = section.options.title || tContainer("action.create");
const menuRightOffset = parentSection.kind === "container" ? 44 : 4;
if (!isEditMode) return null;
const openEditModal = () => {
openModal({
value: section.options,
onSuccessfulEdit: (options) => updateContainer({ containerId: section.id, newOptions: options }),
});
};
const openRemoveModal = () => {
openConfirmModal({
title: tContainer("remove.title"),
children: tContainer("remove.message"),
onConfirm: () => removeContainer({ id: section.id }),
});
};
return (
<Menu withinPortal position="right-start" arrowPosition="center">
<Menu.Target>
<ActionIcon
variant="default"
size={24}
radius="sm"
pos="absolute"
top={-24}
right={menuRightOffset}
style={{ zIndex: 10 }}
aria-label={tItem("menu.label.settingsFor", { name: label })}
>
<IconLayoutKanban size="1rem" />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown miw={128}>
<Menu.Label>{tItem("menu.label.settings")}</Menu.Label>
<Menu.Item leftSection={<IconPencil size={16} />} onClick={openEditModal}>
{tItem("action.edit")}
</Menu.Item>
<Menu.Item
leftSection={<IconArrowsMove size={16} />}
onClick={() => openMoveModal({ entry: section, sourceSectionId: section.parentSectionId })}
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Divider />
<Menu.Label c="red.6">{t("common.dangerZone")}</Menu.Label>
<Menu.Item c="red.6" leftSection={<IconTrash size={16} />} onClick={openRemoveModal}>
{tContainer("action.remove")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
};
@@ -1,33 +1,19 @@
import { useMemo } from "react";
import type { GridItemHTMLElement } from "@homarr/gridstack";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useEditMode } from "@homarr/boards/edit-mode";
import type { DynamicSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import type { ContainerSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import { BoardItemContent } from "../items/item-content";
import { WidgetHoverOverlay } from "../items/widget-hover-overlay";
import { BoardDynamicSection } from "./dynamic-section";
import { GridStackItem } from "./gridstack/gridstack-item";
import { BoardContainerSection } from "./container-section";
import { FixedGridItem } from "./grid/fixed-grid-item";
import { useSectionContext } from "./section-context";
import { useSectionItems } from "./use-section-items";
export const SectionContent = () => {
const { innerSections, items, refs } = useSectionContext();
const { data: session } = useSession();
const [isEditMode] = useEditMode();
const { data: integrations } = clientApi.integration.all.useQuery(undefined, {
enabled: Boolean(session) && isEditMode,
});
const { innerSections, integrations, items } = useSectionContext();
/**
* IMPORTANT: THE ORDER OF THE BELOW ITEMS HAS TO MATCH THE ORDER OF
* THE ITEMS RENDERED WITH GRIDSTACK, OTHERWISE THE ITEMS WILL BE MIXED UP
* @see https://github.com/homarr-labs/homarr/pull/1770
*/
/** Keep portal content order deterministic across static and edit renderers. */
const sortedItems = useMemo(() => {
return [...items, ...innerSections].toSorted((itemA, itemB) => {
if (itemA.yOffset === itemB.yOffset) {
@@ -41,57 +27,39 @@ export const SectionContent = () => {
return (
<>
{sortedItems.map((item) => (
<Item key={item.id} item={item} innerRef={refs.items.current[item.id]} integrations={integrations} />
<SectionContentItem key={item.id} item={item} integrations={integrations} />
))}
</>
);
};
interface ItemProps {
item: DynamicSectionItem | SectionItem;
innerRef: React.RefObject<GridItemHTMLElement | null> | undefined;
item: ContainerSectionItem | SectionItem;
integrations: RouterOutputs["integration"]["all"] | undefined;
}
const Item = ({ item, innerRef, integrations }: ItemProps) => {
export const SectionContentItem = ({ item, integrations }: ItemProps) => {
const minWidth = useMinSize(item, "x");
const minHeight = useMinSize(item, "y");
return (
<GridStackItem
key={item.id}
innerRef={innerRef}
width={item.width}
height={item.height}
xOffset={item.xOffset}
yOffset={item.yOffset}
kind={item.kind}
id={item.id}
type={item.type}
minWidth={minWidth}
minHeight={minHeight}
>
<FixedGridItem key={item.id} item={item} minWidth={minWidth} minHeight={minHeight}>
{item.type === "item" && item.kind !== "app" && <WidgetHoverOverlay item={item} integrations={integrations} />}
{item.type === "item" ? <BoardItemContent item={item} /> : <BoardDynamicSection section={item} />}
</GridStackItem>
{item.type === "item" ? <BoardItemContent item={item} /> : <BoardContainerSection section={item} />}
</FixedGridItem>
);
};
/**
* Calculates the min width / height of a section by taking the maximum of
* the sum of the offset and size of all items and dynamic sections inside.
* @param direction either "x" or "y"
* @param items items of the section
* @param sections sections of the board to look for dynamic sections
* @param parentSectionId the id of the section we want to calculate the min size for
* @returns the min size
* Calculates a container's minimum width or height from its direct content.
*/
const useMinSize = (item: DynamicSectionItem | SectionItem, direction: "x" | "y") => {
export const useMinSize = (item: ContainerSectionItem | SectionItem, direction: "x" | "y") => {
const { items, innerSections } = useSectionItems(item.id);
if (item.type === "item") return undefined;
const size = direction === "x" ? "width" : "height";
return Math.max(
...items.map((item) => item[`${direction}Offset`] + item[size]),
...innerSections.map((item) => item[`${direction}Offset`] + item[size]),
1,
...items.map((childItem) => childItem[`${direction}Offset`] + childItem[size]),
...innerSections.map((childSection) => childSection[`${direction}Offset`] + childSection[size]),
);
};
@@ -1,68 +0,0 @@
import { Badge, Box, Card } from "@mantine/core";
import combineClasses from "clsx";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import type { DynamicSectionItem } from "~/app/[locale]/boards/_types";
import { BoardDynamicSectionMenu } from "./dynamic/dynamic-menu";
import { GridStack } from "./gridstack/gridstack";
import { useSectionContext } from "./section-context";
import classes from "./item.module.css";
interface Props {
section: DynamicSectionItem;
}
export const BoardDynamicSection = ({ section }: Props) => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { ancestorSectionIds } = useSectionContext();
const options = section.options;
return (
<Box
className="grid-stack-item-content"
style={{
overflow: "visible",
}}
>
<Card
className={combineClasses(classes.itemCard, section.options.customCssClasses.join(" "))}
w="100%"
h="100%"
styles={{
root: {
overflow: "visible",
"--opacity": board.opacity / 100,
"--border-color": options.borderColor || undefined,
},
}}
radius={board.itemRadius}
p={0}
>
{options.title && (
<Badge
pos="absolute"
top={-15}
left={10}
size="md"
radius={board.itemRadius}
color="var(--background-color)"
c="var(--mantine-color-text)"
bd="1px solid var(--border-color)"
>
{options.title}
</Badge>
)}
{/* Use unique key by layout to reinitialize gridstack */}
<GridStack
key={`${currentLayoutId}-${section.id}`}
section={section}
ancestorSectionIds={ancestorSectionIds}
className="min-row"
/>
</Card>
<BoardDynamicSectionMenu section={section} />
</Box>
);
};
@@ -1,56 +0,0 @@
import { getBoardLayouts } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import type { Board, DynamicSection, DynamicSectionLayout, EmptySection } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition } from "~/components/board/items/actions/empty-position";
import { getSectionElements } from "~/components/board/items/actions/section-elements";
export const addDynamicSectionCallback = () => (board: Board) => {
const firstSection = board.sections
.filter((section) => section.kind === "empty")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) return board;
const newSection = {
id: createId(),
kind: "dynamic",
options: {
title: "",
borderColor: "",
customCssClasses: [],
},
layouts: createDynamicSectionLayouts(board, firstSection),
} satisfies DynamicSection;
return {
...board,
sections: board.sections.concat(newSection as unknown as DynamicSection),
};
};
const createDynamicSectionLayouts = (board: Board, currentSection: EmptySection): DynamicSectionLayout[] => {
const layouts = getBoardLayouts(board);
return layouts.map((layoutId) => {
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
const emptyPosition = boardLayout
? getFirstEmptyPosition(elements, boardLayout.columnCount)
: { xOffset: 0, yOffset: 0 };
if (!emptyPosition) {
throw new Error("Your board is full");
}
return {
width: 1,
height: 1,
...emptyPosition,
parentSectionId: currentSection.id,
layoutId,
};
});
};
@@ -1,62 +0,0 @@
import type { Board, DynamicSection } from "~/app/[locale]/boards/_types";
export interface RemoveDynamicSectionInput {
id: string;
}
export const removeDynamicSectionCallback =
({ id }: RemoveDynamicSectionInput) =>
(board: Board): Board => {
const sectionToRemove = board.sections.find(
(section): section is DynamicSection => section.id === id && section.kind === "dynamic",
);
if (!sectionToRemove) return board;
return {
...board,
sections: board.sections
.filter((section) => section.id !== id)
.map((section) => {
if (section.kind !== "dynamic") return section;
// Change xOffset and yOffset of sections that were below the removed section and set parentSectionId to the parent of the removed section
return {
...section,
layouts: section.layouts.map((layout) => {
if (layout.parentSectionId !== sectionToRemove.id) return layout;
const removedSectionLayout = sectionToRemove.layouts.find(
(layoutToRemove) => layoutToRemove.layoutId === layout.layoutId,
);
if (!removedSectionLayout) throw new Error("Layout not found");
return {
...layout,
xOffset: layout.xOffset + removedSectionLayout.xOffset,
yOffset: layout.yOffset + removedSectionLayout.yOffset,
parentSectionId: removedSectionLayout.parentSectionId,
};
}),
};
}),
// Move all items in dynamic section to parent of the removed section
items: board.items.map((item) => ({
...item,
layouts: item.layouts.map((layout) => {
if (layout.sectionId !== sectionToRemove.id) return layout;
const removedSectionLayout = sectionToRemove.layouts.find(
(layoutToRemove) => layoutToRemove.layoutId === layout.layoutId,
);
if (!removedSectionLayout) throw new Error("Layout not found");
return {
...layout,
xOffset: layout.xOffset + removedSectionLayout.xOffset,
yOffset: layout.yOffset + removedSectionLayout.yOffset,
sectionId: removedSectionLayout.parentSectionId,
};
}),
})),
};
};
@@ -1,45 +0,0 @@
import { useCallback } from "react";
import type { z } from "zod/v4";
import { useUpdateBoard } from "@homarr/boards/updater";
import type { dynamicSectionOptionsSchema } from "@homarr/validation/shared";
import { addDynamicSectionCallback } from "./actions/add-dynamic-section";
import type { RemoveDynamicSectionInput } from "./actions/remove-dynamic-section";
import { removeDynamicSectionCallback } from "./actions/remove-dynamic-section";
interface UpdateDynamicOptions {
itemId: string;
newOptions: z.infer<typeof dynamicSectionOptionsSchema>;
}
export const useDynamicSectionActions = () => {
const { updateBoard } = useUpdateBoard();
const addDynamicSection = useCallback(() => {
updateBoard(addDynamicSectionCallback());
}, [updateBoard]);
const updateDynamicSection = useCallback(
({ itemId, newOptions }: UpdateDynamicOptions) => {
updateBoard((previous) => ({
...previous,
sections: previous.sections.map((item) => (item.id !== itemId ? item : { ...item, options: newOptions })),
}));
},
[updateBoard],
);
const removeDynamicSection = useCallback(
(input: RemoveDynamicSectionInput) => {
updateBoard(removeDynamicSectionCallback(input));
},
[updateBoard],
);
return {
addDynamicSection,
updateDynamicSection,
removeDynamicSection,
};
};
@@ -1,60 +0,0 @@
"use client";
import { CloseButton, ColorInput, Stack, TextInput, useMantineTheme } from "@mantine/core";
import type { z } from "zod/v4";
import { useZodForm } from "@homarr/form";
import { createModal, ModalFormFooter, modalSizeForm } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
import { TextMultiSelect } from "@homarr/ui";
import { dynamicSectionOptionsSchema } from "@homarr/validation/shared";
interface ModalProps {
value: z.infer<typeof dynamicSectionOptionsSchema>;
onSuccessfulEdit: (value: z.infer<typeof dynamicSectionOptionsSchema>) => void;
}
export const DynamicSectionEditModal = createModal<ModalProps>(({ actions, innerProps }) => {
const t = useI18n();
const theme = useMantineTheme();
const form = useZodForm(dynamicSectionOptionsSchema, {
mode: "controlled",
initialValues: { ...innerProps.value },
});
return (
<form
onSubmit={form.onSubmit((values) => {
innerProps.onSuccessfulEdit(values);
actions.closeModal();
})}
>
<Stack>
<TextInput label={t("section.dynamic.option.title.label")} data-autofocus {...form.getInputProps("title")} />
<TextMultiSelect
label={t("section.dynamic.option.customCssClasses.label")}
{...form.getInputProps("customCssClasses")}
/>
<ColorInput
label={t("section.dynamic.option.borderColor.label")}
format="hex"
swatches={Object.values(theme.colors).map((color) => color[6])}
rightSection={
<CloseButton
onClick={() => form.setFieldValue("borderColor", "")}
style={{ display: form.getInputProps("borderColor").value ? undefined : "none" }}
/>
}
{...form.getInputProps("borderColor")}
/>
<ModalFormFooter onCancel={actions.closeModal} />
</Stack>
</form>
);
}).withOptions({
defaultTitle(t) {
return t("item.edit.title");
},
size: modalSizeForm,
});
@@ -1,73 +0,0 @@
import { ActionIcon, Menu } from "@mantine/core";
import { IconDotsVertical, IconPencil, IconTrash } from "@tabler/icons-react";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { DynamicSectionItem } from "~/app/[locale]/boards/_types";
import { useDynamicSectionActions } from "./dynamic-actions";
import { DynamicSectionEditModal } from "./dynamic-edit-modal";
export const BoardDynamicSectionMenu = ({ section }: { section: DynamicSectionItem }) => {
const t = useI18n();
const tDynamic = useScopedI18n("section.dynamic");
const tItem = useScopedI18n("item");
const { openModal } = useModalAction(DynamicSectionEditModal);
const { updateDynamicSection, removeDynamicSection } = useDynamicSectionActions();
const { openConfirmModal } = useConfirmModal();
const [isEditMode] = useEditMode();
if (!isEditMode) return null;
const openEditModal = () => {
openModal({
value: section.options,
onSuccessfulEdit: (options) => {
updateDynamicSection({
itemId: section.id,
newOptions: options,
});
},
});
};
const openRemoveModal = () => {
openConfirmModal({
title: tDynamic("remove.title"),
children: tDynamic("remove.message"),
onConfirm: () => {
removeDynamicSection({ id: section.id });
},
});
};
return (
<Menu withinPortal position="right-start" arrowPosition="center">
<Menu.Target>
<ActionIcon
variant="default"
radius={"xl"}
pos="absolute"
top={4}
right={4}
style={{ zIndex: 10 }}
aria-label={tItem("menu.label.settings")}
>
<IconDotsVertical size={"1rem"} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown miw={128}>
<Menu.Label>{tItem("menu.label.settings")}</Menu.Label>
<Menu.Item leftSection={<IconPencil size={16} />} onClick={openEditModal}>
{tItem("action.edit")}
</Menu.Item>
<Menu.Divider />
<Menu.Label c="red.6">{t("common.dangerZone")}</Menu.Label>
<Menu.Item c="red.6" leftSection={<IconTrash size={16} />} onClick={openRemoveModal}>
{tDynamic("action.remove")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
};
@@ -1,25 +1,32 @@
import combineClasses from "clsx";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useScopedI18n } from "@homarr/translation/client";
import type { EmptySection } from "~/app/[locale]/boards/_types";
import { GridStack } from "./gridstack/gridstack";
import { SectionGrid } from "./grid/section-grid";
import { useSectionItems } from "./use-section-items";
interface Props {
section: EmptySection;
columnCount: number;
requestedRowCount: number;
railPlacement?: "main" | "left" | "right";
}
export const BoardEmptySection = ({ section }: Props) => {
export const BoardEmptySection = ({ section, columnCount, requestedRowCount, railPlacement = "main" }: Props) => {
const { items, innerSections } = useSectionItems(section.id);
const totalLength = items.length + innerSections.length;
const [isEditMode] = useEditMode();
const t = useScopedI18n("board.landmark");
if (totalLength === 0 && !isEditMode && requestedRowCount === 0) return null;
return (
<GridStack
<SectionGrid
section={section}
style={{ transitionDuration: "0s" }}
className={combineClasses("min-row", totalLength > 0 || isEditMode ? undefined : "grid-stack-empty-wrapper")}
columnCount={columnCount}
requestedRowCount={requestedRowCount}
label={t("items")}
railPlacement={railPlacement}
/>
);
};
@@ -0,0 +1,57 @@
"use client";
import type { ComponentType, PropsWithChildren } from "react";
import { useEffect, useState } from "react";
import { useEditMode } from "@homarr/boards/edit-mode";
import { loadGridEditorAsync } from "./grid-editor-loader";
import { GridEditorRuntimeProvider } from "./grid-editor-runtime";
type BoardGridEditorProviderComponent = ComponentType<PropsWithChildren>;
/**
* Keeps the dnd-kit runtime outside the read-only bundle while guaranteeing
* that every root and nested grid shares one drag-and-drop provider.
*/
export const BoardGridEditorBoundary = ({ children }: PropsWithChildren) => {
const [isEditMode] = useEditMode();
const [Provider, setProvider] = useState<BoardGridEditorProviderComponent | null>(null);
const [hasLoadError, setHasLoadError] = useState(false);
useEffect(() => {
if (!isEditMode || Provider) return;
let cancelled = false;
setHasLoadError(false);
void loadGridEditorAsync()
.then((module) => {
if (!cancelled) setProvider(() => module.BoardGridEditorProvider);
})
.catch(() => {
if (!cancelled) setHasLoadError(true);
});
return () => {
cancelled = true;
};
}, [Provider, isEditMode]);
if (!isEditMode) {
return <GridEditorRuntimeProvider status="idle">{children}</GridEditorRuntimeProvider>;
}
if (hasLoadError) {
return <GridEditorRuntimeProvider status="error">{children}</GridEditorRuntimeProvider>;
}
if (!Provider) {
return <GridEditorRuntimeProvider status="loading">{children}</GridEditorRuntimeProvider>;
}
return (
<GridEditorRuntimeProvider status="ready">
<Provider>{children}</Provider>
</GridEditorRuntimeProvider>
);
};
@@ -0,0 +1,145 @@
import { describe, expect, test } from "vitest";
import { getLogicalTrackSize, LOGICAL_GRID_PITCH } from "~/components/board/layout";
import {
getContinuousGridDelta,
getContinuousResizePlacement,
getPointerProjectedShape,
getSnappedGridCoordinates,
getSnappedGridDelta,
} from "./coordinates";
describe("dnd grid coordinates", () => {
test.each([0.75, 1, 1.25, 2])("maps transformed drag geometry at %sx scale", (scale) => {
const target = { left: 137, top: -42, width: getLogicalTrackSize(8) * scale };
const dragShape = {
left: target.left + 3 * LOGICAL_GRID_PITCH * scale,
top: target.top + 7 * LOGICAL_GRID_PITCH * scale,
};
expect(getSnappedGridCoordinates({ dragShape, target, columnCount: 8 })).toEqual({ x: 3, y: 7 });
});
test("uses the dragged shape origin so a non-center grab retains its pointer offset", () => {
const scale = 0.75;
const target = { left: -280, top: 390, width: getLogicalTrackSize(5) * scale };
const initialShape = { left: target.left, top: target.top, width: 424 * scale, height: 200 * scale };
const pointerDelta = { x: LOGICAL_GRID_PITCH * scale * 2, y: LOGICAL_GRID_PITCH * scale * 3 };
expect(
getSnappedGridCoordinates({
dragShape: {
left: initialShape.left + pointerDelta.x,
top: initialShape.top + pointerDelta.y,
},
target,
columnCount: 5,
}),
).toEqual({ x: 2, y: 3 });
});
test.each([0.75, 1, 1.25, 2])("projects a pointer drag in visual coordinates at %sx scale", (scale) => {
const target = { left: 496, top: -938, width: getLogicalTrackSize(8) * scale };
const initialShape = {
left: target.left + 4 * LOGICAL_GRID_PITCH * scale,
top: target.top + 8 * LOGICAL_GRID_PITCH * scale,
width: getLogicalTrackSize(2) * scale,
height: getLogicalTrackSize(2) * scale,
};
const initialPointer = { x: initialShape.left + 134 * scale, y: initialShape.top + 89 * scale };
const dragShape = getPointerProjectedShape(
{ initialPointer, initialShape },
{ x: initialPointer.x, y: initialPointer.y - LOGICAL_GRID_PITCH * scale },
);
expect(dragShape.left).toBe(initialShape.left);
expect(dragShape).toMatchObject({ width: initialShape.width, height: initialShape.height });
expect(getSnappedGridCoordinates({ dragShape, target, columnCount: 8 })).toEqual({ x: 4, y: 7 });
});
test.each([0.75, 1, 1.25, 2])("snaps resize pointer deltas at %sx scale", (visualScale) => {
expect(
getSnappedGridDelta({
initial: { x: 19, y: 31 },
current: {
x: 19 - 2 * LOGICAL_GRID_PITCH * visualScale,
y: 31 + 4 * LOGICAL_GRID_PITCH * visualScale,
},
visualScale,
}),
).toEqual({ x: -2, y: 4 });
});
test("keeps the visual resize continuous between snapped grid breakpoints", () => {
const visualScale = 0.75;
const delta = getContinuousGridDelta({
initial: { x: 10, y: 20 },
current: {
x: 10 + LOGICAL_GRID_PITCH * visualScale * 0.42,
y: 20 + LOGICAL_GRID_PITCH * visualScale * 0.68,
},
visualScale,
});
expect(delta?.x).toBeCloseTo(0.42);
expect(delta?.y).toBeCloseTo(0.68);
expect(
getSnappedGridDelta({
initial: { x: 10, y: 20 },
current: {
x: 10 + LOGICAL_GRID_PITCH * visualScale * 0.42,
y: 20 + LOGICAL_GRID_PITCH * visualScale * 0.68,
},
visualScale,
}),
).toEqual({ x: 0, y: 1 });
});
test("projects a continuous resize while anchoring the opposite edges and respecting bounds", () => {
const placement = { id: "widget", x: 2, y: 3, w: 3, h: 2 };
expect(
getContinuousResizePlacement({
placement,
direction: "nw",
deltaColumns: 0.35,
deltaRows: -0.6,
columnCount: 8,
maxRowCount: 10,
}),
).toEqual({ id: "widget", x: 2.35, y: 2.4, w: 2.65, h: 2.6 });
expect(
getContinuousResizePlacement({
placement,
direction: "se",
deltaColumns: 99,
deltaRows: 99,
columnCount: 8,
maxRowCount: 7,
}),
).toEqual({ id: "widget", x: 2, y: 3, w: 6, h: 4 });
});
test("uses independently measured visual axes for transformed resize geometry", () => {
expect(
getSnappedGridDelta({
initial: { x: 10, y: 20 },
current: { x: 10 + LOGICAL_GRID_PITCH * 1.25, y: 20 - LOGICAL_GRID_PITCH * 1.5 },
visualScale: { x: 1.25, y: 1.5 },
}),
).toEqual({ x: 1, y: -1 });
});
test("rejects non-positive or non-finite scales", () => {
expect(
getSnappedGridCoordinates({
dragShape: { left: 0, top: 0 },
target: { left: 0, top: 0, width: 0 },
columnCount: 4,
}),
).toBeNull();
expect(
getSnappedGridDelta({ initial: { x: 0, y: 0 }, current: { x: 1, y: 1 }, visualScale: Number.NaN }),
).toBeNull();
});
});
@@ -0,0 +1,133 @@
import { getLogicalTrackSize, LOGICAL_GRID_PITCH } from "~/components/board/layout";
import type { GridPlacement } from "~/components/board/layout";
import type { GridResizeDirection } from "./types";
interface RectangleLike {
left: number;
top: number;
width: number;
}
interface ProjectedRectangle extends RectangleLike {
height: number;
}
export interface DragProjectionOrigin {
initialPointer: { x: number; y: number };
initialShape: ProjectedRectangle;
}
/**
* Projects the dragged shape from the grab point instead of dnd-kit's
* feedback element. The latter can live in a CSS-zoomed overlay whose
* bounding rectangle is in a different coordinate space from pointer events.
*/
export const getPointerProjectedShape = (origin: DragProjectionOrigin, currentPointer: { x: number; y: number }) => ({
left: origin.initialShape.left + currentPointer.x - origin.initialPointer.x,
top: origin.initialShape.top + currentPointer.y - origin.initialPointer.y,
width: origin.initialShape.width,
height: origin.initialShape.height,
});
export const getSnappedGridCoordinates = ({
dragShape,
target,
columnCount,
}: {
dragShape: Pick<RectangleLike, "left" | "top">;
target: RectangleLike;
columnCount: number;
}) => {
const logicalWidth = getLogicalTrackSize(columnCount);
const visualScale = logicalWidth > 0 ? target.width / logicalWidth : 0;
if (!Number.isFinite(visualScale) || visualScale <= 0) return null;
return {
x: Math.round((dragShape.left - target.left) / (LOGICAL_GRID_PITCH * visualScale)),
y: Math.round((dragShape.top - target.top) / (LOGICAL_GRID_PITCH * visualScale)),
};
};
export const getSnappedGridDelta = ({
current,
initial,
visualScale,
}: {
current: { x: number; y: number };
initial: { x: number; y: number };
visualScale: number | { x: number; y: number };
}) => {
const delta = getContinuousGridDelta({ current, initial, visualScale });
if (!delta) return null;
return {
x: Math.round(delta.x),
y: Math.round(delta.y),
};
};
export const getContinuousGridDelta = ({
current,
initial,
visualScale,
}: {
current: { x: number; y: number };
initial: { x: number; y: number };
visualScale: number | { x: number; y: number };
}) => {
const scale = typeof visualScale === "number" ? { x: visualScale, y: visualScale } : visualScale;
if (!Number.isFinite(scale.x) || scale.x <= 0 || !Number.isFinite(scale.y) || scale.y <= 0) return null;
return {
x: (current.x - initial.x) / (LOGICAL_GRID_PITCH * scale.x),
y: (current.y - initial.y) / (LOGICAL_GRID_PITCH * scale.y),
};
};
/** Projects a resize continuously while the committed layout remains snapped. */
export const getContinuousResizePlacement = <TPlacement extends GridPlacement>({
placement,
direction,
deltaColumns,
deltaRows,
columnCount,
maxRowCount,
minWidth = 1,
minHeight = 1,
}: {
placement: TPlacement;
direction: GridResizeDirection;
deltaColumns: number;
deltaRows: number;
columnCount: number;
maxRowCount: number | null;
minWidth?: number;
minHeight?: number;
}): TPlacement => {
const fixedRight = placement.x + placement.w;
const fixedBottom = placement.y + placement.h;
let x = placement.x;
let y = placement.y;
let w = placement.w;
let h = placement.h;
if (direction.includes("w")) {
w = clamp(placement.w - deltaColumns, minWidth, fixedRight);
x = fixedRight - w;
} else if (direction.includes("e")) {
w = clamp(placement.w + deltaColumns, minWidth, columnCount - placement.x);
}
if (direction.includes("n")) {
h = clamp(placement.h - deltaRows, minHeight, fixedBottom);
y = fixedBottom - h;
} else if (direction.includes("s")) {
h = clamp(
placement.h + deltaRows,
minHeight,
maxRowCount === null ? Number.MAX_SAFE_INTEGER : maxRowCount - placement.y,
);
}
return { ...placement, x, y, w, h };
};
const clamp = (value: number, minimum: number, maximum: number) => Math.min(Math.max(value, minimum), maximum);
@@ -0,0 +1,757 @@
import { describe, expect, test } from "vitest";
import { doGridPlacementsOverlap } from "~/components/board/layout";
import {
beginGridTransaction,
cancelGridTransaction,
commitGridTransaction,
previewGridMove,
previewGridResize,
} from "./engine";
import type {
GridPreviewResult,
GridResizeDirection,
GridTransaction,
TransactionalGrid,
TransactionalGridState,
} from "./types";
interface TestPlacement {
id: string;
x: number;
y: number;
w: number;
h: number;
kind: "container" | "item";
marker?: string;
}
const placement = (
id: string,
x: number,
y: number,
w = 1,
h = 1,
kind: TestPlacement["kind"] = "item",
): TestPlacement => ({ id, x, y, w, h, kind, marker: `metadata:${id}` });
const grid = (
id: string,
columnCount: number,
placements: readonly TestPlacement[],
options: Pick<TransactionalGrid<TestPlacement>, "maxRowCount" | "ownerPlacementId" | "parentGridId"> = {},
): TransactionalGrid<TestPlacement> => ({ id, columnCount, placements, ...options });
const state = (...grids: readonly TransactionalGrid<TestPlacement>[]): TransactionalGridState<TestPlacement> => ({
grids,
});
const accept = (result: GridPreviewResult<TestPlacement>): GridTransaction<TestPlacement> => {
if (!result.accepted) throw new Error(`Expected preview to be accepted, received ${result.rejection.code}`);
return result.transaction;
};
const getGrid = (layout: TransactionalGridState<TestPlacement>, id: string) => {
const found = layout.grids.find((candidate) => candidate.id === id);
if (!found) throw new Error(`Missing test grid ${id}`);
return found;
};
const getPlacement = (layout: TransactionalGridState<TestPlacement>, id: string) => {
for (const candidateGrid of layout.grids) {
const found = candidateGrid.placements.find((candidate) => candidate.id === id);
if (found) return found;
}
throw new Error(`Missing test placement ${id}`);
};
const coordinatesById = (layout: TransactionalGridState<TestPlacement>, gridId: string) =>
Object.fromEntries(getGrid(layout, gridId).placements.map(({ id, x, y, w, h }) => [id, { x, y, w, h }]));
const expectValidState = (layout: TransactionalGridState<TestPlacement>) => {
const allIds = new Set<string>();
for (const candidateGrid of layout.grids) {
for (const [index, candidate] of candidateGrid.placements.entries()) {
expect(allIds.has(candidate.id), `duplicate placement ${candidate.id}`).toBe(false);
allIds.add(candidate.id);
expect([candidate.x, candidate.y, candidate.w, candidate.h].every(Number.isInteger)).toBe(true);
expect(candidate.x).toBeGreaterThanOrEqual(0);
expect(candidate.y).toBeGreaterThanOrEqual(0);
expect(candidate.w).toBeGreaterThanOrEqual(1);
expect(candidate.h).toBeGreaterThanOrEqual(1);
expect(candidate.x + candidate.w).toBeLessThanOrEqual(candidateGrid.columnCount);
if (candidateGrid.maxRowCount !== undefined && candidateGrid.maxRowCount !== null) {
expect(candidate.y + candidate.h).toBeLessThanOrEqual(candidateGrid.maxRowCount);
}
for (const other of candidateGrid.placements.slice(index + 1)) {
expect(
doGridPlacementsOverlap(candidate, other),
`${candidate.id} overlaps ${other.id} in ${candidateGrid.id}`,
).toBe(false);
}
}
}
for (const candidateGrid of layout.grids) {
if (!candidateGrid.ownerPlacementId) continue;
const parent = getGrid(layout, candidateGrid.parentGridId ?? "");
expect(parent.placements.some(({ id }) => id === candidateGrid.ownerPlacementId)).toBe(true);
}
};
describe("grid transaction setup", () => {
test("captures detached snapshot and preview copies without mutating caller state", () => {
const original = state(grid("root", 4, [placement("active", 0, 0), placement("other", 2, 3)]));
const transaction = beginGridTransaction(original, { activeId: "active", sourceGridId: "root" });
expect(transaction.snapshot).toEqual(original);
expect(transaction.preview).toEqual(original);
expect(transaction.snapshot).not.toBe(original);
expect(transaction.snapshot.grids[0]).not.toBe(original.grids[0]);
expect(transaction.snapshot.grids[0]?.placements[0]).not.toBe(original.grids[0]?.placements[0]);
expect(transaction.preview).not.toBe(transaction.snapshot);
});
test("rejects a missing active item or stale source-grid hint", () => {
const original = state(grid("root", 2, [placement("active", 0, 0)]));
expect(() => beginGridTransaction(original, { activeId: "missing" })).toThrow('Grid item "missing" does not exist');
expect(() => beginGridTransaction(original, { activeId: "active", sourceGridId: "stale" })).toThrow(
'belongs to grid "root", not "stale"',
);
});
test.each([
{
name: "duplicate grid ids",
layout: state(grid("root", 2, [placement("a", 0, 0)]), grid("root", 2, [placement("b", 0, 0)])),
message: "Duplicate grid id",
},
{
name: "duplicate placement ids across grids",
layout: state(grid("first", 2, [placement("a", 0, 0)]), grid("second", 2, [placement("a", 0, 0)])),
message: "Duplicate grid item id",
},
{
name: "overlaps",
layout: state(grid("root", 3, [placement("a", 0, 0, 2), placement("b", 1, 0, 2)])),
message: "overlap",
},
{
name: "column overflow",
layout: state(grid("root", 2, [placement("a", 1, 0, 2)])),
message: "exceeds grid",
},
{
name: "row overflow",
layout: state(grid("root", 2, [placement("a", 0, 1, 1, 2)], { maxRowCount: 2 })),
message: "exceeds grid",
},
{
name: "missing hierarchy owner",
layout: state(
grid("root", 2, [placement("a", 0, 0)]),
grid("child", 2, [], { parentGridId: "root", ownerPlacementId: "missing" }),
),
message: "Owner item",
},
{
name: "cyclic hierarchy",
layout: state(
grid("first", 2, [placement("owns-second", 0, 0)], {
parentGridId: "second",
ownerPlacementId: "owns-first",
}),
grid("second", 2, [placement("owns-first", 0, 0)], {
parentGridId: "first",
ownerPlacementId: "owns-second",
}),
),
message: "cycle",
},
])("rejects invalid initial state: $name", ({ layout, message }) => {
expect(() => beginGridTransaction(layout, { activeId: layout.grids[0]?.placements[0]?.id ?? "missing" })).toThrow(
message,
);
});
});
describe("same-grid movement", () => {
test("keeps the exact snapshot for a no-op instead of compacting intentional gaps", () => {
const original = state(grid("root", 4, [placement("active", 0, 3), placement("other", 2, 5)]));
const transaction = beginGridTransaction(original, { activeId: "active" });
const moved = accept(previewGridMove(transaction, { targetGridId: "root", x: 0, y: 3 }));
expect(moved.preview).toEqual(original);
expect(moved.preview).not.toBe(original);
});
test("swaps an equal-size item occupying the requested exact slot", () => {
const original = state(
grid("root", 4, [placement("active", 0, 0), placement("target", 1, 0), placement("untouched", 2, 0)]),
);
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
x: 1,
y: 0,
}),
);
expect(coordinatesById(moved.preview, "root")).toEqual({
active: { x: 1, y: 0, w: 1, h: 1 },
target: { x: 0, y: 0, w: 1, h: 1 },
untouched: { x: 2, y: 0, w: 1, h: 1 },
});
});
test("swaps different-size items when both resulting placements remain valid", () => {
const original = state(grid("root", 4, [placement("wide", 0, 0, 2), placement("compact", 2, 0)]));
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "wide" }), {
targetGridId: "root",
x: 2,
y: 0,
}),
);
expect(coordinatesById(moved.preview, "root")).toEqual({
wide: { x: 2, y: 0, w: 2, h: 1 },
compact: { x: 0, y: 0, w: 1, h: 1 },
});
});
test("uses pinned reflow when an exact-slot swap would exceed the grid bounds", () => {
const original = state(grid("root", 4, [placement("compact", 3, 0), placement("wide", 0, 0, 2)]));
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "compact" }), {
targetGridId: "root",
x: 0,
y: 0,
}),
);
expect(coordinatesById(moved.preview, "root")).toEqual({
compact: { x: 0, y: 0, w: 1, h: 1 },
wide: { x: 0, y: 1, w: 2, h: 1 },
});
});
test("pushes a different-size collision without compacting unrelated gaps", () => {
const original = state(
grid("root", 4, [placement("active", 0, 0), placement("wide", 1, 0, 2), placement("lower-left", 0, 1)]),
);
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
x: 1,
y: 0,
}),
);
expect(coordinatesById(moved.preview, "root")).toEqual({
active: { x: 1, y: 0, w: 1, h: 1 },
wide: { x: 1, y: 1, w: 2, h: 1 },
"lower-left": { x: 0, y: 1, w: 1, h: 1 },
});
});
test("swaps laterally as soon as a move pushes into one compatible item", () => {
const original = state(grid("root", 5, [placement("active", 0, 0, 2), placement("target", 2, 0, 2)]));
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
x: 1,
y: 0,
}),
);
expect(getPlacement(moved.preview, "active")).toMatchObject({ x: 2, y: 0, w: 2, h: 1 });
expect(getPlacement(moved.preview, "target")).toMatchObject({ x: 0, y: 0, w: 2, h: 1 });
});
test("swaps the pushed item into the vacated slot when moving from right to left", () => {
const original = state(grid("root", 5, [placement("target", 0, 0, 2), placement("active", 2, 0, 2)]));
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
x: 1,
y: 0,
}),
);
expect(getPlacement(moved.preview, "active")).toMatchObject({ x: 0, y: 0, w: 2, h: 1 });
expect(getPlacement(moved.preview, "target")).toMatchObject({ x: 2, y: 0, w: 2, h: 1 });
});
test("preserves intentional empty rows outside the collision chain", () => {
const original = state(
grid("root", 4, [placement("active", 0, 0), placement("collision", 1, 0, 2), placement("far", 3, 8)]),
);
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
x: 1,
y: 0,
}),
);
expect(getPlacement(moved.preview, "collision")).toMatchObject({ x: 1, y: 1 });
expect(getPlacement(moved.preview, "far")).toMatchObject({ x: 3, y: 8 });
});
test.each([
{ requested: { x: -20, y: -10 }, expected: { x: 0, y: 0 } },
{ requested: { x: 99, y: 99 }, expected: { x: 2, y: 3 } },
{ requested: { x: 2.9, y: 1.9 }, expected: { x: 2, y: 1 } },
])("clamps and quantizes requested coordinates: $requested", ({ requested, expected }) => {
const original = state(grid("root", 4, [placement("active", 1, 1, 2, 2)], { maxRowCount: 5 }));
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "root",
...requested,
}),
);
expect(getPlacement(moved.preview, "active")).toMatchObject(expected);
});
test("produces the same result regardless of backing-array order", () => {
const placements = [
placement("active", 3, 0),
placement("left", 0, 2),
placement("middle", 1, 2),
placement("right", 2, 2),
];
const forward = state(grid("root", 4, placements));
const reversed = state(grid("root", 4, placements.toReversed()));
const input = { targetGridId: "root", x: 0, y: 0 };
const first = accept(previewGridMove(beginGridTransaction(forward, { activeId: "active" }), input));
const second = accept(previewGridMove(beginGridTransaction(reversed, { activeId: "active" }), input));
expect(coordinatesById(first.preview, "root")).toEqual(coordinatesById(second.preview, "root"));
});
test("recomputes every chained preview from the interaction snapshot", () => {
const original = state(
grid("root", 3, [placement("active", 0, 0), placement("middle", 1, 0), placement("last", 2, 0)]),
);
const transaction = beginGridTransaction(original, { activeId: "active" });
const first = accept(previewGridMove(transaction, { targetGridId: "root", x: 1, y: 0 }));
const second = accept(previewGridMove(first, { targetGridId: "root", x: 2, y: 0 }));
expect(coordinatesById(first.preview, "root")).toEqual({
active: { x: 1, y: 0, w: 1, h: 1 },
middle: { x: 0, y: 0, w: 1, h: 1 },
last: { x: 2, y: 0, w: 1, h: 1 },
});
expect(coordinatesById(second.preview, "root")).toEqual({
active: { x: 2, y: 0, w: 1, h: 1 },
middle: { x: 1, y: 0, w: 1, h: 1 },
last: { x: 0, y: 0, w: 1, h: 1 },
});
});
});
describe("cross-grid movement", () => {
test("updates source and target atomically without compacting the source gap", () => {
const original = state(
grid("source", 2, [placement("active", 0, 0), placement("source-neighbor", 0, 1)]),
grid("target", 2, [placement("target-neighbor", 0, 0)]),
);
const moved = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "target",
x: 0,
y: 0,
}),
);
expect(coordinatesById(moved.preview, "source")).toEqual({
"source-neighbor": { x: 0, y: 1, w: 1, h: 1 },
});
expect(coordinatesById(moved.preview, "target")).toEqual({
"target-neighbor": { x: 0, y: 1, w: 1, h: 1 },
active: { x: 0, y: 0, w: 1, h: 1 },
});
expect(getPlacement(moved.preview, "active").marker).toBe("metadata:active");
expect(original).toEqual(
state(
grid("source", 2, [placement("active", 0, 0), placement("source-neighbor", 0, 1)]),
grid("target", 2, [placement("target-neighbor", 0, 0)]),
),
);
expectValidState(moved.preview);
});
test("chained target changes do not leak an earlier cross-grid preview", () => {
const original = state(
grid("source", 2, [placement("active", 0, 0)]),
grid("first-target", 2, [placement("first-neighbor", 0, 0)]),
grid("second-target", 2, [placement("second-neighbor", 0, 0)]),
);
const first = accept(
previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId: "first-target",
x: 0,
y: 0,
}),
);
const second = accept(previewGridMove(first, { targetGridId: "second-target", x: 0, y: 0 }));
expect(getGrid(second.preview, "first-target").placements).toEqual(getGrid(original, "first-target").placements);
expect(getGrid(second.preview, "source").placements).toHaveLength(0);
expect(getPlacement(second.preview, "active")).toMatchObject({ x: 0, y: 0 });
expect(getPlacement(second.preview, "second-neighbor")).toMatchObject({ x: 0, y: 1 });
});
test("moves a container's owned grid with it and supports commit/cancel", () => {
const original = state(
grid("source", 3, [placement("container", 0, 0, 2, 2, "container")]),
grid("target", 3, []),
grid("container-content", 2, [placement("child", 0, 0)], {
parentGridId: "source",
ownerPlacementId: "container",
}),
);
const transaction = beginGridTransaction(original, { activeId: "container" });
const moved = accept(previewGridMove(transaction, { targetGridId: "target", x: 1, y: 2 }));
expect(getGrid(moved.preview, "container-content").parentGridId).toBe("target");
expect(getPlacement(moved.preview, "container")).toMatchObject({ x: 1, y: 2, kind: "container" });
expect(cancelGridTransaction(moved)).toEqual(original);
expect(commitGridTransaction(moved)).toEqual(moved.preview);
expect(commitGridTransaction(moved)).not.toBe(moved.preview);
});
test.each(["child", "grandchild"])("rejects a container move into its %s grid", (targetGridId) => {
const original = state(
grid("root", 4, [placement("container", 0, 0, 2, 2, "container")]),
grid("child", 3, [placement("nested-container", 0, 0, 2, 2, "container")], {
parentGridId: "root",
ownerPlacementId: "container",
}),
grid("grandchild", 2, [], {
parentGridId: "child",
ownerPlacementId: "nested-container",
}),
);
const transaction = beginGridTransaction(original, { activeId: "container" });
const result = previewGridMove(transaction, { targetGridId, x: 0, y: 0 });
expect(result.accepted).toBe(false);
if (result.accepted) throw new Error("Expected descendant move rejection");
expect(result.rejection.code).toBe("descendant-target");
expect(result.transaction).toBe(transaction);
});
test("runs caller guards with hierarchy context and preserves custom rejection details", () => {
const original = state(grid("source", 2, [placement("active", 0, 0)]), grid("target", 2, []));
const transaction = beginGridTransaction(original, { activeId: "active" });
let observedTarget = "";
const guarded = previewGridMove(
transaction,
{ targetGridId: "target", x: 0, y: 0 },
{
guards: [
(context) => {
observedTarget = context.targetGrid.id;
expect(context.active.id).toBe("active");
expect(context.sourceGrid.id).toBe("source");
expect(context.targetIsDescendant).toBe(false);
expect(context.snapshot).toBe(transaction.snapshot);
return true;
},
() => ({ code: "locked-container", message: "Unlock the container first" }),
],
},
);
expect(observedTarget).toBe("target");
expect(guarded.accepted).toBe(false);
if (guarded.accepted) throw new Error("Expected custom guard rejection");
expect(guarded.rejection).toEqual({ code: "locked-container", message: "Unlock the container first" });
const booleanRejection = previewGridMove(
transaction,
{ targetGridId: "target", x: 0, y: 0 },
{
guards: [() => false],
},
);
expect(booleanRejection.accepted).toBe(false);
if (booleanRejection.accepted) throw new Error("Expected boolean guard rejection");
expect(booleanRejection.rejection.code).toBe("guard-rejected");
});
test.each([
{
name: "unknown grid",
original: state(grid("source", 2, [placement("active", 0, 0)])),
input: { targetGridId: "missing", x: 0, y: 0 },
code: "unknown-target-grid",
},
{
name: "destination narrower than the item",
original: state(grid("source", 3, [placement("active", 0, 0, 2)]), grid("target", 1, [])),
input: { targetGridId: "target", x: 0, y: 0 },
code: "item-too-large",
},
{
name: "reflow beyond destination row limit",
original: state(
grid("source", 2, [placement("active", 0, 0, 2)]),
grid("target", 2, [placement("target", 0, 0, 2)], { maxRowCount: 1 }),
),
input: { targetGridId: "target", x: 0, y: 0 },
code: "row-limit",
},
{
name: "non-finite coordinate",
original: state(grid("source", 2, [placement("active", 0, 0)])),
input: { targetGridId: "source", x: Number.NaN, y: 0 },
code: "invalid-coordinate",
},
])("rejects $name without changing the transaction", ({ original, input, code }) => {
const transaction = beginGridTransaction(original, { activeId: "active" });
const result = previewGridMove(transaction, input);
expect(result.accepted).toBe(false);
if (result.accepted) throw new Error("Expected move rejection");
expect(result.rejection.code).toBe(code);
expect(result.transaction).toBe(transaction);
expect(result.transaction.preview).toEqual(original);
});
});
describe("eight-direction resize", () => {
test.each<{
direction: GridResizeDirection;
deltaColumns: number;
deltaRows: number;
expected: Pick<TestPlacement, "x" | "y" | "w" | "h">;
}>([
{ direction: "n", deltaColumns: 0, deltaRows: -1, expected: { x: 3, y: 2, w: 4, h: 5 } },
{ direction: "ne", deltaColumns: 1, deltaRows: -1, expected: { x: 3, y: 2, w: 5, h: 5 } },
{ direction: "e", deltaColumns: 1, deltaRows: 0, expected: { x: 3, y: 3, w: 5, h: 4 } },
{ direction: "se", deltaColumns: 1, deltaRows: 1, expected: { x: 3, y: 3, w: 5, h: 5 } },
{ direction: "s", deltaColumns: 0, deltaRows: 1, expected: { x: 3, y: 3, w: 4, h: 5 } },
{ direction: "sw", deltaColumns: -1, deltaRows: 1, expected: { x: 2, y: 3, w: 5, h: 5 } },
{ direction: "w", deltaColumns: -1, deltaRows: 0, expected: { x: 2, y: 3, w: 5, h: 4 } },
{ direction: "nw", deltaColumns: -1, deltaRows: -1, expected: { x: 2, y: 2, w: 5, h: 5 } },
])("resizes from $direction while anchoring the opposite edge", ({ expected, ...input }) => {
const original = state(grid("root", 12, [placement("active", 3, 3, 4, 4)], { maxRowCount: 12 }));
const resized = accept(previewGridResize(beginGridTransaction(original, { activeId: "active" }), input));
expect(getPlacement(resized.preview, "active")).toMatchObject(expected);
});
test("clamps a north-west shrink to minimum size while keeping right and bottom anchored", () => {
const original = state(grid("root", 12, [placement("active", 3, 3, 4, 4)], { maxRowCount: 12 }));
const resized = accept(
previewGridResize(beginGridTransaction(original, { activeId: "active" }), {
direction: "nw",
deltaColumns: 10,
deltaRows: 10,
minWidth: 2,
minHeight: 2,
}),
);
expect(getPlacement(resized.preview, "active")).toMatchObject({ x: 5, y: 5, w: 2, h: 2 });
});
test.each([
{ direction: "nw" as const, deltaColumns: -99, deltaRows: -99, expected: { x: 0, y: 0, w: 7, h: 7 } },
{ direction: "se" as const, deltaColumns: 99, deltaRows: 99, expected: { x: 3, y: 3, w: 9, h: 9 } },
])("clamps $direction growth to grid bounds", ({ expected, ...input }) => {
const original = state(grid("root", 12, [placement("active", 3, 3, 4, 4)], { maxRowCount: 12 }));
const resized = accept(previewGridResize(beginGridTransaction(original, { activeId: "active" }), input));
expect(getPlacement(resized.preview, "active")).toMatchObject(expected);
});
test("honors explicit maximum dimensions", () => {
const original = state(grid("root", 12, [placement("active", 3, 3, 4, 4)], { maxRowCount: 12 }));
const resized = accept(
previewGridResize(beginGridTransaction(original, { activeId: "active" }), {
direction: "se",
deltaColumns: 99,
deltaRows: 99,
maxWidth: 6,
maxHeight: 5,
}),
);
expect(getPlacement(resized.preview, "active")).toMatchObject({ x: 3, y: 3, w: 6, h: 5 });
});
test("pins the resized item and deterministically pushes collisions", () => {
const original = state(
grid("root", 3, [placement("active", 0, 0, 2), placement("neighbor", 0, 1, 2), placement("side", 2, 2)]),
);
const resized = accept(
previewGridResize(beginGridTransaction(original, { activeId: "active" }), {
direction: "s",
deltaColumns: 0,
deltaRows: 2,
}),
);
expect(coordinatesById(resized.preview, "root")).toEqual({
active: { x: 0, y: 0, w: 2, h: 3 },
neighbor: { x: 0, y: 3, w: 2, h: 1 },
side: { x: 2, y: 2, w: 1, h: 1 },
});
});
test("rejects resize when collision reflow would exceed the row limit", () => {
const original = state(
grid("root", 2, [placement("active", 0, 0, 2), placement("neighbor", 0, 1, 2, 2)], {
maxRowCount: 3,
}),
);
const transaction = beginGridTransaction(original, { activeId: "active" });
const result = previewGridResize(transaction, {
direction: "s",
deltaColumns: 0,
deltaRows: 1,
});
expect(result.accepted).toBe(false);
if (result.accepted) throw new Error("Expected row-limit rejection");
expect(result.rejection.code).toBe("row-limit");
expect(result.transaction).toBe(transaction);
});
test("rejects non-finite deltas and geometrically impossible constraints", () => {
const original = state(grid("root", 4, [placement("active", 0, 0, 2, 2)]));
const transaction = beginGridTransaction(original, { activeId: "active" });
const invalidDelta = previewGridResize(transaction, {
direction: "e",
deltaColumns: Number.POSITIVE_INFINITY,
deltaRows: 0,
});
const impossible = previewGridResize(transaction, {
direction: "w",
deltaColumns: 0,
deltaRows: 0,
minWidth: 5,
maxWidth: 5,
});
expect(invalidDelta.accepted).toBe(false);
if (invalidDelta.accepted) throw new Error("Expected invalid-coordinate rejection");
expect(invalidDelta.rejection.code).toBe("invalid-coordinate");
expect(impossible.accepted).toBe(false);
if (impossible.accepted) throw new Error("Expected resize-constraints rejection");
expect(impossible.rejection.code).toBe("resize-constraints");
});
test.each([{ minWidth: 0 }, { minHeight: 1.5 }, { minWidth: 3, maxWidth: 2 }, { minHeight: 3, maxHeight: 2 }])(
"throws on invalid programmer-supplied constraints: $minWidth $minHeight",
(constraints) => {
const original = state(grid("root", 4, [placement("active", 0, 0, 2, 2)]));
const transaction = beginGridTransaction(original, { activeId: "active" });
expect(() =>
previewGridResize(transaction, {
direction: "se",
deltaColumns: 0,
deltaRows: 0,
...constraints,
}),
).toThrow(RangeError);
},
);
});
describe("transaction completion", () => {
test("a rejection keeps the latest accepted preview, cancel restores start, and commit detaches output", () => {
const original = state(grid("root", 3, [placement("active", 0, 0), placement("other", 1, 0)]));
const started = beginGridTransaction(original, { activeId: "active" });
const moved = accept(previewGridMove(started, { targetGridId: "root", x: 1, y: 0 }));
const rejected = previewGridMove(moved, { targetGridId: "missing", x: 0, y: 0 });
expect(rejected.accepted).toBe(false);
if (rejected.accepted) throw new Error("Expected rejection");
expect(rejected.transaction).toBe(moved);
expect(rejected.transaction.preview).toEqual(moved.preview);
const committed = commitGridTransaction(rejected.transaction);
const cancelled = cancelGridTransaction(rejected.transaction);
expect(committed).toEqual(moved.preview);
expect(committed).not.toBe(moved.preview);
expect(cancelled).toEqual(original);
expect(cancelled).not.toBe(rejected.transaction.snapshot);
});
});
describe("interaction invariant matrix", () => {
test("preserves invariants across every sampled same-grid and cross-grid coordinate", () => {
const original = state(
grid(
"source",
6,
[
placement("active", 0, 0, 2, 2),
placement("source-a", 2, 0, 2),
placement("source-b", 4, 0, 2, 2),
placement("source-c", 2, 1, 2),
],
{ maxRowCount: 10 },
),
grid("target", 5, [placement("target-a", 0, 0), placement("target-b", 1, 0, 2, 2)], {
maxRowCount: 10,
}),
);
for (const targetGridId of ["source", "target"]) {
for (let x = -3; x <= 8; x += 1) {
for (let y = -2; y <= 11; y += 1) {
const result = previewGridMove(beginGridTransaction(original, { activeId: "active" }), {
targetGridId,
x,
y,
});
if (!result.accepted) {
expect(result.rejection.code).toBe("row-limit");
continue;
}
expectValidState(result.transaction.preview);
expect(getPlacement(result.transaction.preview, "active").marker).toBe("metadata:active");
}
}
}
});
test("preserves invariants across every direction and representative signed deltas", () => {
const original = state(grid("root", 8, [placement("active", 2, 2, 3, 3)], { maxRowCount: 9 }));
const directions: readonly GridResizeDirection[] = ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
const deltas = [-20, -3, -1, 0, 1, 3, 20];
for (const direction of directions) {
for (const deltaColumns of deltas) {
for (const deltaRows of deltas) {
const result = previewGridResize(beginGridTransaction(original, { activeId: "active" }), {
direction,
deltaColumns,
deltaRows,
minWidth: 2,
minHeight: 2,
maxWidth: 6,
maxHeight: 7,
});
expect(result.accepted).toBe(true);
if (!result.accepted) throw new Error(`Unexpected ${result.rejection.code} for ${direction}`);
expectValidState(result.transaction.preview);
expect(getPlacement(result.transaction.preview, "active").marker).toBe("metadata:active");
}
}
}
});
});
@@ -0,0 +1,498 @@
import { doGridPlacementsOverlap, getLayoutRowCount, normalizeGridPlacement } from "~/components/board/layout";
import type { GridPlacement } from "~/components/board/layout";
import type {
BeginGridTransactionInput,
GridMoveGuard,
GridMoveInput,
GridMoveOptions,
GridOperationRejection,
GridPreviewResult,
GridResizeDirection,
GridResizeInput,
GridTransaction,
TransactionalGrid,
TransactionalGridState,
} from "./types";
/**
* Starts an immutable interaction transaction. The returned snapshot is the
* rollback source for dnd-kit's `onDragCancel` and the baseline for every
* `onDragMove` / `onDragOver` preview.
*/
export const beginGridTransaction = <TPlacement extends GridPlacement>(
state: TransactionalGridState<TPlacement>,
input: BeginGridTransactionInput,
): GridTransaction<TPlacement> => {
validateGridState(state);
const located = findPlacement(state, input.activeId);
if (!located) throw new Error(`Grid item "${input.activeId}" does not exist`);
if (input.sourceGridId !== undefined && located.grid.id !== input.sourceGridId) {
throw new Error(`Grid item "${input.activeId}" belongs to grid "${located.grid.id}", not "${input.sourceGridId}"`);
}
const snapshot = cloneGridState(state);
return {
activeId: input.activeId,
sourceGridId: located.grid.id,
snapshot,
preview: cloneGridState(snapshot),
};
};
/**
* Computes a move preview from the transaction snapshot. Same-grid moves that
* collide with one item swap into that item's slot when both resulting
* placements remain valid; every other move pins the active item and pushes
* only actual collisions. Intentional empty rows remain untouched.
*/
export const previewGridMove = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
input: GridMoveInput,
options: GridMoveOptions<TPlacement> = {},
): GridPreviewResult<TPlacement> => {
const sourceGrid = getGrid(transaction.snapshot, transaction.sourceGridId);
const targetGrid = findGrid(transaction.snapshot, input.targetGridId);
if (!targetGrid) {
return rejected(transaction, {
code: "unknown-target-grid",
message: `Grid "${input.targetGridId}" does not exist`,
});
}
const active = getPlacement(sourceGrid, transaction.activeId);
const targetIsDescendant = isTargetWithinActiveSubtree(transaction.snapshot, targetGrid.id, transaction.activeId);
if (targetIsDescendant) {
return rejected(transaction, {
code: "descendant-target",
message: `Grid "${targetGrid.id}" is inside item "${active.id}"`,
});
}
const guardRejection = evaluateMoveGuards(options.guards ?? [], {
active,
sourceGrid,
targetGrid,
snapshot: transaction.snapshot,
targetIsDescendant,
});
if (guardRejection) return rejected(transaction, guardRejection);
if (!Number.isFinite(input.x) || !Number.isFinite(input.y)) {
return rejected(transaction, { code: "invalid-coordinate" });
}
if (active.w > targetGrid.columnCount || active.h > getMaximumRows(targetGrid)) {
return rejected(transaction, { code: "item-too-large" });
}
const nextActive = clampMovePlacement(active, input, targetGrid);
const preview =
sourceGrid.id === targetGrid.id
? previewSameGridMove(transaction.snapshot, sourceGrid, active, nextActive)
: previewCrossGridMove(transaction.snapshot, sourceGrid, targetGrid, active, nextActive);
if (!fitsRowLimits(preview)) return rejected(transaction, { code: "row-limit" });
validateGridState(preview);
return accepted(transaction, preview);
};
/**
* Computes an eight-direction resize preview. Deltas describe movement of the
* selected handle, while the opposite edge stays anchored. Bounds and caller
* constraints are applied before pinned collision reflow.
*/
export const previewGridResize = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
input: GridResizeInput,
): GridPreviewResult<TPlacement> => {
const grid = getGrid(transaction.snapshot, transaction.sourceGridId);
const active = getPlacement(grid, transaction.activeId);
if (!Number.isFinite(input.deltaColumns) || !Number.isFinite(input.deltaRows)) {
return rejected(transaction, { code: "invalid-coordinate" });
}
const constraints = getResizeConstraints(input, grid);
const resized = resizePlacement(active, input.direction, input, constraints, grid);
if (!resized) return rejected(transaction, { code: "resize-constraints" });
const preview = cloneGridState(transaction.snapshot);
const previewGrid = getGrid(preview, grid.id);
previewGrid.placements = areCoordinatesEqual(active, resized)
? previewGrid.placements
: resolvePinnedGridCollisions(previewGrid.placements, resized, previewGrid.columnCount);
if (!fitsRowLimits(preview)) return rejected(transaction, { code: "row-limit" });
validateGridState(preview);
return accepted(transaction, preview);
};
/** Returns the latest accepted preview as one atomic state update. */
export const commitGridTransaction = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
): TransactionalGridState<TPlacement> => cloneGridState(transaction.preview);
/** Restores the exact interaction-start snapshot. */
export const cancelGridTransaction = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
): TransactionalGridState<TPlacement> => cloneGridState(transaction.snapshot);
const previewSameGridMove = <TPlacement extends GridPlacement>(
state: TransactionalGridState<TPlacement>,
grid: TransactionalGrid<TPlacement>,
active: TPlacement,
nextActive: TPlacement,
) => {
const preview = cloneGridState(state);
const previewGrid = getGrid(preview, grid.id);
if (areCoordinatesEqual(active, nextActive)) return preview;
const collisions = grid.placements.filter(
(placement) => placement.id !== active.id && doGridPlacementsOverlap(placement, nextActive),
);
const displaced = collisions.length === 1 ? collisions[0] : undefined;
const swapped = displaced
? grid.placements.map((placement) => {
if (placement.id === active.id) return { ...placement, x: displaced.x, y: displaced.y };
if (placement.id === displaced.id) return { ...placement, x: active.x, y: active.y };
return { ...placement };
})
: null;
previewGrid.placements =
swapped && placementsFitGrid(swapped, grid)
? swapped
: resolvePinnedGridCollisions(grid.placements, nextActive, grid.columnCount);
return preview;
};
const placementsFitGrid = <TPlacement extends GridPlacement>(
placements: readonly TPlacement[],
grid: TransactionalGrid<TPlacement>,
) =>
placements.every(
(placement) =>
placement.x >= 0 &&
placement.y >= 0 &&
placement.x + placement.w <= grid.columnCount &&
(grid.maxRowCount === undefined || grid.maxRowCount === null || placement.y + placement.h <= grid.maxRowCount),
) &&
placements.every((placement, index) =>
placements.slice(index + 1).every((other) => !doGridPlacementsOverlap(placement, other)),
);
const previewCrossGridMove = <TPlacement extends GridPlacement>(
state: TransactionalGridState<TPlacement>,
sourceGrid: TransactionalGrid<TPlacement>,
targetGrid: TransactionalGrid<TPlacement>,
active: TPlacement,
nextActive: TPlacement,
) => {
const preview = cloneGridState(state);
const previewSource = getGrid(preview, sourceGrid.id);
const previewTarget = getGrid(preview, targetGrid.id);
previewSource.placements = sourceGrid.placements
.filter((placement) => placement.id !== active.id)
.map((placement) => ({ ...placement }));
previewTarget.placements = resolvePinnedGridCollisions(
[...targetGrid.placements, nextActive],
nextActive,
targetGrid.columnCount,
);
preview.grids = preview.grids.map((grid) =>
grid.ownerPlacementId === active.id ? { ...grid, parentGridId: targetGrid.id } : grid,
);
return preview;
};
/**
* Pins the active placement, keeps every non-colliding item at its persisted
* coordinates, and pushes only the deterministic collision chain downward.
*/
export const resolvePinnedGridCollisions = <TPlacement extends GridPlacement>(
placements: readonly TPlacement[],
pinnedPlacement: TPlacement,
columnCount: number,
): TPlacement[] => {
const normalized = placements.map((placement) =>
normalizeGridPlacement(placement.id === pinnedPlacement.id ? pinnedPlacement : placement, columnCount),
);
const pinned = normalized.find((placement) => placement.id === pinnedPlacement.id);
if (!pinned) throw new Error(`Pinned grid item "${pinnedPlacement.id}" does not exist`);
const placed: TPlacement[] = [pinned];
const candidates = normalized.filter((placement) => placement.id !== pinned.id).toSorted(comparePlacements);
for (const candidate of candidates) {
let resolved = candidate;
for (;;) {
const collisions = placed.filter((placement) => doGridPlacementsOverlap(resolved, placement));
if (collisions.length === 0) break;
resolved = {
...resolved,
y: Math.max(...collisions.map((placement) => placement.y + placement.h)),
};
}
placed.push(resolved);
}
const byId = new Map(placed.map((placement) => [placement.id, placement]));
return normalized.map((placement) => byId.get(placement.id) ?? placement);
};
const comparePlacements = (first: GridPlacement, second: GridPlacement) =>
first.y - second.y || first.x - second.x || first.id.localeCompare(second.id);
const clampMovePlacement = <TPlacement extends GridPlacement>(
placement: TPlacement,
input: GridMoveInput,
grid: TransactionalGrid<TPlacement>,
) => {
const maximumX = grid.columnCount - placement.w;
const maximumY = getMaximumRows(grid) - placement.h;
return {
...placement,
x: clamp(Math.trunc(input.x), 0, maximumX),
y: clamp(Math.trunc(input.y), 0, maximumY),
};
};
interface ResolvedResizeConstraints {
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
}
const getResizeConstraints = <TPlacement extends GridPlacement>(
input: GridResizeInput,
grid: TransactionalGrid<TPlacement>,
): ResolvedResizeConstraints => {
const minWidth = toPositiveInteger(input.minWidth ?? 1, "minWidth");
const minHeight = toPositiveInteger(input.minHeight ?? 1, "minHeight");
const maxWidth = toPositiveInteger(input.maxWidth ?? grid.columnCount, "maxWidth");
const maxHeight = toPositiveInteger(input.maxHeight ?? getMaximumRows(grid), "maxHeight");
if (maxWidth < minWidth) throw new RangeError("maxWidth must be greater than or equal to minWidth");
if (maxHeight < minHeight) throw new RangeError("maxHeight must be greater than or equal to minHeight");
return { minWidth, minHeight, maxWidth, maxHeight };
};
const resizePlacement = <TPlacement extends GridPlacement>(
placement: TPlacement,
direction: GridResizeDirection,
input: GridResizeInput,
constraints: ResolvedResizeConstraints,
grid: TransactionalGrid<TPlacement>,
): TPlacement | null => {
const deltaX = Math.trunc(input.deltaColumns);
const deltaY = Math.trunc(input.deltaRows);
const resizeWest = direction.includes("w");
const resizeEast = direction.includes("e");
const resizeNorth = direction.includes("n");
const resizeSouth = direction.includes("s");
let x = placement.x;
let y = placement.y;
let width = placement.w;
let height = placement.h;
if (resizeWest) {
const fixedRight = placement.x + placement.w;
const maximumWidth = Math.min(constraints.maxWidth, fixedRight);
if (constraints.minWidth > maximumWidth) return null;
width = clamp(placement.w - deltaX, constraints.minWidth, maximumWidth);
x = fixedRight - width;
} else if (resizeEast) {
const maximumWidth = Math.min(constraints.maxWidth, grid.columnCount - placement.x);
if (constraints.minWidth > maximumWidth) return null;
width = clamp(placement.w + deltaX, constraints.minWidth, maximumWidth);
}
if (resizeNorth) {
const fixedBottom = placement.y + placement.h;
const maximumHeight = Math.min(constraints.maxHeight, fixedBottom);
if (constraints.minHeight > maximumHeight) return null;
height = clamp(placement.h - deltaY, constraints.minHeight, maximumHeight);
y = fixedBottom - height;
} else if (resizeSouth) {
const maximumHeight = Math.min(constraints.maxHeight, getMaximumRows(grid) - placement.y);
if (constraints.minHeight > maximumHeight) return null;
height = clamp(placement.h + deltaY, constraints.minHeight, maximumHeight);
}
return { ...placement, x, y, w: width, h: height };
};
const evaluateMoveGuards = <TPlacement extends GridPlacement>(
guards: readonly GridMoveGuard<TPlacement>[],
context: Parameters<GridMoveGuard<TPlacement>>[0],
): GridOperationRejection | null => {
for (const guard of guards) {
const result = guard(context);
if (result === true) continue;
if (result === false) return { code: "guard-rejected" };
return result;
}
return null;
};
const isTargetWithinActiveSubtree = <TPlacement extends GridPlacement>(
state: TransactionalGridState<TPlacement>,
targetGridId: string,
activeId: string,
) => {
let current: TransactionalGrid<TPlacement> | undefined = findGrid(state, targetGridId);
const visited = new Set<string>();
while (current) {
if (current.ownerPlacementId === activeId) return true;
if (!current.parentGridId || visited.has(current.id)) return false;
visited.add(current.id);
current = findGrid(state, current.parentGridId);
}
return false;
};
const accepted = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
preview: TransactionalGridState<TPlacement>,
): GridPreviewResult<TPlacement> => ({
accepted: true,
transaction: { ...transaction, preview },
});
const rejected = <TPlacement extends GridPlacement>(
transaction: GridTransaction<TPlacement>,
rejection: GridOperationRejection,
): GridPreviewResult<TPlacement> => ({ accepted: false, transaction, rejection });
const fitsRowLimits = <TPlacement extends GridPlacement>(state: TransactionalGridState<TPlacement>) =>
state.grids.every((grid) => {
if (grid.maxRowCount === undefined || grid.maxRowCount === null) return true;
return getLayoutRowCount(grid.placements) <= grid.maxRowCount;
});
const getMaximumRows = <TPlacement extends GridPlacement>(grid: TransactionalGrid<TPlacement>) =>
grid.maxRowCount ?? Number.MAX_SAFE_INTEGER;
const cloneGridState = <TPlacement extends GridPlacement>(
state: TransactionalGridState<TPlacement>,
): TransactionalGridState<TPlacement> => ({
grids: state.grids.map((grid) => ({
...grid,
placements: grid.placements.map((placement) => ({ ...placement })),
})),
});
const findGrid = <TPlacement extends GridPlacement>(state: TransactionalGridState<TPlacement>, gridId: string) =>
state.grids.find((grid) => grid.id === gridId);
const getGrid = <TPlacement extends GridPlacement>(state: TransactionalGridState<TPlacement>, gridId: string) => {
const grid = findGrid(state, gridId);
if (!grid) throw new Error(`Grid "${gridId}" does not exist`);
return grid;
};
const getPlacement = <TPlacement extends GridPlacement>(grid: TransactionalGrid<TPlacement>, itemId: string) => {
const placement = grid.placements.find((candidate) => candidate.id === itemId);
if (!placement) throw new Error(`Grid item "${itemId}" does not exist in grid "${grid.id}"`);
return placement;
};
const findPlacement = <TPlacement extends GridPlacement>(state: TransactionalGridState<TPlacement>, itemId: string) => {
for (const grid of state.grids) {
const placement = grid.placements.find((candidate) => candidate.id === itemId);
if (placement) return { grid, placement };
}
return null;
};
const areCoordinatesEqual = (first: GridPlacement, second: GridPlacement) =>
first.x === second.x && first.y === second.y && first.w === second.w && first.h === second.h;
const clamp = (value: number, minimum: number, maximum: number) => Math.min(Math.max(value, minimum), maximum);
const toPositiveInteger = (value: number, name: string) => {
if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) {
throw new RangeError(`${name} must be a positive integer`);
}
return value;
};
const validateGridState = <TPlacement extends GridPlacement>(state: TransactionalGridState<TPlacement>) => {
const gridIds = new Set<string>();
const placementIds = new Set<string>();
const ownerIds = new Set<string>();
for (const grid of state.grids) {
if (gridIds.has(grid.id)) throw new Error(`Duplicate grid id "${grid.id}"`);
gridIds.add(grid.id);
toPositiveInteger(grid.columnCount, `columnCount for grid "${grid.id}"`);
if (grid.maxRowCount !== undefined && grid.maxRowCount !== null) {
toPositiveInteger(grid.maxRowCount, `maxRowCount for grid "${grid.id}"`);
}
for (const placement of grid.placements) {
if (placementIds.has(placement.id)) throw new Error(`Duplicate grid item id "${placement.id}"`);
placementIds.add(placement.id);
validatePlacementBounds(placement, grid);
}
for (let index = 0; index < grid.placements.length; index += 1) {
const placement = grid.placements[index];
if (!placement) continue;
for (const other of grid.placements.slice(index + 1)) {
if (doGridPlacementsOverlap(placement, other)) {
throw new Error(`Grid items "${placement.id}" and "${other.id}" overlap in grid "${grid.id}"`);
}
}
}
}
for (const grid of state.grids) {
if (grid.parentGridId && !gridIds.has(grid.parentGridId)) {
throw new Error(`Parent grid "${grid.parentGridId}" for grid "${grid.id}" does not exist`);
}
if (grid.ownerPlacementId) {
if (!grid.parentGridId) throw new Error(`Owned grid "${grid.id}" must have a parent grid`);
if (ownerIds.has(grid.ownerPlacementId)) {
throw new Error(`Grid item "${grid.ownerPlacementId}" owns more than one grid`);
}
ownerIds.add(grid.ownerPlacementId);
const parent = getGrid(state, grid.parentGridId);
if (!parent.placements.some((placement) => placement.id === grid.ownerPlacementId)) {
throw new Error(`Owner item "${grid.ownerPlacementId}" does not exist in parent grid "${grid.parentGridId}"`);
}
}
}
for (const grid of state.grids) {
const visited = new Set<string>();
let current: TransactionalGrid<TPlacement> | undefined = grid;
while (current?.parentGridId) {
if (visited.has(current.id)) throw new Error(`Grid hierarchy contains a cycle at "${current.id}"`);
visited.add(current.id);
current = getGrid(state, current.parentGridId);
}
}
};
const validatePlacementBounds = <TPlacement extends GridPlacement>(
placement: TPlacement,
grid: TransactionalGrid<TPlacement>,
) => {
const values = [placement.x, placement.y, placement.w, placement.h];
if (values.some((value) => !Number.isFinite(value) || !Number.isInteger(value))) {
throw new Error(`Grid item "${placement.id}" must use finite integer coordinates`);
}
if (placement.x < 0 || placement.y < 0 || placement.w < 1 || placement.h < 1) {
throw new Error(`Grid item "${placement.id}" has invalid bounds`);
}
if (placement.x + placement.w > grid.columnCount) {
throw new Error(`Grid item "${placement.id}" exceeds grid "${grid.id}" columns`);
}
if (placement.y + placement.h > getMaximumRows(grid)) {
throw new Error(`Grid item "${placement.id}" exceeds grid "${grid.id}" rows`);
}
};
@@ -0,0 +1,33 @@
export {
beginGridTransaction,
cancelGridTransaction,
commitGridTransaction,
previewGridMove,
previewGridResize,
resolvePinnedGridCollisions,
} from "./engine";
export {
getContinuousGridDelta,
getContinuousResizePlacement,
getPointerProjectedShape,
getSnappedGridCoordinates,
getSnappedGridDelta,
} from "./coordinates";
export type { DragProjectionOrigin } from "./coordinates";
export { getPreferredNestedExitTargetId } from "./targeting";
export type { GridTargetGeometry } from "./targeting";
export type {
BeginGridTransactionInput,
GridMoveGuard,
GridMoveGuardContext,
GridMoveGuardResult,
GridMoveInput,
GridMoveOptions,
GridOperationRejection,
GridPreviewResult,
GridResizeDirection,
GridResizeInput,
GridTransaction,
TransactionalGrid,
TransactionalGridState,
} from "./types";
@@ -0,0 +1,68 @@
import { describe, expect, test } from "vitest";
import type { GridTargetGeometry } from "./targeting";
import { getPreferredNestedExitTargetId } from "./targeting";
const grid = (
id: string,
rectangle: GridTargetGeometry["rectangle"],
parentGridId: string | null = null,
): GridTargetGeometry => ({ id, parentGridId, rectangle });
const alwaysEligible = () => true;
describe("nested grid exit targeting", () => {
const grids = [
grid("canvas", { left: 0, top: 0, width: 1200, height: 800 }),
grid("container", { left: 200, top: 100, width: 600, height: 500 }, "canvas"),
];
test("keeps the nested grid while most of a large item remains inside", () => {
expect(
getPreferredNestedExitTargetId({
grids,
pointerTargetId: "container",
sourceGridId: "container",
dragShape: { left: 100, top: 150, width: 400, height: 200 },
isEligible: alwaysEligible,
}),
).toBe("container");
});
test("selects the parent before the pointer leaves when most of the item is outside", () => {
expect(
getPreferredNestedExitTargetId({
grids,
pointerTargetId: "container",
sourceGridId: "container",
dragShape: { left: 0, top: 150, width: 400, height: 200 },
isEligible: alwaysEligible,
}),
).toBe("canvas");
});
test("preserves a sibling container selected by the pointer", () => {
const withSibling = [...grids, grid("sibling", { left: 820, top: 100, width: 300, height: 500 }, "canvas")];
expect(
getPreferredNestedExitTargetId({
grids: withSibling,
pointerTargetId: "sibling",
sourceGridId: "container",
dragShape: { left: 820, top: 150, width: 300, height: 200 },
isEligible: alwaysEligible,
}),
).toBe("sibling");
});
test("does not escape to an ineligible parent", () => {
expect(
getPreferredNestedExitTargetId({
grids,
pointerTargetId: "container",
sourceGridId: "container",
dragShape: { left: 0, top: 150, width: 400, height: 200 },
isEligible: (gridId) => gridId !== "canvas",
}),
).toBe("container");
});
});
@@ -0,0 +1,90 @@
interface RectangleLike {
left: number;
top: number;
width: number;
height: number;
}
export interface GridTargetGeometry {
id: string;
parentGridId?: string | null;
rectangle: RectangleLike;
}
interface PreferredNestedExitTargetInput {
grids: readonly GridTargetGeometry[];
pointerTargetId: string;
sourceGridId: string;
dragShape: RectangleLike;
isEligible: (gridId: string) => boolean;
}
const NESTED_EXIT_RETAINED_AREA = 0.7;
/**
* Keeps pointer precision for entering containers, but lets a large item leave
* once a clear portion of its projected shape is visibly outside.
*/
export const getPreferredNestedExitTargetId = ({
grids,
pointerTargetId,
sourceGridId,
dragShape,
isEligible,
}: PreferredNestedExitTargetInput) => {
const byId = new Map(grids.map((grid) => [grid.id, grid]));
const source = byId.get(sourceGridId);
let current = byId.get(pointerTargetId);
if (!source || !current || !isSameGridOrAncestor(current.id, source, byId)) return pointerTargetId;
while (current.parentGridId) {
if (getCoveredAreaRatio(dragShape, current.rectangle) > NESTED_EXIT_RETAINED_AREA) break;
const parent = byId.get(current.parentGridId);
if (!parent || !isEligible(parent.id) || !containsCenter(parent.rectangle, dragShape)) break;
current = parent;
}
return current.id;
};
const isSameGridOrAncestor = (
candidateId: string,
source: GridTargetGeometry,
byId: ReadonlyMap<string, GridTargetGeometry>,
) => {
let current: GridTargetGeometry | undefined = source;
const visited = new Set<string>();
while (current) {
if (current.id === candidateId) return true;
if (!current.parentGridId || visited.has(current.id)) return false;
visited.add(current.id);
current = byId.get(current.parentGridId);
}
return false;
};
const getCoveredAreaRatio = (shape: RectangleLike, target: RectangleLike) => {
const shapeArea = shape.width * shape.height;
if (!Number.isFinite(shapeArea) || shapeArea <= 0) return 1;
const width = Math.max(
0,
Math.min(shape.left + shape.width, target.left + target.width) - Math.max(shape.left, target.left),
);
const height = Math.max(
0,
Math.min(shape.top + shape.height, target.top + target.height) - Math.max(shape.top, target.top),
);
return (width * height) / shapeArea;
};
const containsCenter = (target: RectangleLike, shape: RectangleLike) => {
const center = { x: shape.left + shape.width / 2, y: shape.top + shape.height / 2 };
return (
center.x >= target.left &&
center.x <= target.left + target.width &&
center.y >= target.top &&
center.y <= target.top + target.height
);
};
@@ -0,0 +1,98 @@
import type { GridPlacement } from "~/components/board/layout";
/** A positioned grid with optional ownership metadata for nested containers. */
export interface TransactionalGrid<TPlacement extends GridPlacement = GridPlacement> {
id: string;
columnCount: number;
maxRowCount?: number | null;
/** The grid containing the placement that owns this nested grid. */
parentGridId?: string | null;
/** The container placement whose content is rendered by this grid. */
ownerPlacementId?: string | null;
placements: readonly TPlacement[];
}
/** The complete layout that must change atomically for cross-grid operations. */
export interface TransactionalGridState<TPlacement extends GridPlacement = GridPlacement> {
grids: readonly TransactionalGrid<TPlacement>[];
}
/**
* A drag or resize transaction. Every preview is recomputed from `snapshot`,
* never from the previous preview, so noisy drag-over events cannot accumulate
* coordinate drift.
*/
export interface GridTransaction<TPlacement extends GridPlacement = GridPlacement> {
activeId: string;
sourceGridId: string;
snapshot: TransactionalGridState<TPlacement>;
preview: TransactionalGridState<TPlacement>;
}
export interface BeginGridTransactionInput {
activeId: string;
/** Optional disambiguation and stale-event protection. */
sourceGridId?: string;
}
export interface GridMoveInput {
targetGridId: string;
x: number;
y: number;
}
export type GridResizeDirection = "n" | "ne" | "e" | "se" | "s" | "sw" | "w" | "nw";
export interface GridResizeInput {
direction: GridResizeDirection;
/** Signed displacement of the resize handle in grid columns. */
deltaColumns: number;
/** Signed displacement of the resize handle in grid rows. */
deltaRows: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface GridOperationRejection {
code:
| "descendant-target"
| "guard-rejected"
| "invalid-coordinate"
| "item-too-large"
| "resize-constraints"
| "row-limit"
| "unknown-target-grid"
| (string & {});
message?: string;
}
export interface GridMoveGuardContext<TPlacement extends GridPlacement = GridPlacement> {
active: TPlacement;
sourceGrid: TransactionalGrid<TPlacement>;
targetGrid: TransactionalGrid<TPlacement>;
snapshot: TransactionalGridState<TPlacement>;
/** True when the target is owned by the active container or one of its descendants. */
targetIsDescendant: boolean;
}
export type GridMoveGuardResult = boolean | GridOperationRejection;
export type GridMoveGuard<TPlacement extends GridPlacement = GridPlacement> = (
context: GridMoveGuardContext<TPlacement>,
) => GridMoveGuardResult;
export interface GridMoveOptions<TPlacement extends GridPlacement = GridPlacement> {
guards?: readonly GridMoveGuard<TPlacement>[];
}
export type GridPreviewResult<TPlacement extends GridPlacement = GridPlacement> =
| {
accepted: true;
transaction: GridTransaction<TPlacement>;
}
| {
accepted: false;
transaction: GridTransaction<TPlacement>;
rejection: GridOperationRejection;
};
@@ -0,0 +1,233 @@
"use client";
import type { FocusEvent, KeyboardEvent, PropsWithChildren } from "react";
import { useId, useRef, 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 { ContainerSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import {
getEditableGridCellAttributes,
getLogicalItemStyle,
getReadonlyGridItemAttributes,
} from "~/components/board/layout";
import type { GridPlacement } from "~/components/board/layout";
import { useSectionContext } from "../section-context";
import { beginGridTransaction, commitGridTransaction, previewGridMove, previewGridResize } from "./dnd";
import type { GridTransaction } from "./dnd";
import { useGridEditorRuntimeStatus } from "./grid-editor-runtime";
import type { SectionGridPlacement } from "./use-grid-layout-actions";
import { useGridLayoutActions } from "./use-grid-layout-actions";
import classes from "./section-grid.module.css";
interface FixedGridItemProps {
item: ContainerSectionItem | SectionItem;
minWidth?: number;
minHeight?: number;
}
/**
* Static SSR geometry in view mode and the stable content/keyboard handle in
* edit mode. The focused tile owns grid-based keyboard movement while dnd-kit
* handles pointer and touch input on the outer editor shell.
*/
export const FixedGridItem = ({
item,
minWidth = 1,
minHeight = 1,
children,
}: PropsWithChildren<FixedGridItemProps>) => {
const [isEditMode] = useEditMode();
const runtimeStatus = useGridEditorRuntimeStatus();
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 isEditorActive = isEditMode && runtimeStatus === "ready";
const placement = toPlacement(item);
const renderedPlacements = [...items, ...innerSections].map(toPlacement);
const keyboardGridRef = useRef<{
source: readonly SectionGridPlacement[];
current: readonly SectionGridPlacement[];
}>({
source: renderedPlacements,
current: renderedPlacements,
});
const displayName =
item.type === "item"
? item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`)
: item.options.title.trim() || t("section.container.untitled");
const accessibleLabel = t("item.moveResize.entryLabel", {
name: displayName,
column: String(placement.x + 1),
row: String(placement.y + 1),
});
const semantics = isEditorActive
? getEditableGridCellAttributes({ label: accessibleLabel, placement })
: getReadonlyGridItemAttributes(placement);
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 || !isEditorActive || 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();
if (document.body.hasAttribute("data-board-grid-interacting")) {
setKeyboardEditing(false);
return;
}
if (!arePlacementListsEqual(keyboardGridRef.current.source, renderedPlacements)) {
keyboardGridRef.current = {
source: renderedPlacements,
current: renderedPlacements,
};
}
const placements = keyboardGridRef.current.current;
const current = placements.find((candidate) => candidate.id === item.id);
if (!current) return;
let transaction: GridTransaction<SectionGridPlacement>;
try {
transaction = beginGridTransaction(
{
grids: [
{
id: section.id,
columnCount,
maxRowCount,
placements,
},
],
},
{ activeId: current.id, sourceGridId: section.id },
);
} catch {
keyboardGridRef.current = {
source: renderedPlacements,
current: renderedPlacements,
};
setKeyboardEditing(false);
return;
}
const delta = getKeyboardDelta(event.key);
const result = event.shiftKey
? previewGridResize(transaction, {
direction: "se",
deltaColumns: delta.x,
deltaRows: delta.y,
minWidth,
minHeight,
})
: previewGridMove(transaction, {
targetGridId: section.id,
x: current.x + delta.x,
y: current.y + delta.y,
});
const next = result.transaction.preview.grids[0]?.placements.find((candidate) => candidate.id === item.id);
if (!result.accepted || !next || arePlacementsEqual(current, next)) {
announce(`${accessibleLabel}: ${t("item.moveResize.keyboard.boundary")}`);
return;
}
const committed = commitGridTransaction(result.transaction).grids[0];
if (!committed) return;
keyboardGridRef.current = {
...keyboardGridRef.current,
current: committed.placements,
};
commitSectionGrid({ layoutId: currentLayoutId, sectionId: section.id, placements: committed.placements });
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.target === event.currentTarget) {
setKeyboardEditing(false);
}
};
return (
<Box
{...semantics}
className={combineClasses(isEditorActive ? classes.editorEntry : classes.staticItem)}
style={isEditorActive ? { position: "relative", width: "100%", height: "100%" } : getLogicalItemStyle(placement)}
data-grid-item-id={isEditorActive ? undefined : item.id}
data-grid-item-type={isEditorActive ? undefined : item.type}
data-editor-grid-entry={isEditorActive ? "true" : undefined}
data-type={item.type}
data-kind={item.kind}
data-keyboard-editing={isEditorActive ? String(isKeyboardEditing) : undefined}
aria-describedby={isEditorActive ? instructionsId : undefined}
aria-keyshortcuts={
isEditorActive
? "Enter Space Escape ArrowLeft ArrowRight ArrowUp ArrowDown Shift+ArrowLeft Shift+ArrowRight Shift+ArrowUp Shift+ArrowDown"
: undefined
}
onBlur={isEditorActive ? handleBlur : undefined}
onKeyDown={isEditorActive ? handleKeyboard : undefined}
>
{children}
{isEditorActive && (
<span id={instructionsId} className={classes.liveRegion}>
{t("item.moveResize.keyboard.instructions")}
</span>
)}
</Box>
);
};
const toPlacement = (item: ContainerSectionItem | 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 getKeyboardDelta = (key: "ArrowLeft" | "ArrowRight" | "ArrowUp" | "ArrowDown") => ({
x: key === "ArrowLeft" ? -1 : key === "ArrowRight" ? 1 : 0,
y: key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0,
});
const arePlacementsEqual = (first: GridPlacement, second: GridPlacement) =>
first.x === second.x && first.y === second.y && first.w === second.w && first.h === second.h;
const arePlacementListsEqual = (first: readonly GridPlacement[], second: readonly GridPlacement[]) =>
first.length === second.length &&
first.every((placement, index) => {
const candidate = second[index];
return candidate?.id === placement.id && arePlacementsEqual(placement, candidate);
});
@@ -0,0 +1,14 @@
export const getGridDepth = (gridId: string, parentGridById: ReadonlyMap<string, string | null>) => {
let depth = 0;
let currentGridId = gridId;
const visited = new Set([gridId]);
while (true) {
const parentGridId = parentGridById.get(currentGridId);
if (!parentGridId || visited.has(parentGridId)) return depth;
depth += 1;
visited.add(parentGridId);
currentGridId = parentGridId;
}
};
@@ -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,17 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useContext } from "react";
export type GridEditorRuntimeStatus = "idle" | "loading" | "ready" | "error";
const GridEditorRuntimeContext = createContext<GridEditorRuntimeStatus>("idle");
export const GridEditorRuntimeProvider = ({
children,
status,
}: PropsWithChildren<{ status: GridEditorRuntimeStatus }>) => (
<GridEditorRuntimeContext.Provider value={status}>{children}</GridEditorRuntimeContext.Provider>
);
export const useGridEditorRuntimeStatus = () => useContext(GridEditorRuntimeContext);
@@ -0,0 +1,271 @@
.board-grid-editor {
position: absolute;
inset: 0 auto auto 0;
overflow: visible;
border-radius: var(--mantine-radius-md);
}
.board-grid-entry {
z-index: 1;
overflow: visible;
transition:
left 100ms ease,
top 100ms ease,
width 100ms ease,
height 100ms ease;
}
.board-grid-entry[data-dnd-active="true"],
.board-grid-entry[data-dnd-drag-source="true"] {
z-index: 1000;
transition: none;
}
.board-grid-entry[data-dnd-drag-source="true"] {
opacity: 0.42;
}
.board-grid-drag-overlay[data-dnd-dragging] {
position: fixed !important;
z-index: 10000;
top: var(--dnd-top, 0) !important;
left: var(--dnd-left, 0) !important;
width: var(--dnd-width, auto);
max-width: var(--dnd-width, auto);
height: var(--dnd-height, auto);
max-height: var(--dnd-height, auto);
padding: 0;
margin: 0;
overflow: visible;
color: inherit;
pointer-events: none !important;
background: transparent;
border: 0;
transform: var(--dnd-transform, none) !important;
transition: var(--dnd-transition) !important;
will-change: translate;
}
.board-grid-drag-overlay[data-dnd-dragging]:not([data-dnd-dropping]) {
translate: var(--dnd-translate) !important;
}
.board-grid-drag-overlay[data-dnd-dragging][style*="--dnd-scale"] {
scale: var(--dnd-scale) !important;
transform-origin: var(--dnd-transform-origin) !important;
}
.board-grid-drag-overlay-card {
display: grid;
width: 100%;
height: 100%;
padding: var(--mantine-spacing-md);
overflow: hidden;
font-weight: 600;
color: var(--mantine-color-text);
text-align: center;
overflow-wrap: anywhere;
place-items: center;
background: color-mix(in srgb, var(--mantine-color-body) 92%, transparent);
border: 2px solid var(--mantine-primary-color-filled);
border-radius: var(--mantine-radius-md);
box-shadow: var(--mantine-shadow-lg);
zoom: var(--board-grid-overlay-content-zoom, 1);
}
body[data-board-grid-interacting="drag"] .board-grid-entry,
body[data-board-grid-interacting="drag"] .board-grid-placeholder {
transition: none;
}
.board-grid-content-mount,
.board-grid-portal-content,
.board-grid-portal-content > [data-editor-grid-entry] {
width: 100%;
height: 100%;
overflow: visible;
}
.board-grid-placeholder {
z-index: 0;
background: color-mix(in srgb, var(--mantine-primary-color-filled) 16%, transparent);
border: 2px dashed var(--mantine-primary-color-filled);
border-radius: var(--mantine-radius-md);
pointer-events: none;
transition:
left 100ms ease,
top 100ms ease,
width 100ms ease,
height 100ms ease;
}
.board-grid-placeholder[data-grid-placeholder-mode="resize"] {
z-index: 1001;
background: color-mix(in srgb, var(--mantine-primary-color-filled) 10%, transparent);
}
.board-grid-resize-outline {
z-index: 1002;
background: color-mix(in srgb, var(--mantine-primary-color-filled) 6%, transparent);
border: 2px solid var(--mantine-primary-color-filled);
border-radius: var(--mantine-radius-md);
pointer-events: none;
}
.board-grid-resize-outline[data-grid-resize-valid="false"] {
background: color-mix(in srgb, var(--mantine-color-red-filled) 8%, transparent);
border-color: var(--mantine-color-red-filled);
}
.board-grid-editor[data-dnd-drop-target="true"] {
outline: 2px solid color-mix(in srgb, var(--mantine-primary-color-filled) 60%, transparent);
outline-offset: 4px;
}
.board-grid-editor[data-dnd-drop-target="true"][data-dnd-drop-valid="false"] {
outline-color: var(--mantine-color-red-filled);
}
.board-grid-resize-handle {
position: absolute;
z-index: 20;
display: block;
padding: 0;
appearance: none;
background: transparent;
border: 0;
touch-action: none;
}
.board-grid-resize-handle[data-grid-resize-disabled="true"] {
pointer-events: none;
}
.board-grid-entry[data-grid-item-type="section"][data-grid-section-chrome-active="true"] {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: 4px;
}
.board-grid-entry[data-grid-item-type="section"][data-grid-section-chrome-active="true"]
> .board-grid-resize-handle:not([data-grid-resize-disabled="true"])::after {
opacity: 1;
}
.board-grid-resize-handle::after {
position: absolute;
inset: 50% auto auto 50%;
width: 12px;
height: 3px;
content: "";
background: color-mix(in srgb, var(--mantine-color-text) 70%, transparent);
border-radius: var(--mantine-radius-xl);
opacity: 0;
transform: translate(-50%, -50%);
transition: opacity 100ms ease;
}
.board-grid-entry:hover > .board-grid-resize-handle:not([data-grid-resize-disabled="true"])::after,
.board-grid-resize-handle:not([data-grid-resize-disabled="true"]):focus-visible::after {
opacity: 1;
}
.board-grid-resize-handle:focus-visible {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: -8px;
}
.board-grid-resize-handle[data-grid-resize-handle="n"],
.board-grid-resize-handle[data-grid-resize-handle="s"] {
right: 44px;
left: 44px;
height: 32px;
cursor: ns-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="n"] {
top: 0;
}
.board-grid-resize-handle[data-grid-resize-handle="s"] {
bottom: 0;
}
.board-grid-resize-handle[data-grid-resize-handle="e"],
.board-grid-resize-handle[data-grid-resize-handle="w"] {
top: 44px;
bottom: 44px;
width: 32px;
cursor: ew-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="e"] {
right: 0;
}
.board-grid-resize-handle[data-grid-resize-handle="w"] {
left: 0;
}
.board-grid-resize-handle[data-grid-resize-handle="e"]::after,
.board-grid-resize-handle[data-grid-resize-handle="w"]::after {
width: 3px;
height: 12px;
}
.board-grid-resize-handle[data-grid-resize-handle="ne"],
.board-grid-resize-handle[data-grid-resize-handle="se"],
.board-grid-resize-handle[data-grid-resize-handle="sw"],
.board-grid-resize-handle[data-grid-resize-handle="nw"] {
z-index: 9;
width: 44px;
height: 44px;
}
.board-grid-resize-handle[data-grid-resize-handle="ne"] {
top: 0;
right: 0;
cursor: nesw-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="se"] {
right: 0;
bottom: 0;
cursor: nwse-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="sw"] {
bottom: 0;
left: 0;
cursor: nesw-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="nw"] {
top: 0;
left: 0;
cursor: nwse-resize;
}
.board-grid-resize-handle[data-grid-resize-handle="ne"]::after,
.board-grid-resize-handle[data-grid-resize-handle="sw"]::after {
transform: translate(-50%, -50%) rotate(-45deg);
}
.board-grid-resize-handle[data-grid-resize-handle="se"]::after,
.board-grid-resize-handle[data-grid-resize-handle="nw"]::after {
transform: translate(-50%, -50%) rotate(45deg);
}
@media (hover: none), (pointer: coarse) {
.board-grid-resize-handle:not([data-grid-resize-disabled="true"])::after {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.board-grid-entry,
.board-grid-placeholder,
.board-grid-resize-outline,
.board-grid-resize-handle::after {
transition: none;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,212 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { getRootSectionLane } from "@homarr/definitions";
import type { ContainerSectionItem, 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 classes from "./section-grid.module.css";
interface GridPortalHostContextValue {
announce: (message: string) => void;
integrations: RouterOutputs["integration"]["all"] | undefined;
containers: ReadonlyMap<string, HTMLElement>;
acquireContainer: (id: string) => HTMLElement;
}
const GridPortalHostContext = createContext<GridPortalHostContextValue | null>(null);
/**
* One portal registry owns every edit-mode item on the board. Its content
* containers are stable even when drag-and-drop 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 { data: session } = useSession();
const [isEditMode] = useEditMode();
const { data: integrations } = clientApi.integration.all.useQuery(undefined, {
enabled: Boolean(session) && isEditMode,
});
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 liveEntryIds = useMemo(
() => new Set([...board.items.map((item) => item.id), ...board.sections.map((section) => section.id)]),
[board.items, board.sections],
);
const acquireContainer = useCallback((id: string) => {
const existing = containersRef.current.get(id);
if (existing) return existing;
const container = document.createElement("div");
container.className = "board-grid-portal-content";
container.dataset.boardGridPortal = id;
containersRef.current.set(id, container);
setContainers(new Map(containersRef.current));
return container;
}, []);
useEffect(() => {
// A cross-grid move can briefly have no shell, but the entry still exists
// on the board. Only remove containers whose board entity was deleted.
let didPrune = false;
for (const id of containersRef.current.keys()) {
if (liveEntryIds.has(id)) continue;
containersRef.current.delete(id);
didPrune = true;
}
if (didPrune) setContainers(new Map(containersRef.current));
}, [liveEntryIds]);
const value = useMemo<GridPortalHostContextValue>(
() => ({
announce,
integrations,
containers,
acquireContainer,
}),
[acquireContainer, announce, containers, integrations],
);
return (
<GridPortalHostContext.Provider value={value}>
{children}
<div className={classes.liveRegion} aria-live="polite" aria-atomic="true">
<span key={announcement.id}>{announcement.message}</span>
</div>
</GridPortalHostContext.Provider>
);
};
/**
* Renders stable portal content at this component's logical React position.
* Keep it inside the editor runtime and dnd-kit providers so portaled entries
* inherit the same keyboard, transaction, and nested-grid contexts as shells.
*/
export const BoardGridPortalRenderer = () => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { announce, containers, integrations } = useBoardGridPortalHost();
return (
<>
{Array.from(containers, ([id, container]) => {
const ownerSectionId = getOwnerSectionId(board, currentLayoutId, id);
return ownerSectionId
? createPortal(
<GridPortalContent
itemId={id}
ownerSectionId={ownerSectionId}
integrations={integrations}
announce={announce}
/>,
container,
id,
)
: null;
})}
</>
);
};
export const useBoardGridPortalHost = () => {
const context = useContext(GridPortalHostContext);
if (!context) throw new Error("BoardGridPortalHost is required");
return context;
};
interface GridPortalContentProps {
itemId: string;
ownerSectionId: string;
integrations: RouterOutputs["integration"]["all"] | undefined;
announce: (message: string) => void;
}
const GridPortalContent = ({ itemId, ownerSectionId, integrations, announce }: GridPortalContentProps) => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { items, innerSections } = useSectionItems(ownerSectionId);
const persistedEntry = [...items, ...innerSections].find((candidate) => candidate.id === itemId);
const entry = persistedEntry;
const rawSection = board.sections.find((section) => section.id === ownerSectionId);
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId);
const persistedSection = toGridSection(rawSection, currentLayoutId);
const section = persistedSection;
if (!entry || !section || !currentLayout) return null;
const columnCount =
section.kind === "container"
? section.width
: section.kind === "empty"
? getBoardLaneColumnCount(currentLayout, getRootSectionLane(section.xOffset))
: currentLayout.columnCount;
const configuredMaxRowCount = section.kind === "container" ? 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: "container" }> | ContainerSectionItem | null => {
if (!section) return null;
if (section.kind !== "container") 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 === "container" && candidate.id === entryId);
if (!section || section.kind !== "container") return null;
return section.layouts.find((layout) => layout.layoutId === layoutId)?.parentSectionId ?? null;
};
@@ -0,0 +1,49 @@
import { getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
import type { Board } from "~/app/[locale]/boards/_types";
import type { SectionGridPlacement } from "./use-grid-layout-actions";
export const getSectionGridPlacements = (board: Board, layoutId: string, sectionId: string): SectionGridPlacement[] => [
...board.items.flatMap((item) => {
const layout = item.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.sectionId === sectionId
? [
{
id: item.id,
type: "item" as const,
x: layout.xOffset,
y: layout.yOffset,
w: layout.width,
h: layout.height,
},
]
: [];
}),
...board.sections.flatMap((section) => {
if (section.kind !== "container") return [];
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.parentSectionId === sectionId
? [
{
id: section.id,
type: "section" as const,
x: layout.xOffset,
y: layout.yOffset,
w: layout.width,
h: layout.height,
},
]
: [];
}),
];
export const getSectionGridColumnCount = (board: Board, layoutId: string, sectionId: string): number | null => {
const section = board.sections.find((candidate) => candidate.id === sectionId);
if (!section) return null;
if (section.kind === "container") {
return section.layouts.find((layout) => layout.layoutId === layoutId)?.width ?? null;
}
const layout = board.layouts.find((candidate) => candidate.id === layoutId);
return layout ? getBoardLaneColumnCount(layout, getRootSectionLane(section.xOffset)) : null;
};
@@ -0,0 +1,75 @@
.viewport {
position: relative;
overflow: visible;
}
.staticGrid,
.editorGrid {
position: relative;
overflow: visible;
}
.editorGrid {
position: absolute;
inset: 0 auto auto 0;
}
.staticItem {
overflow: visible;
transition:
left 220ms ease,
top 220ms ease,
width 220ms ease,
height 220ms ease;
}
.editorEntry {
position: relative;
width: 100%;
height: 100%;
overflow: visible;
cursor: grab;
user-select: none;
}
.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,262 @@
"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 { ContainerSectionItem, 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 { useGridEditorRuntimeStatus } from "./grid-editor-runtime";
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: "container" }> | ContainerSectionItem;
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 editorRuntimeStatus = useGridEditorRuntimeStatus();
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,
getContainerMinimumSize(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 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: section.kind === "container" ? 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 && editorRuntimeStatus === "ready" ? (
<GridEditor
sectionId={section.id}
columnCount={columnCount}
rowCount={rowCount}
placements={displayPlacements}
className={combineClasses("board-grid-editor", classes.editorGrid)}
/>
) : isEditMode && editorRuntimeStatus === "loading" ? (
<GridEditorLoading />
) : (
<Box
className={classes.staticGrid}
style={{ width: logicalWidth, height: logicalHeight }}
data-grid-section-id={section.id}
data-kind={section.kind}
data-grid-editor-error={isEditMode && editorRuntimeStatus === "error" ? "true" : undefined}
>
<SectionContent />
</Box>
)}
</Box>
</SectionProvider>
);
};
const getContainerMinimumSize = (
board: ReturnType<typeof useRequiredBoard>,
layoutId: string,
sectionId: string,
visited = new Set<string>(),
): { width: number; height: number } => {
if (visited.has(sectionId)) return { width: 1, height: 1 };
const nextVisited = new Set(visited).add(sectionId);
const directItems: PlacementBounds[] = board.items.flatMap((item) => {
const layout = item.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.sectionId === sectionId ? [layout] : [];
});
const directSections: PlacementBounds[] = board.sections.flatMap((candidate) => {
if (candidate.kind !== "container") return [];
const layout = candidate.layouts.find((candidateLayout) => candidateLayout.layoutId === layoutId);
if (!layout || layout.parentSectionId !== sectionId) return [];
const minimum = getContainerMinimumSize(board, layoutId, candidate.id, nextVisited);
return [
{
...layout,
width: Math.max(layout.width, minimum.width),
height: Math.max(layout.height, minimum.height),
},
];
});
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)),
};
};
interface PlacementBounds {
xOffset: number;
yOffset: number;
width: number;
height: number;
}
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,321 @@
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("../grid-editor-runtime", () => ({
useGridEditorRuntimeStatus: () => "ready",
}));
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;
getClockMock().xOffset = 1;
getClockMock().yOffset = 0;
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
test("moves with the keyboard and swaps an equal-sized destination", () => {
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: 0, y: 0, 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).toHaveBeenCalledWith({
layoutId: "layout",
sectionId: "root",
placements: [
{ id: "weather", type: "item", x: 0, y: 0, w: 1, 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("applies repeated keyboard resizes before board props rerender", () => {
renderWeather(root);
const entry = getEditorEntry(container);
startKeyboardEditing(entry);
act(() => {
entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", shiftKey: true, bubbles: true }));
entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", shiftKey: true, bubbles: true }));
});
expect(mocks.commitSectionGrid).toHaveBeenCalledTimes(2);
expect(mocks.commitSectionGrid).toHaveBeenLastCalledWith({
layoutId: "layout",
sectionId: "root",
placements: [
{ id: "weather", type: "item", x: 0, y: 0, w: 1, h: 3 },
{ id: "clock", type: "item", x: 1, y: 0, w: 1, h: 1 },
],
});
});
test("stops keyboard editing when the rendered grid state is invalid", () => {
getClockMock().xOffset = 0;
renderWeather(root);
const entry = getEditorEntry(container);
startKeyboardEditing(entry);
act(() => entry.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
expect(entry.dataset.keyboardEditing).toBe("false");
expect(mocks.commitSectionGrid).not.toHaveBeenCalled();
expect(mocks.announce).toHaveBeenLastCalledWith(
"widget.weather.name, column 1, row 1: item.moveResize.keyboard.stopped",
);
});
test("uses the whole tile as the focusable move surface without extra drag chrome", () => {
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-affordance"]')).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: 0.5 },
{ ...persisted[1], y: 0.5 },
]);
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 getClockMock = () => {
const item = mocks.items[1];
if (!item) throw new Error("Expected the clock 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,26 @@
import { describe, expect, test } from "vitest";
import { getGridDepth } from "../grid-depth";
describe("grid depth", () => {
test("follows the registered parent chain for deeply nested grids", () => {
const parents = new Map<string, string | null>([
["root", null],
["first", "root"],
["second", "first"],
["third", "second"],
]);
expect(getGridDepth("root", parents)).toBe(0);
expect(getGridDepth("third", parents)).toBe(3);
});
test("stops safely when malformed parent data contains a cycle", () => {
const parents = new Map<string, string | null>([
["first", "second"],
["second", "first"],
]);
expect(getGridDepth("first", parents)).toBe(1);
});
});
@@ -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,89 @@
import { readdirSync, readFileSync } from "node:fs";
import { relative, resolve } from "node:path";
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 current dnd-kit runtime import inside the edit-only module", () => {
const runtimeImports = getSourceFiles(nextjsSourceDirectory)
.flatMap(getRuntimeImports)
.filter(({ specifier }) => isCurrentDndKitImport(specifier))
.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: "@dnd-kit/abstract" },
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/collision" },
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom" },
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/dom/utilities" },
{ file: "components/board/sections/grid/grid-editor.tsx", kind: "static", specifier: "@dnd-kit/react" },
]);
});
test("loads the editor through next/dynamic only in the edit branch", () => {
const source = readFileSync(sectionGridPath, "utf8");
expect(source).toMatch(/import dynamic from ["']next\/dynamic["']/);
expect(source).toMatch(
/const GridEditor = dynamic\(loadGridEditorAsync,\s*{[\s\S]*?loading:\s*GridEditorLoading,[\s\S]*?ssr:\s*false,[\s\S]*?}\);/,
);
expect(source.match(/<GridEditor\b/g)).toHaveLength(1);
expect(source).toMatch(/isEditMode\s*&&\s*editorRuntimeStatus\s*===\s*["']ready["']\s*\?\s*\(\s*<GridEditor\b/);
expect(getRuntimeImports(sectionGridPath).filter(({ specifier }) => specifier === "./grid-editor")).toEqual([]);
expect(
getRuntimeImports(editorLoaderPath)
.filter(({ specifier }) => specifier === "./grid-editor")
.map(({ kind }) => kind),
).toEqual(["dynamic"]);
});
});
const CURRENT_DND_KIT_PACKAGES = ["@dnd-kit/abstract", "@dnd-kit/collision", "@dnd-kit/dom", "@dnd-kit/react"];
const isCurrentDndKitImport = (specifier: string) =>
CURRENT_DND_KIT_PACKAGES.some((packageName) => specifier === packageName || specifier.startsWith(`${packageName}/`));
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 source = readFileSync(filePath, "utf8");
const imports: RuntimeImport[] = [];
const addMatches = (pattern: RegExp, kind: RuntimeImport["kind"], specifierGroup: number) => {
for (const match of source.matchAll(pattern)) {
const specifier = match[specifierGroup];
if (specifier) imports.push({ filePath, kind, specifier });
}
};
addMatches(/(?:^|\n)\s*(?:import|export)\s+(?!type\b)[^;]*?\sfrom\s*["']([^"']+)["']/g, "static", 1);
addMatches(/(?:^|\n)\s*import\s*["']([^"']+)["']/g, "static", 1);
addMatches(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g, "dynamic", 1);
addMatches(/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g, "require", 1);
return imports;
};
const toSourceRelativePath = (filePath: string) => relative(nextjsSourceDirectory, filePath).replaceAll("\\", "/");
@@ -0,0 +1,104 @@
import { act, createElement, useLayoutEffect } 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 { BoardGridPortalHost, useBoardGridPortalHost } from "../grid-portal-host";
const mocks = vi.hoisted(() => ({
board: {
items: [{ id: "weather", layouts: [{ layoutId: "desktop", sectionId: "root" }] }],
sections: [],
},
}));
vi.mock("@homarr/api/client", () => ({
clientApi: {
integration: {
all: {
useQuery: () => ({ data: undefined }),
},
},
},
}));
vi.mock("@homarr/auth/client", () => ({
useSession: () => ({ data: { user: { id: "user" } } }),
}));
vi.mock("@homarr/boards/context", () => ({
useCurrentLayout: () => "desktop",
useRequiredBoard: () => mocks.board,
}));
vi.mock("@homarr/boards/edit-mode", () => ({
useEditMode: () => [true],
}));
describe("board grid portal host", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
mocks.board = {
items: [{ id: "weather", layouts: [{ layoutId: "desktop", sectionId: "root" }] }],
sections: [],
};
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
test("keeps a portal across relocation and prunes it after permanent deletion", () => {
const acquired: HTMLElement[] = [];
renderHost(root, true, 0, acquired);
expect(getContainerCount(container)).toBe("1");
mocks.board = {
items: [{ id: "weather", layouts: [{ layoutId: "desktop", sectionId: "other" }] }],
sections: [],
};
renderHost(root, true, 1, acquired);
expect(getContainerCount(container)).toBe("1");
expect(new Set(acquired).size).toBe(1);
mocks.board = { items: [], sections: [] };
renderHost(root, false, 2, acquired);
expect(getContainerCount(container)).toBe("0");
});
});
const renderHost = (root: Root, acquire: boolean, revision: number, acquired: HTMLElement[]) => {
act(() => {
root.render(
createElement(BoardGridPortalHost, null, createElement(PortalRegistryProbe, { acquire, revision, acquired })),
);
});
};
const PortalRegistryProbe = ({
acquire,
revision,
acquired,
}: {
acquire: boolean;
revision: number;
acquired: HTMLElement[];
}) => {
const portalHost = useBoardGridPortalHost();
useLayoutEffect(() => {
if (acquire) acquired.push(portalHost.acquireContainer("weather"));
}, [acquire, acquired, portalHost, revision]);
return createElement("span", { "data-container-count": String(portalHost.containers.size) });
};
const getContainerCount = (container: HTMLElement) =>
container.querySelector<HTMLElement>("[data-container-count]")?.dataset.containerCount;
@@ -0,0 +1,112 @@
"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 complete section snapshots in one cache update. One drag or resize
* can move several neighbours and can cross section boundaries, so the whole
* transaction must remain atomic.
*/
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) => {
let hasChanges = false;
const 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;
if (
layout.sectionId === sectionId &&
layout.xOffset === placement.x &&
layout.yOffset === placement.y &&
layout.width === placement.w &&
layout.height === placement.h
) {
return layout;
}
return {
...layout,
sectionId,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
};
});
if (!layouts.some((layout, index) => layout !== item.layouts[index])) return item;
hasChanges = true;
return { ...item, layouts };
});
const sections = previous.sections.map((innerSection) => {
if (innerSection.kind !== "container") 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;
if (
layout.parentSectionId === sectionId &&
layout.xOffset === placement.x &&
layout.yOffset === placement.y &&
layout.width === placement.w &&
layout.height === placement.h
) {
return layout;
}
return {
...layout,
parentSectionId: sectionId,
xOffset: placement.x,
yOffset: placement.y,
width: placement.w,
height: placement.h,
};
});
if (!layouts.some((layout, index) => layout !== innerSection.layouts[index])) return innerSection;
hasChanges = true;
return { ...innerSection, layouts };
});
return hasChanges ? { ...previous, items, sections } : previous;
});
},
[updateBoard],
);
const commitSectionGrid = useCallback(
(snapshot: CommitSectionGridInput) => {
commitSectionGrids([snapshot]);
},
[commitSectionGrids],
);
return { commitSectionGrid, commitSectionGrids };
};
@@ -1,62 +0,0 @@
import { useEffect } from "react";
import type { PropsWithChildren } from "react";
import type { BoxProps } from "@mantine/core";
import { Box } from "@mantine/core";
import combineClasses from "clsx";
import type { SectionKind, WidgetKind } from "@homarr/definitions";
import type { GridItemHTMLElement } from "@homarr/gridstack";
interface Props extends BoxProps {
id: string;
type: "item" | "section";
kind: WidgetKind | SectionKind;
xOffset: number;
yOffset: number;
width: number;
height: number;
minWidth?: number;
minHeight?: number;
innerRef: React.RefObject<GridItemHTMLElement | null> | undefined;
}
export const GridStackItem = ({
id,
type,
kind,
xOffset,
yOffset,
width,
height,
minWidth = 1,
minHeight = 1,
innerRef,
children,
...boxProps
}: PropsWithChildren<Props>) => {
useEffect(() => {
if (!innerRef?.current?.gridstackNode) return;
if (type !== "section") return;
innerRef.current.gridstackNode.minW = minWidth;
innerRef.current.gridstackNode.minH = minHeight;
}, [minWidth, minHeight, innerRef, type]);
return (
<Box
{...boxProps}
className={combineClasses("grid-stack-item", boxProps.className)}
data-id={id}
data-type={type}
data-kind={kind}
gs-x={xOffset}
gs-y={yOffset}
gs-w={width}
gs-h={height}
gs-min-w={minWidth}
gs-min-h={minHeight}
ref={innerRef as React.RefObject<HTMLDivElement>}
>
{children}
</Box>
);
};
@@ -1,11 +0,0 @@
import { describe, expect, test } from "vitest";
import { filterRecursiveInnerSections } from "./gridstack";
describe("filterRecursiveInnerSections", () => {
test("removes sections that would recursively render an ancestor", () => {
const innerSections = [{ id: "safe" }, { id: "parent" }, { id: "root" }];
expect(filterRecursiveInnerSections(innerSections, new Set(["root", "parent"]))).toEqual([{ id: "safe" }]);
});
});
@@ -1,46 +0,0 @@
"use client";
import type { BoxProps } from "@mantine/core";
import { Box } from "@mantine/core";
import combineClasses from "clsx";
import type { DynamicSectionItem, Section } from "~/app/[locale]/boards/_types";
import { SectionContent } from "../content";
import { SectionProvider } from "../section-context";
import { useSectionItems } from "../use-section-items";
import { useGridstack } from "./use-gridstack";
interface Props extends BoxProps {
section: Exclude<Section, { kind: "dynamic" }> | DynamicSectionItem;
ancestorSectionIds?: ReadonlySet<string>;
}
export const GridStack = ({ section, ancestorSectionIds = new Set(), ...props }: Props) => {
const { items, innerSections } = useSectionItems(section.id);
const nextAncestorSectionIds = new Set(ancestorSectionIds).add(section.id);
const safeInnerSections = filterRecursiveInnerSections(innerSections, nextAncestorSectionIds);
const itemIds = [...items, ...safeInnerSections].map((item) => item.id);
const { refs } = useGridstack(section, itemIds);
return (
<SectionProvider
value={{ section, ancestorSectionIds: nextAncestorSectionIds, items, innerSections: safeInnerSections, refs }}
>
<Box
{...props}
data-kind={section.kind}
data-section-id={section.id}
className={combineClasses(`grid-stack grid-stack-${section.kind}`, props.className)}
ref={refs.wrapper}
>
<SectionContent />
</Box>
</SectionProvider>
);
};
export const filterRecursiveInnerSections = <T extends { id: string }>(
innerSections: T[],
ancestorSectionIds: ReadonlySet<string>,
) => innerSections.filter((innerSection) => !ancestorSectionIds.has(innerSection.id));
@@ -1,56 +0,0 @@
import type { RefObject } from "react";
import type { GridItemHTMLElement } from "@homarr/gridstack";
import { GridStack } from "@homarr/gridstack";
import type { Section } from "~/app/[locale]/boards/_types";
interface InitializeGridstackProps {
section: Omit<Section, "items">;
itemIds: string[];
refs: {
wrapper: RefObject<HTMLDivElement | null>;
items: RefObject<Record<string, RefObject<GridItemHTMLElement | null>>>;
gridstack: RefObject<GridStack | null>;
};
sectionColumnCount: number;
}
export const initializeGridstack = ({ section, itemIds, refs, sectionColumnCount }: InitializeGridstackProps) => {
if (!refs.wrapper.current) return false;
// initialize gridstack
const newGrid = refs.gridstack;
newGrid.current = GridStack.init(
{
column: sectionColumnCount,
margin: 10,
cellHeight: 128,
float: true,
alwaysShowResizeHandle: true,
acceptWidgets: true,
staticGrid: true,
minRow: section.kind === "dynamic" && "height" in section ? (section.height as number) : 1,
maxRow: section.kind === "dynamic" && "height" in section ? (section.height as number) : 0,
animate: false,
styleInHead: true,
disableRemoveNodeOnDrop: true,
},
// selector of the gridstack item (it's eather category or wrapper)
`.grid-stack-${section.kind}[data-section-id='${section.id}']`,
);
const grid = newGrid.current;
// Must be used to update the column count after the initialization
grid.column(sectionColumnCount, "none");
grid.batchUpdate();
grid.removeAll(false);
itemIds.forEach((id) => {
const ref = refs.items.current[id]?.current;
if (!ref) return;
grid.makeWidget(ref);
});
grid.batchUpdate(false);
return true;
};
@@ -1,372 +0,0 @@
import type { Ref, RefObject } from "react";
import { createRef, useCallback, useEffect, useRef } from "react";
import { useElementSize, useMergedRef } from "@mantine/hooks";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import type { GridHTMLElement, GridItemHTMLElement, GridStack, GridStackNode } from "@homarr/gridstack";
import type { Section } from "~/app/[locale]/boards/_types";
import { useMarkSectionAsReady } from "~/app/[locale]/boards/(content)/_ready-context";
import { useItemActions } from "../../items/item-actions";
import { useSectionActions } from "../section-actions";
import { initializeGridstack } from "./init-gridstack";
export interface UseGridstackRefs {
wrapper: Ref<HTMLDivElement | null>;
items: RefObject<Record<string, RefObject<GridItemHTMLElement | null>>>;
gridstack: RefObject<GridStack | null>;
}
interface UseGristackReturnType {
refs: UseGridstackRefs;
}
/**
* When the size of a gridstack changes we need to update the css variables
* so the gridstack items are displayed correctly
* @param wrapper gridstack wrapper
* @param gridstack gridstack object
* @param width width of the section (column count)
* @param height height of the section (row count)
* @param isDynamic if the section is dynamic
*/
const handleResizeChange = (
wrapper: HTMLDivElement,
gridstack: GridStack,
width: number,
height: number,
isDynamic: boolean,
) => {
wrapper.style.setProperty("--gridstack-column-count", width.toString());
wrapper.style.setProperty("--gridstack-row-count", height.toString());
let cellHeight = wrapper.clientWidth / width;
if (isDynamic) {
cellHeight = wrapper.clientHeight / height;
}
if (!isDynamic) {
document.body.style.setProperty("--gridstack-cell-size", cellHeight.toString());
}
gridstack.cellHeight(cellHeight);
};
export const useGridstack = (section: Omit<Section, "items">, itemIds: string[]): UseGristackReturnType => {
const [isEditMode] = useEditMode();
const markAsReady = useMarkSectionAsReady();
const { moveAndResizeItem, moveItemToSection } = useItemActions();
const { moveAndResizeInnerSection, moveInnerSectionToSection } = useSectionActions();
const wrapperElementRef = useRef<HTMLDivElement | null>(null);
const { ref: measureWrapperRef, width, height } = useElementSize<HTMLDivElement>();
const wrapperRef = useMergedRef(measureWrapperRef, wrapperElementRef);
// references to the diffrent items contained in the gridstack
const itemRefs = useRef<Record<string, RefObject<GridItemHTMLElement | null>>>({});
// reference of the gridstack object for modifications after initialization
const gridRef = useRef<GridStack>(null);
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId)!;
const columnCount =
section.kind === "dynamic" && "width" in section && typeof section.width === "number"
? section.width
: currentLayout.columnCount;
const itemRefKeys = Object.keys(itemRefs.current);
// define items in itemRefs for easy access and reference to items
if (itemRefKeys.length !== itemIds.length) {
// Remove items that are not in the itemIds
// Otherwise when an item is removed and then another item is added, this foreach below will not run.
itemRefKeys.forEach((id) => {
if (!itemIds.includes(id)) {
delete itemRefs.current[id];
}
});
itemIds.forEach((id) => {
itemRefs.current[id] = itemRefs.current[id] ?? createRef();
});
}
const onChange = useCallback(
(changedNode: GridStackNode) => {
const id = changedNode.el?.getAttribute("data-id");
const type = changedNode.el?.getAttribute("data-type");
if (!id || !type) return;
if (type === "item") {
// Updates the react-query state
moveAndResizeItem({
itemId: id,
// We want the following properties to be null by default
// so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xOffset: changedNode.x!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yOffset: changedNode.y!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
width: changedNode.w!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
height: changedNode.h!,
});
return;
}
if (type === "section") {
moveAndResizeInnerSection({
innerSectionId: id,
// We want the following properties to be null by default
// so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xOffset: changedNode.x!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yOffset: changedNode.y!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
width: changedNode.w!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
height: changedNode.h!,
});
return;
}
console.error(`Unknown grid-stack-item type to move. type='${type}' id='${id}'`);
},
[moveAndResizeItem, moveAndResizeInnerSection],
);
const onAdd = useCallback(
(addedNode: GridStackNode) => {
const id = addedNode.el?.getAttribute("data-id");
const type = addedNode.el?.getAttribute("data-type");
if (!id || !type) return;
if (type === "item") {
// Updates the react-query state
moveItemToSection({
itemId: id,
sectionId: section.id,
// We want the following properties to be null by default
// so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xOffset: addedNode.x!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yOffset: addedNode.y!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
width: addedNode.w!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
height: addedNode.h!,
});
return;
}
if (type === "section") {
moveInnerSectionToSection({
innerSectionId: id,
sectionId: section.id,
// We want the following properties to be null by default
// so the next free position is used from the gridstack
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
xOffset: addedNode.x!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yOffset: addedNode.y!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
width: addedNode.w!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
height: addedNode.h!,
});
return;
}
console.error(`Unknown grid-stack-item type to add. type='${type}' id='${id}'`);
},
[moveItemToSection, moveInnerSectionToSection, section.id],
);
// initialize the gridstack
useEffect(() => {
const isReady = initializeGridstack({
section,
itemIds,
refs: {
items: itemRefs,
wrapper: wrapperElementRef,
gridstack: gridRef,
},
sectionColumnCount: columnCount,
});
// If the section is ready mark it as ready
// When all sections are ready the board is ready and will get visible
if (isReady) {
markAsReady(section.id);
}
// Only run this effect when the section items change
}, [itemIds.length, columnCount]);
/**
* IMPORTANT: This effect has to be placed after the effect to initialize the gridstack
* because we need the gridstack object to add the listeners
*/
useEffect(() => {
if (!isEditMode) return;
const currentGrid = gridRef.current;
// Add listener for moving items around in a wrapper
currentGrid?.on("change", (_, nodes) => {
nodes.forEach(onChange);
// For all dynamic section items that changed we want to update the inner gridstack
nodes
.filter((node) => node.el?.getAttribute("data-type") === "section")
.forEach((node) => {
const dynamicInnerGrid = node.el?.querySelector<GridHTMLElement>('.grid-stack[data-kind="dynamic"]');
if (!dynamicInnerGrid?.gridstack) return;
handleResizeChange(
dynamicInnerGrid as HTMLDivElement,
dynamicInnerGrid.gridstack,
node.w ?? 1,
node.h ?? 1,
true,
);
});
});
// Add listener for moving items in config from one wrapper to another
currentGrid?.on("added", (_, nodes) => {
nodes.forEach(onAdd);
});
return () => {
currentGrid?.off("change");
currentGrid?.off("added");
};
}, [isEditMode, onAdd, onChange]);
/**
* IMPORTANT: This effect has to be placed after the effect to initialize the gridstack
* because we need the gridstack object to add the listeners
* Toggle the gridstack to be static or not based on the edit mode
*/
useEffect(() => {
gridRef.current?.setStatic(!isEditMode);
}, [isEditMode]);
const sectionHeight = section.kind === "dynamic" && "height" in section ? (section.height as number) : null;
/**
* IMPORTANT: This effect has to be placed after the effect to initialize the gridstack
* because we need the gridstack object to add the listeners
* We want the amount of rows in a dynamic section to be the height of the section in the outer gridstack
*/
useEffect(() => {
if (!sectionHeight) return;
gridRef.current?.row(sectionHeight);
}, [sectionHeight]);
/**
* IMPORTANT: This effect has to be placed after the effect to initialize the gridstack
* because we need the gridstack object to add the listeners
*/
useCssVariableConfiguration({
columnCount,
gridRef,
wrapperRef: wrapperElementRef,
width,
height,
isDynamic: section.kind === "dynamic",
});
return {
refs: {
items: itemRefs,
wrapper: wrapperRef,
gridstack: gridRef,
},
};
};
interface UseCssVariableConfiguration {
gridRef: UseGridstackRefs["gridstack"];
wrapperRef: RefObject<HTMLDivElement | null>;
width: number;
height: number;
columnCount: number;
isDynamic: boolean;
}
/**
* This hook is used to configure the css variables for the gridstack
* Those css variables are used to define the size of the gridstack items
* @see gridstack.scss
* @param gridRef reference to the gridstack object
* @param wrapperRef reference to the wrapper of the gridstack
* @param width width of the section
* @param height height of the section
* @param columnCount column count of the gridstack
*/
const useCssVariableConfiguration = ({
gridRef,
wrapperRef,
width,
height,
columnCount,
isDynamic,
}: UseCssVariableConfiguration) => {
const onResize = useCallback(() => {
if (!wrapperRef.current) return;
if (!gridRef.current) return;
handleResizeChange(
wrapperRef.current,
gridRef.current,
gridRef.current.getColumn(),
gridRef.current.getRow(),
isDynamic,
);
}, [wrapperRef, gridRef, isDynamic]);
useCallback(() => {
if (!wrapperRef.current) return;
if (!gridRef.current) return;
wrapperRef.current.style.setProperty("--gridstack-column-count", gridRef.current.getColumn().toString());
wrapperRef.current.style.setProperty("--gridstack-row-count", gridRef.current.getRow().toString());
let cellHeight = wrapperRef.current.clientWidth / gridRef.current.getColumn();
if (isDynamic) {
cellHeight = wrapperRef.current.clientHeight / gridRef.current.getRow();
}
gridRef.current.cellHeight(cellHeight);
}, [wrapperRef, gridRef, isDynamic]);
// Define widget-width by calculating the width of one column with mainRef width and column count
useEffect(() => {
onResize();
if (typeof window === "undefined") return;
window.addEventListener("resize", onResize);
const wrapper = wrapperRef.current;
wrapper?.addEventListener("resize", onResize);
return () => {
if (typeof window === "undefined") return;
window.removeEventListener("resize", onResize);
wrapper?.removeEventListener("resize", onResize);
};
}, [wrapperRef, gridRef, onResize]);
// Handle resize of inner sections when there size changes
useEffect(() => {
onResize();
}, [width, height, onResize]);
// Define column count by using the sectionColumnCount
useEffect(() => {
wrapperRef.current?.style.setProperty("--gridstack-column-count", columnCount.toString());
}, [columnCount, wrapperRef]);
};
@@ -15,3 +15,53 @@
background-color: transparent !important;
border-color: transparent !important;
}
.collapsedContainerCard {
background-color: transparent !important;
border-color: transparent !important;
box-shadow: none !important;
}
.containerToggle {
z-index: 9;
overflow: hidden;
color: var(--mantine-color-text);
background-color: var(--background-color);
border-color: var(--border-color);
}
.containerToggle :global(.mantine-Button-inner) {
width: 100%;
min-width: 0;
}
.containerToggle :global(.mantine-Button-label) {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.containerBody {
visibility: visible;
opacity: 1;
transition:
opacity 140ms ease 80ms,
visibility 0s;
}
.containerBody[data-collapsed="true"] {
visibility: hidden;
pointer-events: none;
opacity: 0;
transition:
opacity 120ms ease,
visibility 0s linear 120ms;
}
@media (prefers-reduced-motion: reduce) {
.containerBody,
.containerBody[data-collapsed="true"] {
transition: none;
}
}
@@ -1,18 +1,18 @@
import { describe, expect, test } from "vitest";
import { BoardMockBuilder } from "~/components/board/items/actions/test/mocks/board-mock";
import { DynamicSectionMockBuilder } from "~/components/board/items/actions/test/mocks/dynamic-section-mock";
import { ContainerSectionMockBuilder } from "~/components/board/items/actions/test/mocks/container-section-mock";
import { EmptySectionMockBuilder } from "~/components/board/items/actions/test/mocks/empty-section-mock";
import { wouldCreateSectionCycle } from "./section-actions";
describe("wouldCreateSectionCycle", () => {
test("rejects moving a dynamic section into itself or one of its descendants", () => {
test("rejects moving a container into itself or one of its descendants", () => {
const layoutId = "layout";
const rootSection = new EmptySectionMockBuilder({ id: "root" }).build();
const parentSection = new DynamicSectionMockBuilder({ id: "parent" })
const parentSection = new ContainerSectionMockBuilder({ id: "parent" })
.addLayout({ layoutId, parentSectionId: rootSection.id })
.build();
const childSection = new DynamicSectionMockBuilder({ id: "child" })
const childSection = new ContainerSectionMockBuilder({ id: "child" })
.addLayout({ layoutId, parentSectionId: parentSection.id })
.build();
const board = new BoardMockBuilder().addSections([rootSection, parentSection, childSection]).build();
@@ -32,7 +32,7 @@ export const useSectionActions = () => {
sections: previous.sections.map((section) => {
// Return same section if section is not the one we're moving
if (section.id !== innerSectionId) return section;
if (section.kind !== "dynamic") return section;
if (section.kind !== "container") return section;
return {
...section,
@@ -62,7 +62,7 @@ export const useSectionActions = () => {
sections: previous.sections.map((section) => {
// Return section without changes when not the section we're moving
if (section.id !== innerSectionId) return section;
if (section.kind !== "dynamic") return section;
if (section.kind !== "container") return section;
return {
...section,
@@ -101,7 +101,7 @@ export const wouldCreateSectionCycle = (
visitedSectionIds.add(currentSectionId);
const currentSection = board.sections.find((section) => section.id === currentSectionId);
if (currentSection?.kind !== "dynamic") return false;
if (currentSection?.kind !== "container") return false;
currentSectionId = currentSection.layouts.find((layout) => layout.layoutId === layoutId)?.parentSectionId ?? null;
}
@@ -0,0 +1,46 @@
interface SectionCollapseStorage {
getItem: (key: string) => string | null;
setItem: (key: string, value: string) => void;
removeItem: (key: string) => void;
}
const legacyStorageKey = (sectionId: string) => `homarr-section-collapsed-${sectionId}`;
export const sectionCollapseStorageKey = (sectionId: string) => `homarr-section-collapsed-v2-${sectionId}`;
/**
* Legacy values represented whether the section was open even though the key
* and database column called the value "collapsed". Migrate once into a
* versioned key whose boolean has the corrected meaning.
*/
export const readSectionCollapsedFromStorage = (
storage: SectionCollapseStorage,
sectionId: string,
fallback: boolean,
) => {
const currentKey = sectionCollapseStorageKey(sectionId);
const legacyKey = legacyStorageKey(sectionId);
const current = storage.getItem(currentKey);
if (current !== null) {
storage.removeItem(legacyKey);
return current === "true";
}
const legacy = storage.getItem(legacyKey);
if (legacy === null) return fallback;
const collapsed = legacy !== "true";
storage.setItem(currentKey, String(collapsed));
storage.removeItem(legacyKey);
return collapsed;
};
export const writeSectionCollapsedToStorage = (
storage: SectionCollapseStorage,
sectionId: string,
collapsed: boolean,
) => {
storage.setItem(sectionCollapseStorageKey(sectionId), String(collapsed));
storage.removeItem(legacyStorageKey(sectionId));
};
@@ -0,0 +1,122 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { readSectionCollapsedFromStorage, writeSectionCollapsedToStorage } from "./section-collapse-storage";
interface SectionCollapseContextValue {
collapsedSectionIds: ReadonlySet<string>;
setCollapsed: (sectionId: string, collapsed: boolean) => void;
}
const SectionCollapseContext = createContext<SectionCollapseContextValue | null>(null);
export const BoardSectionCollapseProvider = ({ children }: PropsWithChildren) => {
const board = useRequiredBoard();
const { status } = useSession();
const { mutate } = clientApi.section.changeCollapsed.useMutation();
const [collapsedById, setCollapsedById] = useState<Record<string, boolean>>(() =>
Object.fromEntries(
board.sections.filter((section) => section.kind !== "empty").map((section) => [section.id, section.collapsed]),
),
);
const collapsedByIdRef = useRef(collapsedById);
collapsedByIdRef.current = collapsedById;
useEffect(() => {
setCollapsedById((previous) => {
const next = { ...previous };
for (const section of board.sections) {
if (section.kind === "empty" || section.id in next) continue;
next[section.id] = section.collapsed;
}
return next;
});
}, [board.sections]);
useEffect(() => {
if (status !== "unauthenticated") return;
setCollapsedById((previous) => {
const next = { ...previous };
for (const sectionId of Object.keys(next)) {
next[sectionId] = readSectionCollapsedFromStorage(window.localStorage, sectionId, next[sectionId] ?? false);
}
return next;
});
}, [status]);
const setCollapsed = useCallback(
(sectionId: string, collapsed: boolean) => {
const previousCollapsed = collapsedByIdRef.current[sectionId] ?? false;
collapsedByIdRef.current = { ...collapsedByIdRef.current, [sectionId]: collapsed };
setCollapsedById((previous) => ({ ...previous, [sectionId]: collapsed }));
if (status === "authenticated") {
mutate(
{ sectionId, collapsed },
{
onError: () => {
if (collapsedByIdRef.current[sectionId] !== collapsed) return;
collapsedByIdRef.current = { ...collapsedByIdRef.current, [sectionId]: previousCollapsed };
setCollapsedById((previous) => ({ ...previous, [sectionId]: previousCollapsed }));
},
},
);
} else if (status === "unauthenticated") {
writeSectionCollapsedToStorage(window.localStorage, sectionId, collapsed);
}
},
[mutate, status],
);
const value = useMemo<SectionCollapseContextValue>(
() => ({
collapsedSectionIds: new Set(
Object.entries(collapsedById)
.filter(([, collapsed]) => collapsed)
.map(([sectionId]) => sectionId),
),
setCollapsed,
}),
[collapsedById, setCollapsed],
);
return <SectionCollapseContext.Provider value={value}>{children}</SectionCollapseContext.Provider>;
};
export const useSectionCollapse = ({ sectionId, collapsible }: { sectionId: string; collapsible: boolean }) => {
const context = useContext(SectionCollapseContext);
const [isEditMode] = useEditMode();
if (!context) {
throw new Error("BoardSectionCollapseProvider is required");
}
const isCollapsed = collapsible && context.collapsedSectionIds.has(sectionId);
return {
isCollapsed,
isVisuallyCollapsed: isCollapsed && !isEditMode,
setCollapsed: (collapsed: boolean) => context.setCollapsed(sectionId, collapsed),
toggle: () => context.setCollapsed(sectionId, !isCollapsed),
};
};
export const useCollapsedSectionIds = () => {
const context = useContext(SectionCollapseContext);
const [isEditMode] = useEditMode();
if (!context) {
throw new Error("BoardSectionCollapseProvider is required");
}
return isEditMode ? EMPTY_SET : context.collapsedSectionIds;
};
const EMPTY_SET = new Set<string>();
@@ -1,14 +1,17 @@
import { createContext, useContext } from "react";
import type { DynamicSectionItem, Section, SectionItem } from "~/app/[locale]/boards/_types";
import type { UseGridstackRefs } from "./gridstack/use-gridstack";
import type { RouterOutputs } from "@homarr/api";
import type { ContainerSectionItem, Section, SectionItem } from "~/app/[locale]/boards/_types";
interface SectionContextProps {
section: Exclude<Section, { kind: "dynamic" }> | DynamicSectionItem;
ancestorSectionIds: ReadonlySet<string>;
innerSections: DynamicSectionItem[];
section: Exclude<Section, { kind: "container" }> | ContainerSectionItem;
innerSections: ContainerSectionItem[];
items: SectionItem[];
refs: UseGridstackRefs;
integrations: RouterOutputs["integration"]["all"] | undefined;
columnCount: number;
maxRowCount: number | null;
announce: (message: string) => void;
}
const SectionContext = createContext<SectionContextProps | null>(null);
@@ -0,0 +1,53 @@
import { describe, expect, test } from "vitest";
import {
readSectionCollapsedFromStorage,
sectionCollapseStorageKey,
writeSectionCollapsedToStorage,
} from "../section-collapse-storage";
describe("section collapse storage", () => {
test.each([
["true", false],
["false", true],
])("inverts a legacy open value of %s exactly once", (legacyValue, expectedCollapsed) => {
const sectionId = "media";
const legacyKey = `homarr-section-collapsed-${sectionId}`;
const storage = createStorage({ [legacyKey]: legacyValue });
expect(readSectionCollapsedFromStorage(storage, sectionId, false)).toBe(expectedCollapsed);
expect(storage.getItem(legacyKey)).toBeNull();
expect(storage.getItem(sectionCollapseStorageKey(sectionId))).toBe(String(expectedCollapsed));
expect(readSectionCollapsedFromStorage(storage, sectionId, !expectedCollapsed)).toBe(expectedCollapsed);
});
test("uses the corrected fallback when no browser preference exists", () => {
const storage = createStorage();
expect(readSectionCollapsedFromStorage(storage, "first", true)).toBe(true);
expect(readSectionCollapsedFromStorage(storage, "second", false)).toBe(false);
});
test("writes only the versioned corrected state", () => {
const sectionId = "media";
const legacyKey = `homarr-section-collapsed-${sectionId}`;
const storage = createStorage({ [legacyKey]: "true" });
writeSectionCollapsedToStorage(storage, sectionId, true);
expect(storage.getItem(legacyKey)).toBeNull();
expect(storage.getItem(sectionCollapseStorageKey(sectionId))).toBe("true");
});
});
const createStorage = (initial: Record<string, string> = {}) => {
const values = new Map(Object.entries(initial));
return {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
removeItem: (key: string) => {
values.delete(key);
},
};
};
@@ -0,0 +1,78 @@
import { describe, expect, test } from "vitest";
import { getSectionItemsForLayout } from "../use-open-section-apps";
describe("getSectionItemsForLayout", () => {
test("includes items in recursively nested containers", () => {
const board = {
sections: [
{ id: "root", kind: "empty" },
{
id: "first",
kind: "container",
layouts: [{ layoutId: "desktop", parentSectionId: "root" }],
},
{
id: "second",
kind: "container",
layouts: [{ layoutId: "desktop", parentSectionId: "first" }],
},
],
items: [
{ id: "direct", layouts: [{ layoutId: "desktop", sectionId: "root" }] },
{ id: "nested", layouts: [{ layoutId: "desktop", sectionId: "second" }] },
],
};
expect(getSectionItemsForLayout(board, "root", "desktop").map((item) => item.id)).toEqual(["direct", "nested"]);
});
test("uses containment from only the requested responsive layout", () => {
const board = {
sections: [
{ id: "root", kind: "empty" },
{ id: "other", kind: "empty" },
{
id: "container",
kind: "container",
layouts: [
{ layoutId: "mobile", parentSectionId: "root" },
{ layoutId: "desktop", parentSectionId: "other" },
],
},
],
items: [
{
id: "app",
layouts: [
{ layoutId: "mobile", sectionId: "container" },
{ layoutId: "desktop", sectionId: "container" },
],
},
],
};
expect(getSectionItemsForLayout(board, "root", "mobile").map((item) => item.id)).toEqual(["app"]);
expect(getSectionItemsForLayout(board, "root", "desktop")).toEqual([]);
});
test("does not loop when malformed section containment is cyclic", () => {
const board = {
sections: [
{
id: "root",
kind: "container",
layouts: [{ layoutId: "desktop", parentSectionId: "child" }],
},
{
id: "child",
kind: "container",
layouts: [{ layoutId: "desktop", parentSectionId: "root" }],
},
],
items: [{ id: "app", layouts: [{ layoutId: "desktop", sectionId: "child" }] }],
};
expect(getSectionItemsForLayout(board, "root", "desktop").map((item) => item.id)).toEqual(["app"]);
});
});
@@ -0,0 +1,128 @@
import { use, useCallback, useMemo } from "react";
import { clientApi } from "@homarr/api/client";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { useConfirmModal } from "@homarr/modals";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "@homarr/widgets/definition";
import { loadWidgetDefinition, reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import type { Item } from "~/app/[locale]/boards/_types";
interface SectionItemLayout {
layoutId: string;
sectionId: string;
}
interface SectionLayout {
layoutId: string;
parentSectionId: string;
}
interface SectionTreeItem {
layouts: readonly SectionItemLayout[];
}
interface SectionTreeSection {
id: string;
kind: string;
layouts?: readonly SectionLayout[];
}
interface SectionTree<TItem extends SectionTreeItem> {
items: readonly TItem[];
sections: readonly SectionTreeSection[];
}
/**
* Finds every item contained by a section in one responsive layout. Containers
* can be nested, so their descendants are traversed recursively.
*/
export const getSectionItemsForLayout = <TItem extends SectionTreeItem>(
board: SectionTree<TItem>,
rootSectionId: string,
layoutId: string,
) => {
const childrenByParent = new Map<string, string[]>();
for (const section of board.sections) {
if (section.kind !== "container") continue;
const layout = section.layouts?.find((candidate) => candidate.layoutId === layoutId);
if (!layout) continue;
const children = childrenByParent.get(layout.parentSectionId) ?? [];
children.push(section.id);
childrenByParent.set(layout.parentSectionId, children);
}
const includedSectionIds = new Set([rootSectionId]);
const queue = [rootSectionId];
for (const sectionId of queue) {
for (const childSectionId of childrenByParent.get(sectionId) ?? []) {
if (includedSectionIds.has(childSectionId)) continue;
includedSectionIds.add(childSectionId);
queue.push(childSectionId);
}
}
return board.items.filter((item) =>
item.layouts.some((layout) => layout.layoutId === layoutId && includedSectionIds.has(layout.sectionId)),
);
};
export const useOpenSectionApps = (sectionId: string, enabled: boolean) => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const settings = useSettings();
const { openConfirmModal } = useConfirmModal();
const t = useI18n();
const appDefinition = use(loadWidgetDefinition("app"));
const appIds = useMemo(() => {
const items: Item[] = getSectionItemsForLayout(board, sectionId, currentLayoutId);
return Array.from(
new Set(
items
.filter((item) => item.kind === "app")
.map(
(item) =>
(
reduceWidgetOptionsWithDefinition(
appDefinition,
settings,
item.options,
) as WidgetComponentProps<"app">["options"]
).appId,
)
.filter((appId): appId is string => typeof appId === "string"),
),
);
}, [appDefinition, board, currentLayoutId, sectionId, settings]);
const { data: apps = [], isLoading } = clientApi.app.byIds.useQuery(appIds, {
enabled: enabled && appIds.length > 0,
staleTime: 30_000,
});
const open = useCallback(() => {
const appsWithUrls = apps.filter((app) => app.href && app.href.length > 0);
for (const app of appsWithUrls) {
const openedWindow = window.open(app.href ?? undefined);
if (openedWindow) continue;
openConfirmModal({
title: t("section.openAllInNewTabs.title"),
children: t("section.openAllInNewTabs.text"),
});
break;
}
}, [apps, openConfirmModal, t]);
return {
open,
isLoading: enabled && appIds.length > 0 && isLoading,
};
};
@@ -2,16 +2,16 @@ import { useMemo } from "react";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import type { DynamicSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import type { ContainerSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
export const useSectionItems = (sectionId: string): { innerSections: DynamicSectionItem[]; items: SectionItem[] } => {
export const useSectionItems = (sectionId: string): { innerSections: ContainerSectionItem[]; items: SectionItem[] } => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const innerSections = useMemo(
() =>
board.sections
.filter((innerSection) => innerSection.kind === "dynamic")
.filter((innerSection) => innerSection.kind === "container")
.map(({ layouts, ...innerSection }) => {
const layout = layouts.find((layout) => layout.layoutId === currentLayoutId);