merge: stack widget modernization on dnd kit

This commit is contained in:
Thomas Camlong committed 2026-08-08 20:40:26 +02:00
commit 9edeba5cd2
940 files changed
+104475 -33649

No files matched your search

@@ -1,50 +1,43 @@
import { getBoardLayouts } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import type { Modify } from "@homarr/common/types";
import { getRootSectionLane } from "@homarr/definitions";
import type { WidgetKind } from "@homarr/definitions";
import { widgetDefaultSizes } from "@homarr/definitions";
import type { BoardItemAdvancedOptions } from "@homarr/validation/shared";
import type { Board, EmptySection, Item, ItemLayout } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition, getNearestEmptyPosition } from "./empty-position";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { getFirstEmptyPosition } from "./empty-position";
import { getSectionElements } from "./section-elements";
export interface BoardPlacementHint {
sectionId: string;
layoutId: string;
xOffset: number;
yOffset: number;
}
export interface CreateItemInput {
id?: string;
kind: WidgetKind;
options?: Record<string, unknown>;
integrationIds?: string[];
advancedOptions?: BoardItemAdvancedOptions;
placement?: BoardPlacementHint;
}
export const createItemCallback =
({ id, kind, options = {}, integrationIds = [], advancedOptions, placement }: CreateItemInput) =>
({ id, kind, options = {}, integrationIds = [] }: CreateItemInput) =>
(previous: Board): Board => {
const firstSection = previous.sections
.filter((section): section is EmptySection => section.kind === "empty")
.filter(
(section): section is EmptySection =>
section.kind === "empty" && getRootSectionLane(section.xOffset) === "main",
)
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection && !placement) return previous;
const defaultSectionId = firstSection?.id ?? placement?.sectionId;
if (!defaultSectionId) return previous;
if (!firstSection) return previous;
const itemLayouts = createItemLayouts(previous, firstSection, kind);
const widget = {
id: id ?? createId(),
kind,
options,
layouts: createItemLayouts(previous, defaultSectionId, kind, placement),
layouts: itemLayouts,
integrationIds,
advancedOptions: advancedOptions ?? {
advancedOptions: {
title: null,
customCssClasses: [],
borderColor: "",
@@ -66,31 +59,21 @@ const defaultItemSize = { width: 1, height: 1 };
const getWidgetItemSize = (kind: WidgetKind) => widgetDefaultSizes[kind] ?? defaultItemSize;
const createItemLayouts = (
board: Board,
defaultSectionId: string,
kind: WidgetKind,
placement?: BoardPlacementHint,
): ItemLayout[] => {
const createItemLayouts = (board: Board, currentSection: EmptySection, kind: WidgetKind): ItemLayout[] => {
const layouts = getBoardLayouts(board);
const itemSize = getWidgetItemSize(kind);
return layouts.map((layoutId) => {
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
const targetSectionId = placement?.layoutId === layoutId ? placement.sectionId : defaultSectionId;
const elements = getSectionElements(board, { sectionId: targetSectionId, layoutId });
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
const columnCount = boardLayout ? getBoardLaneColumnCount(boardLayout, "main") : itemSize.width;
const size = {
width: Math.min(itemSize.width, columnCount),
height: itemSize.height,
};
const targetSection = board.sections.find((section) => section.id === targetSectionId);
const dynamicLayout =
targetSection?.kind === "dynamic"
? targetSection.layouts.find((layout) => layout.layoutId === layoutId)
: undefined;
const columnCount = dynamicLayout?.width ?? boardLayout?.columnCount ?? 1;
const rowCount = dynamicLayout?.height ?? 9999;
const emptyPosition = boardLayout
? placement?.layoutId === layoutId
? getNearestEmptyPosition(elements, columnCount, rowCount, placement, itemSize)
: getFirstEmptyPosition(elements, columnCount, rowCount, itemSize)
? getFirstEmptyPosition(elements, columnCount, undefined, size)
: { xOffset: 0, yOffset: 0 };
if (!emptyPosition) {
@@ -98,10 +81,10 @@ const createItemLayouts = (
}
return {
width: itemSize.width,
height: itemSize.height,
width: size.width,
height: size.height,
...emptyPosition,
sectionId: targetSectionId,
sectionId: currentSection.id,
layoutId,
};
});
@@ -1,6 +1,8 @@
import { createId } from "@homarr/common";
import { getRootSectionLane } from "@homarr/definitions";
import type { Board, EmptySection, ItemLayout, Section } from "~/app/[locale]/boards/_types";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { getFirstEmptyPosition } from "./empty-position";
import { getSectionElements } from "./section-elements";
@@ -15,16 +17,17 @@ export const duplicateItemCallback =
if (!itemToDuplicate) return previous;
const clonedItem = structuredClone(itemToDuplicate);
const clonedLayouts = clonedItem.layouts.map((layout) => ({
...layout,
...getNextPosition(previous, layout),
}));
return {
...previous,
items: previous.items.concat({
...clonedItem,
id: createId(),
layouts: clonedItem.layouts.map((layout) => ({
...layout,
...getNextPosition(previous, layout),
})),
layouts: clonedLayouts,
}),
};
};
@@ -42,8 +45,10 @@ const getNextPosition = (board: Board, layout: ItemLayout): { xOffset: number; y
}
const firstSection = board.sections
.filter((section): section is EmptySection => section.kind === "empty")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.filter(
(section): section is EmptySection => section.kind === "empty" && getRootSectionLane(section.xOffset) === "main",
)
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) {
@@ -67,18 +72,21 @@ const getEmptySectionPosition = (
layout: ItemLayout,
section: Section,
): { xOffset: number; yOffset: number } | undefined => {
const boardLayout = board.layouts.find((boardLayout) => boardLayout.id === layout.layoutId);
const boardLayout = board.layouts.find((candidate) => candidate.id === layout.layoutId);
if (!boardLayout) return;
const sectionElements = getSectionElements(board, { sectionId: layout.sectionId, layoutId: layout.layoutId });
if (section.kind !== "dynamic") {
return getFirstEmptyPosition(sectionElements, boardLayout.columnCount, undefined, {
const sectionElements = getSectionElements(board, { sectionId: section.id, layoutId: layout.layoutId });
if (section.kind === "empty") {
const columnCount = getBoardLaneColumnCount(boardLayout, getRootSectionLane(section.xOffset));
const size = {
width: layout.width,
height: layout.height,
});
};
return getFirstEmptyPosition(sectionElements, columnCount, undefined, size);
}
const sectionLayout = section.layouts.find((sectionLayout) => sectionLayout.layoutId === layout.layoutId);
const sectionLayout = section.layouts.find((candidate) => candidate.layoutId === layout.layoutId);
if (!sectionLayout) return;
return getFirstEmptyPosition(sectionElements, sectionLayout.width, sectionLayout.height, {
@@ -8,55 +8,18 @@ export const getFirstEmptyPosition = (
) => {
for (let yOffset = 0; yOffset < rowCount + 1 - size.height; yOffset++) {
for (let xOffset = 0; xOffset < columnCount + 1 - size.width; xOffset++) {
if (isPositionEmpty(elements, { xOffset, yOffset }, size)) {
const isOccupied = elements.some(
(element) =>
element.yOffset < yOffset + size.height &&
element.yOffset + element.height > yOffset &&
element.xOffset < xOffset + size.width &&
element.xOffset + element.width > xOffset,
);
if (!isOccupied) {
return { xOffset, yOffset };
}
}
}
return undefined;
};
export const getNearestEmptyPosition = (
elements: Pick<SectionItem, "yOffset" | "xOffset" | "width" | "height">[],
columnCount: number,
rowCount: number,
preferred: { xOffset: number; yOffset: number },
size: { width: number; height: number },
) => {
const maxX = columnCount - size.width;
const maxY = rowCount - size.height;
if (maxX < 0 || maxY < 0) return undefined;
const clamped = {
xOffset: Math.min(Math.max(0, preferred.xOffset), maxX),
yOffset: Math.min(Math.max(0, preferred.yOffset), maxY),
};
if (isPositionEmpty(elements, clamped, size)) return clamped;
const lastOccupiedRow = elements.reduce((maximum, element) => Math.max(maximum, element.yOffset + element.height), 0);
const searchMaxY = Math.min(maxY, Math.max(clamped.yOffset + 20, lastOccupiedRow + size.height));
let best: { xOffset: number; yOffset: number; distance: number } | undefined;
for (let yOffset = 0; yOffset <= searchMaxY; yOffset++) {
for (let xOffset = 0; xOffset <= maxX; xOffset++) {
if (!isPositionEmpty(elements, { xOffset, yOffset }, size)) continue;
const distance = Math.abs(xOffset - clamped.xOffset) + Math.abs(yOffset - clamped.yOffset);
if (!best || distance < best.distance) best = { xOffset, yOffset, distance };
}
}
return best && { xOffset: best.xOffset, yOffset: best.yOffset };
};
const isPositionEmpty = (
elements: Pick<SectionItem, "yOffset" | "xOffset" | "width" | "height">[],
position: { xOffset: number; yOffset: number },
size: { width: number; height: number },
) =>
!elements.some(
(element) =>
element.yOffset < position.yOffset + size.height &&
element.yOffset + element.height > position.yOffset &&
element.xOffset < position.xOffset + size.width &&
element.xOffset + element.width > position.xOffset,
);
@@ -1,8 +1,8 @@
import type { Board } from "~/app/[locale]/boards/_types";
export const getSectionElements = (board: Board, { sectionId, layoutId }: { sectionId: string; layoutId: string }) => {
const dynamicSectionsOfFirstSection = board.sections
.filter((section) => section.kind === "dynamic")
const containersOfSection = board.sections
.filter((section) => section.kind === "container")
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.map(({ layouts, ...section }) => ({ ...section, ...layouts.find((layout) => layout.layoutId === layoutId)! }))
.filter((section) => section.parentSectionId === sectionId);
@@ -14,5 +14,5 @@ export const getSectionElements = (board: Board, { sectionId, layoutId }: { sect
}))
.filter((item) => item.sectionId === sectionId);
return [...items, ...dynamicSectionsOfFirstSection];
return [...items, ...containersOfSection];
};
@@ -5,7 +5,7 @@ import * as boardContext from "@homarr/boards/context";
import { createItemCallback } from "../create-item";
import * as emptyPositionModule from "../empty-position";
import { BoardMockBuilder } from "./mocks/board-mock";
import { DynamicSectionMockBuilder } from "./mocks/dynamic-section-mock";
import { ContainerSectionMockBuilder } from "./mocks/container-section-mock";
import { ItemMockBuilder } from "./mocks/item-mock";
import { LayoutMockBuilder } from "./mocks/layout-mock";
@@ -56,9 +56,9 @@ describe("item actions create-item", () => {
],
}),
);
expect(emptyPositionSpy).toHaveBeenCalledWith([], layout.columnCount, 9999, { height: 1, width: 1 });
expect(emptyPositionSpy).toHaveBeenCalledWith([], layout.columnCount, undefined, { height: 1, width: 1 });
});
test("should correctly pass dynamic section and items to getFirstEmptyPosition", () => {
test("should correctly pass containers and items to getFirstEmptyPosition", () => {
// Arrange
const itemKind = "clock";
const emptyPosition = { xOffset: 5, yOffset: 5 };
@@ -67,21 +67,21 @@ describe("item actions create-item", () => {
const itemAndSectionPosition = { height: 2, width: 3, yOffset: 2, xOffset: 1 };
const layout = new LayoutMockBuilder({ id: layoutId, columnCount: 4 }).build();
const dynamicSectionInFirstSection = new DynamicSectionMockBuilder({ id: "4" })
const containerInFirstSection = new ContainerSectionMockBuilder({ id: "4" })
.addLayout({ ...itemAndSectionPosition, layoutId, parentSectionId: firstSectionId })
.build();
const itemInFirstSection = new ItemMockBuilder({ id: "12" })
.addLayout({ ...itemAndSectionPosition, layoutId, sectionId: firstSectionId })
.build();
const otherDynamicSection = new DynamicSectionMockBuilder({ id: "5" }).addLayout({ layoutId }).build();
const otherContainer = new ContainerSectionMockBuilder({ id: "5" }).addLayout({ layoutId }).build();
const otherItem = new ItemMockBuilder({ id: "13" }).addLayout({ layoutId }).build();
const board = new BoardMockBuilder()
.addLayout(layout)
.addEmptySection({ id: "1", yOffset: 2 })
.addEmptySection({ id: firstSectionId, yOffset: 0 })
.addEmptySection({ id: "3", yOffset: 1 })
.addSection(dynamicSectionInFirstSection)
.addSection(otherDynamicSection)
.addSection(containerInFirstSection)
.addSection(otherContainer)
.addItem(itemInFirstSection)
.addItem(otherItem)
.build();
@@ -98,8 +98,10 @@ describe("item actions create-item", () => {
// Assert
expect(result.items.length).toBe(3);
const item = result.items.find((item) => item.id !== itemInFirstSection.id && item.id !== otherItem.id);
expect(item).toEqual(
const createdItem = result.items.find(
(candidate) => candidate.id !== itemInFirstSection.id && candidate.id !== otherItem.id,
);
expect(createdItem).toEqual(
expect.objectContaining({
kind: itemKind,
layouts: [{ ...emptyPosition, height: 1, width: 1, sectionId: firstSectionId, layoutId }],
@@ -108,62 +110,35 @@ describe("item actions create-item", () => {
expect(spy).toHaveBeenCalledWith(
[expect.objectContaining(itemAndSectionPosition), expect.objectContaining(itemAndSectionPosition)],
layout.columnCount,
9999,
undefined,
{ height: 1, width: 1 },
);
});
test("uses the clicked section and nearest cell for the active layout", () => {
const activeLayoutId = "desktop";
const secondaryLayoutId = "mobile";
const rootSectionId = "root";
const targetSectionId = "target";
const activeLayout = new LayoutMockBuilder({ id: activeLayoutId, columnCount: 12 }).build();
const secondaryLayout = new LayoutMockBuilder({ id: secondaryLayoutId, columnCount: 4 }).build();
const targetSection = new DynamicSectionMockBuilder({ id: targetSectionId })
.addLayout({
layoutId: activeLayoutId,
parentSectionId: rootSectionId,
width: 4,
test("clamps wide defaults and places below a full automatic canvas", () => {
const board = new BoardMockBuilder().addEmptySection({ id: "canvas", yOffset: 0 }).build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 1;
board.items.push(
new ItemMockBuilder({ id: "existing" })
.addLayout({ layoutId: layout.id, sectionId: "canvas", width: 1, height: 1 })
.build(),
);
const result = createItemCallback({ id: "created", kind: "mediaMissing" })(board);
const created = result.items.find((item) => item.id === "created");
expect(created?.layouts).toEqual([
expect.objectContaining({
layoutId: layout.id,
sectionId: "canvas",
width: 1,
height: 3,
})
.build();
const board = new BoardMockBuilder()
.addLayout(activeLayout)
.addLayout(secondaryLayout)
.addEmptySection({ id: rootSectionId, yOffset: 0 })
.addSection(targetSection)
.build();
vi.spyOn(boardContext, "getBoardLayouts").mockReturnValue([activeLayoutId, secondaryLayoutId]);
const result = createItemCallback({
kind: "clock",
placement: {
sectionId: targetSectionId,
layoutId: activeLayoutId,
xOffset: 2,
yOffset: 1,
},
})(board);
expect(result.items.at(0)?.layouts).toEqual([
{
layoutId: activeLayoutId,
sectionId: targetSectionId,
xOffset: 2,
yOffset: 1,
width: 1,
height: 1,
},
{
layoutId: secondaryLayoutId,
sectionId: rootSectionId,
xOffset: 0,
yOffset: 0,
width: 1,
height: 1,
},
yOffset: 1,
}),
]);
});
});
@@ -1,4 +1,4 @@
import { describe, expect, test, vi } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import { duplicateItemCallback } from "../duplicate-item";
import * as emptyPositionModule from "../empty-position";
@@ -7,6 +7,10 @@ import { ItemMockBuilder } from "./mocks/item-mock";
import { LayoutMockBuilder } from "./mocks/layout-mock";
describe("item actions duplicate-item", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("should copy it in the same section", () => {
// Arrange
const itemKind = "minecraftServerStatus";
@@ -61,4 +65,28 @@ describe("item actions duplicate-item", () => {
}),
);
});
test("uses the next automatic canvas row when it is the first available space", () => {
const board = new BoardMockBuilder().addEmptySection({ id: "canvas", yOffset: 0 }).build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 1;
const currentItem = new ItemMockBuilder({ id: "source" })
.addLayout({ layoutId: layout.id, sectionId: "canvas", width: 1, height: 1 })
.build();
board.items.push(currentItem);
const result = duplicateItemCallback({ itemId: currentItem.id })(board);
const duplicated = result.items.find((item) => item.id !== currentItem.id);
expect(duplicated?.layouts[0]).toEqual(
expect.objectContaining({
layoutId: layout.id,
sectionId: "canvas",
xOffset: 0,
yOffset: 1,
}),
);
});
});
@@ -1,7 +1,7 @@
import { describe, expect, test } from "vitest";
import type { Item } from "~/app/[locale]/boards/_types";
import { getFirstEmptyPosition, getNearestEmptyPosition } from "../empty-position";
import { getFirstEmptyPosition } from "../empty-position";
describe("get first empty position", () => {
test.each([
@@ -106,39 +106,7 @@ describe("get first empty position", () => {
expect(result).toEqual(expectedX !== undefined ? { xOffset: expectedX, yOffset: expectedY } : undefined);
});
test("does not place a wide item beyond the right edge", () => {
const elements = createElementsFromLayout([["a", "a", "a", " "]]);
expect(getFirstEmptyPosition(elements, 4, undefined, { width: 2, height: 1 })).toEqual({
xOffset: 0,
yOffset: 1,
});
});
});
describe("get nearest empty position", () => {
test("keeps the preferred cell when it fits", () => {
expect(getNearestEmptyPosition([], 4, 4, { xOffset: 2, yOffset: 1 }, { width: 1, height: 1 })).toEqual({
xOffset: 2,
yOffset: 1,
});
});
test("chooses the nearest available cell when the preferred cell is occupied", () => {
const elements = [{ xOffset: 2, yOffset: 1, width: 1, height: 1 }];
expect(getNearestEmptyPosition(elements, 4, 4, { xOffset: 2, yOffset: 1 }, { width: 1, height: 1 })).toEqual({
xOffset: 2,
yOffset: 0,
});
});
test("returns undefined when the item cannot fit within a bounded section", () => {
expect(getNearestEmptyPosition([], 1, 1, { xOffset: 0, yOffset: 0 }, { width: 2, height: 1 })).toBeUndefined();
});
});
const createElementsFromLayout = (layout: string[][]) => {
const elements: (Pick<Item["layouts"][number], "xOffset" | "yOffset" | "width" | "height"> & { char: string })[] = [];
for (let yOffset = 0; yOffset < layout.length; yOffset++) {
@@ -0,0 +1,123 @@
import { describe, expect, test } from "vitest";
import { getMoveTargets } from "../../item-move-modal";
import { BoardMockBuilder } from "./mocks/board-mock";
import { ContainerSectionMockBuilder } from "./mocks/container-section-mock";
import { EmptySectionMockBuilder } from "./mocks/empty-section-mock";
import { ItemMockBuilder } from "./mocks/item-mock";
describe("item move targets", () => {
test("offers the canvas, enabled gutters, and nested sections", () => {
const board = new BoardMockBuilder().build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected the board mock to contain a layout");
layout.id = "layout";
layout.columnCount = 6;
layout.leftGutterColumnCount = 1;
layout.rightGutterColumnCount = 1;
board.sections.push(
new EmptySectionMockBuilder({ id: "canvas", xOffset: 0 }).build(),
new EmptySectionMockBuilder({ id: "left-gutter", xOffset: -1 }).build(),
new EmptySectionMockBuilder({ id: "right-gutter", xOffset: 1 }).build(),
new ContainerSectionMockBuilder({
id: "container",
options: {
title: "",
customCssClasses: [],
borderColor: "",
showLabel: true,
collapsible: false,
showOpenAll: false,
},
})
.addLayout({
layoutId: layout.id,
parentSectionId: "canvas",
width: 2,
height: 2,
})
.build(),
);
const targets = getMoveTargets(
board,
layout.id,
{
id: "weather",
type: "item",
xOffset: 0,
yOffset: 0,
width: 1,
height: 1,
},
{
canvas: "Dashboard canvas",
container: "New section",
leftRail: "Left dashboard rail",
rightRail: "Right dashboard rail",
numbered: (name, index) => `${name}, destination ${index}`,
located: (name, location, index) => `${name}, ${location}, destination ${index}`,
},
);
expect(targets.map((target) => target.label)).toEqual([
"Dashboard canvas, destination 1",
"Left dashboard rail, destination 2",
"Right dashboard rail, destination 3",
"New section, destination 4",
]);
expect(new Set(targets.map((target) => target.label))).toHaveLength(targets.length);
});
test("does not offer canvases that are narrower than a nested section's contents", () => {
const board = new BoardMockBuilder().build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected the board mock to contain a layout");
layout.id = "layout";
layout.columnCount = 5;
layout.leftGutterColumnCount = 2;
const section = new ContainerSectionMockBuilder({ id: "source" })
.addLayout({
layoutId: layout.id,
parentSectionId: "canvas",
width: 4,
height: 2,
})
.build();
board.sections.push(
new EmptySectionMockBuilder({ id: "canvas" }).build(),
new EmptySectionMockBuilder({ id: "left-gutter", xOffset: -1 }).build(),
section,
);
board.items.push(
new ItemMockBuilder({ id: "nested" })
.addLayout({
layoutId: layout.id,
sectionId: section.id,
xOffset: 2,
width: 2,
})
.build(),
);
const sourceLayout = section.layouts[0];
if (!sourceLayout) throw new Error("Expected the source section to contain a layout");
const targets = getMoveTargets(
board,
layout.id,
{ ...sourceLayout, id: section.id, type: "section" },
{
canvas: "Canvas",
container: "Section",
leftRail: "Left",
rightRail: "Right",
numbered: (name, index) => `${name} ${index}`,
located: (name, location, index) => `${name} ${location} ${index}`,
},
);
expect(targets).toEqual([]);
});
});
@@ -1,7 +1,7 @@
import { createId } from "@homarr/common";
import type { Board, DynamicSection, EmptySection, Item, Section } from "~/app/[locale]/boards/_types";
import { DynamicSectionMockBuilder } from "./dynamic-section-mock";
import type { Board, ContainerSection, EmptySection, Item, Section } from "~/app/[locale]/boards/_types";
import { ContainerSectionMockBuilder } from "./container-section-mock";
import { EmptySectionMockBuilder } from "./empty-section-mock";
import { ItemMockBuilder } from "./item-mock";
import { LayoutMockBuilder } from "./layout-mock";
@@ -45,6 +45,8 @@ export class BoardMockBuilder {
id: createId(),
name: "Base",
columnCount: 12,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 0,
},
],
@@ -56,8 +58,8 @@ export class BoardMockBuilder {
return this.addSection(new EmptySectionMockBuilder(emptySection).build());
}
public addDynamicSection(dynamicSection?: Partial<DynamicSection>): BoardMockBuilder {
return this.addSection(new DynamicSectionMockBuilder(dynamicSection).build());
public addContainer(container?: Partial<ContainerSection>): BoardMockBuilder {
return this.addSection(new ContainerSectionMockBuilder(container).build());
}
public addSection(section: Section): BoardMockBuilder {
@@ -1,23 +0,0 @@
import { createId } from "@homarr/common";
import type { CategorySection } from "~/app/[locale]/boards/_types";
export class CategorySectionMockBuilder {
private readonly section: CategorySection;
constructor(section?: Partial<CategorySection>) {
this.section = {
id: createId(),
kind: "category",
xOffset: 0,
yOffset: 0,
name: "Category",
collapsed: false,
...section,
} satisfies CategorySection;
}
public build(): CategorySection {
return this.section;
}
}
@@ -0,0 +1,38 @@
import { createId } from "@homarr/common";
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
import type { ContainerSection } from "~/app/[locale]/boards/_types";
type ContainerSectionMock = Omit<Partial<ContainerSection>, "options"> & {
options?: Partial<ContainerSection["options"]>;
};
export class ContainerSectionMockBuilder {
private readonly section: ContainerSection;
constructor(section?: ContainerSectionMock) {
this.section = {
id: section?.id ?? createId(),
kind: "container",
collapsed: section?.collapsed ?? false,
layouts: section?.layouts ?? [],
options: containerSectionOptionsSchema.parse(section?.options),
};
}
public addLayout(layout?: Partial<ContainerSection["layouts"][0]>): ContainerSectionMockBuilder {
this.section.layouts.push({
layoutId: layout?.layoutId ?? createId(),
parentSectionId: layout?.parentSectionId ?? createId(),
xOffset: layout?.xOffset ?? 0,
yOffset: layout?.yOffset ?? 0,
width: layout?.width ?? 1,
height: layout?.height ?? 1,
});
return this;
}
public build(): ContainerSection {
return structuredClone(this.section);
}
}
@@ -1,38 +0,0 @@
import { createId } from "@homarr/common";
import type { DynamicSection } from "~/app/[locale]/boards/_types";
export class DynamicSectionMockBuilder {
private readonly section: DynamicSection;
constructor(section?: Partial<DynamicSection>) {
this.section = {
id: createId(),
kind: "dynamic",
options: {
title: "",
borderColor: "",
customCssClasses: [],
},
layouts: [],
...section,
} satisfies DynamicSection;
}
public addLayout(layout?: Partial<DynamicSection["layouts"][0]>): DynamicSectionMockBuilder {
this.section.layouts.push({
layoutId: "1",
height: 1,
width: 1,
xOffset: 0,
yOffset: 0,
parentSectionId: "0",
...layout,
} satisfies DynamicSection["layouts"][0]);
return this;
}
public build(): DynamicSection {
return this.section;
}
}
@@ -10,6 +10,8 @@ export class LayoutMockBuilder {
id: createId(),
name: "Base",
columnCount: 12,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 0,
...layout,
} satisfies Board["layouts"][0];
@@ -10,3 +10,17 @@
background-color: var(--background-color) !important;
border-color: var(--border-color) !important;
}
.editModeInertContent {
display: contents;
}
.editModeInertContent[data-board-grid-inert-content="true"] {
pointer-events: none;
user-select: none;
}
.editModeInertContent[data-board-grid-inert-content="true"] * {
pointer-events: none !important;
user-select: none !important;
}
@@ -1,26 +1,28 @@
import type { CSSProperties, KeyboardEvent } from "react";
import { useEffect, useRef, useState } from "react";
import type { ComponentType, CSSProperties, KeyboardEvent, MutableRefObject } from "react";
import { Suspense, use, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Badge, Box, Card, Portal } from "@mantine/core";
import dynamic from "next/dynamic";
import type { CardProps } from "@mantine/core";
import { Badge, Box, Card, Center, Loader, Portal } from "@mantine/core";
import { useElementSize, useIsomorphicEffect, useViewportSize } from "@mantine/hooks";
import { QueryErrorResetBoundary, useQueryClient } from "@tanstack/react-query";
import combineClasses from "clsx";
import { NoIntegrationSelectedError } from "@homarr/widgets/errors/classes";
import type { FallbackProps } from "react-error-boundary";
import { ErrorBoundary } from "react-error-boundary";
import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import type { WidgetRuntimeRef } from "@homarr/widgets";
import { WidgetError } from "@homarr/widgets/errors";
import {
createWidgetRuntimeState,
loadWidgetDynamic,
reduceWidgetOptionsWithDefaultValues,
getWidgetQueryKeys,
supportsAdvancedFocus as definitionSupportsAdvancedFocus,
widgetImports,
} from "@homarr/widgets";
import { WidgetError } from "@homarr/widgets/errors";
} from "@homarr/widgets/definition";
import type { WidgetComponentProps, WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets/definition";
import { loadWidgetResources, reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import advancedFocusClasses from "../advanced-focus/advanced-focus.module.css";
@@ -31,35 +33,136 @@ import { redirectShiftWheel } from "../advanced-focus/wheel";
import classes from "../sections/item.module.css";
import { useItemActions } from "./item-actions";
import itemContentClasses from "./item-content.module.css";
import { BoardItemMenu } from "./item-menu";
import { WidgetContextMenu } from "./widget-context-menu";
import { removePersistedWidgetQueries } from "./widget-query-recovery";
import { removeWidgetDataQueries } from "./widget-query-recovery";
const BoardItemMenu = dynamic(() => import("./item-menu").then((module) => module.BoardItemMenu), {
ssr: false,
});
interface BoardItemContentProps {
item: SectionItem;
}
const getOverflowFromKind = (kind: SectionItem["kind"]) => {
if (kind === "iframe") return "hidden";
if (kind === "systemResources") return "visible";
return undefined;
const getOverflowFromKind = (kind: SectionItem["kind"], hasCustomCssClasses: boolean) => {
if (kind === "systemResources") return { overflowX: "visible", overflowY: "visible" } as const;
if (kind === "iframe") return { overflowX: "hidden", overflowY: "hidden" } as const;
if (hasCustomCssClasses) return {};
return { overflowX: "hidden", overflowY: "auto" } as const;
};
type BoardItemCardProps = CardProps & {
item: SectionItem;
innerRef: (element: HTMLDivElement | null) => void;
};
const BoardItemCard = ({ item, innerRef, children, ...cardProps }: BoardItemCardProps) => {
const board = useRequiredBoard();
return (
<Card
{...cardProps}
ref={innerRef}
w="100%"
h="100%"
data-grid-item-content
className={combineClasses(
classes.itemCard,
`${item.kind}-wrapper`,
"board-grid-item-content",
item.advancedOptions.customCssClasses.join(" "),
)}
radius={board.itemRadius}
styles={{
root: {
"--opacity": board.opacity / 100,
containerType: "size",
...getOverflowFromKind(item.kind, item.advancedOptions.customCssClasses.length > 0),
"--border-color": item.advancedOptions.borderColor !== "" ? item.advancedOptions.borderColor : undefined,
},
}}
p={0}
>
{children}
</Card>
);
};
const WidgetDefinitionLoadError = ({
error,
resetErrorBoundary,
item,
innerRef,
}: FallbackProps & Pick<BoardItemCardProps, "item" | "innerRef">) => (
<BoardItemCard item={item} innerRef={innerRef}>
<Center h="100%">
<WidgetError error={error} resetErrorBoundary={resetErrorBoundary} />
</Center>
</BoardItemCard>
);
export const BoardItemContent = ({ item }: BoardItemContentProps) => {
const { ref: contentRef, width, height } = useElementSize<HTMLDivElement>();
const { ref, width, height } = useElementSize<HTMLDivElement>();
const widgetStateRef = useRef<Record<string, unknown> | null>(null);
const widgetRuntimeRef = useRef(createWidgetRuntimeState());
return (
<ErrorBoundary
resetKeys={[item.kind]}
fallbackRender={(fallbackProps) => <WidgetDefinitionLoadError {...fallbackProps} item={item} innerRef={ref} />}
>
<Suspense
fallback={
<BoardItemCard item={item} innerRef={ref}>
<Center h="100%">
<Loader size="sm" />
</Center>
</BoardItemCard>
}
>
<LoadedBoardItemContent
item={item}
width={width}
height={height}
widgetStateRef={widgetStateRef}
widgetRuntimeRef={widgetRuntimeRef}
contentRef={ref}
/>
</Suspense>
</ErrorBoundary>
);
};
interface LoadedBoardItemContentProps {
item: SectionItem;
width: number;
height: number;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef;
contentRef: (element: HTMLDivElement | null) => void;
}
const LoadedBoardItemContent = ({
item,
width,
height,
widgetStateRef,
widgetRuntimeRef,
contentRef,
}: LoadedBoardItemContentProps) => {
const { definition, Component } = use(loadWidgetResources(item.kind));
const sourceRef = useRef<HTMLDivElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
const { width: viewportWidth, height: viewportHeight } = useViewportSize();
const board = useRequiredBoard();
const t = useI18n();
const widgetName = t(`widget.${item.kind}.name`);
const advancedViewLabel = t("item.advancedFocus.label", { widget: widgetName });
const [isEditMode] = useEditMode();
const widgetRuntimeRef = useRef(createWidgetRuntimeState());
const cardRef = useRef<HTMLDivElement>(null);
const [manualSurface, setManualSurface] = useState<HTMLDivElement | null>(null);
const [surfacePortalTarget, setSurfacePortalTarget] = useState<HTMLDivElement | null>(null);
const { active, open, close, dismiss, hover, leave } = useAdvancedFocus();
const supportsAdvancedFocus = definitionSupportsAdvancedFocus(widgetImports[item.kind].definition);
const supportsAdvancedFocus = definitionSupportsAdvancedFocus(definition);
const widgetName = t(`widget.${item.kind}.name`);
const advancedViewLabel = t("item.advancedFocus.label", { widget: widgetName });
const advancedViewId = `advanced-focus-${item.id}`;
const activeFocus = supportsAdvancedFocus && active?.itemId === item.id ? active : null;
const isAdvanced = activeFocus !== null;
@@ -70,8 +173,6 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
const isPreview = activeFocus?.activation === "preview";
const isManual = activeFocus?.activation === "manual";
// Keep one widget subtree mounted while moving its stable portal target between the grid and viewport layers.
// This preserves iframe/editor state and escapes Gridstack's transformed containing block.
useIsomorphicEffect(() => {
if (!supportsAdvancedFocus) return;
const target = document.createElement("div");
@@ -80,12 +181,8 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
return () => target.remove();
}, [supportsAdvancedFocus]);
// Responsive layout changes remount grid items. Never leave their focus backdrop orphaned.
useEffect(() => () => dismiss(item.id), [dismiss, item.id]);
const openAdvanced = (autofocusClose = false) => {
if (sourceRef.current) open(item.id, sourceRef.current, { activation: "manual", autofocusClose });
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (
event.currentTarget !== event.target ||
@@ -96,8 +193,9 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
)
return;
event.preventDefault();
openAdvanced(true);
if (sourceRef.current) open(item.id, sourceRef.current, { activation: "manual", autofocusClose: true });
};
useEffect(() => {
const surface = isManual ? manualSurface : cardRef.current;
if (!isAdvanced || !surface) return;
@@ -125,7 +223,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
};
const previewStyle =
isPreview && advancedRect
isPreview && advancedRect && activeFocus
? ({
left: advancedRect.left,
top: advancedRect.top,
@@ -145,6 +243,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
role={isPreview ? "region" : undefined}
aria-label={isPreview ? advancedViewLabel : undefined}
data-advanced-focus-surface={isPreview || undefined}
data-grid-item-content
radius={board.itemRadius}
p={isAdvanced ? undefined : 0}
h={isManual ? "100%" : isAdvanced ? undefined : "100%"}
@@ -152,6 +251,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
className={combineClasses(
classes.itemCard,
`${item.kind}-wrapper`,
"board-grid-item-content",
isPreview && advancedFocusClasses.surface,
activeFocus?.phase === "closing" && isPreview && advancedFocusClasses.surfaceClosing,
item.advancedOptions.customCssClasses.join(" "),
@@ -160,29 +260,60 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
root: {
"--opacity": isAdvanced ? 0.98 : board.opacity / 100,
containerType: "size",
overflow: getOverflowFromKind(item.kind),
...getOverflowFromKind(item.kind, item.advancedOptions.customCssClasses.length > 0),
"--border-color": item.advancedOptions.borderColor !== "" ? item.advancedOptions.borderColor : undefined,
},
}}
style={previewStyle}
>
<Box ref={contentRef} w="100%" h="100%" mih={0}>
<InnerContent
item={item}
width={width}
height={height}
widgetRuntimeRef={widgetRuntimeRef}
displayMode={isAdvanced ? "advanced" : "compact"}
/>
<ErrorBoundary
resetKeys={[item.kind]}
fallbackRender={({ resetErrorBoundary, error }) => (
<>
{isEditMode && (
<BoardItemMenu item={item} definition={definition} resetErrorBoundary={resetErrorBoundary} />
)}
<div
className={itemContentClasses.editModeInertContent}
data-board-grid-inert-content={isEditMode ? "true" : undefined}
inert={isEditMode}
>
<WidgetError definition={definition} error={error} resetErrorBoundary={resetErrorBoundary} />
</div>
</>
)}
>
<InnerContent
item={item}
width={width}
height={height}
widgetStateRef={widgetStateRef}
widgetRuntimeRef={widgetRuntimeRef}
displayMode={isAdvanced ? "advanced" : "compact"}
definition={definition}
Component={Component}
/>
</ErrorBoundary>
</Box>
</Card>
);
return (
<>
<WidgetContextMenu item={item} widgetRuntimeRef={widgetRuntimeRef} sourceRef={sourceRef}>
<WidgetContextMenu
item={item}
definition={definition}
widgetStateRef={widgetStateRef}
widgetRuntimeRef={widgetRuntimeRef}
sourceRef={sourceRef}
>
<Box
ref={sourceRef}
w="100%"
h="100%"
data-advanced-focus-source
data-item-id={item.id}
tabIndex={!isEditMode && supportsAdvancedFocus ? 0 : undefined}
role={!isEditMode && supportsAdvancedFocus ? "group" : undefined}
aria-label={
@@ -198,7 +329,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
onPointerLeave={() => {
if (supportsAdvancedFocus) leave(item.id);
}}
className={combineClasses("grid-stack-item-content", isAdvanced && advancedFocusClasses.sourcePlaceholder)}
className={combineClasses(isAdvanced && advancedFocusClasses.sourcePlaceholder)}
>
<div ref={(node) => mountPortalTarget(node, "compact")} className={advancedFocusClasses.surfaceHost}>
{!supportsAdvancedFocus && widgetCard}
@@ -212,7 +343,7 @@ export const BoardItemContent = ({ item }: BoardItemContentProps) => {
/>
</Portal>
)}
{isManual && advancedRect && closePosition && (
{isManual && activeFocus && advancedRect && closePosition && (
<AdvancedFocusManualSurface
opened={activeFocus.phase === "visible"}
phase={activeFocus.phase}
@@ -262,37 +393,47 @@ interface InnerContentProps {
item: SectionItem;
width: number;
height: number;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef;
displayMode: "compact" | "advanced";
definition: WidgetDefinition;
Component: ComponentType<WidgetComponentProps<SectionItem["kind"]>>;
}
const InnerContent = ({ item, ...dimensions }: InnerContentProps) => {
const InnerContent = ({ item, definition, Component, ...dimensions }: InnerContentProps) => {
const settings = useSettings();
const board = useRequiredBoard();
const [isEditMode] = useEditMode();
const Comp = loadWidgetDynamic(item.kind);
const { definition } = widgetImports[item.kind];
const options = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
const options = reduceWidgetOptionsWithDefinition(definition, settings, item.options);
const newItem = { ...item, options };
const { updateItemOptions } = useItemActions();
const { removeItem, updateItemOptions } = useItemActions();
const updateOptions = ({ newOptions }: { newOptions: Record<string, unknown> }) =>
updateItemOptions({ itemId: item.id, newOptions });
const widgetSupportsIntegrations =
"supportedIntegrations" in definition && definition.supportedIntegrations.length >= 1;
"supportedIntegrations" in definition && (definition.supportedIntegrations?.length ?? 0) >= 1;
const queryClient = useQueryClient();
const widgetQueryKeys = getWidgetQueryKeys(definition, item.kind);
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={() => {
removePersistedWidgetQueries(queryClient);
removeWidgetDataQueries(queryClient, widgetQueryKeys);
reset();
}}
fallbackRender={({ resetErrorBoundary, error }) => (
<>
<BoardItemMenu offset={4} item={newItem} resetErrorBoundary={resetErrorBoundary} />
<WidgetError kind={item.kind} error={error} resetErrorBoundary={resetErrorBoundary} />
{isEditMode && (
<BoardItemMenu item={newItem} definition={definition} resetErrorBoundary={resetErrorBoundary} />
)}
<div
className={itemContentClasses.editModeInertContent}
data-board-grid-inert-content={isEditMode ? "true" : undefined}
inert={isEditMode}
>
<WidgetError definition={definition} error={error} resetErrorBoundary={resetErrorBoundary} />
</div>
</>
)}
>
@@ -304,23 +445,31 @@ const InnerContent = ({ item, ...dimensions }: InnerContentProps) => {
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false)
}
/>
<BoardItemMenu offset={4} item={newItem} />
<Comp
options={options as never}
integrationIds={item.integrationIds}
isEditMode={isEditMode}
boardId={board.id}
itemId={item.id}
setOptions={(partialNewOptions) =>
updateOptions({
newOptions: {
...options,
...partialNewOptions.newOptions,
},
})
}
{...dimensions}
/>
{isEditMode && <BoardItemMenu item={newItem} definition={definition} />}
<div
className={itemContentClasses.editModeInertContent}
data-board-grid-inert-content={isEditMode ? "true" : undefined}
data-homarr-widget-ready={item.kind}
inert={isEditMode}
>
<Component
options={options as never}
integrationIds={item.integrationIds}
isEditMode={isEditMode}
boardId={board.id}
itemId={item.id}
removeItem={() => removeItem({ itemId: item.id })}
setOptions={(partialNewOptions) =>
updateOptions({
newOptions: {
...options,
...partialNewOptions.newOptions,
},
})
}
{...dimensions}
/>
</div>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
@@ -1,48 +1,48 @@
import { useEffect, useMemo, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { ActionIcon, Menu } from "@mantine/core";
import { IconCopy, IconDotsVertical, IconLayoutKanban, IconPencil, IconTrash } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useEditMode } from "@homarr/boards/edit-mode";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useSettings } from "@homarr/settings";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { widgetImports } from "@homarr/widgets";
import { WidgetEditModal } from "@homarr/widgets/modals";
import type { WidgetDefinition } from "@homarr/widgets/definition";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import { useSectionContext } from "../sections/section-context";
import { useItemActions } from "./item-actions";
import { ItemMoveModal } from "./item-move-modal";
import { useOpenItemMoveModal } from "./item-move-modal";
import { LazyWidgetEditModal, preloadWidgetEditModal } from "./lazy-widget-edit-modal";
interface BoardItemMenuProps {
offset: number;
item: SectionItem;
definition: WidgetDefinition;
resetErrorBoundary?: () => void;
}
export const BoardItemMenu = (props: BoardItemMenuProps) => {
const { data: session } = useSession();
if (!session) return null;
const [isEditMode] = useEditMode();
if (!session || !isEditMode) return null;
return <BoardItemMenuInner {...props} />;
};
const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuProps) => {
const BoardItemMenuInner = ({ item, definition, resetErrorBoundary }: BoardItemMenuProps) => {
const { data: session } = useSession();
const canDuplicate = item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
const refResetErrorBoundaryOnNextRender = useRef(false);
const tItem = useScopedI18n("item");
const t = useI18n();
const { openModal } = useModalAction(WidgetEditModal);
const { openModal: openMoveModal } = useModalAction(ItemMoveModal);
const { openModal } = useModalAction(LazyWidgetEditModal);
const openMoveModal = useOpenItemMoveModal();
const { openConfirmModal } = useConfirmModal();
const [isEditMode] = useEditMode();
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations, duplicateItem, removeItem } =
useItemActions();
const { data: integrationData, isPending } = clientApi.integration.all.useQuery();
const currentDefinition = useMemo(() => widgetImports[item.kind].definition, [item.kind]);
const { gridstack } = useSectionContext().refs;
const { integrations: integrationData = [], section } = useSectionContext();
const settings = useSettings();
const label = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`);
// Reset error boundary on next render if item has been edited
useEffect(() => {
@@ -52,12 +52,11 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
}
}, [item, resetErrorBoundary]);
if (!isEditMode || isPending) return null;
const openEditModal = () => {
openModal(
{
kind: item.kind,
definition,
value: {
advancedOptions: item.advancedOptions,
options: item.options,
@@ -78,19 +77,19 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
});
refResetErrorBoundaryOnNextRender.current = true;
},
integrationData: (integrationData ?? []).filter(
integrationData: integrationData.filter(
(integration) =>
"supportedIntegrations" in currentDefinition &&
(currentDefinition.supportedIntegrations as string[]).some((kind) => kind === integration.kind),
"supportedIntegrations" in definition &&
(definition.supportedIntegrations as string[]).some((kind) => kind === integration.kind),
),
integrationSupport: "supportedIntegrations" in currentDefinition,
integrationSupport: "supportedIntegrations" in definition,
settings,
itemId: item.id,
appId: item.kind === "app" ? (item.options.appId as string | undefined) : undefined,
},
{
title(t) {
return `${t("item.edit.title")} - ${t(`widget.${item.kind}.name`)}`;
title(translate) {
return `${translate("item.edit.title")} - ${translate(`widget.${item.kind}.name`)}`;
},
},
);
@@ -107,37 +106,48 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
};
return (
<Menu withinPortal position="right-start" arrowPosition="center">
<Menu withinPortal position="right-start" arrowPosition="center" opened={isMenuOpen} onChange={setIsMenuOpen}>
<Menu.Target>
<ActionIcon
variant="default"
radius={"xl"}
size={24}
radius="sm"
pos="absolute"
top={offset}
right={offset}
style={{ zIndex: "var(--mantine-z-index-popover)" }}
aria-label={tItem("menu.label.settings")}
top={12}
right={8}
style={{ zIndex: 10 }}
data-board-widget-settings
aria-label={tItem("menu.label.settingsFor", { name: label })}
>
<IconDotsVertical size={"1rem"} />
<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}>
<Menu.Item
leftSection={<IconPencil size={16} />}
onClick={openEditModal}
onFocus={preloadWidgetEditModal}
onPointerEnter={preloadWidgetEditModal}
>
{tItem("action.edit")}
</Menu.Item>
<Menu.Item
leftSection={<IconLayoutKanban size={16} />}
onClick={() => {
if (!gridstack.current) return;
openMoveModal({ item, columnCount: gridstack.current.getColumn(), gridStack: gridstack.current });
openMoveModal({
entry: item,
sourceSectionId: section.id,
});
}}
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</Menu.Item>
{canDuplicate && (
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</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}>
@@ -1,94 +1,220 @@
import { useCallback, useRef } from "react";
import { Grid, NumberInput, Stack } from "@mantine/core";
import { useCallback, useMemo } from "react";
import { Grid, NumberInput, Select, Stack } from "@mantine/core";
import { z } from "zod/v4";
import { useCurrentLayout, useRequiredBoard } from "@homarr/boards/context";
import { getRootSectionLane } from "@homarr/definitions";
import { useZodForm } from "@homarr/form";
import type { GridStack } from "@homarr/gridstack";
import { createModal, ModalFormFooter, modalSizeForm } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
import { createModal, ModalFormFooter, modalSizeForm, useModalAction } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
import type { Item, SectionItem } from "~/app/[locale]/boards/_types";
import type { Board, ContainerSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
import { getLayoutRowCount } from "../layout";
import { resolvePinnedGridCollisions } from "../sections/grid/dnd";
import { getSectionGridColumnCount, getSectionGridPlacements } from "../sections/grid/section-grid-placements";
import type { CommitSectionGridInput, SectionGridPlacement } from "../sections/grid/use-grid-layout-actions";
import { useGridLayoutActions } from "../sections/grid/use-grid-layout-actions";
interface InnerProps {
gridStack: GridStack;
item: Pick<SectionItem, "id" | "width" | "height" | "xOffset" | "yOffset">;
columnCount: number;
export type MovableEntry = Pick<
SectionItem | ContainerSectionItem,
"id" | "type" | "width" | "height" | "xOffset" | "yOffset"
>;
export interface OpenItemMoveModalInput {
entry: MovableEntry;
sourceSectionId: string;
}
interface InnerProps extends OpenItemMoveModalInput {
board: Board;
currentLayoutId: string;
commitSectionGrids: (snapshots: readonly CommitSectionGridInput[]) => void;
}
interface MoveTarget {
id: string;
label: string;
columnCount: number;
maxRowCount: number | null;
}
interface MoveTargetLabels {
canvas: string;
container: string;
leftRail: string;
rightRail: string;
numbered: (name: string, index: number) => string;
located: (name: string, location: string, index: number) => string;
}
type MoveTargetCandidate = Omit<MoveTarget, "label"> & {
name: string;
location?: string;
};
export const ItemMoveModal = createModal<InnerProps>(({ actions, innerProps }) => {
const t = useI18n();
const maxWidthRef = useRef(innerProps.columnCount - innerProps.item.xOffset);
const tLandmark = useScopedI18n("board.landmark");
const tContainer = useScopedI18n("section.container");
const tMoveResize = useScopedI18n("item.moveResize");
const { board, commitSectionGrids, currentLayoutId, entry, sourceSectionId } = innerProps;
const minimumSize = useMemo(
() => getEntryMinimumSize(board, currentLayoutId, entry),
[board, currentLayoutId, entry],
);
const targets = useMemo(
() =>
getMoveTargets(board, currentLayoutId, entry, {
canvas: tLandmark("canvas"),
container: tContainer("action.create"),
leftRail: tLandmark("leftRail"),
rightRail: tLandmark("rightRail"),
numbered: (name, index) => tMoveResize("target.numbered", { name, index: String(index) }),
located: (name, location, index) =>
tMoveResize("target.located", {
name,
location,
index: String(index),
}),
}),
[board, currentLayoutId, entry, tContainer, tLandmark, tMoveResize],
);
const targetById = useMemo(() => new Map(targets.map((target) => [target.id, target])), [targets]);
const initialTarget = targetById.get(sourceSectionId) ?? targets[0];
if (!initialTarget) {
throw new Error("No valid dashboard section is available for this item");
}
const form = useZodForm(
z.object({
xOffset: z
.number()
.min(0)
.max(innerProps.columnCount - 1),
yOffset: z.number().min(0),
width: z.number().min(1).max(maxWidthRef.current),
height: z.number().min(1),
sectionId: z.string().min(1),
xOffset: z.number().int().min(0).max(32767),
yOffset: z.number().int().min(0).max(32767),
width: z.number().int().min(1).max(32767),
height: z.number().int().min(1).max(32767),
}),
{
initialValues: {
xOffset: innerProps.item.xOffset,
yOffset: innerProps.item.yOffset,
width: innerProps.item.width,
height: innerProps.item.height,
},
onValuesChange(values, previous) {
if (values.xOffset !== previous.xOffset) {
maxWidthRef.current = innerProps.columnCount - values.xOffset;
}
sectionId: initialTarget.id,
xOffset: entry.xOffset,
yOffset: entry.yOffset,
width: entry.width,
height: entry.height,
},
},
);
const selectedTarget = targetById.get(form.values.sectionId) ?? initialTarget;
const handleSubmit = useCallback(
(values: Pick<Item["layouts"][number], "height" | "width" | "xOffset" | "yOffset">) => {
const gridItem = innerProps.gridStack
.getGridItems()
.find((item) => item.getAttribute("data-id") === innerProps.item.id);
if (!gridItem) return;
innerProps.gridStack.update(gridItem, {
h: values.height,
w: values.width,
x: values.xOffset,
(values: { sectionId: string; xOffset: number; yOffset: number; width: number; height: number }) => {
const target = targetById.get(values.sectionId);
if (!target) return;
const width = Math.max(minimumSize.width, Math.min(values.width, target.columnCount));
const height = Math.max(minimumSize.height, values.height);
const nextPlacement: SectionGridPlacement = {
id: entry.id,
type: entry.type,
x: Math.min(values.xOffset, target.columnCount - width),
y: values.yOffset,
});
w: width,
h: height,
};
const targetPlacements = getSectionGridPlacements(board, currentLayoutId, target.id).filter(
(placement) => placement.id !== entry.id,
);
const resolvedTarget = resolvePinnedGridCollisions(
[...targetPlacements, nextPlacement],
nextPlacement,
target.columnCount,
);
if (target.maxRowCount !== null && getLayoutRowCount(resolvedTarget) > target.maxRowCount) {
form.setFieldError("height", tMoveResize("keyboard.boundary"));
return;
}
const snapshots =
sourceSectionId === target.id
? [{ layoutId: currentLayoutId, sectionId: target.id, placements: resolvedTarget }]
: [
{
layoutId: currentLayoutId,
sectionId: sourceSectionId,
placements: getSectionGridPlacements(board, currentLayoutId, sourceSectionId).filter(
(placement) => placement.id !== entry.id,
),
},
{ layoutId: currentLayoutId, sectionId: target.id, placements: resolvedTarget },
];
commitSectionGrids(snapshots);
actions.closeModal();
focusMovedEntry(entry.id, target.id);
},
[actions, innerProps.gridStack, innerProps.item.id],
[
actions,
board,
commitSectionGrids,
currentLayoutId,
entry,
form,
minimumSize,
sourceSectionId,
targetById,
tMoveResize,
],
);
return (
<form onSubmit={form.onSubmit(handleSubmit, console.error)}>
<Stack>
<Select
data={targets.map((target) => ({ value: target.id, label: target.label }))}
label={tMoveResize("field.section.label")}
data-autofocus
allowDeselect={false}
searchable
{...form.getInputProps("sectionId")}
/>
<Grid>
<Grid.Col span={{ base: 12, md: 6 }}>
<NumberInput
label={t("item.moveResize.field.xOffset.label")}
data-autofocus
label={tMoveResize("field.xOffset.label")}
min={0}
max={innerProps.columnCount - 1}
max={selectedTarget.columnCount - 1}
{...form.getInputProps("xOffset")}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<NumberInput label={t("item.moveResize.field.yOffset.label")} min={0} {...form.getInputProps("yOffset")} />
<NumberInput
label={tMoveResize("field.yOffset.label")}
min={0}
max={selectedTarget.maxRowCount === null ? undefined : selectedTarget.maxRowCount - 1}
{...form.getInputProps("yOffset")}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<NumberInput
label={t("item.moveResize.field.width.label")}
min={1}
max={innerProps.columnCount - form.values.xOffset}
label={tMoveResize("field.width.label")}
min={minimumSize.width}
max={selectedTarget.columnCount - Math.min(form.values.xOffset, selectedTarget.columnCount - 1)}
{...form.getInputProps("width")}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<NumberInput label={t("item.moveResize.field.height.label")} min={1} {...form.getInputProps("height")} />
<NumberInput
label={tMoveResize("field.height.label")}
min={minimumSize.height}
max={
selectedTarget.maxRowCount === null
? undefined
: selectedTarget.maxRowCount - Math.min(form.values.yOffset, selectedTarget.maxRowCount - 1)
}
{...form.getInputProps("height")}
/>
</Grid.Col>
</Grid>
<ModalFormFooter onCancel={actions.closeModal} />
@@ -101,3 +227,137 @@ export const ItemMoveModal = createModal<InnerProps>(({ actions, innerProps }) =
},
size: modalSizeForm,
});
export const useOpenItemMoveModal = () => {
const board = useRequiredBoard();
const currentLayoutId = useCurrentLayout();
const { commitSectionGrids } = useGridLayoutActions();
const { openModal } = useModalAction(ItemMoveModal);
return useCallback(
(input: OpenItemMoveModalInput) => {
openModal({
...input,
board,
currentLayoutId,
commitSectionGrids,
});
},
[board, commitSectionGrids, currentLayoutId, openModal],
);
};
export const getMoveTargets = (
board: Board,
layoutId: string,
entry: MovableEntry,
labels: MoveTargetLabels,
): MoveTarget[] => {
const minimum = getEntryMinimumSize(board, layoutId, entry);
const candidates = board.sections.flatMap((section): MoveTargetCandidate[] => {
if (section.kind === "empty") {
const columnCount = getSectionColumnCount(board, layoutId, section.id);
const lane = getRootSectionLane(section.xOffset);
if (columnCount === 0) return [];
return minimum.width <= columnCount
? [
{
id: section.id,
name: lane === "left" ? labels.leftRail : lane === "right" ? labels.rightRail : labels.canvas,
columnCount,
maxRowCount: getSectionMaxRowCount(board, layoutId, section.id),
},
]
: [];
}
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
if (!layout) return [];
if (
(entry.type === "section" && isSameOrDescendant(board, layoutId, section.id, entry.id)) ||
minimum.width > layout.width ||
minimum.height > layout.height
) {
return [];
}
return [
{
id: section.id,
name: section.options.title || labels.container,
columnCount: layout.width,
maxRowCount: layout.height,
},
];
});
return candidates.map(({ name, location, ...target }, index) => ({
...target,
label: location ? labels.located(name, location, index + 1) : labels.numbered(name, index + 1),
}));
};
const getSectionColumnCount = (board: Board, layoutId: string, sectionId: string) => {
const layout = board.layouts.find((candidate) => candidate.id === layoutId);
if (!layout) throw new Error(`Layout "${layoutId}" was not found`);
const section = board.sections.find((candidate) => candidate.id === sectionId);
if (!section) throw new Error(`Section "${sectionId}" was not found`);
const columnCount = getSectionGridColumnCount(board, layoutId, sectionId);
if (columnCount === null) throw new Error(`Section "${sectionId}" has no current layout`);
return columnCount;
};
const getSectionMaxRowCount = (board: Board, layoutId: string, sectionId: string) => {
const section = board.sections.find((candidate) => candidate.id === sectionId);
if (!section) return null;
if (section.kind === "container") {
return section.layouts.find((candidate) => candidate.layoutId === layoutId)?.height ?? null;
}
return null;
};
const getEntryMinimumSize = (board: Board, layoutId: string, entry: MovableEntry) => {
if (entry.type === "item") return { width: 1, height: 1 };
const children = getSectionGridPlacements(board, layoutId, entry.id);
return {
width: Math.max(1, ...children.map((child) => child.x + child.w)),
height: Math.max(1, ...children.map((child) => child.y + child.h)),
};
};
const isSameOrDescendant = (board: Board, layoutId: string, candidateId: string, ancestorId: string) => {
let current: string | undefined = candidateId;
const visited = new Set<string>();
while (current && !visited.has(current)) {
if (current === ancestorId) return true;
visited.add(current);
const section = board.sections.find((candidate) => candidate.id === current && candidate.kind === "container");
if (!section || section.kind !== "container") return false;
current = section.layouts.find((layout) => layout.layoutId === layoutId)?.parentSectionId;
}
return false;
};
const focusMovedEntry = (entryId: string, sectionId: string) => {
let attempts = 0;
const tryFocus = () => {
const section = Array.from(document.querySelectorAll<HTMLElement>("[data-grid-section-id]")).find(
(candidate) => candidate.dataset.gridSectionId === sectionId,
);
const entry = Array.from(section?.querySelectorAll<HTMLElement>(":scope > [data-grid-item-id]") ?? []).find(
(candidate) => candidate.dataset.gridItemId === entryId,
);
const editorEntry = entry?.querySelector<HTMLElement>("[data-editor-grid-entry]");
if (editorEntry) {
editorEntry.focus();
return;
}
attempts += 1;
if (attempts < 10) requestAnimationFrame(tryFocus);
};
requestAnimationFrame(tryFocus);
};
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vitest";
import { resolveMatchingIntegrationsAsync, tryLockSelection, unlockSelection } from "./item-select-data";
describe("widget selection lock", () => {
it("rejects repeated selection synchronously until the active selection finishes", () => {
const lock = { current: false };
expect(tryLockSelection(lock)).toBe(true);
expect(tryLockSelection(lock)).toBe(false);
unlockSelection(lock);
expect(tryLockSelection(lock)).toBe(true);
});
});
describe("resolveMatchingIntegrationsAsync", () => {
it("waits for the shared integration query before a cold integration-backed selection", async () => {
const ensureDataAsync = vi.fn(async () => [
{ id: "matching", kind: "sonarr" as const },
{ id: "other", kind: "radarr" as const },
]);
await expect(
resolveMatchingIntegrationsAsync({
hasIntegrationSupport: true,
supportedIntegrations: ["sonarr"],
currentData: undefined,
ensureDataAsync,
}),
).resolves.toEqual([{ id: "matching", kind: "sonarr" }]);
expect(ensureDataAsync).toHaveBeenCalledOnce();
});
it("does not wait for integrations when the widget has no integration support", async () => {
const ensureDataAsync = vi.fn(async () => [{ id: "unused", kind: "sonarr" as const }]);
await expect(
resolveMatchingIntegrationsAsync({
hasIntegrationSupport: false,
supportedIntegrations: [],
currentData: undefined,
ensureDataAsync,
}),
).resolves.toEqual([]);
expect(ensureDataAsync).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,28 @@
import type { IntegrationKind } from "@homarr/definitions";
export const tryLockSelection = (lock: { current: boolean }) => {
if (lock.current) return false;
lock.current = true;
return true;
};
export const unlockSelection = (lock: { current: boolean }) => {
lock.current = false;
};
export const resolveMatchingIntegrationsAsync = async <TIntegration extends { kind: IntegrationKind }>({
hasIntegrationSupport,
supportedIntegrations,
currentData,
ensureDataAsync,
}: {
hasIntegrationSupport: boolean;
supportedIntegrations: readonly IntegrationKind[];
currentData: TIntegration[] | undefined;
ensureDataAsync: () => Promise<TIntegration[]>;
}) => {
if (!hasIntegrationSupport) return [];
const integrations = currentData ?? (await ensureDataAsync());
return integrations.filter((integration) => supportedIntegrations.includes(integration.kind));
};
@@ -1,25 +1,20 @@
.selectionCard {
overflow: hidden;
}
.selectionActions {
opacity: 1;
.action {
opacity: 0;
transition: opacity 150ms ease;
}
.card:hover .action,
.card:focus-within .action {
opacity: 1;
}
@media (hover: hover) and (pointer: fine) {
.selectionActions {
opacity: 0;
}
.selectionCard:hover .selectionActions,
.selectionCard:focus-within .selectionActions {
@media (hover: none), (pointer: coarse) {
.action {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.selectionActions {
.action {
transition: none;
}
}
@@ -1,11 +1,12 @@
import { useMemo, useState } from "react";
import { useMemo, useRef, useState } from "react";
import { Avatar, Box, Button, Card, Center, Divider, Group, Image, Stack, Text, Tooltip } from "@mantine/core";
import { IconApi } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { usePersistBoard } from "@homarr/boards/updater";
import { createId, objectEntries } from "@homarr/common";
import { getIconUrl, getIntegrationName } from "@homarr/definitions";
import { useSession } from "@homarr/auth/client";
import { createId } from "@homarr/common";
import { getIconUrl, getIntegrationName, widgetIntegrationSupport, widgetKinds } from "@homarr/definitions";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
import { createModal, modalSizeSelect, useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
@@ -13,68 +14,55 @@ import { useSettings } from "@homarr/settings";
import { useI18n } from "@homarr/translation/client";
import { SelectGridLayout, selectGridCardHeight } from "@homarr/ui";
import type { TablerIcon } from "@homarr/ui";
import { reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/widgets";
import { WidgetEditModal } from "@homarr/widgets/modals";
import { widgetCatalogIcons } from "@homarr/widgets/catalog";
import { loadWidgetDefinition, reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { useItemActions } from "./item-actions";
import type { BoardPlacementHint, CreateItemInput } from "./actions/create-item";
import { createItemCallback } from "./actions/create-item";
import { resolveMatchingIntegrationsAsync, tryLockSelection, unlockSelection } from "./item-select-data";
import { LazyWidgetEditModal, preloadWidgetEditModal } from "./lazy-widget-edit-modal";
import classes from "./item-select-modal.module.css";
interface ItemSelectModalProps {
placement?: BoardPlacementHint;
board: { id: string; name: string };
persistImmediately: boolean;
interface ItemSelectModalContentProps {
actions: { closeModal: () => void };
integrationData: RouterOutputs["integration"]["all"] | undefined;
customWidgetDefs: RouterOutputs["customWidget"]["available"] | undefined;
ensureIntegrationDataAsync: () => Promise<RouterOutputs["integration"]["all"]>;
isAdmin: boolean;
}
export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, innerProps }) => {
const ItemSelectModalContent = ({
actions,
integrationData,
customWidgetDefs,
ensureIntegrationDataAsync,
isAdmin,
}: ItemSelectModalContentProps) => {
const [search, setSearch] = useState("");
const [loadingSelection, setLoadingSelection] = useState<string | null>(null);
const selectionLock = useRef(false);
const t = useI18n();
const { createItem } = useItemActions();
const { openModal: openEditModal } = useModalAction(WidgetEditModal);
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery({ boardId: innerProps.board.id });
const { createItem, updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations } = useItemActions();
const { openModal: openEditModal } = useModalAction(LazyWidgetEditModal);
const settings = useSettings();
const { updateAndPersistBoard } = usePersistBoard(innerProps.board);
const createAndPersist = (input: CreateItemInput) => {
try {
if (!innerProps.persistImmediately) {
createItem(input);
return;
}
updateAndPersistBoard(createItemCallback(input), {
onError: () => {
showErrorNotification({
title: t("item.create.notification.error.title"),
message: t("item.create.notification.error.message"),
});
},
});
} catch {
showErrorNotification({
title: t("item.create.notification.error.title"),
message: t("item.create.notification.error.message"),
});
}
};
const availableKinds = useMemo(() => new Set((integrationData ?? []).map((i) => i.kind)), [integrationData]);
const items = useMemo(
() =>
objectEntries(widgetImports)
.filter(([kind]) => kind !== "customApi")
.map(([kind, value]) => ({
kind,
supportedIntegrations:
"supportedIntegrations" in value.definition
? value.definition.supportedIntegrations.filter((integration) => integration !== "mock")
: [],
icon: value.definition.icon,
name: t(`widget.${kind}.name`),
description: t(`widget.${kind}.description`),
}))
widgetKinds
.filter((kind) => kind !== "customApi")
.map((kind) => {
return {
kind,
supportedIntegrations: (widgetIntegrationSupport[kind] ?? []).filter(
(integration) => integration !== "mock",
),
icon: widgetCatalogIcons[kind],
name: t(`widget.${kind}.name`),
description: t(`widget.${kind}.description`),
};
})
.sort((itemA, itemB) => {
if (itemA.kind === "app") return -1;
if (itemB.kind === "app") return 1;
@@ -95,67 +83,112 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
}, [items, search]);
const filteredCustomWidgets = useMemo(
() =>
(customWidgetDefs ?? []).filter((def) => def.enabled && def.name.toLowerCase().includes(search.toLowerCase())),
() => (customWidgetDefs ?? []).filter((def) => def.name.toLowerCase().includes(search.toLowerCase())),
[customWidgetDefs, search],
);
const handleAddCustomWidget = (definitionId: string) => {
const itemId = createId();
const defaultOptions = reduceWidgetOptionsWithDefaultValues("customApi", settings);
createAndPersist({
id: itemId,
kind: "customApi",
integrationIds: [],
options: { ...defaultOptions, definitionId },
placement: innerProps.placement,
const notifyDefinitionLoadError = (error: unknown) => {
showErrorNotification({
title: t("common.error"),
message: error instanceof Error ? error.message : String(error),
});
actions.closeModal();
};
const handleAdd = (kind: WidgetKind) => {
const definition = widgetImports[kind].definition;
const hasIntegrationSupport = "supportedIntegrations" in definition;
const matchingIntegrations = hasIntegrationSupport
? (integrationData ?? []).filter((integration) =>
(definition.supportedIntegrations as string[]).includes(integration.kind),
)
: [];
const integrationIds = matchingIntegrations.map((i) => i.id);
const itemId = createId();
const defaultOptions = reduceWidgetOptionsWithDefaultValues(kind, settings);
actions.closeModal();
openEditModal(
{
kind,
value: {
advancedOptions: { title: null, customCssClasses: [], borderColor: "" },
options: defaultOptions,
integrationIds,
},
onSuccessfulEdit: ({ options, integrationIds: newIntegrationIds, advancedOptions }) => {
createAndPersist({
id: itemId,
kind,
const handleAddCustomWidget = async (customWidgetDefinition: NonNullable<typeof customWidgetDefs>[number]) => {
if (!tryLockSelection(selectionLock)) return;
setLoadingSelection(`custom:${customWidgetDefinition.id}`);
preloadWidgetEditModal();
try {
const definition = await loadWidgetDefinition("customApi");
const itemId = createId();
const defaultOptions = reduceWidgetOptionsWithDefinition(definition, settings);
const options = {
...defaultOptions,
definitionId: customWidgetDefinition.id,
configuration: customWidgetDefinition.defaultOptions,
configurationVersion: customWidgetDefinition.updatedAt.getTime(),
};
actions.closeModal();
openEditModal(
{
kind: "customApi",
definition,
value: {
advancedOptions: { title: null, customCssClasses: [], borderColor: "" },
options,
integrationIds: newIntegrationIds,
advancedOptions,
placement: innerProps.placement,
});
integrationIds: [],
},
onSuccessfulEdit: ({ options: configuredOptions, advancedOptions }) => {
createItem({ id: itemId, kind: "customApi", integrationIds: [] });
updateItemOptions({ itemId, newOptions: configuredOptions });
updateItemAdvancedOptions({ itemId, newAdvancedOptions: advancedOptions });
},
integrationData: [],
integrationSupport: false,
settings,
},
integrationData: matchingIntegrations,
integrationSupport: hasIntegrationSupport,
settings,
boardId: innerProps.board.id,
},
{
title: (titleT) => `${titleT("item.edit.title")} - ${titleT(`widget.${kind}.name`)}`,
},
);
{
title: (titleT) => `${titleT("item.edit.title")} - ${customWidgetDefinition.name}`,
},
);
} catch (error) {
notifyDefinitionLoadError(error);
} finally {
unlockSelection(selectionLock);
setLoadingSelection(null);
}
};
const handleAdd = async (kind: WidgetKind) => {
if (!tryLockSelection(selectionLock)) return;
setLoadingSelection(kind);
preloadWidgetEditModal();
try {
const definition = await loadWidgetDefinition(kind);
const hasIntegrationSupport = "supportedIntegrations" in definition;
const matchingIntegrations = await resolveMatchingIntegrationsAsync({
hasIntegrationSupport,
supportedIntegrations: definition.supportedIntegrations ?? [],
currentData: integrationData,
ensureDataAsync: ensureIntegrationDataAsync,
});
const integrationIds = matchingIntegrations.map((i) => i.id);
const itemId = createId();
const defaultOptions = reduceWidgetOptionsWithDefinition(definition, settings);
createItem({ id: itemId, kind, integrationIds });
actions.closeModal();
openEditModal(
{
kind,
definition,
value: {
advancedOptions: { title: null, customCssClasses: [], borderColor: "" },
options: defaultOptions,
integrationIds,
},
onSuccessfulEdit: ({ options, integrationIds: newIntegrationIds, advancedOptions }) => {
updateItemOptions({ itemId, newOptions: options });
updateItemAdvancedOptions({ itemId, newAdvancedOptions: advancedOptions });
updateItemIntegrations({ itemId, newIntegrations: newIntegrationIds });
},
integrationData: matchingIntegrations,
integrationSupport: hasIntegrationSupport,
settings,
},
{
title: (titleT) => `${titleT("item.edit.title")} - ${titleT(`widget.${kind}.name`)}`,
},
);
} catch (error) {
notifyDefinitionLoadError(error);
} finally {
unlockSelection(selectionLock);
setLoadingSelection(null);
}
};
return (
@@ -164,9 +197,9 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
onSearchChange={setSearch}
placeholder={`${t("item.create.search")}...`}
onSearchKeyDown={(event) => {
if (event.key === "Enter" && filteredItems.length === 1) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
handleAdd(filteredItems[0]!.kind);
if (event.key === "Enter" && loadingSelection === null && filteredItems.length === 1) {
const [item] = filteredItems;
if (item) void handleAdd(item.kind);
}
}}
>
@@ -174,12 +207,18 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
<WidgetItem
key={item.kind}
item={item}
onSelect={() => handleAdd(item.kind)}
onSelect={() => void handleAdd(item.kind)}
onIntent={() => {
void loadWidgetDefinition(item.kind).catch(() => undefined);
preloadWidgetEditModal();
}}
disabled={loadingSelection !== null}
loading={loadingSelection === item.kind}
hasMatchingIntegration={item.supportedIntegrations.some((kind) => availableKinds.has(kind))}
/>
))}
{filteredCustomWidgets.length > 0 && (
{isAdmin && (
<>
<Divider
label={t("customWidget.page.list.title")}
@@ -188,18 +227,19 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
style={{ gridColumn: "1 / -1" }}
/>
{filteredCustomWidgets.map((def) => (
<Card key={def.id} h={selectGridCardHeight} withBorder pos="relative" className={classes.selectionCard}>
<Card
key={def.id}
className={classes.card}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden" }}
onPointerEnter={() => void loadWidgetDefinition("customApi").catch(() => undefined)}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
{def.iconUrl ? (
<Image
src={def.iconUrl}
alt=""
w={22}
h={22}
fit="contain"
style={{ flexShrink: 0, marginTop: 2 }}
/>
<Image src={def.iconUrl} w={22} h={22} fit="contain" style={{ flexShrink: 0, marginTop: 2 }} />
) : (
<IconApi size={22} style={{ flexShrink: 0, marginTop: 2 }} />
)}
@@ -208,37 +248,78 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description}
{def.description ?? ""}
</Text>
</Stack>
<Box
className={classes.action}
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
className={classes.selectionActions}
style={{
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleAddCustomWidget(def.id)} variant="light" size="xs" fullWidth>
<Button
onClick={() => void handleAddCustomWidget(def)}
variant="light"
size="xs"
fullWidth
disabled={loadingSelection !== null}
loading={loadingSelection === `custom:${def.id}`}
>
{t("item.create.addToBoard")}
</Button>
</Box>
</Card>
))}
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
</>
)}
{filteredItems.length === 0 && filteredCustomWidgets.length === 0 && (
{filteredItems.length === 0 && (!isAdmin || filteredCustomWidgets.length === 0) && (
<Center p="xl">
<Text c="dimmed">{t("common.noResults")}</Text>
</Center>
)}
</SelectGridLayout>
);
}).withOptions({
};
const ItemSelectModalFrame = ({
actions,
innerProps,
}: {
actions: { closeModal: () => void };
innerProps: { boardId: string };
}) => {
const utils = clientApi.useUtils();
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery(
{ boardId: innerProps.boardId },
{ enabled: isAdmin },
);
return (
<ItemSelectModalContent
actions={actions}
integrationData={integrationData}
customWidgetDefs={customWidgetDefs}
ensureIntegrationDataAsync={() => utils.integration.all.ensureData()}
isAdmin={isAdmin}
/>
);
};
export const ItemSelectModal = createModal<{ boardId: string }>((props) => (
<ItemSelectModalFrame {...props} />
)).withOptions({
defaultTitle: (t) => t("item.create.title"),
size: modalSizeSelect,
});
@@ -246,6 +327,9 @@ export const ItemSelectModal = createModal<ItemSelectModalProps>(({ actions, inn
const WidgetItem = ({
item,
onSelect,
onIntent,
disabled,
loading,
hasMatchingIntegration,
}: {
item: {
@@ -256,20 +340,27 @@ const WidgetItem = ({
icon: TablerIcon;
};
onSelect: () => void;
onIntent: () => void;
disabled: boolean;
loading: boolean;
hasMatchingIntegration: boolean;
}) => {
const t = useI18n();
return (
<Card
className={classes.card}
h={selectGridCardHeight}
withBorder
pos="relative"
className={classes.selectionCard}
style={{
overflow: "hidden",
borderColor: hasMatchingIntegration ? "var(--mantine-color-blue-6)" : undefined,
borderWidth: hasMatchingIntegration ? 2 : undefined,
}}
onFocus={onIntent}
onPointerEnter={onIntent}
aria-busy={loading || undefined}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
@@ -286,17 +377,17 @@ const WidgetItem = ({
<SupportedIntegrations integrations={item.supportedIntegrations} />
</Stack>
<Box
className={classes.action}
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
className={classes.selectionActions}
style={{
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={onSelect} variant="light" size="xs" fullWidth>
<Button onClick={onSelect} variant="light" size="xs" fullWidth disabled={disabled} loading={loading}>
{t(`item.create.addToBoard`)}
</Button>
</Box>
@@ -0,0 +1,68 @@
"use client";
import { Suspense, use } from "react";
import { Center, Loader } from "@mantine/core";
import { ErrorBoundary } from "react-error-boundary";
import type { WidgetKind } from "@homarr/definitions";
import { createModal, modalSizeForm } from "@homarr/modals";
import { WidgetError } from "@homarr/widgets/errors";
import type { WidgetEditModalProps } from "@homarr/widgets/modals";
let widgetEditModalPromise: Promise<typeof import("@homarr/widgets/modals")> | undefined;
export const loadWidgetEditModal = () => {
if (widgetEditModalPromise) return widgetEditModalPromise;
const currentPromise = import("@homarr/widgets/modals");
widgetEditModalPromise = currentPromise;
void currentPromise.catch(() => {
if (widgetEditModalPromise === currentPromise) widgetEditModalPromise = undefined;
});
return currentPromise;
};
export const preloadWidgetEditModal = () => void loadWidgetEditModal().catch(() => undefined);
interface LazyWidgetEditModalContentProps {
actions: { closeModal: () => void };
innerProps: WidgetEditModalProps<WidgetKind>;
}
const LazyWidgetEditModalContent = (props: LazyWidgetEditModalContentProps) => {
const { WidgetEditModal } = use(loadWidgetEditModal());
const Component = WidgetEditModal.component;
return <Component {...props} />;
};
export const LazyWidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>((props) => (
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => (
<Center py="xl">
<WidgetError
error={error}
resetErrorBoundary={() => {
widgetEditModalPromise = undefined;
resetErrorBoundary();
}}
/>
</Center>
)}
>
<Suspense
fallback={
<Center py="xl">
<Loader size="sm" />
</Center>
}
>
<LazyWidgetEditModalContent {...props} />
</Suspense>
</ErrorBoundary>
)).withOptions({
keepMounted: true,
defaultTitle(t) {
return t("item.edit.title");
},
size: modalSizeForm,
});
@@ -1,18 +1,9 @@
"use client";
import type { ReactNode, RefObject } from "react";
import type { MutableRefObject, ReactNode, RefObject } from "react";
import { useCallback, useMemo, useState } from "react";
import { Group, Loader, Menu, Text, Tooltip } from "@mantine/core";
import {
IconAlertTriangle,
IconCircleCheck,
IconCopy,
IconLayoutKanban,
IconMaximize,
IconRefresh,
IconSettings,
IconTrash,
} from "@tabler/icons-react";
import { IconAlertTriangle, IconCircleCheck, IconMaximize, IconRefresh, IconSettings } from "@tabler/icons-react";
import type { QueryClient, QueryKey } from "@tanstack/react-query";
import { useIsFetching, useQueryClient } from "@tanstack/react-query";
@@ -22,60 +13,56 @@ import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
import { usePersistBoard } from "@homarr/boards/updater";
import { useTimeAgo } from "@homarr/common";
import { useConfirmModal, useModalAction } from "@homarr/modals";
import { useModalAction } from "@homarr/modals";
import { showErrorNotification } from "@homarr/notifications";
import { useSettings } from "@homarr/settings";
import { translateIfNecessary } from "@homarr/translation";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { TranslationFunction } from "@homarr/translation";
import type { WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets";
import {
getWidgetQueryKeys,
getWidgetRuntimeQueries,
reduceWidgetOptionsWithDefaultValues,
supportsAdvancedFocus,
widgetImports,
} from "@homarr/widgets";
import { WidgetEditModal } from "@homarr/widgets/modals";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets/definition";
import { getWidgetQueryKeys, getWidgetRuntimeQueries, supportsAdvancedFocus } from "@homarr/widgets/definition";
import { reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import { useAdvancedFocus } from "../advanced-focus/context";
import { useBoardPermissions } from "../permissions/client";
import { useSectionContext } from "../sections/section-context";
import { useItemActions } from "./item-actions";
import { ItemMoveModal } from "./item-move-modal";
import { LazyWidgetEditModal, preloadWidgetEditModal } from "./lazy-widget-edit-modal";
import { matchesWidgetItemQuery } from "./widget-query-scope";
interface WidgetContextMenuProps {
item: SectionItem;
definition: WidgetDefinition;
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
widgetRuntimeRef: WidgetRuntimeRef;
sourceRef: RefObject<HTMLElement | null>;
children: ReactNode;
}
export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children }: WidgetContextMenuProps) => {
export const WidgetContextMenu = ({
item,
definition,
widgetRuntimeRef,
sourceRef,
children,
}: WidgetContextMenuProps) => {
const { data: session } = useSession();
const [isEditMode] = useEditMode();
const board = useRequiredBoard();
const { hasChangeAccess } = useBoardPermissions(board);
const { updateAndPersistBoard } = usePersistBoard(board);
const tItem = useScopedI18n("item");
const tMenu = useScopedI18n("item.menu.label");
const t = useI18n();
const settings = useSettings();
const isRightClickEnabled = settings.enableRightClickOnWidgets;
const { openModal } = useModalAction(WidgetEditModal);
const { openModal: openMoveModal } = useModalAction(ItemMoveModal);
const { openConfirmModal } = useConfirmModal();
const { updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations, duplicateItem, removeItem } =
useItemActions();
const { data: integrationData, isPending } = clientApi.integration.all.useQuery();
const currentDefinition = useMemo(
() => widgetImports[item.kind].definition as WidgetDefinition & { kind: string },
[item.kind],
);
const canOpenAdvancedFocus = supportsAdvancedFocus(currentDefinition);
const { gridstack } = useSectionContext().refs;
const { openModal } = useModalAction(LazyWidgetEditModal);
const { updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations } = useItemActions();
const hasSupportedIntegrations = (definition.supportedIntegrations?.length ?? 0) > 0;
const { data: integrationData = [], isPending } = clientApi.integration.all.useQuery(undefined, {
enabled: hasSupportedIntegrations,
});
const canConfigureWidget =
hasChangeAccess && (item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false));
const canOpenAdvancedFocus = supportsAdvancedFocus(definition);
const queryClient = useQueryClient();
const { open: openAdvancedFocus } = useAdvancedFocus();
const integrationsWithInteractAccess = useIntegrationsWithInteractAccess();
@@ -96,12 +83,10 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
);
const options = useMemo(
() => reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options),
[item.kind, settings, item.options],
() => reduceWidgetOptionsWithDefinition(definition, settings, item.options),
[definition, settings, item.options],
);
const widgetQueryKeys = useMemo(() => getWidgetQueryKeys(currentDefinition), [currentDefinition]);
const widgetQueryMatcher = "queryMatcher" in currentDefinition ? currentDefinition.queryMatcher : undefined;
const widgetQueryKeys = useMemo(() => getWidgetQueryKeys(definition, item.kind), [definition, item.kind]);
const matchesWidgetQuery = useCallback(
(queryKey: QueryKey) =>
matchesWidgetItemQuery(
@@ -114,9 +99,9 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
options,
runtimeQueries: getWidgetRuntimeQueries(widgetRuntimeRef),
},
widgetQueryMatcher,
definition.queryMatcher,
),
[board.id, item.id, item.integrationIds, options, widgetQueryKeys, widgetQueryMatcher, widgetRuntimeRef],
[board.id, definition.queryMatcher, item.id, item.integrationIds, options, widgetQueryKeys, widgetRuntimeRef],
);
const isWidgetFetching =
useIsFetching({
@@ -134,11 +119,6 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
const setItemOptions = useCallback(
(partial: Record<string, unknown>) => {
if (isEditMode) {
updateItemOptions({ itemId: item.id, newOptions: { ...options, ...partial } });
return;
}
persistBoard((previous) => ({
...previous,
items: previous.items.map((boardItem) =>
@@ -146,18 +126,18 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
),
}));
},
[isEditMode, item.id, options, persistBoard, updateItemOptions],
[item.id, persistBoard],
);
type OptionDef = { type: string; skipContextMenu?: boolean };
const toggleOptions = useMemo(() => {
if (!hasChangeAccess) return [];
const rawOptions = currentDefinition.createOptions(settings) as unknown as Record<string, OptionDef>;
return Object.entries(rawOptions).filter(([, def]) => def.type === "switch" && !def.skipContextMenu);
}, [currentDefinition, hasChangeAccess, settings]);
if (!canConfigureWidget) return [];
const rawOptions = definition.createOptions(settings) as unknown as Record<string, OptionDef>;
return Object.entries(rawOptions).filter(([, option]) => option.type === "switch" && !option.skipContextMenu);
}, [canConfigureWidget, definition, settings]);
const widgetContextActions =
currentDefinition.contextActions?.({
definition.contextActions?.({
options,
setOptions: setItemOptions,
integrationIds: item.integrationIds,
@@ -174,38 +154,34 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
openModal(
{
kind: item.kind,
definition,
value: {
advancedOptions: item.advancedOptions,
options: item.options,
integrationIds: item.integrationIds,
},
onSuccessfulEdit: (editResult) => {
if (isEditMode) {
updateItemOptions({ itemId: item.id, newOptions: editResult.options });
updateItemAdvancedOptions({ itemId: item.id, newAdvancedOptions: editResult.advancedOptions });
updateItemIntegrations({ itemId: item.id, newIntegrations: editResult.integrationIds });
} else {
persistBoard((previous) => ({
...previous,
items: previous.items.map((boardItem) =>
boardItem.id !== item.id
? boardItem
: {
...boardItem,
options: editResult.options,
advancedOptions: editResult.advancedOptions,
integrationIds: editResult.integrationIds,
},
),
}));
}
updateItemOptions({ itemId: item.id, newOptions: editResult.options });
updateItemAdvancedOptions({ itemId: item.id, newAdvancedOptions: editResult.advancedOptions });
updateItemIntegrations({ itemId: item.id, newIntegrations: editResult.integrationIds });
persistBoard((previous) => ({
...previous,
items: previous.items.map((boardItem) =>
boardItem.id !== item.id
? boardItem
: {
...boardItem,
options: editResult.options,
advancedOptions: editResult.advancedOptions,
integrationIds: editResult.integrationIds,
},
),
}));
},
integrationData: (integrationData ?? []).filter(
(integration) =>
"supportedIntegrations" in currentDefinition &&
(currentDefinition.supportedIntegrations as string[]).some((kind) => kind === integration.kind),
integrationData: integrationData.filter((integration) =>
definition.supportedIntegrations?.some((kind) => kind === integration.kind),
),
integrationSupport: "supportedIntegrations" in currentDefinition,
integrationSupport: definition.supportedIntegrations !== undefined,
settings,
appId: item.kind === "app" ? (item.options.appId as string | undefined) : undefined,
},
@@ -213,16 +189,15 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
{ title: (fn: any) => `${fn("item.edit.title")} - ${fn(`widget.${item.kind}.name`)}` },
);
}, [
openModal,
definition,
integrationData,
item,
updateItemOptions,
openModal,
persistBoard,
settings,
updateItemAdvancedOptions,
updateItemIntegrations,
integrationData,
currentDefinition,
settings,
isEditMode,
persistBoard,
updateItemOptions,
]);
const handleToggle = useCallback(
@@ -230,10 +205,9 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
[setItemOptions],
);
if (!session) return <>{children}</>;
if (!isRightClickEnabled) return <>{children}</>;
if (!session || !settings.enableRightClickOnWidgets || isEditMode) return <>{children}</>;
const visibleWidgetActions = widgetContextActions.filter((a) => !a.hidden);
const visibleWidgetActions = widgetContextActions.filter((action) => !action.hidden);
return (
<Menu
@@ -255,13 +229,13 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
onClick={() => {
if (sourceRef.current) openAdvancedFocus(item.id, sourceRef.current);
}}
disabled={isEditMode}
>
{t("item.advancedFocus.open")}
</Menu.Item>
<Menu.Divider />
</>
)}
{toggleOptions.length > 0 && (
<>
<Menu.Label>{tMenu("options")}</Menu.Label>
@@ -296,77 +270,32 @@ export const WidgetContextMenu = ({ item, widgetRuntimeRef, sourceRef, children
</>
)}
{isEditMode && (
<>
{(toggleOptions.length > 0 || visibleWidgetActions.length > 0) && <Menu.Divider />}
<Menu.Item
closeMenuOnClick
leftSection={<IconLayoutKanban size={16} />}
onClick={() => {
if (!gridstack.current) return;
openMoveModal({ item, columnCount: gridstack.current.getColumn(), gridStack: gridstack.current });
}}
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item
closeMenuOnClick
leftSection={<IconCopy size={16} />}
onClick={() => duplicateItem({ itemId: item.id })}
>
{tItem("action.duplicate")}
</Menu.Item>
</>
)}
<>
{(toggleOptions.length > 0 || visibleWidgetActions.length > 0 || isEditMode) && <Menu.Divider />}
<Menu.Item
leftSection={isWidgetFetching ? <Loader size={16} /> : <IconRefresh size={16} />}
onClick={handleRefetch}
disabled={isWidgetFetching}
>
<Group justify="space-between" wrap="nowrap" gap="sm">
{tMenu("refresh")}
<WidgetQueryStatus
queryClient={queryClient}
matchesQuery={matchesWidgetQuery}
isFetching={isWidgetFetching}
t={t}
/>
</Group>
</Menu.Item>
{hasChangeAccess && (
<Menu.Item
closeMenuOnClick
leftSection={<IconSettings size={16} />}
onClick={openEditModal}
disabled={isPending}
>
{tMenu("settings")}
</Menu.Item>
)}
</>
{isEditMode && (
<>
<Menu.Divider />
<Menu.Item
closeMenuOnClick
color="red"
leftSection={<IconTrash size={16} />}
onClick={() => {
openConfirmModal({
title: tItem("remove.title"),
children: tItem("remove.message"),
onConfirm: () => removeItem({ itemId: item.id }),
});
}}
>
{tItem("action.remove")}
</Menu.Item>
</>
)}
{(toggleOptions.length > 0 || visibleWidgetActions.length > 0) && <Menu.Divider />}
<Menu.Item
leftSection={isWidgetFetching ? <Loader size={16} /> : <IconRefresh size={16} />}
onClick={handleRefetch}
disabled={isWidgetFetching}
>
<Group justify="space-between" wrap="nowrap" gap="sm">
{tMenu("refresh")}
<WidgetQueryStatus
queryClient={queryClient}
matchesQuery={matchesWidgetQuery}
isFetching={isWidgetFetching}
t={t}
/>
</Group>
</Menu.Item>
<Menu.Item
closeMenuOnClick
leftSection={<IconSettings size={16} />}
onClick={openEditModal}
onFocus={preloadWidgetEditModal}
onPointerEnter={preloadWidgetEditModal}
disabled={!canConfigureWidget || (hasSupportedIntegrations && isPending)}
>
{tMenu("settings")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
@@ -408,8 +337,7 @@ const WidgetQueryStatus = ({ queryClient, matchesQuery, isFetching, t }: WidgetQ
);
}
const hasError = queries.some((q) => q.state.status === "error");
const hasError = queries.some((query) => query.state.status === "error");
if (hasError) {
return (
<Tooltip label={t("item.menu.status.error")} position="left">
@@ -1,155 +0,0 @@
import { objectEntries } from "@homarr/common";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
import type { SettingsContextProps } from "@homarr/settings/creator";
import type { WidgetOptionDefinition, WidgetOptionType } from "@homarr/widgets";
import { reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/widgets";
import type { SectionItem } from "~/app/[locale]/boards/_types";
export type Translator = {
(key: string): string;
};
export interface HoverMetadataItem {
label: string;
value: string;
}
const maxMetadataItems = 3;
const skippedOptionTypes: Partial<Record<WidgetOptionType, true>> = {
app: true,
anchorNote: true,
dynamicSelect: true,
sortableItemList: true,
multiReleasesRepositories: true,
umamiEventName: true,
umamiEventNames: true,
umamiWebsite: true,
};
const isEqualValue = (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right);
type OptionDefinitionWithRules = WidgetOptionDefinition & {
shouldHide?: (options: never, integrationKinds: IntegrationKind[]) => boolean;
options?: readonly { value: unknown; label: unknown }[];
};
type OptionFormatter = (value: unknown, definition: OptionDefinitionWithRules, t: Translator) => string | null;
const resolveSelectLabel = (value: unknown, definition: OptionDefinitionWithRules, t: Translator) => {
const match = definition.options?.find((option) => option.value === value);
const label = match?.label;
const fallbackLabel = () => String(value);
const labelResolvers: Record<string, () => string> = {
function: () => (label as (translator: Translator) => string)(t),
string: () => label as string,
missing: fallbackLabel,
};
const labelType = typeof label;
const resolveLabel: () => string = labelResolvers[labelType] ?? fallbackLabel;
return resolveLabel();
};
const optionTypeFormatters: Partial<Record<WidgetOptionType, OptionFormatter>> = {
switch: (value, _, t) => {
const switchLabels: Record<string, string> = {
true: t("common.action.show"),
false: t("common.action.hide"),
};
return switchLabels[String(Boolean(value))] ?? null;
},
text: (value) => {
const text = String(value).trim();
return text.length > 0 ? text : null;
},
number: (value) => String(value),
slider: (value) => String(value),
select: (value, definition, t) => resolveSelectLabel(value, definition, t),
multiSelect: (value) => {
const items = value as unknown[];
return items.length > 0 ? String(items.length) : null;
},
multiText: (value) => {
const items = (value as string[]).filter((entry) => entry.trim().length > 0);
return items.length > 0 ? items.join(", ") : null;
},
location: (value) => {
const location = value as { name?: string };
const name = location.name?.trim() ?? "";
return name.length > 0 ? name : null;
},
};
const formatOptionValue = (
type: WidgetOptionType,
value: unknown,
definition: OptionDefinitionWithRules,
t: Translator,
) => {
const formatter = optionTypeFormatters[type];
return formatter?.(value, definition, t) ?? null;
};
const getOptionLabel = (kind: WidgetKind, key: string, t: Translator) => {
const labelKey = `widget.${kind}.option.${key}.label`;
const translated = t(labelKey);
return translated === labelKey ? key : translated;
};
export const collectWidgetHoverMetadata = (
item: SectionItem,
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
integrationKinds: IntegrationKind[],
t: Translator,
): HoverMetadataItem[] => {
const { definition } = widgetImports[item.kind];
const optionDefinitions = definition.createOptions(settings) as Record<string, OptionDefinitionWithRules>;
const resolvedOptions = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
return objectEntries(optionDefinitions)
.filter(([key, optionDefinition]) => {
const skip = skippedOptionTypes[optionDefinition.type];
const hidden = optionDefinition.shouldHide?.(resolvedOptions as never, integrationKinds);
const unchanged = isEqualValue(resolvedOptions[key], optionDefinition.defaultValue);
return !skip && !hidden && !unchanged;
})
.map(([key, optionDefinition]) => {
const formattedValue = formatOptionValue(optionDefinition.type, resolvedOptions[key], optionDefinition, t);
return {
label: getOptionLabel(item.kind, key, t),
value: formattedValue ?? "",
};
})
.filter((entry) => entry.value.length > 0)
.slice(0, maxMetadataItems);
};
interface DisplayNameSource {
matches: (item: SectionItem, options: Record<string, unknown>) => boolean;
resolve: (item: SectionItem, options: Record<string, unknown>) => string;
}
const displayNameSources: DisplayNameSource[] = [
{
matches: (item) => Boolean(item.advancedOptions.title?.trim()),
resolve: (item) => item.advancedOptions.title?.trim() ?? "",
},
{
matches: (item, options) =>
item.kind === "clock" &&
Boolean(options.customTitleToggle) &&
String(options.customTitle ?? "").trim().length > 0,
resolve: (_, options) => String(options.customTitle).trim(),
},
];
export const resolveWidgetDisplayName = (
item: SectionItem,
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
t: Translator,
) => {
const resolvedOptions = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
const source = displayNameSources.find((entry) => entry.matches(item, resolvedOptions));
return source?.resolve(item, resolvedOptions) ?? t(`widget.${item.kind}.name`);
};
@@ -2,19 +2,18 @@
position: absolute;
left: 10px;
right: 10px;
bottom: calc(100% - 10px);
margin-bottom: 1px;
z-index: var(--mantine-z-index-app);
top: 10px;
z-index: 200;
pointer-events: none;
opacity: 0;
transform: translateY(6px);
transform: translateY(-6px);
transition:
opacity 150ms ease,
transform 150ms ease;
}
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):hover) .wrapper,
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):focus-within) .wrapper {
:global([data-type="item"]:not([data-kind="app"]):hover) .wrapper,
:global([data-type="item"]:not([data-kind="app"]):focus-within) .wrapper {
opacity: 1;
transform: translateY(0);
}
@@ -32,7 +31,7 @@
align-items: center;
gap: 8px;
min-height: 28px;
padding: 4px 8px;
padding: 4px 36px 4px 8px;
border: 1px solid var(--border-color);
border-radius: var(--mantine-radius-md);
background-color: var(--background-color);
@@ -101,6 +100,11 @@
overflow: hidden;
}
.metadataLabel {
color: var(--mantine-color-dimmed);
flex-shrink: 0;
}
@media (forced-colors: active) {
.panel {
border-color: CanvasText;
@@ -110,11 +114,6 @@
}
}
.metadataLabel {
color: var(--mantine-color-dimmed);
flex-shrink: 0;
}
.metadataValue {
overflow: hidden;
text-overflow: ellipsis;
@@ -1,12 +1,13 @@
"use client";
import { Suspense, use } from "react";
import { Avatar, Text, Tooltip } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { useEditMode } from "@homarr/boards/edit-mode";
import { getIconUrl } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { widgetImports } from "@homarr/widgets";
import { loadWidgetDefinition } from "@homarr/widgets/manifest";
import type { SectionItem } from "~/app/[locale]/boards/_types";
import classes from "./widget-hover-overlay.module.css";
@@ -18,8 +19,19 @@ interface WidgetHoverOverlayProps {
export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayProps) => {
const [isEditMode] = useEditMode();
if (!isEditMode) return null;
return (
<Suspense fallback={null}>
<LoadedWidgetHoverOverlay item={item} integrations={integrations} />
</Suspense>
);
};
const LoadedWidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayProps) => {
const t = useI18n();
const { definition } = widgetImports[item.kind];
const definition = use(loadWidgetDefinition(item.kind));
const WidgetIcon = definition.icon;
const displayName = item.advancedOptions.title?.trim() || t(`widget.${item.kind}.name`);
@@ -28,12 +40,8 @@ export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayPro
item.integrationIds.includes(integration.id),
);
if (!isEditMode) {
return null;
}
return (
<div className={classes.wrapper}>
<div className={classes.wrapper} data-board-widget-header>
<div className={classes.panel}>
<div className={classes.nameSection}>
<WidgetIcon size={14} stroke={1.75} className={classes.widgetIcon} />
@@ -1,27 +1,36 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, test } from "vitest";
import { removePersistedWidgetQueries } from "./widget-query-recovery";
import { removeWidgetDataQueries } from "./widget-query-recovery";
describe("removePersistedWidgetQueries", () => {
test("removes stale widget queries and allows fresh data to be fetched", async () => {
describe("removeWidgetDataQueries", () => {
test("removes only the failed widget prefix and allows fresh data to be fetched", async () => {
const queryClient = new QueryClient();
const crashedWidgetQueryKey = [["widget", "mediaServer", "getCurrentStreams"], { input: {} }];
const sameWidgetQueryKey = [["widget", "mediaServer", "getLibraries"], { input: {} }];
const unrelatedWidgetQueryKey = [["widget", "calendar", "getEvents"], { input: {} }];
const appQueryKey = [["app", "byId"], { input: {} }];
const unrelatedQueryKey = [["user", "me"], { input: {} }];
queryClient.setQueryData(crashedWidgetQueryKey, "stale");
queryClient.setQueryData(sameWidgetQueryKey, "related");
queryClient.setQueryData(unrelatedWidgetQueryKey, "other-widget");
queryClient.setQueryData(appQueryKey, "app");
queryClient.setQueryData(unrelatedQueryKey, "unrelated");
removePersistedWidgetQueries(queryClient);
removeWidgetDataQueries(queryClient, [[["widget", "mediaServer"]]]);
expect(queryClient.getQueryData(crashedWidgetQueryKey)).toBeUndefined();
expect(queryClient.getQueryData(sameWidgetQueryKey)).toBeUndefined();
expect(queryClient.getQueryData(unrelatedWidgetQueryKey)).toBe("other-widget");
expect(queryClient.getQueryData(appQueryKey)).toBe("app");
expect(queryClient.getQueryData(unrelatedQueryKey)).toBe("unrelated");
await expect(
queryClient.fetchQuery({ queryKey: crashedWidgetQueryKey, queryFn: () => Promise.resolve("fresh") }),
).resolves.toBe("fresh");
});
test("removes persisted queries outside the widget router", () => {
test("uses an explicit supporting query prefix without purging other supporting data", () => {
const queryClient = new QueryClient();
const dockerQueryKey = [["docker", "getContainers"], { input: {} }];
const appQueryKey = [["app", "byId"], { input: {} }];
@@ -31,14 +40,14 @@ describe("removePersistedWidgetQueries", () => {
queryClient.setQueryData(appQueryKey, "stale");
queryClient.setQueryData(unrelatedQueryKey, "unrelated");
removePersistedWidgetQueries(queryClient);
removeWidgetDataQueries(queryClient, [[["docker", "getContainers"]]]);
expect(queryClient.getQueryData(dockerQueryKey)).toBeUndefined();
expect(queryClient.getQueryData(appQueryKey)).toBeUndefined();
expect(queryClient.getQueryData(appQueryKey)).toBe("stale");
expect(queryClient.getQueryData(unrelatedQueryKey)).toBe("unrelated");
});
test("removes persisted widget queries when the widget kind and query path differ", () => {
test("uses the definition query prefix when the widget kind and query path differ", () => {
const queryClient = new QueryClient();
const crashedWidgetQueryKey = [["widget", "anchorNotes", "getNote"], { input: {} }];
const unrelatedQueryKey = [["user", "me"], { input: {} }];
@@ -46,7 +55,7 @@ describe("removePersistedWidgetQueries", () => {
queryClient.setQueryData(crashedWidgetQueryKey, "stale");
queryClient.setQueryData(unrelatedQueryKey, "unrelated");
removePersistedWidgetQueries(queryClient);
removeWidgetDataQueries(queryClient, [[["widget", "anchorNotes"]]]);
expect(queryClient.getQueryData(crashedWidgetQueryKey)).toBeUndefined();
expect(queryClient.getQueryData(unrelatedQueryKey)).toBe("unrelated");
@@ -1,7 +1,5 @@
import type { QueryClient } from "@tanstack/react-query";
import type { QueryClient, QueryKey } from "@tanstack/react-query";
import { isPersistableWidgetQueryKey } from "@homarr/api/query-cache";
export const removePersistedWidgetQueries = (queryClient: QueryClient) => {
queryClient.removeQueries({ predicate: (query) => isPersistableWidgetQueryKey(query.queryKey) });
export const removeWidgetDataQueries = (queryClient: QueryClient, queryKeys: readonly QueryKey[]) => {
queryKeys.forEach((queryKey) => queryClient.removeQueries({ queryKey }));
};