feat: rebuild board grid with dnd-kit

This commit is contained in:
Thomas Camlong authored and ajnart committed 2026-08-13 19:52:59 +02:00
1 parent 5bde4d3cc5
commit 1f5311e93b
107 files changed
+5628 -3209

No files matched your search

@@ -1,51 +0,0 @@
import { createId } from "@homarr/common";
import { createLogger } from "@homarr/core/infrastructure/logs";
import type { Database } from "@homarr/db";
import { sections } from "@homarr/db/schema";
import type { OldmarrConfig } from "@homarr/old-schema";
const logger = createLogger({ module: "importSections" });
export const insertSectionsAsync = async (
db: Database,
categories: OldmarrConfig["categories"],
wrappers: OldmarrConfig["wrappers"],
boardId: string,
) => {
logger.info("Importing old homarr sections", { boardId, categories: categories.length, wrappers: wrappers.length });
const wrapperIds = wrappers.map((section) => section.id);
const categoryIds = categories.map((section) => section.id);
const idMaps = new Map<string, string>([...wrapperIds, ...categoryIds].map((id) => [id, createId()]));
const wrappersToInsert = wrappers.map((section) => ({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: idMaps.get(section.id)!,
boardId,
xOffset: 0,
yOffset: section.position,
kind: "empty" as const,
}));
const categoriesToInsert = categories.map((section) => ({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: idMaps.get(section.id)!,
boardId,
xOffset: 0,
yOffset: section.position,
kind: "category" as const,
name: section.name,
}));
if (wrappersToInsert.length > 0) {
await db.insert(sections).values(wrappersToInsert);
}
if (categoriesToInsert.length > 0) {
await db.insert(sections).values(categoriesToInsert);
}
logger.info("Imported sections", { count: wrappersToInsert.length + categoriesToInsert.length });
return idMaps;
};
@@ -12,7 +12,7 @@ import { mapColumnCount } from "../../mappers/map-column-count";
import { moveWidgetsAndAppsIfMerge } from "../../move-widgets-and-apps-merge";
import { prepareItems } from "../../prepare/prepare-items";
import type { prepareMultipleImports } from "../../prepare/prepare-multiple";
import { prepareSections } from "../../prepare/prepare-sections";
import { placePreparedSections, prepareSections } from "../../prepare/prepare-sections";
import type { InitialOldmarrImportSettings } from "../../settings";
const logger = createLogger({ module: "boardCollection" });
@@ -26,6 +26,7 @@ export const createBoardInsertCollection = (
"boards",
"layouts",
"sections",
"sectionLayouts",
"items",
"itemLayouts",
]);
@@ -87,21 +88,18 @@ export const createBoardInsertCollection = (
{} as Record<BoardSize, string>,
);
insertCollection.layouts.push(
...boardSizes.map((size) => ({
id: layoutMapping[size],
boardId: mappedBoard.id,
columnCount: mapColumnCount(board.config.settings.customization.gridstack, size),
breakpoint: mapBreakpoint(size),
name: getBoardSizeName(size),
})),
);
const preparedLayouts = boardSizes.map((size) => ({
id: layoutMapping[size],
boardId: mappedBoard.id,
columnCount: mapColumnCount(board.config.settings.customization.gridstack, size),
breakpoint: mapBreakpoint(size),
name: getBoardSizeName(size),
}));
insertCollection.layouts.push(...preparedLayouts);
const preparedSections = prepareSections(mappedBoard.id, { wrappers, categories });
for (const section of preparedSections.values()) {
insertCollection.sections.push(section);
}
insertCollection.sections.push(...preparedSections.sections);
logger.debug("Added sections to board insert collection", { count: insertCollection.sections.length });
const preparedItems = prepareItems(
@@ -111,10 +109,11 @@ export const createBoardInsertCollection = (
settings: board.config.settings,
},
appsMap,
preparedSections,
preparedSections.byLegacyId,
layoutMapping,
mappedBoard.id,
);
insertCollection.sectionLayouts.push(...placePreparedSections(preparedSections, preparedItems, preparedLayouts));
preparedItems.forEach(({ layouts, ...item }) => {
insertCollection.items.push(item);
insertCollection.itemLayouts.push(...layouts);
+23 -9
View File
@@ -1,24 +1,38 @@
import { stringify } from "superjson";
import { createId } from "@homarr/common";
import type { InferInsertModel } from "@homarr/db";
import type { sections } from "@homarr/db/schema";
import type { OldmarrCategorySection, OldmarrEmptySection } from "@homarr/old-schema";
import { emptySuperJSON, rootSectionOffsets } from "@homarr/definitions";
import type { OldmarrCategorySection } from "@homarr/old-schema";
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
export const mapCategorySection = (
export const mapLegacyCategoryContainer = (
boardId: string,
category: OldmarrCategorySection,
): InferInsertModel<typeof sections> => ({
id: createId(),
boardId,
kind: "category",
xOffset: 0,
yOffset: category.position,
name: category.name,
kind: "container",
xOffset: null,
yOffset: null,
name: null,
options: stringify(
containerSectionOptionsSchema.parse({
title: category.name.slice(0, 64),
showLabel: true,
collapsible: true,
showOpenAll: true,
}),
),
});
export const mapEmptySection = (boardId: string, wrapper: OldmarrEmptySection): InferInsertModel<typeof sections> => ({
export const mapMainRootSection = (boardId: string): InferInsertModel<typeof sections> => ({
id: createId(),
boardId,
kind: "empty",
xOffset: 0,
yOffset: wrapper.position,
xOffset: rootSectionOffsets.main,
yOffset: 0,
name: null,
options: emptySuperJSON,
});
@@ -0,0 +1,87 @@
import { parse } from "superjson";
import { describe, expect, test } from "vitest";
import { placePreparedSections, prepareSections } from "./prepare-sections";
describe("prepareSections", () => {
test("maps legacy blocks into one root and durable containers", () => {
const prepared = prepareSections("board", {
categories: [{ id: "category", name: "Media", position: 1 }],
wrappers: [{ id: "wrapper", position: 0 }],
});
const root = prepared.sections.find((section) => section.kind === "empty");
const container = prepared.sections.find((section) => section.kind === "container");
if (!root || !container) throw new Error("Expected a root and a container");
expect(prepared.sections).toHaveLength(2);
expect(root).toMatchObject({ boardId: "board", xOffset: 0, yOffset: 0 });
expect(container).toMatchObject({ boardId: "board", xOffset: null, yOffset: null, name: null });
expect(parse(container.options ?? "{}")).toMatchObject({
title: "Media",
showLabel: true,
collapsible: true,
showOpenAll: true,
});
expect(prepared.byLegacyId.get("category")?.id).toBe(container.id);
expect(prepared.byLegacyId.get("wrapper")?.id).not.toBe(root.id);
});
test("places root content and containers in legacy order for every layout", () => {
const prepared = prepareSections("board", {
categories: [{ id: "category", name: "Media", position: 1 }],
wrappers: [{ id: "wrapper", position: 0 }],
});
const wrapperPlacementId = prepared.byLegacyId.get("wrapper")?.id;
const containerId = prepared.byLegacyId.get("category")?.id;
if (!wrapperPlacementId || !containerId) throw new Error("Expected mapped section ids");
const preparedItems = [
{
layouts: [
{
itemId: "root-item",
layoutId: "layout",
sectionId: wrapperPlacementId,
xOffset: 1,
yOffset: 0,
width: 2,
height: 2,
},
],
},
{
layouts: [
{
itemId: "container-item",
layoutId: "layout",
sectionId: containerId,
xOffset: 0,
yOffset: 1,
width: 3,
height: 2,
},
],
},
];
const layouts = placePreparedSections(prepared, preparedItems, [{ id: "layout", columnCount: 12 }]);
expect(preparedItems[0]?.layouts[0]).toMatchObject({
sectionId: prepared.mainRootId,
xOffset: 1,
yOffset: 0,
});
expect(preparedItems[1]?.layouts[0]).toMatchObject({ sectionId: containerId, yOffset: 1 });
expect(layouts).toEqual([
{
sectionId: containerId,
layoutId: "layout",
parentSectionId: prepared.mainRootId,
xOffset: 0,
yOffset: 2,
width: 12,
height: 3,
},
]);
});
});
@@ -1,13 +1,115 @@
import { createId } from "@homarr/common";
import type { InferInsertModel } from "@homarr/db";
import type { itemLayouts, sectionLayouts, sections } from "@homarr/db/schema";
import type { OldmarrConfig } from "@homarr/old-schema";
import { mapCategorySection, mapEmptySection } from "../mappers/map-section";
import { mapLegacyCategoryContainer, mapMainRootSection } from "../mappers/map-section";
interface PreparedSectionBlock {
id: string;
legacyId: string;
position: number;
type: "container" | "root-content";
}
interface PreparedSections {
blocks: PreparedSectionBlock[];
byLegacyId: Map<string, { id: string }>;
mainRootId: string;
sections: InferInsertModel<typeof sections>[];
}
interface PreparedItemWithLayouts {
layouts: InferInsertModel<typeof itemLayouts>[];
}
export const prepareSections = (
boardId: string,
{ categories, wrappers }: Pick<OldmarrConfig, "categories" | "wrappers">,
) =>
new Map(
categories
.map((category) => [category.id, mapCategorySection(boardId, category)] as const)
.concat(wrappers.map((wrapper) => [wrapper.id, mapEmptySection(boardId, wrapper)] as const)),
);
): PreparedSections => {
const mainRoot = mapMainRootSection(boardId);
const containers = categories.map((category) => ({
category,
section: mapLegacyCategoryContainer(boardId, category),
}));
const rootContent = wrappers.map((wrapper) => ({ wrapper, id: createId() }));
return {
mainRootId: mainRoot.id,
sections: [mainRoot, ...containers.map(({ section }) => section)],
byLegacyId: new Map([
...containers.map(({ category, section }) => [category.id, { id: section.id }] as const),
...rootContent.map(({ wrapper, id }) => [wrapper.id, { id }] as const),
]),
blocks: [
...containers.map(({ category, section }) => ({
id: section.id,
legacyId: category.id,
position: category.position,
type: "container" as const,
})),
...rootContent.map(({ wrapper, id }) => ({
id,
legacyId: wrapper.id,
position: wrapper.position,
type: "root-content" as const,
})),
].toSorted(
(first, second) =>
first.position - second.position ||
(first.type === second.type
? first.legacyId.localeCompare(second.legacyId)
: first.type === "container"
? -1
: 1),
),
};
};
/**
* Old Homarr stored each top-level block in its own coordinate space. The
* current model has one main root and places labelled containers inside it.
* This compacts those blocks in their legacy order without changing the
* coordinates of content inside a container.
*/
export const placePreparedSections = (
preparedSections: PreparedSections,
preparedItems: PreparedItemWithLayouts[],
preparedLayouts: { id: string; columnCount: number }[],
): InferInsertModel<typeof sectionLayouts>[] => {
const result: InferInsertModel<typeof sectionLayouts>[] = [];
for (const layout of preparedLayouts) {
let nextRow = 0;
for (const block of preparedSections.blocks) {
const content = preparedItems.flatMap((item) =>
item.layouts.filter((itemLayout) => itemLayout.layoutId === layout.id && itemLayout.sectionId === block.id),
);
const contentHeight = Math.max(0, ...content.map((itemLayout) => itemLayout.yOffset + itemLayout.height));
if (block.type === "container") {
const height = Math.max(1, contentHeight);
result.push({
sectionId: block.id,
layoutId: layout.id,
parentSectionId: preparedSections.mainRootId,
xOffset: 0,
yOffset: nextRow,
width: layout.columnCount,
height,
});
nextRow += height;
continue;
}
for (const itemLayout of content) {
itemLayout.sectionId = preparedSections.mainRootId;
itemLayout.yOffset += nextRow;
}
nextRow += contentHeight;
}
}
return result;
};