feat: complete automatic mobile board UX
This commit is contained in:
1 parent
cf83e0d849
commit
7959c20d88
87 files changed
+2850
-570
No files matched your search
@@ -49,6 +49,7 @@ import {
|
||||
boardDuplicateSchema,
|
||||
boardRenameSchema,
|
||||
boardSaveLayoutSchema,
|
||||
boardSaveLayoutsSchema,
|
||||
boardSavePartialSettingsSchema,
|
||||
boardSavePermissionsSchema,
|
||||
boardSaveSchema,
|
||||
@@ -687,7 +688,7 @@ export const boardRouter = createTRPCRouter({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Set a board's desktop column count and remove legacy responsive layouts. Requires modify permission. REQUIRED: id (board ID), columnCount (1-24)",
|
||||
"Set a board's desktop column count while preserving saved responsive layouts. Requires modify permission. REQUIRED: id (board ID), columnCount (1-24)",
|
||||
},
|
||||
})
|
||||
.input(boardSaveLayoutSchema)
|
||||
@@ -761,12 +762,8 @@ export const boardRouter = createTRPCRouter({
|
||||
|
||||
await transaction
|
||||
.update(schema.layouts)
|
||||
.set({ name: "Base", columnCount: input.columnCount, breakpoint: 0 })
|
||||
.set({ columnCount: input.columnCount })
|
||||
.where(eq(schema.layouts.id, desktopLayout.id));
|
||||
|
||||
await transaction
|
||||
.delete(schema.layouts)
|
||||
.where(and(eq(schema.layouts.boardId, board.id), not(eq(schema.layouts.id, desktopLayout.id))));
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
@@ -811,18 +808,230 @@ export const boardRouter = createTRPCRouter({
|
||||
|
||||
transaction
|
||||
.update(layouts)
|
||||
.set({ name: "Base", columnCount: input.columnCount, breakpoint: 0 })
|
||||
.set({ columnCount: input.columnCount })
|
||||
.where(eq(layouts.id, desktopLayout.id))
|
||||
.run();
|
||||
|
||||
transaction
|
||||
.delete(layouts)
|
||||
.where(and(eq(layouts.boardId, board.id), not(eq(layouts.id, desktopLayout.id))))
|
||||
.run();
|
||||
});
|
||||
},
|
||||
});
|
||||
}),
|
||||
saveLayouts: protectedProcedure
|
||||
.input(boardSaveLayoutsSchema)
|
||||
.output(boardSaveLayoutsSchema.shape.layouts)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
|
||||
|
||||
const board = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id);
|
||||
const addedLayouts = filterAddedItems(input.layouts, board.layouts);
|
||||
const layoutsToInsert: InferInsertModel<typeof layouts>[] = [];
|
||||
const itemSectionLayoutsToInsert: InferInsertModel<typeof itemLayouts>[] = [];
|
||||
const sectionLayoutsToInsert: InferInsertModel<typeof sectionLayouts>[] = [];
|
||||
const savedLayoutIds = new Map<string, string>();
|
||||
|
||||
for (const addedLayout of addedLayouts) {
|
||||
const layoutId = createId();
|
||||
savedLayoutIds.set(addedLayout.id, layoutId);
|
||||
|
||||
layoutsToInsert.push({
|
||||
id: layoutId,
|
||||
name: addedLayout.name,
|
||||
columnCount: addedLayout.columnCount,
|
||||
breakpoint: addedLayout.breakpoint,
|
||||
boardId: board.id,
|
||||
});
|
||||
|
||||
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutA.columnCount - layoutB.columnCount);
|
||||
const layoutToClone =
|
||||
sortedLayouts.find((layout) => layout.columnCount >= addedLayout.columnCount) ?? sortedLayouts.at(-1);
|
||||
|
||||
if (!layoutToClone) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Board must have a layout" });
|
||||
}
|
||||
|
||||
const updatedBoardLayout = getUpdatedBoardLayout(board, {
|
||||
previous: {
|
||||
layoutId: layoutToClone.id,
|
||||
columnCount: layoutToClone.columnCount,
|
||||
},
|
||||
current: {
|
||||
layoutId,
|
||||
columnCount: addedLayout.columnCount,
|
||||
},
|
||||
});
|
||||
|
||||
itemSectionLayoutsToInsert.push(...updatedBoardLayout.itemSectionLayouts);
|
||||
sectionLayoutsToInsert.push(...updatedBoardLayout.sectionLayouts);
|
||||
}
|
||||
|
||||
const updatedLayouts = filterUpdatedItems(input.layouts, board.layouts);
|
||||
const itemSectionLayoutsToUpdate: InferInsertModel<typeof itemLayouts>[] = [];
|
||||
const sectionLayoutsToUpdate: InferInsertModel<typeof sectionLayouts>[] = [];
|
||||
const layoutsToUpdate: typeof input.layouts = [];
|
||||
|
||||
for (const updatedLayout of updatedLayouts) {
|
||||
const dbLayout = board.layouts.find((layout) => layout.id === updatedLayout.id);
|
||||
if (!dbLayout) continue;
|
||||
|
||||
if (dbLayout.columnCount !== updatedLayout.columnCount) {
|
||||
const updatedBoardLayout = getUpdatedBoardLayout(board, {
|
||||
previous: {
|
||||
layoutId: dbLayout.id,
|
||||
columnCount: dbLayout.columnCount,
|
||||
},
|
||||
current: {
|
||||
layoutId: dbLayout.id,
|
||||
columnCount: updatedLayout.columnCount,
|
||||
},
|
||||
});
|
||||
|
||||
itemSectionLayoutsToUpdate.push(...updatedBoardLayout.itemSectionLayouts);
|
||||
sectionLayoutsToUpdate.push(...updatedBoardLayout.sectionLayouts);
|
||||
}
|
||||
|
||||
layoutsToUpdate.push(updatedLayout);
|
||||
}
|
||||
|
||||
const removedLayoutIds = filterRemovedItems(input.layouts, board.layouts).map((layout) => layout.id);
|
||||
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(db, schema) {
|
||||
await db.transaction(async (transaction) => {
|
||||
if (layoutsToInsert.length > 0) {
|
||||
await transaction.insert(schema.layouts).values(layoutsToInsert);
|
||||
}
|
||||
if (itemSectionLayoutsToInsert.length > 0) {
|
||||
await transaction.insert(schema.itemLayouts).values(itemSectionLayoutsToInsert);
|
||||
}
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
await transaction.insert(schema.sectionLayouts).values(sectionLayoutsToInsert);
|
||||
}
|
||||
|
||||
for (const itemSectionLayout of itemSectionLayoutsToUpdate) {
|
||||
await transaction
|
||||
.update(schema.itemLayouts)
|
||||
.set({
|
||||
height: itemSectionLayout.height,
|
||||
width: itemSectionLayout.width,
|
||||
xOffset: itemSectionLayout.xOffset,
|
||||
yOffset: itemSectionLayout.yOffset,
|
||||
sectionId: itemSectionLayout.sectionId,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(schema.itemLayouts.itemId, itemSectionLayout.itemId),
|
||||
eq(schema.itemLayouts.layoutId, itemSectionLayout.layoutId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const sectionLayout of sectionLayoutsToUpdate) {
|
||||
await transaction
|
||||
.update(schema.sectionLayouts)
|
||||
.set({
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(schema.sectionLayouts.sectionId, sectionLayout.sectionId),
|
||||
eq(schema.sectionLayouts.layoutId, sectionLayout.layoutId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const layout of layoutsToUpdate) {
|
||||
await transaction
|
||||
.update(schema.layouts)
|
||||
.set({
|
||||
name: layout.name,
|
||||
columnCount: layout.columnCount,
|
||||
breakpoint: layout.breakpoint,
|
||||
})
|
||||
.where(eq(schema.layouts.id, layout.id));
|
||||
}
|
||||
|
||||
if (removedLayoutIds.length > 0) {
|
||||
await transaction.delete(schema.layouts).where(inArray(schema.layouts.id, removedLayoutIds));
|
||||
}
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
if (layoutsToInsert.length > 0) {
|
||||
transaction.insert(layouts).values(layoutsToInsert).run();
|
||||
}
|
||||
if (itemSectionLayoutsToInsert.length > 0) {
|
||||
transaction.insert(itemLayouts).values(itemSectionLayoutsToInsert).run();
|
||||
}
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
transaction.insert(sectionLayouts).values(sectionLayoutsToInsert).run();
|
||||
}
|
||||
|
||||
for (const itemSectionLayout of itemSectionLayoutsToUpdate) {
|
||||
transaction
|
||||
.update(itemLayouts)
|
||||
.set({
|
||||
height: itemSectionLayout.height,
|
||||
width: itemSectionLayout.width,
|
||||
xOffset: itemSectionLayout.xOffset,
|
||||
yOffset: itemSectionLayout.yOffset,
|
||||
sectionId: itemSectionLayout.sectionId,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(itemLayouts.itemId, itemSectionLayout.itemId),
|
||||
eq(itemLayouts.layoutId, itemSectionLayout.layoutId),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
}
|
||||
|
||||
for (const sectionLayout of sectionLayoutsToUpdate) {
|
||||
transaction
|
||||
.update(sectionLayouts)
|
||||
.set({
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(sectionLayouts.sectionId, sectionLayout.sectionId),
|
||||
eq(sectionLayouts.layoutId, sectionLayout.layoutId),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
}
|
||||
|
||||
for (const layout of layoutsToUpdate) {
|
||||
transaction
|
||||
.update(layouts)
|
||||
.set({
|
||||
name: layout.name,
|
||||
columnCount: layout.columnCount,
|
||||
breakpoint: layout.breakpoint,
|
||||
})
|
||||
.where(eq(layouts.id, layout.id))
|
||||
.run();
|
||||
}
|
||||
|
||||
if (removedLayoutIds.length > 0) {
|
||||
transaction.delete(layouts).where(inArray(layouts.id, removedLayoutIds)).run();
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return input.layouts.map((layout) => ({
|
||||
...layout,
|
||||
id: savedLayoutIds.get(layout.id) ?? layout.id,
|
||||
}));
|
||||
}),
|
||||
savePartialBoardSettings: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/settings", tags: ["boards"], protect: true },
|
||||
@@ -1491,16 +1700,16 @@ export const boardRouter = createTRPCRouter({
|
||||
}
|
||||
|
||||
const itemId = createId();
|
||||
|
||||
await ctx.db.insert(items).values({
|
||||
const itemRow = {
|
||||
id: itemId,
|
||||
boardId: input.boardId,
|
||||
kind: input.kind,
|
||||
options: superjson.stringify(input.options),
|
||||
advancedOptions: emptySuperJSON,
|
||||
});
|
||||
};
|
||||
|
||||
const layoutRows: (typeof itemLayouts.$inferInsert)[] = [];
|
||||
const defaultSize = widgetDefaultSizes[input.kind as WidgetKind] ?? { width: 1, height: 1 };
|
||||
|
||||
for (const layout of board.layouts) {
|
||||
const existingInSection = board.items
|
||||
@@ -1519,14 +1728,17 @@ export const boardRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
const defaultSize = widgetDefaultSizes[input.kind as WidgetKind] ?? { width: 1, height: 1 };
|
||||
const layoutItemSize = {
|
||||
...defaultSize,
|
||||
width: Math.min(defaultSize.width, layout.columnCount),
|
||||
};
|
||||
|
||||
const fitsAt = (x: number, y: number) => {
|
||||
if (x + defaultSize.width > layout.columnCount) return false;
|
||||
for (let dy = 0; dy < defaultSize.height; dy++) {
|
||||
if (x + layoutItemSize.width > layout.columnCount) return false;
|
||||
for (let dy = 0; dy < layoutItemSize.height; dy++) {
|
||||
const row = occupied[y + dy];
|
||||
if (!row) continue;
|
||||
for (let dx = 0; dx < defaultSize.width; dx++) {
|
||||
for (let dx = 0; dx < layoutItemSize.width; dx++) {
|
||||
if (row[x + dx]) return false;
|
||||
}
|
||||
}
|
||||
@@ -1544,8 +1756,8 @@ export const boardRouter = createTRPCRouter({
|
||||
layoutId: layout.id,
|
||||
xOffset: x,
|
||||
yOffset: y,
|
||||
width: defaultSize.width,
|
||||
height: defaultSize.height,
|
||||
width: layoutItemSize.width,
|
||||
height: layoutItemSize.height,
|
||||
});
|
||||
placed = true;
|
||||
}
|
||||
@@ -1560,15 +1772,32 @@ export const boardRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
if (layoutRows.length > 0) {
|
||||
await ctx.db.insert(itemLayouts).values(layoutRows);
|
||||
}
|
||||
const integrationRows = input.integrationIds.map((integrationId) => ({ itemId, integrationId }));
|
||||
|
||||
if (input.integrationIds.length > 0) {
|
||||
await ctx.db
|
||||
.insert(integrationItems)
|
||||
.values(input.integrationIds.map((integrationId) => ({ itemId, integrationId })));
|
||||
}
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(db, schema) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await transaction.insert(schema.items).values(itemRow);
|
||||
if (layoutRows.length > 0) {
|
||||
await transaction.insert(schema.itemLayouts).values(layoutRows);
|
||||
}
|
||||
if (integrationRows.length > 0) {
|
||||
await transaction.insert(schema.integrationItems).values(integrationRows);
|
||||
}
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
transaction.insert(items).values(itemRow).run();
|
||||
if (layoutRows.length > 0) {
|
||||
transaction.insert(itemLayouts).values(layoutRows).run();
|
||||
}
|
||||
if (integrationRows.length > 0) {
|
||||
transaction.insert(integrationItems).values(integrationRows).run();
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return { itemId };
|
||||
}),
|
||||
|
||||
@@ -19,6 +19,7 @@ import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
|
||||
const boardServerSettingsSchema = z.object({
|
||||
homeBoardId: z.string().nullable(),
|
||||
mobileHomeBoardId: z.string().nullable(),
|
||||
enableAutomaticMobileLayout: z.boolean(),
|
||||
enableStatusByDefault: z.boolean(),
|
||||
forceDisableStatus: z.boolean(),
|
||||
}) satisfies z.ZodType<ServerSettings["board"]>;
|
||||
@@ -39,7 +40,7 @@ export const serverSettingsRouter = createTRPCRouter({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get global board defaults, including desktop/mobile home board IDs and status behavior. Requires admin permission",
|
||||
"Get global board defaults, including desktop/mobile home board IDs, automatic mobile layout mode, and status behavior. Requires admin permission",
|
||||
},
|
||||
})
|
||||
.input(z.void())
|
||||
@@ -54,7 +55,7 @@ export const serverSettingsRouter = createTRPCRouter({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Update global board defaults. Requires admin permission. Optional fields: homeBoardId, mobileHomeBoardId, enableStatusByDefault, forceDisableStatus. Home board IDs must reference public boards or be null",
|
||||
"Update global board defaults. Requires admin permission. Optional fields: homeBoardId, mobileHomeBoardId, enableAutomaticMobileLayout, enableStatusByDefault, forceDisableStatus. Home board IDs must reference public boards or be null",
|
||||
},
|
||||
})
|
||||
.input(boardServerSettingsUpdateSchema)
|
||||
@@ -103,10 +104,19 @@ export const serverSettingsRouter = createTRPCRouter({
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const current = await getServerSettingByKeyAsync(ctx.db, input.settingsKey);
|
||||
await updateServerSettingByKeyAsync(ctx.db, input.settingsKey, {
|
||||
const next = {
|
||||
...current,
|
||||
...input.value,
|
||||
} as ServerSettings[keyof ServerSettings]);
|
||||
} as ServerSettings[keyof ServerSettings];
|
||||
const existing = await ctx.db.query.serverSettings.findFirst({
|
||||
where: eq(serverSettings.settingKey, input.settingsKey),
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await updateServerSettingByKeyAsync(ctx.db, input.settingsKey, next);
|
||||
} else {
|
||||
await insertServerSettingByKeyAsync(ctx.db, input.settingsKey, next);
|
||||
}
|
||||
}),
|
||||
initSettings: onboardingProcedure
|
||||
.requiresStep("settings")
|
||||
|
||||
@@ -4,7 +4,7 @@ import { describe, expect, it, test, vi } from "vitest";
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import type { Database, InferInsertModel } from "@homarr/db";
|
||||
import { and, eq } from "@homarr/db";
|
||||
import { and, eq, not } from "@homarr/db";
|
||||
import {
|
||||
boardGroupPermissions,
|
||||
boards,
|
||||
@@ -1382,6 +1382,187 @@ describe("saveGroupBoardPermissions should save group board permissions", () =>
|
||||
);
|
||||
});
|
||||
|
||||
const createExistingLayout = (id: string) => ({
|
||||
id,
|
||||
name: "Base",
|
||||
columnCount: 10,
|
||||
breakpoint: 0,
|
||||
});
|
||||
|
||||
const createNewLayout = (columnCount: number) => ({
|
||||
id: createId(),
|
||||
name: "New layout",
|
||||
columnCount,
|
||||
breakpoint: 1400,
|
||||
});
|
||||
|
||||
describe("saveLayouts should preserve legacy responsive layout editing", () => {
|
||||
test("should add a layout and clone item and dynamic-section placements", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId, sectionId, itemId } = await createFullBoardAsync(db, "default");
|
||||
const assignments = await createItemsAndSectionsAsync(db, {
|
||||
boardId,
|
||||
layoutId,
|
||||
sectionId,
|
||||
});
|
||||
const newLayout = createNewLayout(3);
|
||||
|
||||
const savedLayouts = await caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [createExistingLayout(layoutId), newLayout],
|
||||
});
|
||||
|
||||
const layout = expectToBeDefined(
|
||||
await db.query.layouts.findFirst({
|
||||
where: not(eq(layouts.id, layoutId)),
|
||||
}),
|
||||
);
|
||||
expect(layout).toMatchObject({
|
||||
name: newLayout.name,
|
||||
columnCount: newLayout.columnCount,
|
||||
breakpoint: newLayout.breakpoint,
|
||||
});
|
||||
expect(savedLayouts).toEqual([createExistingLayout(layoutId), { ...newLayout, id: layout.id }]);
|
||||
await expectLayoutForRootLayoutAsync(db, sectionId, layout.id, {
|
||||
...assignments.inRoot,
|
||||
a: itemId,
|
||||
});
|
||||
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layout.id, assignments.inDynamicSection);
|
||||
|
||||
await caller.saveLayouts({ id: boardId, layouts: savedLayouts });
|
||||
await expect(db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) })).resolves.toHaveLength(2);
|
||||
});
|
||||
|
||||
test("should update layout metadata and positions", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId, sectionId, itemId } = await createFullBoardAsync(db, "default");
|
||||
const assignments = await createItemsAndSectionsAsync(db, {
|
||||
boardId,
|
||||
layoutId,
|
||||
sectionId,
|
||||
});
|
||||
|
||||
await caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [
|
||||
{
|
||||
id: layoutId,
|
||||
name: "Phone",
|
||||
columnCount: 3,
|
||||
breakpoint: 480,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) })).resolves.toMatchObject({
|
||||
name: "Phone",
|
||||
columnCount: 3,
|
||||
breakpoint: 480,
|
||||
});
|
||||
await expectLayoutForRootLayoutAsync(db, sectionId, layoutId, {
|
||||
...assignments.inRoot,
|
||||
a: itemId,
|
||||
});
|
||||
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection);
|
||||
});
|
||||
|
||||
test("should remove layouts omitted from the saved responsive configuration", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
|
||||
await caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [createNewLayout(12)],
|
||||
});
|
||||
|
||||
await expect(db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("should reject duplicate responsive breakpoints", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
|
||||
await expect(
|
||||
caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [
|
||||
createExistingLayout(layoutId),
|
||||
{
|
||||
...createNewLayout(4),
|
||||
breakpoint: 0,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
|
||||
test("should reject duplicate responsive layout IDs", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
const existingLayout = createExistingLayout(layoutId);
|
||||
|
||||
await expect(
|
||||
caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [existingLayout, { ...existingLayout, name: "Phone", breakpoint: 480 }],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
|
||||
test("should reject fractional responsive layout values", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
|
||||
await expect(
|
||||
caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [{ ...createExistingLayout(layoutId), breakpoint: 480.5 }],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
|
||||
await expect(
|
||||
caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [{ ...createExistingLayout(layoutId), columnCount: 3.5 }],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("addItem should preserve every saved layout", () => {
|
||||
test("should clamp wide widgets to a retained narrow layout", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
const mobileLayoutId = createId();
|
||||
await db.insert(layouts).values({
|
||||
id: mobileLayoutId,
|
||||
name: "Mobile",
|
||||
columnCount: 1,
|
||||
breakpoint: 480,
|
||||
boardId,
|
||||
});
|
||||
|
||||
const { itemId } = await caller.addItem({
|
||||
boardId,
|
||||
kind: "mediaMissing",
|
||||
});
|
||||
|
||||
const savedItemLayouts = await db.query.itemLayouts.findMany({
|
||||
where: eq(itemLayouts.itemId, itemId),
|
||||
});
|
||||
expect(savedItemLayouts).toHaveLength(2);
|
||||
expect(savedItemLayouts).toContainEqual(expect.objectContaining({ layoutId, width: 4 }));
|
||||
expect(savedItemLayouts).toContainEqual(expect.objectContaining({ layoutId: mobileLayoutId, width: 1 }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveLayout should save the desktop layout", () => {
|
||||
test("should update position of items when column count changes", async () => {
|
||||
// Arrange
|
||||
@@ -1407,7 +1588,7 @@ describe("saveLayout should save the desktop layout", () => {
|
||||
});
|
||||
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection);
|
||||
});
|
||||
test("should keep the desktop layout and remove legacy responsive layouts", async () => {
|
||||
test("should preserve legacy layouts and desktop metadata", async () => {
|
||||
// Arrange
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
@@ -1434,15 +1615,18 @@ describe("saveLayout should save the desktop layout", () => {
|
||||
// Act
|
||||
await caller.saveLayout({
|
||||
id: boardId,
|
||||
columnCount: 16,
|
||||
columnCount: 14,
|
||||
});
|
||||
|
||||
// Assert
|
||||
const savedLayouts = await db.query.layouts.findMany({ where: eq(layouts.boardId, boardId) });
|
||||
expect(savedLayouts).toEqual([
|
||||
expect.objectContaining({ id: desktopLayoutId, name: "Base", columnCount: 16, breakpoint: 0 }),
|
||||
]);
|
||||
expect(savedLayouts.some((layout) => layout.id === layoutId)).toBe(false);
|
||||
expect(savedLayouts).toHaveLength(2);
|
||||
expect(savedLayouts).toContainEqual(
|
||||
expect.objectContaining({ id: layoutId, name: "Base", columnCount: 10, breakpoint: 0 }),
|
||||
);
|
||||
expect(savedLayouts).toContainEqual(
|
||||
expect.objectContaining({ id: desktopLayoutId, name: "Large", columnCount: 14, breakpoint: 1200 }),
|
||||
);
|
||||
});
|
||||
test("should fail when board not found", async () => {
|
||||
// Arrange
|
||||
|
||||
@@ -56,6 +56,33 @@ describe("getAll server settings", () => {
|
||||
});
|
||||
|
||||
describe("saveSettings", () => {
|
||||
test("saveSettings should persist settings when defaults are not seeded", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
|
||||
await caller.saveSettings({
|
||||
settingsKey: "board",
|
||||
value: {
|
||||
enableAutomaticMobileLayout: false,
|
||||
},
|
||||
});
|
||||
|
||||
const dbSettings = await db.select().from(serverSettings);
|
||||
expect(dbSettings).toStrictEqual([
|
||||
{
|
||||
settingKey: "board",
|
||||
value: stringify({
|
||||
...defaultServerSettings.board,
|
||||
enableAutomaticMobileLayout: false,
|
||||
}),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("saveSettings should update settings and return true when it updated only one", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
@@ -103,6 +130,27 @@ describe("board settings API", () => {
|
||||
await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board);
|
||||
});
|
||||
|
||||
test("getBoardSettings should backfill the automatic layout default for legacy values", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
const legacyBoardSettings = {
|
||||
homeBoardId: defaultServerSettings.board.homeBoardId,
|
||||
mobileHomeBoardId: defaultServerSettings.board.mobileHomeBoardId,
|
||||
enableStatusByDefault: defaultServerSettings.board.enableStatusByDefault,
|
||||
forceDisableStatus: defaultServerSettings.board.forceDisableStatus,
|
||||
};
|
||||
await db.insert(serverSettings).values({
|
||||
settingKey: "board",
|
||||
value: stringify(legacyBoardSettings),
|
||||
});
|
||||
|
||||
await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board);
|
||||
});
|
||||
|
||||
test("updateBoardSettings should insert settings when defaults are not persisted", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
@@ -145,6 +193,7 @@ describe("board settings API", () => {
|
||||
await caller.updateBoardSettings({ homeBoardId: boardId });
|
||||
const result = await caller.updateBoardSettings({
|
||||
mobileHomeBoardId: boardId,
|
||||
enableAutomaticMobileLayout: false,
|
||||
enableStatusByDefault: false,
|
||||
});
|
||||
|
||||
@@ -152,6 +201,7 @@ describe("board settings API", () => {
|
||||
...defaultServerSettings.board,
|
||||
homeBoardId: boardId,
|
||||
mobileHomeBoardId: boardId,
|
||||
enableAutomaticMobileLayout: false,
|
||||
enableStatusByDefault: false,
|
||||
});
|
||||
const dbSettings = await db.select().from(serverSettings);
|
||||
|
||||
@@ -2,36 +2,53 @@ import { getIntegrationKindsByCategory } from "@homarr/definitions";
|
||||
import { mediaReleaseRequestHandler } from "@homarr/request-handler/media-release";
|
||||
|
||||
import { createManyIntegrationMiddleware } from "../../middlewares/integration";
|
||||
import { settleIntegrationQueries } from "../../settle-integrations";
|
||||
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "../../settle-integrations";
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
|
||||
export const mediaReleaseRouter = createTRPCRouter({
|
||||
getMediaReleases: publicProcedure
|
||||
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRelease")))
|
||||
.query(async ({ ctx }) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
ctx.integrations,
|
||||
async (integration) => {
|
||||
const innerHandler = mediaReleaseRequestHandler.handler(integration, {});
|
||||
const { data, timestamp } = await innerHandler.getDataAsync();
|
||||
const mediaReleasesProcedure = publicProcedure.concat(
|
||||
createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRelease")),
|
||||
);
|
||||
|
||||
return {
|
||||
integration: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
kind: integration.kind,
|
||||
updatedAt: timestamp,
|
||||
},
|
||||
releases: data,
|
||||
};
|
||||
type MediaReleaseIntegration = Parameters<typeof mediaReleaseRequestHandler.handler>[0];
|
||||
|
||||
const getMediaReleasesWithProvenanceAsync = async (integrations: MediaReleaseIntegration[]) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
integrations,
|
||||
async (integration) => {
|
||||
const innerHandler = mediaReleaseRequestHandler.handler(integration, {});
|
||||
const { data, timestamp, isStale } = await innerHandler.getDataWithProvenanceAsync();
|
||||
|
||||
return {
|
||||
integration: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
kind: integration.kind,
|
||||
updatedAt: timestamp,
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
return results.flatMap((result) =>
|
||||
result.releases.map((release) => ({
|
||||
...release,
|
||||
integration: result.integration,
|
||||
})),
|
||||
);
|
||||
}),
|
||||
releases: data,
|
||||
isStale,
|
||||
};
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
const items = results.flatMap((result) =>
|
||||
result.releases.map((release) => ({
|
||||
...release,
|
||||
integration: result.integration,
|
||||
})),
|
||||
);
|
||||
|
||||
return {
|
||||
items,
|
||||
...getIntegrationQueryProvenance(integrations.length, results),
|
||||
};
|
||||
};
|
||||
|
||||
export const mediaReleaseRouter = createTRPCRouter({
|
||||
getMediaReleases: mediaReleasesProcedure.query(async ({ ctx }) => {
|
||||
return (await getMediaReleasesWithProvenanceAsync(ctx.integrations)).items;
|
||||
}),
|
||||
getMediaReleasesWithProvenance: mediaReleasesProcedure.query(async ({ ctx }) => {
|
||||
return await getMediaReleasesWithProvenanceAsync(ctx.integrations);
|
||||
}),
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod/v4";
|
||||
import { getIntegrationKindsByCategory } from "@homarr/definitions";
|
||||
import { createIntegrationAsync } from "@homarr/integrations";
|
||||
import { mediaRequestStatusConfiguration } from "@homarr/integrations/types";
|
||||
import type { MediaRequestListInput } from "@homarr/request-handler/media-request-list";
|
||||
import {
|
||||
mediaRequestListInputSchema,
|
||||
mediaRequestListRequestHandler,
|
||||
@@ -10,11 +11,93 @@ import {
|
||||
import { mediaRequestStatsRequestHandler } from "@homarr/request-handler/media-request-stats";
|
||||
|
||||
import { createManyIntegrationMiddleware, createOneIntegrationMiddleware } from "../../middlewares/integration";
|
||||
import { settleIntegrationQueries } from "../../settle-integrations";
|
||||
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "../../settle-integrations";
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
|
||||
|
||||
const latestRequestsProcedure = publicProcedure
|
||||
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
|
||||
.input(mediaRequestListInputSchema);
|
||||
const requestStatsProcedure = publicProcedure.concat(
|
||||
createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")),
|
||||
);
|
||||
|
||||
type MediaRequestIntegration = Parameters<typeof mediaRequestListRequestHandler.handler>[0];
|
||||
type MediaRequestStatsIntegration = Parameters<typeof mediaRequestStatsRequestHandler.handler>[0];
|
||||
|
||||
const getLatestRequestsWithProvenanceAsync = async (
|
||||
integrations: MediaRequestIntegration[],
|
||||
input: MediaRequestListInput,
|
||||
) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
integrations,
|
||||
async (integration) => {
|
||||
const { data, isStale } = await mediaRequestListRequestHandler
|
||||
.handler(integration, input)
|
||||
.getDataWithProvenanceAsync();
|
||||
return {
|
||||
integration: { id: integration.id, name: integration.name, kind: integration.kind },
|
||||
data,
|
||||
isStale,
|
||||
};
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
const items = results
|
||||
.flatMap(({ data, integration }) =>
|
||||
data.map((request) => ({
|
||||
...request,
|
||||
integrationId: integration.id,
|
||||
})),
|
||||
)
|
||||
.toSorted((dataA, dataB) => {
|
||||
if (dataA.status === dataB.status) {
|
||||
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
|
||||
}
|
||||
|
||||
return (
|
||||
mediaRequestStatusConfiguration[dataA.status].position - mediaRequestStatusConfiguration[dataB.status].position
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
...getIntegrationQueryProvenance(integrations.length, results),
|
||||
};
|
||||
};
|
||||
|
||||
const getRequestStatsWithProvenanceAsync = async (integrations: MediaRequestStatsIntegration[]) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
integrations,
|
||||
async (integration) => {
|
||||
const { data, isStale } = await mediaRequestStatsRequestHandler
|
||||
.handler(integration, {})
|
||||
.getDataWithProvenanceAsync();
|
||||
return {
|
||||
integration: { id: integration.id, name: integration.name, kind: integration.kind },
|
||||
data,
|
||||
isStale,
|
||||
};
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
|
||||
return {
|
||||
stats: results.flatMap((result) => result.data.stats),
|
||||
users: results
|
||||
.flatMap((result) =>
|
||||
result.data.users.map((user) => ({
|
||||
...user,
|
||||
integration: result.integration,
|
||||
})),
|
||||
)
|
||||
.toSorted(({ requestCount: countA }, { requestCount: countB }) => countB - countA),
|
||||
integrations: results.map((result) => result.integration),
|
||||
...getIntegrationQueryProvenance(integrations.length, results),
|
||||
};
|
||||
};
|
||||
|
||||
export const mediaRequestsRouter = createTRPCRouter({
|
||||
getLatestRequests: publicProcedure
|
||||
getLatestRequests: latestRequestsProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
@@ -22,36 +105,13 @@ export const mediaRequestsRouter = createTRPCRouter({
|
||||
"Get latest media requests from Overseerr/Jellyseerr with their status (pending, approved, declined, failed, completed). REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all). OPTIONAL: statuses (array of statuses to include, must be non-empty) and recentDays (number 0-365; 0 disables the time filter).",
|
||||
},
|
||||
})
|
||||
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
|
||||
.input(mediaRequestListInputSchema)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
ctx.integrations,
|
||||
async (integration) => {
|
||||
const { data } = await mediaRequestListRequestHandler.handler(integration, input).getDataAsync();
|
||||
return { integration: { id: integration.id, name: integration.name, kind: integration.kind }, data };
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
return results
|
||||
.flatMap(({ data, integration }) =>
|
||||
data.map((request) => ({
|
||||
...request,
|
||||
integrationId: integration.id,
|
||||
})),
|
||||
)
|
||||
.toSorted((dataA, dataB) => {
|
||||
if (dataA.status === dataB.status) {
|
||||
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
|
||||
}
|
||||
|
||||
return (
|
||||
mediaRequestStatusConfiguration[dataA.status].position -
|
||||
mediaRequestStatusConfiguration[dataB.status].position
|
||||
);
|
||||
});
|
||||
return (await getLatestRequestsWithProvenanceAsync(ctx.integrations, input)).items;
|
||||
}),
|
||||
getStats: publicProcedure
|
||||
getLatestRequestsWithProvenance: latestRequestsProcedure.query(async ({ ctx, input }) => {
|
||||
return await getLatestRequestsWithProvenanceAsync(ctx.integrations, input);
|
||||
}),
|
||||
getStats: requestStatsProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
@@ -59,30 +119,17 @@ export const mediaRequestsRouter = createTRPCRouter({
|
||||
"Get media request statistics including total counts and top requesters. REQUIRED: integrationIds (array of Overseerr/Jellyseerr integration IDs from integration_all)",
|
||||
},
|
||||
})
|
||||
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("mediaRequest")))
|
||||
.query(async ({ ctx }) => {
|
||||
const results = await settleIntegrationQueries(
|
||||
ctx.integrations,
|
||||
async (integration) => {
|
||||
const { data } = await mediaRequestStatsRequestHandler.handler(integration, {}).getDataAsync();
|
||||
return { integration: { id: integration.id, name: integration.name, kind: integration.kind }, data };
|
||||
},
|
||||
{ throwOnAllFailure: true },
|
||||
);
|
||||
const result = await getRequestStatsWithProvenanceAsync(ctx.integrations);
|
||||
return {
|
||||
stats: results.flatMap((result) => result.data.stats),
|
||||
users: results
|
||||
.map((result) =>
|
||||
result.data.users.map((user) => ({
|
||||
...user,
|
||||
integration: result.integration,
|
||||
})),
|
||||
)
|
||||
.flat()
|
||||
.toSorted(({ requestCount: countA }, { requestCount: countB }) => countB - countA),
|
||||
integrations: results.map((result) => result.integration),
|
||||
stats: result.stats,
|
||||
users: result.users,
|
||||
integrations: result.integrations,
|
||||
};
|
||||
}),
|
||||
getStatsWithProvenance: requestStatsProcedure.query(async ({ ctx }) => {
|
||||
return await getRequestStatsWithProvenanceAsync(ctx.integrations);
|
||||
}),
|
||||
answerRequest: protectedProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { settleIntegrationQueries } from "./settle-integrations";
|
||||
import { getIntegrationQueryProvenance, settleIntegrationQueries } from "./settle-integrations";
|
||||
|
||||
const integrations = [
|
||||
{ id: "first", name: "First", kind: "mock" },
|
||||
@@ -76,3 +76,19 @@ describe("settleIntegrationQueries", () => {
|
||||
).resolves.toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getIntegrationQueryProvenance", () => {
|
||||
it("counts dropped and stale integration results independently", () => {
|
||||
expect(getIntegrationQueryProvenance(4, [{ isStale: false }, { isStale: true }, { isStale: true }])).toEqual({
|
||||
failedIntegrationCount: 1,
|
||||
staleIntegrationCount: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not report failures for complete current results", () => {
|
||||
expect(getIntegrationQueryProvenance(2, [{ isStale: false }, {}])).toEqual({
|
||||
failedIntegrationCount: 0,
|
||||
staleIntegrationCount: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,19 @@ interface Options<TIntegration extends IntegrationLike, TResult> {
|
||||
throwOnAllFailure?: boolean;
|
||||
}
|
||||
|
||||
export interface IntegrationQueryProvenance {
|
||||
failedIntegrationCount: number;
|
||||
staleIntegrationCount: number;
|
||||
}
|
||||
|
||||
export const getIntegrationQueryProvenance = (
|
||||
selectedIntegrationCount: number,
|
||||
results: readonly { isStale?: boolean }[],
|
||||
): IntegrationQueryProvenance => ({
|
||||
failedIntegrationCount: Math.max(0, selectedIntegrationCount - results.length),
|
||||
staleIntegrationCount: results.filter((result) => result.isStale === true).length,
|
||||
});
|
||||
|
||||
export async function settleIntegrationQueries<TIntegration extends IntegrationLike, TResult>(
|
||||
integrations: TIntegration[],
|
||||
fn: (integration: TIntegration) => Promise<TResult>,
|
||||
|
||||
@@ -33,6 +33,7 @@ test("MCP tools should contain expected procedures", () => {
|
||||
expect(toolNames).toContain("app_byId");
|
||||
expect(toolNames).toContain("app_create");
|
||||
expect(toolNames).toContain("board_savePartialBoardSettings");
|
||||
expect(toolNames).toContain("board_saveLayout");
|
||||
expect(toolNames).toContain("board_duplicateBoard");
|
||||
expect(toolNames).toContain("info_getInfo");
|
||||
expect(toolNames).toContain("invite_getAll");
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@homarr/api": "workspace:^0.1.0",
|
||||
"@homarr/settings": "workspace:^0.1.0",
|
||||
"react": "catalog:",
|
||||
"react-dom": "catalog:"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
|
||||
import { getBoardLayouts, getCurrentLayout, getDesktopLayout } from "./context";
|
||||
|
||||
const createBoard = () =>
|
||||
({
|
||||
layouts: [
|
||||
{ id: "small", name: "Small", columnCount: 4, breakpoint: 0 },
|
||||
{ id: "medium", name: "Medium", columnCount: 8, breakpoint: 768 },
|
||||
{ id: "large", name: "Large", columnCount: 12, breakpoint: 1200 },
|
||||
],
|
||||
}) as RouterOutputs["board"]["getBoardByName"];
|
||||
|
||||
describe("board layout selection", () => {
|
||||
test("automatic mode always uses the desktop layout", () => {
|
||||
const board = createBoard();
|
||||
|
||||
expect(getDesktopLayout(board).id).toBe("large");
|
||||
expect(getCurrentLayout(board, true, 390)).toBe("large");
|
||||
});
|
||||
|
||||
test.each([
|
||||
[390, "small"],
|
||||
[768, "medium"],
|
||||
[1024, "medium"],
|
||||
[1440, "large"],
|
||||
])("legacy mode selects the matching responsive layout at %spx", (viewportWidth, expectedLayoutId) => {
|
||||
expect(getCurrentLayout(createBoard(), false, viewportWidth)).toBe(expectedLayoutId);
|
||||
});
|
||||
|
||||
test("keeps every saved layout available for reversible mutations", () => {
|
||||
expect(getBoardLayouts(createBoard())).toEqual(["small", "medium", "large"]);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { createContext, useContext, useEffect } from "react";
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getActiveQueryCacheBoardId, setActiveQueryCacheBoardId } from "@homarr/api/query-cache";
|
||||
import { useSettings } from "@homarr/settings";
|
||||
|
||||
import { updateBoardName } from "./updater";
|
||||
|
||||
@@ -73,10 +74,6 @@ export const useOptionalBoard = () => {
|
||||
return context?.board ?? null;
|
||||
};
|
||||
|
||||
export const getCurrentLayout = (board: RouterOutputs["board"]["getBoardByName"]) => {
|
||||
return getDesktopLayout(board).id;
|
||||
};
|
||||
|
||||
export const getDesktopLayout = (board: RouterOutputs["board"]["getBoardByName"]) => {
|
||||
const layout = board.layouts
|
||||
.toSorted(
|
||||
@@ -91,9 +88,57 @@ export const getDesktopLayout = (board: RouterOutputs["board"]["getBoardByName"]
|
||||
return layout;
|
||||
};
|
||||
|
||||
export const useCurrentLayout = () => getCurrentLayout(useRequiredBoard());
|
||||
export const getCurrentLayout = (
|
||||
board: RouterOutputs["board"]["getBoardByName"],
|
||||
enableAutomaticMobileLayout: boolean,
|
||||
viewportWidth?: number,
|
||||
) => {
|
||||
if (enableAutomaticMobileLayout || viewportWidth === undefined) {
|
||||
return getDesktopLayout(board).id;
|
||||
}
|
||||
|
||||
export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) => [getCurrentLayout(board)];
|
||||
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutB.breakpoint - layoutA.breakpoint);
|
||||
const layout = sortedLayouts.find((candidate) => candidate.breakpoint <= viewportWidth) ?? sortedLayouts.at(-1);
|
||||
|
||||
if (!layout) {
|
||||
throw new Error("Board must have a layout");
|
||||
}
|
||||
|
||||
return layout.id;
|
||||
};
|
||||
|
||||
export const useCurrentLayout = () => {
|
||||
const board = useRequiredBoard();
|
||||
const { enableAutomaticMobileLayout } = useSettings();
|
||||
const [currentLayout, setCurrentLayout] = useState(() =>
|
||||
getCurrentLayout(
|
||||
board,
|
||||
enableAutomaticMobileLayout,
|
||||
!enableAutomaticMobileLayout && typeof window !== "undefined" ? window.innerWidth : undefined,
|
||||
),
|
||||
);
|
||||
|
||||
const updateCurrentLayout = useCallback(() => {
|
||||
setCurrentLayout(getCurrentLayout(board, enableAutomaticMobileLayout, window.innerWidth));
|
||||
}, [board, enableAutomaticMobileLayout]);
|
||||
|
||||
useEffect(() => {
|
||||
updateCurrentLayout();
|
||||
|
||||
if (enableAutomaticMobileLayout) return;
|
||||
|
||||
window.addEventListener("resize", updateCurrentLayout);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", updateCurrentLayout);
|
||||
};
|
||||
}, [enableAutomaticMobileLayout, updateCurrentLayout]);
|
||||
|
||||
return currentLayout;
|
||||
};
|
||||
|
||||
export const getBoardLayouts = (board: RouterOutputs["board"]["getBoardByName"]) =>
|
||||
board.layouts.map((layout) => layout.id);
|
||||
|
||||
export const useLayouts = () => {
|
||||
const board = useRequiredBoard();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { BoardEditAction, BoardEditActionEvent } from "./edit-mode";
|
||||
import { boardEditActionEventName, requestBoardEditAction } from "./edit-mode";
|
||||
|
||||
describe("requestBoardEditAction", () => {
|
||||
test("runs the action immediately when no edit guard is mounted", () => {
|
||||
const action = vi.fn();
|
||||
|
||||
requestBoardEditAction(action);
|
||||
|
||||
expect(action).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("lets an edit guard defer the action until the user confirms", () => {
|
||||
const action = vi.fn();
|
||||
let deferredAction: BoardEditAction | undefined;
|
||||
const listener = (event: Event) => {
|
||||
event.preventDefault();
|
||||
deferredAction = (event as BoardEditActionEvent).detail.action;
|
||||
};
|
||||
document.addEventListener(boardEditActionEventName, listener, { once: true });
|
||||
|
||||
requestBoardEditAction(action);
|
||||
expect(action).not.toHaveBeenCalled();
|
||||
|
||||
void deferredAction?.();
|
||||
expect(action).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,28 @@ import { useDisclosure } from "@mantine/hooks";
|
||||
|
||||
const EditModeContext = createContext<ReturnType<typeof useDisclosure> | null>(null);
|
||||
|
||||
export const boardEditActionEventName = "homarr:board-edit-action";
|
||||
|
||||
export type BoardEditActionResult = boolean | void;
|
||||
export type BoardEditAction = () => BoardEditActionResult | Promise<BoardEditActionResult>;
|
||||
export type BoardEditActionEvent = CustomEvent<{ action: BoardEditAction }>;
|
||||
|
||||
export const requestBoardEditAction = (action: BoardEditAction) => {
|
||||
if (typeof document === "undefined") {
|
||||
void action();
|
||||
return;
|
||||
}
|
||||
|
||||
const event: BoardEditActionEvent = new CustomEvent(boardEditActionEventName, {
|
||||
cancelable: true,
|
||||
detail: { action },
|
||||
});
|
||||
|
||||
if (document.dispatchEvent(event)) {
|
||||
void action();
|
||||
}
|
||||
};
|
||||
|
||||
const noop = () => undefined;
|
||||
const readOnlyEditMode = [false, { open: noop, close: noop, toggle: noop, set: noop }] satisfies ReturnType<
|
||||
typeof useDisclosure
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { stringify } from "superjson";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { eq } from "@homarr/db";
|
||||
import {
|
||||
getServerSettingByKeyAsync,
|
||||
getServerSettingsAsync,
|
||||
shouldEnableAutomaticMobileLayoutForUpgrade,
|
||||
} from "@homarr/db/queries";
|
||||
import { boards, layouts, serverSettings } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import { defaultServerSettings } from "@homarr/server-settings";
|
||||
|
||||
import { seedServerSettingsAsync } from "./seed";
|
||||
|
||||
describe("automatic mobile layout upgrade default", () => {
|
||||
test("enables automatic mode for a new instance", () => {
|
||||
expect(shouldEnableAutomaticMobileLayoutForUpgrade([])).toBe(true);
|
||||
});
|
||||
|
||||
test("enables automatic mode when every existing board has only its canonical layout", () => {
|
||||
expect(
|
||||
shouldEnableAutomaticMobileLayoutForUpgrade([
|
||||
{ boardId: "first", name: "Base", breakpoint: 0 },
|
||||
{ boardId: "second", name: "Base", breakpoint: 0 },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("preserves legacy mode when a board has multiple responsive layouts", () => {
|
||||
expect(
|
||||
shouldEnableAutomaticMobileLayoutForUpgrade([
|
||||
{ boardId: "board", name: "Base", breakpoint: 0 },
|
||||
{ boardId: "board", name: "Mobile", breakpoint: 480 },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ boardId: "board", name: "Phone", breakpoint: 0 },
|
||||
{ boardId: "board", name: "Base", breakpoint: 480 },
|
||||
])("preserves legacy mode for a noncanonical saved layout", (existingLayout) => {
|
||||
expect(shouldEnableAutomaticMobileLayoutForUpgrade([existingLayout])).toBe(false);
|
||||
});
|
||||
|
||||
test("uses the upgrade heuristic when migrations and seeding are skipped", async () => {
|
||||
const db = createDb();
|
||||
const boardId = createId();
|
||||
await db.insert(boards).values({ id: boardId, name: "dashboard", isPublic: false });
|
||||
await db.insert(layouts).values([
|
||||
{ id: createId(), boardId, name: "Base", columnCount: 12, breakpoint: 0 },
|
||||
{ id: createId(), boardId, name: "Phone", columnCount: 4, breakpoint: 480 },
|
||||
]);
|
||||
|
||||
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toMatchObject({
|
||||
enableAutomaticMobileLayout: false,
|
||||
});
|
||||
await expect(getServerSettingsAsync(db)).resolves.toMatchObject({
|
||||
board: {
|
||||
enableAutomaticMobileLayout: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("backfills legacy responsive instances once without overriding an explicit choice", async () => {
|
||||
const db = createDb();
|
||||
const boardId = createId();
|
||||
await db.insert(boards).values({ id: boardId, name: "dashboard", isPublic: false });
|
||||
await db.insert(layouts).values([
|
||||
{ id: createId(), boardId, name: "Base", columnCount: 12, breakpoint: 0 },
|
||||
{ id: createId(), boardId, name: "Phone", columnCount: 4, breakpoint: 480 },
|
||||
]);
|
||||
await db.insert(serverSettings).values({
|
||||
settingKey: "board",
|
||||
value: stringify({
|
||||
homeBoardId: null,
|
||||
mobileHomeBoardId: null,
|
||||
enableStatusByDefault: true,
|
||||
forceDisableStatus: false,
|
||||
}),
|
||||
});
|
||||
|
||||
await seedServerSettingsAsync(db);
|
||||
await seedServerSettingsAsync(db);
|
||||
|
||||
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toStrictEqual({
|
||||
...defaultServerSettings.board,
|
||||
enableAutomaticMobileLayout: false,
|
||||
});
|
||||
|
||||
await db
|
||||
.update(serverSettings)
|
||||
.set({
|
||||
value: stringify({
|
||||
...defaultServerSettings.board,
|
||||
enableAutomaticMobileLayout: true,
|
||||
}),
|
||||
})
|
||||
.where(eq(serverSettings.settingKey, "board"));
|
||||
|
||||
await seedServerSettingsAsync(db);
|
||||
|
||||
await expect(getServerSettingByKeyAsync(db, "board")).resolves.toStrictEqual(defaultServerSettings.board);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import { getMaxGroupPositionAsync, placeAllWidgetsAsync } from "../queries";
|
||||
import {
|
||||
getServerSettingByKeyAsync,
|
||||
insertServerSettingByKeyAsync,
|
||||
shouldEnableAutomaticMobileLayoutForUpgrade,
|
||||
updateServerSettingByKeyAsync,
|
||||
} from "../queries/server-setting";
|
||||
|
||||
@@ -245,19 +246,33 @@ const seedDefaultSearchEnginesAsync = async (db: Database) => {
|
||||
console.log("Set Homarr docs as the default search engine");
|
||||
};
|
||||
|
||||
const seedServerSettingsAsync = async (db: Database) => {
|
||||
export const seedServerSettingsAsync = async (db: Database) => {
|
||||
const serverSettingsData = await db.query.serverSettings.findMany();
|
||||
const existingLayouts = await db.query.layouts.findMany({
|
||||
columns: {
|
||||
boardId: true,
|
||||
name: true,
|
||||
breakpoint: true,
|
||||
},
|
||||
});
|
||||
const defaultsForThisInstance = {
|
||||
...defaultServerSettings,
|
||||
board: {
|
||||
...defaultServerSettings.board,
|
||||
enableAutomaticMobileLayout: shouldEnableAutomaticMobileLayoutForUpgrade(existingLayouts),
|
||||
},
|
||||
};
|
||||
|
||||
for (const settingsKey of defaultServerSettingsKeys) {
|
||||
const currentDbEntry = serverSettingsData.find((setting) => setting.settingKey === settingsKey);
|
||||
if (!currentDbEntry) {
|
||||
await insertServerSettingByKeyAsync(db, settingsKey, defaultServerSettings[settingsKey]);
|
||||
await insertServerSettingByKeyAsync(db, settingsKey, defaultsForThisInstance[settingsKey]);
|
||||
console.log(`Created serverSetting through seed key=${settingsKey}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentSettings = await getServerSettingByKeyAsync(db, settingsKey);
|
||||
const defaultSettings = defaultServerSettings[settingsKey];
|
||||
const currentSettings = SuperJSON.parse<(typeof defaultServerSettings)[typeof settingsKey]>(currentDbEntry.value);
|
||||
const defaultSettings = defaultsForThisInstance[settingsKey];
|
||||
const missingKeys = objectKeys(defaultSettings).filter((key) => !(key in currentSettings));
|
||||
|
||||
if (missingKeys.length === 0) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import SuperJSON from "superjson";
|
||||
import { parse, stringify } from "superjson";
|
||||
|
||||
import type { ServerSettings } from "@homarr/server-settings";
|
||||
import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
|
||||
@@ -7,23 +7,71 @@ import type { Database } from "..";
|
||||
import { eq } from "..";
|
||||
import { serverSettings } from "../schema";
|
||||
|
||||
interface ExistingBoardLayout {
|
||||
boardId: string;
|
||||
name: string;
|
||||
breakpoint: number;
|
||||
}
|
||||
|
||||
export const shouldEnableAutomaticMobileLayoutForUpgrade = (existingLayouts: ExistingBoardLayout[]) => {
|
||||
const layoutCounts = new Map<string, number>();
|
||||
|
||||
for (const layout of existingLayouts) {
|
||||
if (layout.name !== "Base" || layout.breakpoint !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const nextCount = (layoutCounts.get(layout.boardId) ?? 0) + 1;
|
||||
if (nextCount > 1) {
|
||||
return false;
|
||||
}
|
||||
layoutCounts.set(layout.boardId, nextCount);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const getAutomaticMobileLayoutUpgradeDefaultAsync = async (db: Database) => {
|
||||
const existingLayouts = await db.query.layouts.findMany({
|
||||
columns: {
|
||||
boardId: true,
|
||||
name: true,
|
||||
breakpoint: true,
|
||||
},
|
||||
});
|
||||
|
||||
return shouldEnableAutomaticMobileLayoutForUpgrade(existingLayouts);
|
||||
};
|
||||
|
||||
export const getServerSettingsAsync = async (db: Database) => {
|
||||
const settings = await db.query.serverSettings.findMany();
|
||||
|
||||
return defaultServerSettingsKeys.reduce((acc, settingKey) => {
|
||||
const setting = settings.find((setting) => setting.settingKey === settingKey);
|
||||
const mergedSettings = defaultServerSettingsKeys.reduce((acc, settingKey) => {
|
||||
const setting = settings.find((candidate) => candidate.settingKey === settingKey);
|
||||
if (!setting) {
|
||||
// Typescript is not happy because the key is a union and it does not know that they are the same
|
||||
acc[settingKey] = defaultServerSettings[settingKey] as never;
|
||||
acc[settingKey] = { ...defaultServerSettings[settingKey] } as never;
|
||||
return acc;
|
||||
}
|
||||
|
||||
const persistedSettings = parse<Record<string, unknown>>(setting.value);
|
||||
acc[settingKey] = {
|
||||
...defaultServerSettings[settingKey],
|
||||
...SuperJSON.parse(setting.value),
|
||||
};
|
||||
...persistedSettings,
|
||||
} as never;
|
||||
return acc;
|
||||
}, {} as ServerSettings);
|
||||
|
||||
const persistedBoardSettings = settings.find((setting) => setting.settingKey === "board");
|
||||
const parsedBoardSettings = persistedBoardSettings
|
||||
? parse<Partial<ServerSettings["board"]>>(persistedBoardSettings.value)
|
||||
: {};
|
||||
|
||||
if (typeof parsedBoardSettings.enableAutomaticMobileLayout !== "boolean") {
|
||||
mergedSettings.board.enableAutomaticMobileLayout = await getAutomaticMobileLayoutUpgradeDefaultAsync(db);
|
||||
}
|
||||
|
||||
return mergedSettings;
|
||||
};
|
||||
|
||||
export const getServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>(db: Database, key: TKey) => {
|
||||
@@ -32,10 +80,31 @@ export const getServerSettingByKeyAsync = async <TKey extends keyof ServerSettin
|
||||
});
|
||||
|
||||
if (!dbSettings) {
|
||||
if (key === "board") {
|
||||
return {
|
||||
...defaultServerSettings.board,
|
||||
enableAutomaticMobileLayout: await getAutomaticMobileLayoutUpgradeDefaultAsync(db),
|
||||
} as ServerSettings[TKey];
|
||||
}
|
||||
|
||||
return defaultServerSettings[key];
|
||||
}
|
||||
|
||||
return SuperJSON.parse<ServerSettings[TKey]>(dbSettings.value);
|
||||
const persistedSettings = parse<Partial<ServerSettings[TKey]>>(dbSettings.value);
|
||||
const mergedSettings = {
|
||||
...defaultServerSettings[key],
|
||||
...persistedSettings,
|
||||
} as ServerSettings[TKey];
|
||||
|
||||
if (
|
||||
key === "board" &&
|
||||
typeof (persistedSettings as Partial<ServerSettings["board"]>).enableAutomaticMobileLayout !== "boolean"
|
||||
) {
|
||||
(mergedSettings as ServerSettings["board"]).enableAutomaticMobileLayout =
|
||||
await getAutomaticMobileLayoutUpgradeDefaultAsync(db);
|
||||
}
|
||||
|
||||
return mergedSettings;
|
||||
};
|
||||
|
||||
export const updateServerSettingByKeyAsync = async <TKey extends keyof ServerSettings>(
|
||||
@@ -46,7 +115,7 @@ export const updateServerSettingByKeyAsync = async <TKey extends keyof ServerSet
|
||||
await db
|
||||
.update(serverSettings)
|
||||
.set({
|
||||
value: SuperJSON.stringify(value),
|
||||
value: stringify(value),
|
||||
})
|
||||
.where(eq(serverSettings.settingKey, key));
|
||||
};
|
||||
@@ -58,6 +127,6 @@ export const insertServerSettingByKeyAsync = async <TKey extends keyof ServerSet
|
||||
) => {
|
||||
await db.insert(serverSettings).values({
|
||||
settingKey: key,
|
||||
value: SuperJSON.stringify(value),
|
||||
value: stringify(value),
|
||||
});
|
||||
};
|
||||
@@ -16,6 +16,7 @@ export interface ConfirmModalProps {
|
||||
children: ReactNode;
|
||||
onConfirm?: () => MaybePromise<void>;
|
||||
onCancel?: () => MaybePromise<void>;
|
||||
onClose?: () => void;
|
||||
closeOnConfirm?: boolean;
|
||||
closeOnCancel?: boolean;
|
||||
cancelProps?: ButtonProps & ComponentPropsWithoutRef<"button">;
|
||||
|
||||
@@ -127,6 +127,7 @@ const ActiveModal = ({ modal, state, handleCloseModal }: ActiveModalProps) => {
|
||||
interface OpenModalOptions {
|
||||
keepMounted?: boolean;
|
||||
title?: stringOrTranslation;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export const useModalAction = <TModal extends ModalDefinition>(modal: TModal) => {
|
||||
@@ -147,6 +148,10 @@ export const useConfirmModal = () => {
|
||||
const { openModal } = useModalAction(ConfirmModal);
|
||||
|
||||
return {
|
||||
openConfirmModal: (props: ConfirmModalProps) => openModal(props, { title: props.title }),
|
||||
openConfirmModal: (props: ConfirmModalProps) =>
|
||||
openModal(props, {
|
||||
title: props.title,
|
||||
onClose: props.onClose,
|
||||
}),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { createRequestHandler } from "./request-handler";
|
||||
|
||||
describe("createRequestHandler", () => {
|
||||
test("keeps the standard result contract free of cache provenance", async () => {
|
||||
const requestHandler = createRequestHandler({
|
||||
requestAsync: vi.fn().mockResolvedValue("current"),
|
||||
});
|
||||
|
||||
const result = await requestHandler.handler({ integrationId: "first" }).getDataAsync();
|
||||
|
||||
expect(result).toMatchObject({ data: "current", timestamp: expect.any(Date) });
|
||||
expect(result).not.toHaveProperty("isStale");
|
||||
});
|
||||
|
||||
test("marks an expired cache fallback as stale while preserving its timestamp", async () => {
|
||||
const requestAsync = vi.fn().mockResolvedValueOnce("cached").mockRejectedValueOnce(new Error("offline"));
|
||||
const requestHandler = createRequestHandler({
|
||||
requestAsync,
|
||||
cacheTtlMs: 0,
|
||||
fallbackToStaleOnError: true,
|
||||
});
|
||||
const handler = requestHandler.handler({ integrationId: "first" });
|
||||
|
||||
const fresh = await handler.getDataWithProvenanceAsync();
|
||||
const fallback = await handler.getDataWithProvenanceAsync();
|
||||
|
||||
expect(fresh).toMatchObject({ data: "cached", isStale: false });
|
||||
expect(fallback).toEqual({
|
||||
data: "cached",
|
||||
timestamp: fresh.timestamp,
|
||||
isStale: true,
|
||||
});
|
||||
expect(requestAsync).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("does not hide an initial error when no cache exists", async () => {
|
||||
const requestHandler = createRequestHandler({
|
||||
requestAsync: vi.fn().mockRejectedValue(new Error("offline")),
|
||||
fallbackToStaleOnError: true,
|
||||
});
|
||||
|
||||
await expect(requestHandler.handler({ integrationId: "first" }).getDataWithProvenanceAsync()).rejects.toThrow(
|
||||
"offline",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ interface Options<TData, TInput extends Record<string, unknown>> {
|
||||
}
|
||||
|
||||
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
|
||||
type RequestResult<TData> = Pick<CacheEntry<TData>, "data" | "timestamp"> & { isStale: boolean };
|
||||
|
||||
const MAX_CACHE_SIZE = 1000;
|
||||
const DEFAULT_TTL_MS = 10_000;
|
||||
@@ -20,21 +21,21 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
|
||||
options: Options<TData, TInput>,
|
||||
) => {
|
||||
const cache = new Map<string, CacheEntry<TData>>();
|
||||
const inflight = new Map<string, Promise<CacheEntry<TData>>>();
|
||||
const inflight = new Map<string, Promise<RequestResult<TData>>>();
|
||||
|
||||
return {
|
||||
invalidateCache: () => {
|
||||
cache.clear();
|
||||
inflight.clear();
|
||||
},
|
||||
handler: (input: TInput) => ({
|
||||
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
||||
handler: (input: TInput) => {
|
||||
const getDataWithProvenanceAsync = async (): Promise<RequestResult<TData>> => {
|
||||
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||
const key = JSON.stringify(input);
|
||||
|
||||
const cached = cache.get(key);
|
||||
if (cached && Date.now() < cached.expiresAt) {
|
||||
return { data: cached.data, timestamp: cached.timestamp };
|
||||
return { data: cached.data, timestamp: cached.timestamp, isStale: false };
|
||||
}
|
||||
|
||||
const existing = inflight.get(key);
|
||||
@@ -51,19 +52,27 @@ export const createRequestHandler = <TData, TInput extends Record<string, unknow
|
||||
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
||||
cache.set(key, entry);
|
||||
inflight.delete(key);
|
||||
return entry;
|
||||
return { data: entry.data, timestamp: entry.timestamp, isStale: false };
|
||||
})
|
||||
.catch((err) => {
|
||||
inflight.delete(key);
|
||||
if (options.fallbackToStaleOnError && cached) {
|
||||
return cached;
|
||||
return { data: cached.data, timestamp: cached.timestamp, isStale: true };
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
inflight.set(key, promise);
|
||||
return promise;
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
async getDataAsync(): Promise<Pick<RequestResult<TData>, "data" | "timestamp">> {
|
||||
const { data, timestamp } = await getDataWithProvenanceAsync();
|
||||
return { data, timestamp };
|
||||
},
|
||||
getDataWithProvenanceAsync,
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -13,4 +13,5 @@ export const mediaReleaseRequestHandler = createIntegrationRequestHandler<
|
||||
const integrationInstance = await createIntegrationAsync(integration);
|
||||
return await integrationInstance.getMediaReleasesAsync();
|
||||
},
|
||||
fallbackToStaleOnError: true,
|
||||
});
|
||||
@@ -27,6 +27,7 @@ export const defaultServerSettings = {
|
||||
board: {
|
||||
homeBoardId: null as string | null,
|
||||
mobileHomeBoardId: null as string | null,
|
||||
enableAutomaticMobileLayout: true,
|
||||
enableStatusByDefault: true,
|
||||
forceDisableStatus: false,
|
||||
},
|
||||
|
||||
@@ -12,14 +12,14 @@ export type SettingsContextProps = Pick<
|
||||
| "pingIconsEnabled"
|
||||
| "enableRightClickOnWidgets"
|
||||
> &
|
||||
Pick<ServerSettings["board"], "enableStatusByDefault" | "forceDisableStatus"> &
|
||||
Pick<ServerSettings["board"], "enableAutomaticMobileLayout" | "enableStatusByDefault" | "forceDisableStatus"> &
|
||||
Pick<ServerSettings["user"], "enableGravatar">;
|
||||
|
||||
export interface PublicServerSettings {
|
||||
search: Pick<ServerSettings["search"], "defaultSearchEngineId">;
|
||||
board: Pick<
|
||||
ServerSettings["board"],
|
||||
"homeBoardId" | "mobileHomeBoardId" | "enableStatusByDefault" | "forceDisableStatus"
|
||||
"homeBoardId" | "mobileHomeBoardId" | "enableAutomaticMobileLayout" | "enableStatusByDefault" | "forceDisableStatus"
|
||||
>;
|
||||
user: Pick<ServerSettings["user"], "enableGravatar">;
|
||||
}
|
||||
@@ -51,6 +51,7 @@ export const createSettings = ({
|
||||
mobileHomeBoardId: user?.mobileHomeBoardId ?? serverSettings.board.mobileHomeBoardId,
|
||||
pingIconsEnabled: user?.pingIconsEnabled ?? false,
|
||||
enableRightClickOnWidgets: user?.enableRightClickOnWidgets ?? true,
|
||||
enableAutomaticMobileLayout: serverSettings.board.enableAutomaticMobileLayout,
|
||||
enableStatusByDefault: serverSettings.board.enableStatusByDefault,
|
||||
forceDisableStatus: serverSettings.board.forceDisableStatus,
|
||||
enableGravatar: serverSettings.user.enableGravatar,
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"dependencies": {
|
||||
"@homarr/api": "workspace:^0.1.0",
|
||||
"@homarr/auth": "workspace:^0.1.0",
|
||||
"@homarr/boards": "workspace:^0.1.0",
|
||||
"@homarr/common": "workspace:^0.1.0",
|
||||
"@homarr/definitions": "workspace:^0.1.0",
|
||||
"@homarr/integrations": "workspace:^0.1.0",
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { DayOfWeek } from "@mantine/dates";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { requestBoardEditAction } from "@homarr/boards/edit-mode";
|
||||
import type { ColorScheme } from "@homarr/definitions";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
@@ -160,7 +161,7 @@ export const useUserPreferences = () => {
|
||||
|
||||
const clientSetters: Partial<Record<UserPreferenceKey, (value: unknown) => void>> = {
|
||||
colorScheme: (value) => setColorScheme(value as ColorScheme),
|
||||
locale: (value) => changeLocale(value as typeof currentLocale),
|
||||
locale: (value) => requestBoardEditAction(() => changeLocale(value as typeof currentLocale)),
|
||||
fullPreferencesPage: () => undefined,
|
||||
};
|
||||
|
||||
|
||||
@@ -1495,6 +1495,10 @@
|
||||
"docker": "Docker",
|
||||
"preferences": "Your preferences",
|
||||
"logout": "Logout",
|
||||
"logoutError": {
|
||||
"title": "Logout failed",
|
||||
"message": "Your session is still active. Please try again."
|
||||
},
|
||||
"login": "Login",
|
||||
"homeBoard": "Your home board",
|
||||
"loggedOut": "Logged out",
|
||||
@@ -4382,7 +4386,15 @@
|
||||
"description": "Configure the layout used on desktop and larger screens."
|
||||
},
|
||||
"mobile": {
|
||||
"description": "On mobile, items are automatically arranged in two columns and cannot be moved or resized. Named categories and dynamic sections appear as headings, never as layout containers."
|
||||
"automaticDescription": "On mobile, items are automatically arranged in two columns and cannot be moved or resized. Named categories and dynamic sections appear as headings, never as layout containers."
|
||||
},
|
||||
"responsive": {
|
||||
"title": "Responsive layouts",
|
||||
"description": "Automatic mobile layout is disabled for this server. Configure the saved layouts selected at each viewport breakpoint; these layouts can also be edited directly on mobile.",
|
||||
"defaultName": "New layout",
|
||||
"action": {
|
||||
"add": "Add layout"
|
||||
}
|
||||
}
|
||||
},
|
||||
"background": {
|
||||
@@ -4832,6 +4844,13 @@
|
||||
"mobileLabel": "Global mobile board",
|
||||
"description": "Only public boards are available for selection"
|
||||
},
|
||||
"mobileLayout": {
|
||||
"title": "Mobile layout",
|
||||
"enable": {
|
||||
"label": "Use automatic mobile layout",
|
||||
"description": "Arrange every board into a read-only two-column layout on phones and small tablets. Turn this off to use saved responsive layouts and mobile layout editing. Saved responsive layouts are kept when this is enabled."
|
||||
}
|
||||
},
|
||||
"status": {
|
||||
"title": "App status",
|
||||
"enableStatusByDefault": {
|
||||
|
||||
@@ -24,7 +24,7 @@ export const boardNameSchema = z
|
||||
.min(1)
|
||||
.max(255)
|
||||
.regex(/^[A-Za-z0-9-_]*$/);
|
||||
export const boardColumnCountSchema = z.number().min(1).max(24);
|
||||
export const boardColumnCountSchema = z.number().int().min(1).max(24);
|
||||
|
||||
export const boardByNameSchema = z.object({
|
||||
name: boardNameSchema,
|
||||
@@ -75,6 +75,46 @@ export const boardSaveLayoutSchema = z.object({
|
||||
columnCount: boardColumnCountSchema,
|
||||
});
|
||||
|
||||
const responsiveBoardLayoutsSchema = z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string().trim().nonempty().max(32),
|
||||
columnCount: boardColumnCountSchema,
|
||||
breakpoint: z.number().int().min(0).max(32767),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.superRefine((layouts, context) => {
|
||||
const seenBreakpoints = new Set<number>();
|
||||
const seenIds = new Set<string>();
|
||||
|
||||
layouts.forEach((layout, index) => {
|
||||
if (seenIds.has(layout.id)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Each responsive layout must have a unique ID",
|
||||
path: [index, "id"],
|
||||
});
|
||||
}
|
||||
seenIds.add(layout.id);
|
||||
|
||||
if (seenBreakpoints.has(layout.breakpoint)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Each responsive layout must have a unique breakpoint",
|
||||
path: [index, "breakpoint"],
|
||||
});
|
||||
}
|
||||
seenBreakpoints.add(layout.breakpoint);
|
||||
});
|
||||
});
|
||||
|
||||
export const boardSaveLayoutsSchema = z.object({
|
||||
id: z.string(),
|
||||
layouts: responsiveBoardLayoutsSchema,
|
||||
});
|
||||
|
||||
export const boardSaveSchema = z.object({
|
||||
id: z.string(),
|
||||
sections: z.array(sectionSchema),
|
||||
|
||||
@@ -7,13 +7,16 @@ import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { useRegisterSpotlightContextResults } from "@homarr/spotlight";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { MaskedOrNormalImage } from "@homarr/ui";
|
||||
|
||||
import { WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import classes from "./bookmark.module.css";
|
||||
|
||||
export default function BookmarksWidget({ options, itemId }: WidgetComponentProps<"bookmarks">) {
|
||||
export default function BookmarksWidget({ options, itemId, displayMode }: WidgetComponentProps<"bookmarks">) {
|
||||
const board = useRequiredBoard();
|
||||
const t = useI18n();
|
||||
const { data = [] } = clientApi.app.byIds.useQuery(options.items, {
|
||||
select(data) {
|
||||
return data.toSorted((appA, appB) => options.items.indexOf(appA.id) - options.items.indexOf(appB.id));
|
||||
@@ -41,6 +44,21 @@ export default function BookmarksWidget({ options, itemId }: WidgetComponentProp
|
||||
[data],
|
||||
);
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
return (
|
||||
<WidgetMobileSummary
|
||||
value={data.length}
|
||||
label={options.title || t("widget.bookmarks.name")}
|
||||
description={
|
||||
data
|
||||
.map((app) => app.name)
|
||||
.slice(0, 2)
|
||||
.join(" · ") || t("board.mobile.details")
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack h="100%" gap="sm" p="sm">
|
||||
{options.title.length > 0 && (
|
||||
|
||||
@@ -10,8 +10,13 @@ import { BookmarkAddButton } from "./add-button";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("bookmarks", {
|
||||
icon: IconBookmark,
|
||||
mobile: { supportsDetailView: true },
|
||||
queryKey: [["app"]],
|
||||
mobile: {
|
||||
width: 2,
|
||||
height: 1,
|
||||
supportsCompactSummary: true,
|
||||
supportsDetailView: true,
|
||||
},
|
||||
queryKey: [["app", "byIds"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
title: factory.text(),
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useSettings } from "@homarr/settings";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { CalendarDay } from "./calender-day";
|
||||
import classes from "./component.module.css";
|
||||
@@ -44,8 +45,8 @@ const FetchCalendar = ({ month, setMonth, isEditMode, integrationIds, options, d
|
||||
const { data, error, isPending } = clientApi.widget.calendar.findAllEvents.useQuery(input);
|
||||
const events = useMemo(() => data?.flatMap((item) => item.events) ?? [], [data]);
|
||||
|
||||
if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
|
||||
if (displayMode === "mobileSummary" && error && !data) throw error;
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, data !== undefined);
|
||||
|
||||
return (
|
||||
<CalendarBase
|
||||
@@ -55,7 +56,11 @@ const FetchCalendar = ({ month, setMonth, isEditMode, integrationIds, options, d
|
||||
setMonth={setMonth}
|
||||
options={options}
|
||||
displayMode={displayMode}
|
||||
isStale={Boolean(error) || (data?.length ?? 0) < integrationIds.length}
|
||||
isStale={hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: data?.length,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -125,7 +130,7 @@ const CalendarBase = ({
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
const calendar = (
|
||||
<Calendar
|
||||
defaultDate={new Date()}
|
||||
onPreviousMonth={(month) => setMonth(new Date(month))}
|
||||
@@ -205,6 +210,7 @@ const CalendarBase = ({
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return <WidgetDataState hasWarning={isStale}>{calendar}</WidgetDataState>;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError } from "./query-state";
|
||||
|
||||
describe("widget query state", () => {
|
||||
test.each([
|
||||
{ error: new Error("refresh failed") },
|
||||
{ failedIntegrationCount: 1 },
|
||||
{ staleIntegrationCount: 1 },
|
||||
{ expectedIntegrationCount: 2, receivedIntegrationCount: 1 },
|
||||
])("warns when data provenance is incomplete or stale", (provenance) => {
|
||||
expect(hasWidgetDataWarning(provenance)).toBe(true);
|
||||
});
|
||||
|
||||
test("does not warn for complete current data", () => {
|
||||
expect(
|
||||
hasWidgetDataWarning({
|
||||
failedIntegrationCount: 0,
|
||||
staleIntegrationCount: 0,
|
||||
expectedIntegrationCount: 2,
|
||||
receivedIntegrationCount: 2,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("throws an initial query error", () => {
|
||||
const error = new Error("initial request failed");
|
||||
expect(() => throwOnInitialQueryError(error, false)).toThrow(error);
|
||||
});
|
||||
|
||||
test("keeps cached data visible after a refresh error", () => {
|
||||
expect(() => throwOnInitialQueryError(new Error("refresh failed"), true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Box, Center, Tooltip } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
interface WidgetQueryProvenance {
|
||||
error?: unknown;
|
||||
failedIntegrationCount?: number;
|
||||
staleIntegrationCount?: number;
|
||||
expectedIntegrationCount?: number;
|
||||
receivedIntegrationCount?: number;
|
||||
}
|
||||
|
||||
export const hasWidgetDataWarning = ({
|
||||
error,
|
||||
failedIntegrationCount = 0,
|
||||
staleIntegrationCount = 0,
|
||||
expectedIntegrationCount,
|
||||
receivedIntegrationCount,
|
||||
}: WidgetQueryProvenance) =>
|
||||
Boolean(error) ||
|
||||
failedIntegrationCount > 0 ||
|
||||
staleIntegrationCount > 0 ||
|
||||
(expectedIntegrationCount !== undefined &&
|
||||
receivedIntegrationCount !== undefined &&
|
||||
receivedIntegrationCount < expectedIntegrationCount);
|
||||
|
||||
export const throwOnInitialQueryError = (error: unknown, hasData: boolean) => {
|
||||
if (error && !hasData) throw error;
|
||||
};
|
||||
|
||||
interface WidgetDataStateProps {
|
||||
children: ReactNode;
|
||||
hasWarning: boolean;
|
||||
}
|
||||
|
||||
export function WidgetDataState({ children, hasWarning }: WidgetDataStateProps) {
|
||||
const t = useI18n();
|
||||
const label = t("board.mobile.dataWarning");
|
||||
|
||||
return (
|
||||
<Box pos="relative" h="100%" w="100%">
|
||||
{hasWarning && (
|
||||
<Tooltip label={label} position="left" withArrow>
|
||||
<Center
|
||||
component="output"
|
||||
aria-label={label}
|
||||
pos="absolute"
|
||||
bottom={4}
|
||||
w={28}
|
||||
h={28}
|
||||
style={{
|
||||
insetInlineStart: 4,
|
||||
zIndex: 4,
|
||||
borderRadius: "var(--mantine-radius-sm)",
|
||||
background: "light-dark(var(--mantine-color-yellow-1), var(--mantine-color-dark-6))",
|
||||
}}
|
||||
>
|
||||
<IconAlertTriangle
|
||||
size={16}
|
||||
color="light-dark(var(--mantine-color-yellow-9), var(--mantine-color-yellow-3))"
|
||||
aria-hidden
|
||||
/>
|
||||
</Center>
|
||||
</Tooltip>
|
||||
)}
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("customApi", {
|
||||
icon: IconApi,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: { supportsDetailView: true, unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "customApi"]],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
|
||||
@@ -9,7 +9,7 @@ export const widgetKind = "dnsHoleControls";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition(widgetKind, {
|
||||
icon: IconDeviceGamepad,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: { supportsDetailView: true, unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "dnsHole"]],
|
||||
refetchInterval: 5,
|
||||
createOptions() {
|
||||
|
||||
@@ -9,6 +9,7 @@ export const widgetKind = "dnsHoleSummary";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition(widgetKind, {
|
||||
icon: IconAd,
|
||||
mobile: { unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "dnsHole"]],
|
||||
refetchInterval: 5,
|
||||
createOptions() {
|
||||
|
||||
@@ -50,6 +50,7 @@ import type { ExtendedClientStatus, ExtendedDownloadClientItem } from "@homarr/i
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
@@ -129,7 +130,7 @@ const DownloadClientsMobileSummary = ({
|
||||
});
|
||||
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
if (error && !data) throw error;
|
||||
throwOnInitialQueryError(error, data !== undefined);
|
||||
|
||||
const currentItems = data ?? [];
|
||||
const selectedClients = currentItems.filter(({ integration }) => integrationIds.includes(integration.id));
|
||||
@@ -148,7 +149,11 @@ const DownloadClientsMobileSummary = ({
|
||||
value={visibleItemCount}
|
||||
label={t("name")}
|
||||
description={`${t("items.downSpeed.columnTitle")}: ${formatByteRate(totalDownloadSpeed)}`}
|
||||
isStale={Boolean(error) || currentItems.length < integrationIds.length}
|
||||
isStale={hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: currentItems.length,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -163,10 +168,11 @@ const DownloadClientsTable = ({
|
||||
integrationIds.includes(id) ? [id] : [],
|
||||
);
|
||||
|
||||
const { data: currentItems = [] } = clientApi.widget.downloads.getJobsAndStatuses.useQuery({
|
||||
const { data: queryData, error: queryError } = clientApi.widget.downloads.getJobsAndStatuses.useQuery({
|
||||
integrationIds,
|
||||
limitPerIntegration: options.limitPerIntegration,
|
||||
});
|
||||
const currentItems = queryData ?? [];
|
||||
|
||||
const t = useScopedI18n("widget.downloads");
|
||||
const tCommon = useScopedI18n("common");
|
||||
@@ -694,15 +700,24 @@ const DownloadClientsTable = ({
|
||||
{ up: 0, down: 0 },
|
||||
);
|
||||
|
||||
throwOnInitialQueryError(queryError, queryData !== undefined);
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error: queryError,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: currentItems.length,
|
||||
});
|
||||
|
||||
if (options.columns.length === 0)
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Text>{t("errors.noColumns")}</Text>
|
||||
</Center>
|
||||
<WidgetDataState hasWarning={hasWarning}>
|
||||
<Center h="100%">
|
||||
<Text>{t("errors.noColumns")}</Text>
|
||||
</Center>
|
||||
</WidgetDataState>
|
||||
);
|
||||
|
||||
//The actual widget
|
||||
return (
|
||||
const content = (
|
||||
<Stack gap={0} h="100%" display="flex">
|
||||
<MantineReactTable table={table} />
|
||||
<Group
|
||||
@@ -728,6 +743,7 @@ const DownloadClientsTable = ({
|
||||
<ItemInfoModal items={data} currentIndex={clickedIndex} opened={opened} onClose={close} />
|
||||
</Stack>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
};
|
||||
|
||||
interface ItemInfoModalProps {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("firewall", {
|
||||
icon: IconWall,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: { supportsDetailView: true, unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "firewall"]],
|
||||
refetchInterval: 5,
|
||||
createOptions() {
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { TablerIcon } from "@homarr/ui";
|
||||
import { OverflowBadge } from "@homarr/ui";
|
||||
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export default function MediaReleasesWidget({
|
||||
@@ -23,29 +24,33 @@ export default function MediaReleasesWidget({
|
||||
integrationIds,
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"mediaReleases">) {
|
||||
const { data, error, isPending } = clientApi.widget.mediaRelease.getMediaReleases.useQuery({
|
||||
const { data, error, isPending } = clientApi.widget.mediaRelease.getMediaReleasesWithProvenance.useQuery({
|
||||
integrationIds,
|
||||
});
|
||||
const t = useI18n("widget.mediaReleases");
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
if (error && !data) throw error;
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, data !== undefined);
|
||||
|
||||
const releases = data ?? [];
|
||||
const releases = data?.items ?? [];
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
failedIntegrationCount: data?.failedIntegrationCount,
|
||||
staleIntegrationCount: data?.staleIntegrationCount,
|
||||
});
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
return (
|
||||
<WidgetMobileSummary
|
||||
value={releases.length}
|
||||
label={t("name")}
|
||||
description={releases[0]?.title}
|
||||
isStale={Boolean(error)}
|
||||
isStale={hasWarning}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const releases = data ?? [];
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<Stack p="xs" gap="sm">
|
||||
{releases.map((item, index) => (
|
||||
<Fragment key={item.id}>
|
||||
@@ -55,10 +60,11 @@ export default function MediaReleasesWidget({
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
}
|
||||
|
||||
interface ItemProps {
|
||||
item: RouterOutputs["widget"]["mediaRelease"]["getMediaReleases"][number];
|
||||
item: RouterOutputs["widget"]["mediaRelease"]["getMediaReleasesWithProvenance"]["items"][number];
|
||||
options: WidgetComponentProps<"mediaReleases">["options"];
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetEmptyState } from "../../common/empty-state";
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../../common/query-state";
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import { NoIntegrationDataError } from "../../errors/no-data-integration";
|
||||
import classes from "../search-button.module.css";
|
||||
@@ -39,11 +40,7 @@ export default function MediaServerWidget({
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"mediaRequests-requestList">) {
|
||||
const t = useScopedI18n("widget.mediaRequests-requestList");
|
||||
const {
|
||||
data: mediaRequests,
|
||||
error,
|
||||
isPending,
|
||||
} = clientApi.widget.mediaRequests.getLatestRequests.useQuery({
|
||||
const { data, error, isPending } = clientApi.widget.mediaRequests.getLatestRequestsWithProvenance.useQuery({
|
||||
integrationIds,
|
||||
statuses:
|
||||
options.statusFilter.length > 0
|
||||
@@ -52,23 +49,38 @@ export default function MediaServerWidget({
|
||||
recentDays: options.recentDays,
|
||||
});
|
||||
|
||||
if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
|
||||
if (displayMode === "mobileSummary" && error && !mediaRequests) throw error;
|
||||
if (!mediaRequests) return <WidgetEmptyState />;
|
||||
if (mediaRequests.length === 0) throw new NoIntegrationDataError();
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, data !== undefined);
|
||||
if (!data) return <WidgetEmptyState />;
|
||||
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
failedIntegrationCount: data.failedIntegrationCount,
|
||||
staleIntegrationCount: data.staleIntegrationCount,
|
||||
});
|
||||
|
||||
if (data.items.length === 0 && !hasWarning) throw new NoIntegrationDataError();
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
return (
|
||||
<WidgetMobileSummary
|
||||
value={mediaRequests.length}
|
||||
value={data.items.length}
|
||||
label={t("name")}
|
||||
description={mediaRequests[0]?.name}
|
||||
isStale={Boolean(error)}
|
||||
description={data.items[0]?.name}
|
||||
isStale={hasWarning}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
if (data.items.length === 0) {
|
||||
return (
|
||||
<WidgetDataState hasWarning={hasWarning}>
|
||||
<WidgetEmptyState />
|
||||
</WidgetDataState>
|
||||
);
|
||||
}
|
||||
|
||||
const content = (
|
||||
<Box className={classes.searchRoot}>
|
||||
{!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />}
|
||||
<ScrollArea
|
||||
@@ -77,7 +89,7 @@ export default function MediaServerWidget({
|
||||
style={{ pointerEvents: isEditMode ? "none" : undefined }}
|
||||
>
|
||||
<Stack className="mediaRequests-list-list" gap="xs" p="sm">
|
||||
{mediaRequests.map((mediaRequest) => (
|
||||
{data.items.map((mediaRequest) => (
|
||||
<MediaRequestCard
|
||||
key={`${mediaRequest.integrationId}-${mediaRequest.id}`}
|
||||
request={mediaRequest}
|
||||
@@ -89,6 +101,7 @@ export default function MediaServerWidget({
|
||||
</ScrollArea>
|
||||
</Box>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
}
|
||||
|
||||
const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => {
|
||||
@@ -110,7 +123,7 @@ const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[]
|
||||
};
|
||||
|
||||
interface MediaRequestCardProps {
|
||||
request: RouterOutputs["widget"]["mediaRequests"]["getLatestRequests"][number];
|
||||
request: RouterOutputs["widget"]["mediaRequests"]["getLatestRequestsWithProvenance"]["items"][number];
|
||||
isTiny: boolean;
|
||||
options: WidgetComponentProps<"mediaRequests-requestList">["options"];
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ import { openMediaRequestSearch } from "@homarr/spotlight";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetEmptyState } from "../../common/empty-state";
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../../common/query-state";
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import { NoIntegrationDataError } from "../../errors/no-data-integration";
|
||||
import classes from "./component.module.css";
|
||||
@@ -34,16 +36,30 @@ export default function MediaServerWidget({
|
||||
integrationIds,
|
||||
isEditMode,
|
||||
width,
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"mediaRequests-requestStats">) {
|
||||
const t = useScopedI18n("widget.mediaRequests-requestStats");
|
||||
const { data: requestStats } = clientApi.widget.mediaRequests.getStats.useQuery({
|
||||
const {
|
||||
data: requestStats,
|
||||
error,
|
||||
isPending,
|
||||
} = clientApi.widget.mediaRequests.getStatsWithProvenance.useQuery({
|
||||
integrationIds,
|
||||
});
|
||||
|
||||
const board = useRequiredBoard();
|
||||
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, requestStats !== undefined);
|
||||
if (!requestStats) return <WidgetEmptyState />;
|
||||
if (requestStats.users.length === 0 && requestStats.stats.length === 0) throw new NoIntegrationDataError();
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
failedIntegrationCount: requestStats.failedIntegrationCount,
|
||||
staleIntegrationCount: requestStats.staleIntegrationCount,
|
||||
});
|
||||
if (requestStats.users.length === 0 && requestStats.stats.length === 0 && !hasWarning) {
|
||||
throw new NoIntegrationDataError();
|
||||
}
|
||||
|
||||
const data = [
|
||||
{
|
||||
@@ -88,9 +104,23 @@ export default function MediaServerWidget({
|
||||
},
|
||||
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
const total = data.find((stat) => stat.name === "total")?.number ?? 0;
|
||||
const pending = data.find((stat) => stat.name === "pending")?.number ?? 0;
|
||||
|
||||
return (
|
||||
<WidgetMobileSummary
|
||||
value={total}
|
||||
label={t("titles.stats.total")}
|
||||
description={`${pending} ${t("titles.stats.pending")}`}
|
||||
isStale={hasWarning}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const isTiny = width < 256;
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<Box className={searchClasses.searchRoot}>
|
||||
{!isEditMode && <MediaRequestSearchButton integrationIds={integrationIds} />}
|
||||
<Stack
|
||||
@@ -173,6 +203,7 @@ export default function MediaServerWidget({
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
}
|
||||
|
||||
const MediaRequestSearchButton = ({ integrationIds }: { integrationIds: string[] }) => {
|
||||
|
||||
@@ -7,7 +7,12 @@ import { createWidgetDefinition } from "../../definition";
|
||||
|
||||
export const { componentLoader, definition } = createWidgetDefinition("mediaRequests-requestStats", {
|
||||
icon: IconChartBar,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: {
|
||||
width: 2,
|
||||
height: 1,
|
||||
supportsCompactSummary: true,
|
||||
supportsDetailView: true,
|
||||
},
|
||||
queryKey: [["widget", "mediaRequests"]],
|
||||
createOptions() {
|
||||
return {};
|
||||
|
||||
@@ -25,6 +25,7 @@ import type { TablerIcon } from "@homarr/ui";
|
||||
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
|
||||
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export default function MediaServerWidget({ displayMode, ...props }: WidgetComponentProps<"mediaServer">) {
|
||||
@@ -43,10 +44,9 @@ const MediaServerMobileSummary = ({
|
||||
});
|
||||
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
if (error && !data) throw error;
|
||||
throwOnInitialQueryError(error, data !== undefined);
|
||||
|
||||
const currentStreams = data ?? [];
|
||||
const hasPartialFailure = currentStreams.length < integrationIds.length;
|
||||
const playingSessions = currentStreams
|
||||
.flatMap((stream) => stream.sessions)
|
||||
.filter((session) => session.currentlyPlaying !== null);
|
||||
@@ -56,7 +56,11 @@ const MediaServerMobileSummary = ({
|
||||
value={playingSessions.length}
|
||||
label={t("items.currentlyPlaying")}
|
||||
description={playingSessions[0]?.currentlyPlaying?.name}
|
||||
isStale={Boolean(error) || hasPartialFailure}
|
||||
isStale={hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: currentStreams.length,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -65,10 +69,11 @@ const MediaServerTable = ({
|
||||
options,
|
||||
integrationIds,
|
||||
}: Pick<WidgetComponentProps<"mediaServer">, "options" | "integrationIds">) => {
|
||||
const { data: currentStreams = [] } = clientApi.widget.mediaServer.getCurrentStreams.useQuery({
|
||||
const { data: queryData, error } = clientApi.widget.mediaServer.getCurrentStreams.useQuery({
|
||||
integrationIds,
|
||||
showOnlyPlaying: options.showOnlyPlaying,
|
||||
});
|
||||
const currentStreams = queryData ?? [];
|
||||
|
||||
const t = useScopedI18n("widget.mediaServer");
|
||||
const columns = useMemo<MRT_ColumnDef<StreamSession>[]>(
|
||||
@@ -292,8 +297,14 @@ const MediaServerTable = ({
|
||||
integrationName: session?.integrationName,
|
||||
};
|
||||
});
|
||||
throwOnInitialQueryError(error, queryData !== undefined);
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: currentStreams.length,
|
||||
});
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<Stack gap={0} h="100%" display="flex">
|
||||
<MantineReactTable table={table} />
|
||||
<Group
|
||||
@@ -317,6 +328,7 @@ const MediaServerTable = ({
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
};
|
||||
|
||||
const ItemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useTimeAgo } from "@homarr/common";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export default function NotificationsWidget({
|
||||
@@ -38,17 +39,20 @@ export default function NotificationsWidget({
|
||||
[notificationIntegrations],
|
||||
);
|
||||
|
||||
if (displayMode === "mobileSummary") {
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
if (error && !notificationIntegrations) throw error;
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, notificationIntegrations !== undefined);
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: notificationIntegrations?.length,
|
||||
});
|
||||
|
||||
const notifications = notificationIntegrations ?? [];
|
||||
if (displayMode === "mobileSummary") {
|
||||
const latestNotification = sortedNotifications[0];
|
||||
const isStale = Boolean(error) || notifications.length < integrationIds.length;
|
||||
const summary = latestNotification ? (
|
||||
<NotificationMobileSummary notification={latestNotification} isStale={isStale} />
|
||||
<NotificationMobileSummary notification={latestNotification} isStale={hasWarning} />
|
||||
) : (
|
||||
<WidgetMobileSummary value={0} label={t("name")} description={t("noItems")} isStale={isStale} />
|
||||
<WidgetMobileSummary value={0} label={t("name")} description={t("noItems")} isStale={hasWarning} />
|
||||
);
|
||||
|
||||
if (!latestNotification?.href) return summary;
|
||||
@@ -68,7 +72,7 @@ export default function NotificationsWidget({
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<ScrollArea className="scroll-area-w100" w="100%" p="sm">
|
||||
<Stack w={"100%"} gap="sm">
|
||||
{sortedNotifications.length > 0 ? (
|
||||
@@ -117,6 +121,7 @@ export default function NotificationsWidget({
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
}
|
||||
|
||||
const NotificationMobileSummary = ({
|
||||
|
||||
@@ -5,7 +5,7 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("tracearr", {
|
||||
icon: IconActivityHeartbeat,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: { supportsDetailView: true, unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "tracearr"]],
|
||||
refetchInterval: 5,
|
||||
createOptions() {
|
||||
|
||||
@@ -8,7 +8,7 @@ export const timeFrameValues = ["today", "24h", "7d", "30d", "month", "lastMonth
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("umami", {
|
||||
icon: IconChartBar,
|
||||
mobile: { supportsDetailView: true },
|
||||
mobile: { supportsDetailView: true, unmountWhenOffscreen: true },
|
||||
queryKey: [["widget", "umami"]],
|
||||
refetchInterval: null,
|
||||
supportedIntegrations: ["umami"],
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetEmptyState } from "../common/empty-state";
|
||||
import { WidgetMobileLoading, WidgetMobileSummary } from "../common/mobile-summary";
|
||||
import { hasWidgetDataWarning, throwOnInitialQueryError, WidgetDataState } from "../common/query-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { NoIntegrationDataError } from "../errors/no-data-integration";
|
||||
import classes from "./component.module.css";
|
||||
@@ -117,11 +118,15 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
|
||||
} = clientApi.widget.uptimeKuma.getDashboard.useQuery({
|
||||
integrationIds,
|
||||
});
|
||||
const hasPartialFailure = (dashboardData?.length ?? 0) < integrationIds.length;
|
||||
|
||||
if (displayMode === "mobileSummary" && isPending) return <WidgetMobileLoading />;
|
||||
if (displayMode === "mobileSummary" && error && !dashboardData) throw error;
|
||||
if (isPending) return <WidgetMobileLoading />;
|
||||
throwOnInitialQueryError(error, dashboardData !== undefined);
|
||||
if (!dashboardData) return <WidgetEmptyState />;
|
||||
const hasWarning = hasWidgetDataWarning({
|
||||
error,
|
||||
expectedIntegrationCount: integrationIds.length,
|
||||
receivedIntegrationCount: dashboardData.length,
|
||||
});
|
||||
|
||||
const combined = dashboardData.reduce<UptimeKumaDashboardData>(
|
||||
(acc, item) => ({
|
||||
@@ -163,13 +168,13 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
|
||||
value={formatNumber(combined[primaryStat], 0)}
|
||||
label={t(`stats.${primaryStat}`)}
|
||||
description={supportingDescription}
|
||||
isStale={Boolean(error) || hasPartialFailure}
|
||||
isStale={hasWarning}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!hasContent) {
|
||||
return <WidgetMobileSummary value="—" label={t("name")} isStale={Boolean(error) || hasPartialFailure} />;
|
||||
return <WidgetMobileSummary value="—" label={t("name")} isStale={hasWarning} />;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -177,7 +182,7 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
|
||||
value={`${formatNumber(uptimeValue, 1)}%`}
|
||||
label={t("averageUptime")}
|
||||
description={supportingDescription}
|
||||
isStale={Boolean(error) || hasPartialFailure}
|
||||
isStale={hasWarning}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -186,7 +191,7 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
|
||||
heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats];
|
||||
const heroRingClass = heroVariantByRing[String(options.showUptimeRing) as keyof typeof heroVariantByRing];
|
||||
|
||||
return (
|
||||
const content = (
|
||||
<div className={classes.root}>
|
||||
{showHero && (
|
||||
<div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}>
|
||||
@@ -241,6 +246,7 @@ function UptimeKumaContent({ integrationIds, options, width, displayMode }: Upti
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return <WidgetDataState hasWarning={hasWarning}>{content}</WidgetDataState>;
|
||||
}
|
||||
|
||||
function clampPercent(value: number): number {
|
||||
|
||||
Reference in new issue
Block a user