feat: protect responsive board layouts

This commit is contained in:
ajnart committed 2026-08-13 19:55:38 +02:00
1 parent 4df62221c7
commit 30c00ea30d
30 files changed
+1055 -254

No files matched your search

@@ -0,0 +1 @@
ALTER TABLE `layout` ADD `role` varchar(16) DEFAULT 'custom' NOT NULL;
@@ -323,6 +323,13 @@
"when": 1786212549933,
"tag": "0045_add_layout_gutters",
"breakpoints": true
},
{
"idx": 46,
"version": "5",
"when": 1786215199760,
"tag": "0046_add_layout_role",
"breakpoints": true
}
]
}
@@ -0,0 +1 @@
ALTER TABLE "layout" ADD COLUMN "role" varchar(16) DEFAULT 'custom' NOT NULL;
@@ -85,6 +85,13 @@
"when": 1786212457549,
"tag": "0011_add_layout_gutters",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1786215201393,
"tag": "0012_add_layout_role",
"breakpoints": true
}
]
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, test } from "vitest";
import { createId } from "@homarr/common";
import { eq } from "@homarr/db";
import { boards, itemLayouts, items, layouts, sections } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import { emptySuperJSON } from "@homarr/definitions";
import { seedProtectedBoardLayoutsAsync } from "./seed";
describe("protected board layout migration", () => {
test("turns a single saved layout into Base and generates Mobile", async () => {
const db = createDb();
const boardId = createId();
const baseLayoutId = createId();
const sectionId = createId();
const itemId = createId();
await db.insert(boards).values({ id: boardId, name: "single" });
await db.insert(layouts).values({
id: baseLayoutId,
boardId,
name: "Wide",
columnCount: 12,
breakpoint: 0,
});
await db.insert(sections).values({ id: sectionId, boardId, kind: "empty", xOffset: 0, yOffset: 0 });
await db.insert(items).values({ id: itemId, boardId, kind: "clock", options: emptySuperJSON });
await db.insert(itemLayouts).values({
itemId,
sectionId,
layoutId: baseLayoutId,
width: 5,
height: 2,
xOffset: 6,
yOffset: 1,
});
await seedProtectedBoardLayoutsAsync(db);
await seedProtectedBoardLayoutsAsync(db);
const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) });
expect(savedLayouts).toHaveLength(2);
expect(savedLayouts.find((layout) => layout.role === "base")).toMatchObject({
id: baseLayoutId,
name: "Wide",
columnCount: 12,
breakpoint: 768,
});
const mobileLayout = savedLayouts.find((layout) => layout.role === "mobile");
expect(mobileLayout).toMatchObject({ name: "Mobile", columnCount: 3, breakpoint: 0 });
const mobileItemPosition = await db.query.itemLayouts.findFirst({
where: eq(itemLayouts.layoutId, mobileLayout?.id ?? ""),
});
expect(mobileItemPosition).toMatchObject({ width: 3, height: 2, xOffset: 0, yOffset: 0 });
});
test("assigns roles and resolves duplicate breakpoints without rebuilding existing layouts", async () => {
const db = createDb();
const boardId = createId();
await db.insert(boards).values({ id: boardId, name: "responsive" });
await db.insert(layouts).values([
{ id: "layout-mobile", boardId, name: "Phone", columnCount: 3, breakpoint: 0 },
{ id: "layout-tablet-a", boardId, name: "Tablet A", columnCount: 6, breakpoint: 480 },
{ id: "layout-tablet-b", boardId, name: "Tablet B", columnCount: 8, breakpoint: 480 },
{ id: "layout-wide", boardId, name: "Wide", columnCount: 12, breakpoint: 1200 },
]);
await seedProtectedBoardLayoutsAsync(db);
await seedProtectedBoardLayoutsAsync(db);
const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) });
expect(savedLayouts.toSorted((layoutA, layoutB) => layoutA.breakpoint - layoutB.breakpoint)).toMatchObject([
{ id: "layout-mobile", name: "Phone", columnCount: 3, breakpoint: 0, role: "mobile" },
{ id: "layout-tablet-a", name: "Tablet A", columnCount: 6, breakpoint: 480, role: "custom" },
{ id: "layout-tablet-b", name: "Tablet B", columnCount: 8, breakpoint: 481, role: "custom" },
{ id: "layout-wide", name: "Wide", columnCount: 12, breakpoint: 1200, role: "base" },
]);
});
test("creates both protected layouts for a board with no layouts", async () => {
const db = createDb();
const boardId = createId();
await db.insert(boards).values({ id: boardId, name: "empty" });
await seedProtectedBoardLayoutsAsync(db);
await seedProtectedBoardLayoutsAsync(db);
const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) });
expect(savedLayouts).toHaveLength(2);
expect(savedLayouts).toEqual(
expect.arrayContaining([
expect.objectContaining({ role: "mobile", columnCount: 3, breakpoint: 0 }),
expect.objectContaining({ role: "base", columnCount: 10, breakpoint: 768 }),
]),
);
});
});
+234 -11
View File
@@ -1,6 +1,6 @@
import SuperJSON from "superjson";
import { createId, objectKeys } from "@homarr/common";
import { createId, generateResponsiveGridFor, objectKeys } from "@homarr/common";
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import {
createDocumentationLink,
@@ -11,11 +11,12 @@ import {
getIntegrationName,
integrationDefs,
integrationKinds,
normalizeBoardLayoutRoles,
} from "@homarr/definitions";
import type { WidgetKind } from "@homarr/definitions";
import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
import type { Database } from "..";
import type { Database, InferInsertModel } from "..";
import { eq, inArray } from "..";
import { getMaxGroupPositionAsync, placeAllWidgetsAsync } from "../queries";
import {
@@ -39,6 +40,7 @@ import {
onboarding,
searchEngines,
sections,
sectionLayouts,
users,
} from "../schema";
import type { Integration } from "../schema";
@@ -65,6 +67,215 @@ export const seedDataAsync = async (db: Database) => {
if (isTruthyEnv(process.env.DEMO_MODE)) {
await seedDemoUserAsync(db);
}
await seedProtectedBoardLayoutsAsync(db);
};
export const seedProtectedBoardLayoutsAsync = async (db: Database, boardId?: string) => {
const dbBoards = await db.query.boards.findMany({
where: boardId ? eq(boards.id, boardId) : undefined,
with: {
layouts: true,
items: { with: { layouts: true } },
sections: { with: { layouts: true } },
},
});
for (const board of dbBoards) {
if (board.layouts.length === 0) {
await db.insert(layouts).values([
{
id: createId(),
name: "Mobile",
columnCount: 3,
breakpoint: 0,
role: "mobile",
boardId: board.id,
},
{
id: createId(),
name: "Base",
columnCount: 10,
breakpoint: 768,
role: "base",
boardId: board.id,
},
]);
continue;
}
if (board.layouts.length === 1) {
const [baseLayout] = board.layouts;
if (!baseLayout) continue;
const mobileLayout = {
id: createId(),
name: "Mobile",
columnCount: 3,
breakpoint: 0,
role: "mobile" as const,
boardId: board.id,
};
await db.update(layouts).set({ role: "base", breakpoint: 768 }).where(eq(layouts.id, baseLayout.id));
await db.insert(layouts).values(mobileLayout);
await insertMissingProjectedPositionsAsync(
db,
board,
{ ...baseLayout, role: "base", breakpoint: 768 },
mobileLayout,
);
continue;
}
const normalizedLayouts = normalizeBoardLayoutRoles(board.layouts);
const alreadyNormalized = normalizedLayouts.every((layout) => {
const previousLayout = board.layouts.find((candidate) => candidate.id === layout.id);
return layout.breakpoint === previousLayout?.breakpoint && previousLayout.role === layout.role;
});
if (!alreadyNormalized) {
for (const layout of normalizedLayouts) {
await db
.update(layouts)
.set({ breakpoint: layout.breakpoint, role: layout.role })
.where(eq(layouts.id, layout.id));
}
}
const mobileLayout = normalizedLayouts[0];
const baseLayout = normalizedLayouts.at(-1);
if (mobileLayout && baseLayout) {
await insertMissingProjectedPositionsAsync(
db,
board,
{ ...baseLayout, role: "base" },
{ ...mobileLayout, role: "mobile" },
);
}
}
};
interface BoardWithLayoutPositions {
items: Array<{
id: string;
layouts: Array<{
layoutId: string;
sectionId: string;
width: number;
height: number;
xOffset: number;
yOffset: number;
}>;
}>;
sections: Array<{
id: string;
kind: string;
layouts: Array<{
layoutId: string;
parentSectionId: string | null;
width: number;
height: number;
xOffset: number;
yOffset: number;
}>;
}>;
}
const insertMissingProjectedPositionsAsync = async (
db: Database,
board: BoardWithLayoutPositions,
sourceLayout: InferInsertModel<typeof layouts>,
targetLayout: InferInsertModel<typeof layouts>,
) => {
const elements = [
...board.items.flatMap((item) => {
const layout = item.layouts.find((itemLayout) => itemLayout.layoutId === sourceLayout.id);
return layout
? [
{
id: item.id,
type: "item" as const,
width: layout.width,
height: layout.height,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
sectionId: layout.sectionId,
},
]
: [];
}),
...board.sections.flatMap((section) => {
if (section.kind !== "dynamic") return [];
const layout = section.layouts.find((sectionLayout) => sectionLayout.layoutId === sourceLayout.id);
return layout?.parentSectionId
? [
{
id: section.id,
type: "section" as const,
width: layout.width,
height: layout.height,
xOffset: layout.xOffset,
yOffset: layout.yOffset,
sectionId: layout.parentSectionId,
},
]
: [];
}),
];
const projectedElements = board.sections
.filter((section) => section.kind !== "dynamic")
.flatMap(
(section) =>
generateResponsiveGridFor({
items: elements,
previousWidth: sourceLayout.columnCount,
width: targetLayout.columnCount,
sectionId: section.id,
}).items,
);
const existingItemIds = new Set(
board.items
.filter((item) => item.layouts.some((layout) => layout.layoutId === targetLayout.id))
.map((item) => item.id),
);
const itemPositions = projectedElements
.filter((element) => element.type === "item" && !existingItemIds.has(element.id))
.map(
(element): InferInsertModel<typeof itemLayouts> => ({
itemId: element.id,
layoutId: targetLayout.id,
sectionId: element.sectionId,
width: element.width,
height: element.height,
xOffset: element.xOffset,
yOffset: element.yOffset,
}),
);
const existingSectionIds = new Set(
board.sections
.filter((section) => section.layouts.some((layout) => layout.layoutId === targetLayout.id))
.map((section) => section.id),
);
const sectionPositions = projectedElements
.filter((element) => element.type === "section" && !existingSectionIds.has(element.id))
.map(
(element): InferInsertModel<typeof sectionLayouts> => ({
sectionId: element.id,
layoutId: targetLayout.id,
parentSectionId: element.sectionId,
width: element.width,
height: element.height,
xOffset: element.xOffset,
yOffset: element.yOffset,
}),
);
if (itemPositions.length > 0) await db.insert(itemLayouts).values(itemPositions);
if (sectionPositions.length > 0) await db.insert(sectionLayouts).values(sectionPositions);
};
const seedEveryoneGroupAsync = async (db: Database) => {
@@ -271,13 +482,24 @@ const seedDefaultBoardAsync = async (db: Database) => {
yOffset: 0,
boardId,
});
await db.insert(layouts).values({
id: createId(),
name: "Base",
columnCount: 10,
breakpoint: 0,
boardId,
});
await db.insert(layouts).values([
{
id: createId(),
name: "Mobile",
columnCount: 3,
breakpoint: 0,
role: "mobile",
boardId,
},
{
id: createId(),
name: "Base",
columnCount: 10,
breakpoint: 768,
role: "base",
boardId,
},
]);
const everyoneGroupRow = await db.query.groups.findFirst({
where: eq(groups.name, everyoneGroup),
@@ -508,7 +730,8 @@ const seedDemoUserAsync = async (db: Database) => {
id: layoutId,
name: "Base",
columnCount: 12,
breakpoint: 0,
breakpoint: 768,
role: "base",
boardId,
});
@@ -598,7 +821,7 @@ const seedBoardWidgetsAsync = async (db: Database) => {
if (!board) return;
const section = board.sections.find((sec) => sec.kind === "empty");
const layout = board.layouts[0];
const layout = board.layouts.find((candidate) => candidate.role === "base") ?? board.layouts[0];
if (!section || !layout) return;
const allIntegrations = await db.query.integrations.findMany();
@@ -0,0 +1 @@
ALTER TABLE `layout` ADD `role` text DEFAULT 'custom' NOT NULL;
@@ -309,6 +309,13 @@
"when": 1786212459480,
"tag": "0043_add_layout_gutters",
"breakpoints": true
},
{
"idx": 44,
"version": "6",
"when": 1786215203092,
"tag": "0044_add_layout_role",
"breakpoints": true
}
]
}
@@ -0,0 +1,57 @@
import { describe, expect, test } from "vitest";
import { createId } from "@homarr/common";
import { boards, layouts, sections } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import { placeAllWidgetsAsync } from "./widget-placement";
describe("placeAllWidgetsAsync", () => {
test("creates independent positions for every target layout", async () => {
const db = createDb();
const boardId = createId();
const sectionId = createId();
const mobileLayoutId = createId();
const baseLayoutId = createId();
await db.insert(boards).values({ id: boardId, name: "dashboard" });
await db.insert(sections).values({ id: sectionId, kind: "empty", xOffset: 0, yOffset: 0, boardId });
await db.insert(layouts).values([
{
id: mobileLayoutId,
name: "Mobile",
role: "mobile",
columnCount: 3,
breakpoint: 0,
boardId,
},
{
id: baseLayoutId,
name: "Base",
role: "base",
columnCount: 10,
breakpoint: 768,
boardId,
},
]);
await placeAllWidgetsAsync(
db,
[
{ boardId, sectionId, layoutId: mobileLayoutId, columnCount: 3 },
{ boardId, sectionId, layoutId: baseLayoutId, columnCount: 10 },
],
[],
[{ id: createId(), name: "Homarr" }],
);
const placedItems = await db.query.items.findMany({ with: { layouts: true } });
expect(placedItems.length).toBeGreaterThan(0);
expect(placedItems.every((item) => item.layouts.length === 2)).toBe(true);
expect(
placedItems.every((item) =>
item.layouts.some((layout) => layout.layoutId === mobileLayoutId && layout.width <= 3),
),
).toBe(true);
expect(placedItems.every((item) => item.layouts.some((layout) => layout.layoutId === baseLayoutId))).toBe(true);
});
});
+37 -28
View File
@@ -30,46 +30,54 @@ interface PlacementContext extends BoardTarget {
const placeWidgetAsync = async (
db: Database,
ctx: PlacementContext,
contexts: PlacementContext[],
kind: WidgetKind,
linkedIntegrationIds: string[],
options?: string,
size?: { width: number; height: number },
) => {
const itemWidth = size?.width ?? 2;
const itemHeight = size?.height ?? 2;
const boardId = contexts.at(0)?.boardId;
if (!boardId) return;
if (ctx.xOffset + itemWidth > ctx.columnCount) {
ctx.xOffset = 0;
ctx.yOffset += ctx.rowMaxHeight;
ctx.rowMaxHeight = 0;
}
const desiredItemWidth = size?.width ?? 2;
const itemHeight = size?.height ?? 2;
const itemId = createId();
await db.insert(items).values({
id: itemId,
boardId: ctx.boardId,
boardId,
kind,
options: options ?? emptySuperJSON,
advancedOptions: emptySuperJSON,
});
await db.insert(itemLayouts).values({
itemId,
sectionId: ctx.sectionId,
layoutId: ctx.layoutId,
xOffset: ctx.xOffset,
yOffset: ctx.yOffset,
width: itemWidth,
height: itemHeight,
});
await db.insert(itemLayouts).values(
contexts.map((ctx) => {
const itemWidth = Math.min(ctx.columnCount, desiredItemWidth);
if (ctx.xOffset + itemWidth > ctx.columnCount) {
ctx.xOffset = 0;
ctx.yOffset += ctx.rowMaxHeight;
ctx.rowMaxHeight = 0;
}
const placement = {
itemId,
sectionId: ctx.sectionId,
layoutId: ctx.layoutId,
xOffset: ctx.xOffset,
yOffset: ctx.yOffset,
width: itemWidth,
height: itemHeight,
};
ctx.rowMaxHeight = Math.max(ctx.rowMaxHeight, itemHeight);
ctx.xOffset += itemWidth;
return placement;
}),
);
for (const integrationId of linkedIntegrationIds) {
await db.insert(integrationItems).values({ itemId, integrationId });
}
ctx.rowMaxHeight = Math.max(ctx.rowMaxHeight, itemHeight);
ctx.xOffset += itemWidth;
};
interface App {
@@ -79,16 +87,17 @@ interface App {
export const placeAllWidgetsAsync = async (
db: Database,
target: BoardTarget,
target: BoardTarget | BoardTarget[],
allIntegrations: Integration[],
allApps: App[],
) => {
const ctx: PlacementContext = {
...target,
const targets = Array.isArray(target) ? target : [target];
const contexts: PlacementContext[] = targets.map((currentTarget) => ({
...currentTarget,
xOffset: 0,
yOffset: 0,
rowMaxHeight: 0,
};
}));
const placedWidgets = new Set<WidgetKind>();
@@ -106,7 +115,7 @@ export const placeAllWidgetsAsync = async (
const options = config?.options ? superjson.stringify(config.options) : undefined;
await placeWidgetAsync(
db,
ctx,
contexts,
widgetKind,
matchingIds,
options,
@@ -118,7 +127,7 @@ export const placeAllWidgetsAsync = async (
for (const app of allApps) {
await placeWidgetAsync(
db,
ctx,
contexts,
"app",
[],
superjson.stringify({ appId: app.id, openInNewTab: true, showTitle: true }),
@@ -138,7 +147,7 @@ export const placeAllWidgetsAsync = async (
options = { ...options, items: bookmarkAppIds };
}
await placeWidgetAsync(db, ctx, config.kind, [], options ? superjson.stringify(options) : undefined, {
await placeWidgetAsync(db, contexts, config.kind, [], options ? superjson.stringify(options) : undefined, {
width: config.width,
height: config.height,
});
+2
View File
@@ -34,6 +34,7 @@ import type {
IntegrationKind,
IntegrationPermission,
IntegrationSecretKind,
LayoutRole,
OnboardingStep,
SearchEngineType,
SectionKind,
@@ -343,6 +344,7 @@ export const layouts = mysqlTable("layout", {
leftGutterColumnCount: tinyint().notNull().default(0),
rightGutterColumnCount: tinyint().notNull().default(0),
breakpoint: smallint().notNull().default(0),
role: varchar({ length: 16 }).$type<LayoutRole>().notNull().default("custom"),
});
export const itemLayouts = mysqlTable(
+2
View File
@@ -33,6 +33,7 @@ import type {
IntegrationKind,
IntegrationPermission,
IntegrationSecretKind,
LayoutRole,
OnboardingStep,
SearchEngineType,
SectionKind,
@@ -342,6 +343,7 @@ export const layouts = pgTable("layout", {
leftGutterColumnCount: smallint().notNull().default(0),
rightGutterColumnCount: smallint().notNull().default(0),
breakpoint: smallint().notNull().default(0),
role: varchar({ length: 16 }).$type<LayoutRole>().notNull().default("custom"),
});
export const itemLayouts = pgTable(
+2
View File
@@ -21,6 +21,7 @@ import type {
IntegrationKind,
IntegrationPermission,
IntegrationSecretKind,
LayoutRole,
OnboardingStep,
SearchEngineType,
SectionKind,
@@ -327,6 +328,7 @@ export const layouts = sqliteTable("layout", {
leftGutterColumnCount: int().notNull().default(0),
rightGutterColumnCount: int().notNull().default(0),
breakpoint: int().notNull().default(0),
role: text().$type<LayoutRole>().notNull().default("custom"),
});
export const itemLayouts = sqliteTable(