merge: stack auto mobile boards

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

No files matched your search

+37 -17
View File
@@ -1,28 +1,48 @@
# Create T3 App
# Homarr web application
This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.
This workspace contains Homarr's Next.js application. It consumes the shared API, authentication, database, board,
widget, translation, and UI packages from this monorepo.
## What's next? How do I make an app with this?
Run commands from the repository root:
We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.
```sh
pnpm install --frozen-lockfile
cp .env.example .env
```
If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
Keep infrastructure running in the first terminal:
- [Next.js](https://nextjs.org)
- [NextAuth.js](https://next-auth.js.org)
- [Drizzle](https://orm.drizzle.team)
- [Tailwind CSS](https://tailwindcss.com)
- [tRPC](https://trpc.io)
```sh
pnpm docker:dev
```
## Learn More
Apply migrations and start the application in a second terminal:
To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources:
```sh
pnpm db:migration:sqlite:run
pnpm dev
```
- [Documentation](https://create.t3.gg/)
- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials
The app listens on `http://127.0.0.1:3000`. Configure an absolute writable `DB_URL`, `AUTH_SECRET`, and
`SECRET_ENCRYPTION_KEY` in `.env` before first startup.
You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome!
To test Custom Widgets against a local Community Workshop, start PocketBase and the docs in separate terminals:
## How do I deploy this?
```sh
pnpm docker:workshop
WORKSHOP_API_URL=http://127.0.0.1:8090 pnpm dev:docs
```
Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.
Then set:
```dotenv
HOMARR_WEBSITE_URL=http://127.0.0.1:3003
WORKSHOP_API_URL=http://127.0.0.1:8090
WORKSHOP_WEB_URL=http://127.0.0.1:3003/workshop
```
Server-rendered runtime configuration exposes those URLs to the browser, so changing a production container's
environment does not require rebuilding the Next.js bundle.
See [`apps/docs/docs/advanced/development/getting-started.mdx`](../docs/docs/advanced/development/getting-started.mdx)
for the full contributor setup.
+4
View File
@@ -79,6 +79,10 @@ const nextConfig: NextConfig = {
{
source: "/(.*)", // Apply CSP to all routes
headers: [
{
key: "Accept-CH",
value: "Sec-CH-Viewport-Width",
},
{
key: "Content-Security-Policy",
// worker-src / media-src with blob: is necessary for video.js, see https://github.com/homarr-labs/homarr/issues/3912 and https://stackoverflow.com/questions/65792855/problem-with-video-js-and-content-security-policy-csp
+7 -1
View File
@@ -14,8 +14,12 @@
"with-env": "dotenv -e ../../.env --"
},
"dependencies": {
"@dnd-kit/abstract": "catalog:",
"@dnd-kit/collision": "catalog:",
"@dnd-kit/core": "catalog:",
"@dnd-kit/dom": "catalog:",
"@dnd-kit/modifiers": "catalog:",
"@dnd-kit/react": "catalog:",
"@dnd-kit/sortable": "catalog:",
"@dnd-kit/utilities": "catalog:",
"@gfazioli/mantine-onboarding-tour": "catalog:",
@@ -26,12 +30,12 @@
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/cron-job-status": "workspace:^0.1.0",
"@homarr/custom-widgets": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/docker": "workspace:^0.1.0",
"@homarr/form": "workspace:^0.1.0",
"@homarr/forms-collection": "workspace:^0.1.0",
"@homarr/gridstack": "catalog:",
"@homarr/icons": "workspace:^0.1.0",
"@homarr/image-proxy": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0",
@@ -50,9 +54,11 @@
"@homarr/validation": "workspace:^0.1.0",
"@homarr/websocket": "workspace:^0.1.0",
"@homarr/widgets": "workspace:^0.1.0",
"@homarr/workshop": "workspace:^0.1.0",
"@mantine/colors-generator": "catalog:",
"@mantine/core": "catalog:",
"@mantine/dropzone": "catalog:",
"@mantine/form": "catalog:",
"@mantine/hooks": "catalog:",
"@mantine/modals": "catalog:",
"@mantine/tiptap": "catalog:",
@@ -1,84 +0,0 @@
"use client";
import { useCallback } from "react";
import { Group, Menu } from "@mantine/core";
import { IconBox, IconBoxAlignTop, IconChevronDown, IconPlug, IconPlus, IconResize } from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import { useModalAction } from "@homarr/modals";
import { AppSelectModal } from "@homarr/modals-collection";
import { useI18n } from "@homarr/translation/client";
import { useItemActions } from "~/components/board/items/item-actions";
import { ItemSelectModal } from "~/components/board/items/item-select-modal";
import { useCategoryActions } from "~/components/board/sections/category/category-actions";
import { CategoryEditModal } from "~/components/board/sections/category/category-edit-modal";
import { useDynamicSectionActions } from "~/components/board/sections/dynamic/dynamic-actions";
import { IntegrationSelectModal } from "~/components/integration/integration-select-modal";
import { HeaderButton } from "~/components/layout/header/button";
export const BoardAddMenu = () => {
const { data: session } = useSession();
const { openModal: openCategoryEditModal } = useModalAction(CategoryEditModal);
const { openModal: openItemSelectModal } = useModalAction(ItemSelectModal);
const { openModal: openAppSelectModal } = useModalAction(AppSelectModal);
const { openModal: openIntegrationSelectModal } = useModalAction(IntegrationSelectModal);
const { addCategoryToEnd } = useCategoryActions();
const { addDynamicSection } = useDynamicSectionActions();
const { createItem } = useItemActions();
const t = useI18n();
const handleAddCategory = useCallback(
() =>
openCategoryEditModal(
{
category: { id: "new", name: "" },
onSuccess({ name }) {
addCategoryToEnd({ name });
},
submitLabel: t("section.category.create.submit"),
},
{ title: (translate) => translate("section.category.create.title") },
),
[addCategoryToEnd, openCategoryEditModal, t],
);
return (
<Menu position="bottom-end">
<Menu.Target>
<HeaderButton w="auto" px={4}>
<Group gap={4} wrap="nowrap">
<IconPlus stroke={1.5} />
<IconChevronDown color="gray" size={16} />
</Group>
</HeaderButton>
</Menu.Target>
<Menu.Dropdown style={{ transform: "translate(-3px, 0)" }}>
<Menu.Item leftSection={<IconResize size={20} />} onClick={() => openItemSelectModal()}>
{t("item.action.create")}
</Menu.Item>
<Menu.Item
leftSection={<IconBox size={20} />}
onClick={() =>
openAppSelectModal({
onSelect: (app) => createItem({ kind: "app", options: { appId: app.id } }),
withCreate: session?.user.permissions.includes("app-create") ?? false,
})
}
>
{t("app.action.add")}
</Menu.Item>
<Menu.Item leftSection={<IconPlug size={20} />} onClick={() => openIntegrationSelectModal({})}>
{t("integration.action.create")}
</Menu.Item>
<Menu.Divider />
<Menu.Item leftSection={<IconBoxAlignTop size={20} />} onClick={handleAddCategory}>
{t("section.category.action.create")}
</Menu.Item>
<Menu.Item leftSection={<IconResize size={20} />} onClick={addDynamicSection}>
{t("section.dynamic.action.create")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
};
@@ -0,0 +1,22 @@
.columns {
display: grid;
align-items: start;
gap: 24px;
}
.lane {
min-width: 0;
}
.gutter {
position: relative;
top: 0;
align-self: start;
padding-top: 24px;
margin-top: -24px;
max-height: calc(100dvh - var(--app-shell-header-offset, 0px) - var(--mantine-spacing-md));
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
transform: translateY(var(--board-gutter-sticky-offset, 0px));
}
@@ -1,46 +1,189 @@
"use client";
import { useEffect, useState } from "react";
import { Box, Paper, Stack, Text } from "@mantine/core";
import { useCurrentLayout, useLayoutOverride, useRequiredBoard } from "@homarr/boards/context";
import { useCurrentLayout, useInitialViewportWidth, useLayoutOverride, useRequiredBoard } from "@homarr/boards/context";
import { useScopedI18n } from "@homarr/translation/client";
import { getRepresentativeLayoutWidth } from "../_layout-utils";
import { BoardCategorySection } from "~/components/board/sections/category-section";
import { BoardAdvancedFocusProvider } from "~/components/board/advanced-focus/context";
import {
getBoardLaneColumnCount,
getInitialBoardLogicalHeight,
getLogicalTrackSize,
LOGICAL_GRID_GAP,
getRootSectionForLane,
} from "~/components/board/layout";
import { ScaledBoardCanvas } from "~/components/board/layout/scaled-board-canvas";
import { BoardEmptySection } from "~/components/board/sections/empty-section";
import { BoardGridEditorBoundary } from "~/components/board/sections/grid/board-grid-editor-boundary";
import { BoardGridPortalHost, BoardGridPortalRenderer } from "~/components/board/sections/grid/grid-portal-host";
import { BoardSectionCollapseProvider } from "~/components/board/sections/section-collapse";
import { BoardBackgroundVideo } from "~/components/layout/background";
import classes from "./_client.module.css";
const APP_SHELL_INLINE_PADDING = 32;
const useFixedBoardGutters = () => {
const [columns, setColumns] = useState<HTMLDivElement | null>(null);
useEffect(() => {
if (!columns) return;
let frame = 0;
const update = () => {
frame = 0;
const columnsRect = columns.getBoundingClientRect();
const headerBottom = document.querySelector("[data-app-shell-header]")?.getBoundingClientRect().bottom ?? 0;
const stickyTop = Math.max(0, headerBottom + 16);
for (const gutter of columns.querySelectorAll<HTMLElement>("[data-board-gutter]")) {
const rect = gutter.getBoundingClientRect();
if (gutter.offsetWidth <= 0) continue;
const effectiveScale = rect.width / gutter.offsetWidth;
if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) continue;
const previousOffset = Number(gutter.dataset.stickyOffset ?? 0);
const uncorrectedTop = rect.top - previousOffset * effectiveScale;
const maximumTop = columnsRect.bottom - rect.height;
const targetTop = Math.min(stickyTop, maximumTop);
const nextOffset = Math.max(0, targetTop - uncorrectedTop) / effectiveScale;
gutter.dataset.stickyOffset = String(nextOffset);
gutter.style.setProperty("--board-gutter-sticky-offset", `${nextOffset}px`);
}
};
const scheduleUpdate = () => {
if (frame !== 0) return;
frame = window.requestAnimationFrame(update);
};
const resizeObserver = new ResizeObserver(scheduleUpdate);
resizeObserver.observe(columns);
document.addEventListener("scroll", scheduleUpdate, { capture: true, passive: true });
window.addEventListener("scroll", scheduleUpdate, { passive: true });
window.addEventListener("resize", scheduleUpdate, { passive: true });
scheduleUpdate();
return () => {
window.cancelAnimationFrame(frame);
resizeObserver.disconnect();
document.removeEventListener("scroll", scheduleUpdate, { capture: true });
window.removeEventListener("scroll", scheduleUpdate);
window.removeEventListener("resize", scheduleUpdate);
};
}, [columns]);
return setColumns;
};
export const ClientBoard = () => {
const board = useRequiredBoard();
const t = useScopedI18n("board.landmark");
const tPreview = useScopedI18n("board.setting.section.layout.preview");
const currentLayoutId = useCurrentLayout();
const initialViewportWidth = useInitialViewportWidth();
const layoutOverrideId = useLayoutOverride();
const columnsRef = useFixedBoardGutters();
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId) ?? board.layouts.at(0);
if (!currentLayout) throw new Error("Expected the board to contain a layout");
const fullWidthSortedSections = board.sections
.filter((section) => section.kind === "empty" || section.kind === "category")
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
const mainSection = getRootSectionForLane(board, "main");
const leftSection = getRootSectionForLane(board, "left");
const rightSection = getRootSectionForLane(board, "right");
if (!mainSection) throw new Error("Expected the board to contain a main canvas section");
const leftColumnCount = getBoardLaneColumnCount(currentLayout, "left");
const mainColumnCount = getBoardLaneColumnCount(currentLayout, "main");
const rightColumnCount = getBoardLaneColumnCount(currentLayout, "right");
const laneWidths = [leftColumnCount, mainColumnCount, rightColumnCount]
.filter((columnCount) => columnCount > 0)
.map(getLogicalTrackSize);
const logicalWidth =
laneWidths.reduce((total, width) => total + width, 0) + (laneWidths.length - 1) * LOGICAL_GRID_GAP;
const initialLogicalHeight = getInitialBoardLogicalHeight(board, currentLayoutId) + LOGICAL_GRID_GAP;
const representativeWidth = layoutOverrideId ? getRepresentativeLayoutWidth(currentLayout, board.layouts) : null;
const initialAvailableWidth = Math.max(1, (representativeWidth ?? initialViewportWidth) - APP_SHELL_INLINE_PADDING);
const gridTemplateColumns = [
leftColumnCount > 0 ? `${getLogicalTrackSize(leftColumnCount)}px` : null,
`${getLogicalTrackSize(mainColumnCount)}px`,
rightColumnCount > 0 ? `${getLogicalTrackSize(rightColumnCount)}px` : null,
]
.filter((value) => value !== null)
.join(" ");
const content = (
<Box h="100%" pos="relative" data-homarr-dev-benchmark-board>
<BoardBackgroundVideo />
<Stack h="100%">
{fullWidthSortedSections.map((section) =>
section.kind === "empty" ? (
<BoardEmptySection key={`${currentLayoutId}-${section.id}`} section={section} />
) : (
<BoardCategorySection key={`${currentLayoutId}-${section.id}`} section={section} />
),
)}
</Stack>
</Box>
<BoardAdvancedFocusProvider>
<Box h="100%" pos="relative" data-homarr-dev-benchmark-board>
<BoardBackgroundVideo />
<BoardSectionCollapseProvider>
<BoardGridPortalHost>
<ScaledBoardCanvas
logicalWidth={logicalWidth}
initialLogicalHeight={initialLogicalHeight}
initialAvailableWidth={initialAvailableWidth}
label={board.name}
>
<BoardGridEditorBoundary key={currentLayoutId}>
<BoardGridPortalRenderer />
<div
ref={columnsRef}
className={classes.columns}
style={{ gridTemplateColumns, paddingTop: LOGICAL_GRID_GAP }}
>
{leftColumnCount > 0 && leftSection && (
<aside
className={`${classes.lane} ${classes.gutter}`}
aria-label={t("leftRail")}
data-board-gutter="left"
>
<BoardEmptySection
key={`${currentLayoutId}-${leftSection.id}`}
section={leftSection}
columnCount={leftColumnCount}
requestedRowCount={0}
railPlacement="left"
/>
</aside>
)}
<section className={classes.lane} aria-label={t("canvas")}>
<BoardEmptySection
key={`${currentLayoutId}-${mainSection.id}`}
section={mainSection}
columnCount={mainColumnCount}
requestedRowCount={0}
/>
</section>
{rightColumnCount > 0 && rightSection && (
<aside
className={`${classes.lane} ${classes.gutter}`}
aria-label={t("rightRail")}
data-board-gutter="right"
>
<BoardEmptySection
key={`${currentLayoutId}-${rightSection.id}`}
section={rightSection}
columnCount={rightColumnCount}
requestedRowCount={0}
railPlacement="right"
/>
</aside>
)}
</div>
</BoardGridEditorBoundary>
</ScaledBoardCanvas>
</BoardGridPortalHost>
</BoardSectionCollapseProvider>
</Box>
</BoardAdvancedFocusProvider>
);
if (!layoutOverrideId) return content;
if (representativeWidth === null) return content;
const currentLayout = board.layouts.find((layout) => layout.id === currentLayoutId);
if (!currentLayout) return content;
const representativeWidth = getRepresentativeLayoutWidth(currentLayout, board.layouts);
return (
<Stack align="center" gap="xs" p="md" mih="100%">
<Text size="xs" c="dimmed" fw={500}>
@@ -2,9 +2,6 @@ import type { Metadata } from "next";
import { cache } from "react";
import { TRPCError } from "@trpc/server";
// Placed here because gridstack styles are used for board content
import "~/styles/gridstack.scss";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { makeQueryClient } from "@homarr/api/shared";
import { IntegrationProvider } from "@homarr/auth/client";
@@ -21,7 +18,7 @@ import { createMetaTitle } from "~/metadata";
import { env } from "~/env";
import { createBoardLayout } from "../_layout-creator";
import type { Board, Item } from "../_types";
import { DynamicClientBoard } from "./_dynamic-client";
import { ClientBoard } from "./_client";
import { BoardContentHeaderActions } from "./_header-actions";
const logger = createLogger({ module: "createBoardContentPage" });
@@ -76,7 +73,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<IntegrationProvider integrations={integrations}>
<DynamicClientBoard />
<ClientBoard />
</IntegrationProvider>
</HydrationBoundary>
);
@@ -1,24 +0,0 @@
"use client";
import dynamic from "next/dynamic";
import { SimpleGrid, Skeleton, Stack } from "@mantine/core";
const BoardLoadingShell = () => (
<Stack h="100%" p="md" aria-busy aria-label="Loading dashboard" role="status">
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
{[2, 1, 2, 2, 1, 2].map((rows, index) => (
<Skeleton
key={index}
data-homarr-dev-benchmark-board-shell
height={rows * 96}
radius="var(--mantine-radius-default)"
/>
))}
</SimpleGrid>
</Stack>
);
export const DynamicClientBoard = dynamic(() => import("./_client").then((mod) => mod.ClientBoard), {
ssr: false,
loading: BoardLoadingShell,
});
@@ -0,0 +1,79 @@
"use client";
import { Group, Menu } from "@mantine/core";
import { IconBox, IconChevronDown, IconLayoutGridAdd, IconPlug, IconPlus, IconResize } from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { useModalAction } from "@homarr/modals";
import { AppSelectModal } from "@homarr/modals-collection";
import { useI18n } from "@homarr/translation/client";
import { useItemActions } from "~/components/board/items/item-actions";
import { ItemSelectModal } from "~/components/board/items/item-select-modal";
import { useContainerActions } from "~/components/board/sections/container/container-actions";
import { IntegrationSelectModal } from "~/components/integration/integration-select-modal";
import { HeaderButton } from "~/components/layout/header/button";
export default function BoardEditActions() {
return <AddMenu />;
}
const AddMenu = () => {
const { data: session } = useSession();
const board = useRequiredBoard();
const { openModal: openItemSelectModal } = useModalAction(ItemSelectModal);
const { openModal: openAppSelectModal } = useModalAction(AppSelectModal);
const { openModal: openIntegrationSelectModal } = useModalAction(IntegrationSelectModal);
const { addContainer } = useContainerActions();
const { createItem } = useItemActions();
const t = useI18n();
const handleSelectItem = () => {
openItemSelectModal({ boardId: board.id });
};
const handleSelectApp = () => {
openAppSelectModal({
onSelect: (app) => {
createItem({
kind: "app",
options: { appId: app.id },
});
},
withCreate: session?.user.permissions.includes("app-create") ?? false,
});
};
const handleAddIntegration = () => {
openIntegrationSelectModal({});
};
return (
<Menu position="bottom-end">
<Menu.Target>
<HeaderButton w="auto" px={4} aria-label={t("board.action.addContent")}>
<Group gap={4} wrap="nowrap">
<IconPlus stroke={1.5} />
<IconChevronDown color="gray" size={16} />
</Group>
</HeaderButton>
</Menu.Target>
<Menu.Dropdown style={{ transform: "translate(-3px, 0)" }}>
<Menu.Item leftSection={<IconResize size={20} />} onClick={handleSelectItem}>
{t("item.action.create")}
</Menu.Item>
<Menu.Item leftSection={<IconBox size={20} />} onClick={handleSelectApp}>
{t("app.action.add")}
</Menu.Item>
<Menu.Item leftSection={<IconPlug size={20} />} onClick={handleAddIntegration}>
{t("integration.action.create")}
</Menu.Item>
<Menu.Divider />
<Menu.Item leftSection={<IconLayoutGridAdd size={20} />} onClick={addContainer}>
{t("section.container.action.create")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
};
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { startTransition, useCallback, useEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { useRouter, useSearchParams } from "next/navigation";
import { Box, Center, Loader, Menu, ScrollArea } from "@mantine/core";
@@ -10,7 +10,6 @@ import {
IconLayoutBoard,
IconPencil,
IconPencilOff,
IconPlus,
IconReplace,
IconSettings,
IconX,
@@ -28,22 +27,32 @@ import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { useBoardPermissions } from "~/components/board/permissions/client";
import { loadGridEditorAsync, scheduleGridEditorWarmup } from "~/components/board/sections/grid/grid-editor-loader";
import { HeaderButton } from "~/components/layout/header/button";
import { TourTarget } from "~/components/layout/header/tour-target";
import type * as EditActionsModule from "./_edit-actions";
const loadBoardAddMenu = () => import("./_board-add-menu");
const preloadBoardAddMenu = () => void loadBoardAddMenu().catch(() => undefined);
const BoardAddMenu = dynamic(() => loadBoardAddMenu().then(({ BoardAddMenu: AddMenu }) => AddMenu), {
loading: () => (
<HeaderButton loading>
<IconPlus stroke={1.5} />
</HeaderButton>
),
});
let editActionsModulePromise: Promise<typeof EditActionsModule> | undefined;
const loadEditActionsAsync = () => {
editActionsModulePromise ??= import("./_edit-actions").catch((error: unknown) => {
editActionsModulePromise = undefined;
throw error;
});
return editActionsModulePromise;
};
const loadBoardEditorAsync = async () =>
await Promise.all([
loadGridEditorAsync(),
loadEditActionsAsync(),
import("~/components/board/items/item-menu"),
import("~/components/board/sections/container/container-menu"),
]);
const BoardEditActions = dynamic(loadEditActionsAsync, { ssr: false });
export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const [isEditMode] = useEditMode();
const board = useRequiredBoard();
const t = useI18n();
const { hasChangeAccess } = useBoardPermissions(board);
if (!hasChangeAccess) {
@@ -52,13 +61,13 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool
return (
<>
{isEditMode && <BoardAddMenu />}
{isEditMode && <BoardEditActions />}
<EditModeMenu demoReadOnly={demoReadOnly} />
{!demoReadOnly && (
<TourTarget id="board-settings">
<HeaderButton href={`/boards/${board.name}/settings`}>
<HeaderButton href={`/boards/${board.name}/settings`} aria-label={t("board.action.settings")}>
<IconSettings stroke={1.5} />
</HeaderButton>
</TourTarget>
@@ -71,6 +80,8 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool
const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const [isEditMode, { open, close }] = useEditMode();
const [editorLoadState, setEditorLoadState] = useState<"scheduled" | "loading" | "ready" | "error">("scheduled");
const [isEnteringEditMode, setIsEnteringEditMode] = useState(false);
const board = useRequiredBoard();
const utils = clientApi.useUtils();
const router = useRouter();
@@ -83,6 +94,9 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
searchParams.get("edit") === "true" &&
searchParams.get("layout") !== null &&
searchParams.get("returnTo") === "settings";
const latestBoardRef = useRef(board);
latestBoardRef.current = board;
const { mutate: saveBoard, isPending } = clientApi.board.saveBoard.useMutation({
onSuccess() {
showSuccessNotification({
@@ -90,6 +104,7 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
message: t("notification.success.message"),
});
void utils.board.getBoardByName.invalidate({ name: board.name });
void utils.widget.customApi.getData.invalidate();
void revalidatePathActionAsync(`/boards/${board.name}`);
close();
if (returnToLayoutSettings) router.push(`/boards/${board.name}/settings?tab=layout`);
@@ -107,13 +122,55 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
close();
}, [utils, board.name, close]);
const toggle = useCallback(() => {
const prepareEditorAsync = useCallback(async () => {
if (editorLoadState === "ready") return;
setEditorLoadState("loading");
try {
await loadBoardEditorAsync();
setEditorLoadState("ready");
} catch {
setEditorLoadState("error");
throw new Error("Unable to load the board editor");
}
}, [editorLoadState]);
useEffect(() => {
return scheduleGridEditorWarmup(async () => {
setEditorLoadState("loading");
try {
await loadBoardEditorAsync();
setEditorLoadState("ready");
} catch {
setEditorLoadState("error");
}
});
}, []);
const prewarmEditor = useCallback(() => {
void prepareEditorAsync().catch(() => {
// A click or hotkey retries and reports the error.
});
}, [prepareEditorAsync]);
const toggle = useCallback(async () => {
if (isEditMode) {
if (demoReadOnly) return discardDemoChanges();
return saveBoard(board);
return saveBoard(latestBoardRef.current);
}
open();
}, [board, isEditMode, demoReadOnly, saveBoard, open, discardDemoChanges]);
setIsEnteringEditMode(true);
try {
await prepareEditorAsync();
startTransition(open);
} catch {
showErrorNotification({
title: t("notification.loadError.title"),
message: t("notification.loadError.message"),
});
} finally {
setIsEnteringEditMode(false);
}
}, [demoReadOnly, discardDemoChanges, isEditMode, open, prepareEditorAsync, saveBoard, t]);
const cancelLayoutEdit = useCallback(() => {
openConfirmModal({
@@ -130,7 +187,7 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
});
}, [board.name, close, commonT, openConfirmModal, router, utils.board.getBoardByName]);
useHotkeys([[hotkeys.toggleBoardEdit, toggle]]);
useHotkeys([[hotkeys.toggleBoardEdit, () => void toggle()]]);
usePreventLeaveWithDirty(isEditMode);
if (returnToLayoutSettings) {
@@ -157,10 +214,15 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
return (
<TourTarget id="board-edit-mode">
<HeaderButton
onClick={toggle}
loading={isPending}
onFocus={preloadBoardAddMenu}
onPointerEnter={preloadBoardAddMenu}
onClick={() => void toggle()}
onFocus={prewarmEditor}
onPointerEnter={prewarmEditor}
loading={isPending || isEnteringEditMode}
data-testid="board-edit-mode-toggle"
data-board-editor-preload-state={editorLoadState}
aria-busy={isPending || isEnteringEditMode}
aria-label={isEditMode ? (demoReadOnly ? t("exit") : t("save")) : t("enter")}
aria-pressed={isEditMode}
>
{isEditMode ? <IconPencilOff stroke={1.5} /> : <IconPencil stroke={1.5} />}
</HeaderButton>
@@ -169,6 +231,7 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
};
const SelectBoardsMenu = () => {
const t = useI18n();
const [isOpen, setIsOpen] = useState(false);
const utils = clientApi.useUtils();
const { data: boards = [], isPending } = clientApi.board.getAllBoards.useQuery(undefined, { enabled: isOpen });
@@ -179,7 +242,7 @@ const SelectBoardsMenu = () => {
<Box onFocus={preloadBoards} onPointerEnter={preloadBoards}>
<Menu position="bottom-end" opened={isOpen} onChange={setIsOpen}>
<Menu.Target>
<HeaderButton w="auto" px={4}>
<HeaderButton w="auto" px={4} aria-label={t("board.action.switch")}>
<IconReplace stroke={1.5} />
</HeaderButton>
</Menu.Target>
@@ -0,0 +1,54 @@
import { createElement, act } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { BoardIntegrationProvider } from "./_integration-provider";
const mocks = vi.hoisted(() => ({
providedIntegrations: undefined as unknown,
}));
vi.mock("@homarr/auth/client", async () => {
const React = await import("react");
return {
IntegrationProvider: ({ children, integrations }: { children: React.ReactNode; integrations: unknown }) => {
mocks.providedIntegrations = integrations;
return React.createElement(React.Fragment, null, children);
},
};
});
describe("board integration provider", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
mocks.providedIntegrations = undefined;
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
test("provides the permission-filtered server result without a second client query", () => {
const initialIntegrations = [{ id: "initial" }];
act(() => {
root.render(
createElement(
BoardIntegrationProvider,
{ initialIntegrations: initialIntegrations as never },
createElement("span", null, "board"),
),
);
});
expect(mocks.providedIntegrations).toBe(initialIntegrations);
});
});
@@ -0,0 +1,14 @@
"use client";
import type { PropsWithChildren } from "react";
import type { RouterOutputs } from "@homarr/api";
import { IntegrationProvider } from "@homarr/auth/client";
interface Props {
initialIntegrations: RouterOutputs["integration"]["all"];
}
export const BoardIntegrationProvider = ({ initialIntegrations, children }: PropsWithChildren<Props>) => {
return <IntegrationProvider integrations={initialIntegrations}>{children}</IntegrationProvider>;
};
@@ -8,10 +8,12 @@ import "~/styles/prismjs.scss";
import { IconInfoCircle } from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import type { UseFormReturnType } from "@homarr/form";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { SectionCard } from "~/components/manage/section-card";
import { WorkshopCssImportButton } from "~/components/workshop/workshop-css-import-button";
import type { FormValues } from "./_settings-form";
import classes from "./customcss.module.css";
@@ -20,6 +22,8 @@ interface Props {
}
export const CustomCssSettingsContent = ({ form }: Props) => {
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const t = useI18n();
const customCssT = useScopedI18n("board.field.customCss");
@@ -30,6 +34,7 @@ export const CustomCssSettingsContent = ({ form }: Props) => {
<Alert variant="light" color="cyan" title={customCssT("customClassesAlert.title")} icon={<IconInfoCircle />}>
{customCssT("customClassesAlert.description")}
</Alert>
{isAdmin && <WorkshopCssImportButton onImport={(css) => form.setFieldValue("customCss", css)} />}
</SectionCard>
);
};
@@ -59,7 +59,7 @@
}
}
.dynamicTile {
.containerTile {
border-style: dashed;
background: color-mix(in srgb, var(--mantine-color-default) 88%, var(--mantine-primary-color-light));
}
@@ -4,6 +4,7 @@ import { Badge, Box, Group, Stack, Text, ThemeIcon, Tooltip } from "@mantine/cor
import { IconLayoutGrid } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { MaskedOrNormalImage } from "@homarr/ui";
import { widgetCatalogIcons } from "@homarr/widgets/catalog";
@@ -17,7 +18,7 @@ interface Props {
board: Board;
layout: BoardLayout;
layouts: BoardLayout[];
sourceLayout: Pick<BoardLayout, "id" | "columnCount">;
sourceLayout: BoardLayout;
apps: RouterOutputs["app"]["byIds"];
}
@@ -31,8 +32,8 @@ export const LayoutPreview = ({ board, layout, layouts, sourceLayout, apps }: Pr
const previewWidth = `${(representativeWidth / largestRepresentativeWidth) * 100}%`;
const appsById = new Map(apps.map((app) => [app.id, app]));
const rootSections = board.sections
.filter((section) => section.kind !== "dynamic")
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset);
.filter((section) => section.kind === "empty")
.toSorted((sectionA, sectionB) => sectionA.xOffset - sectionB.xOffset);
return (
<Stack gap={6} align="center" w="100%">
@@ -53,18 +54,14 @@ export const LayoutPreview = ({ board, layout, layouts, sourceLayout, apps }: Pr
<Stack gap="xs">
{rootSections.map((section) => {
const sectionElements = elements.filter((element) => element.sectionId === section.id);
if (sectionElements.length === 0) return null;
const columnCount = getBoardLaneColumnCount(layout, getRootSectionLane(section.xOffset));
if (sectionElements.length === 0 || columnCount === 0) return null;
return (
<Stack key={section.id} gap={4} className={classes.section}>
{section.kind === "category" && (
<Text size="xs" fw={600}>
{section.name}
</Text>
)}
<Box
className={classes.grid}
style={{ gridTemplateColumns: `repeat(${layout.columnCount}, minmax(0, 1fr))` }}
style={{ gridTemplateColumns: `repeat(${columnCount}, minmax(0, 1fr))` }}
>
{sectionElements.map((element) => {
const item =
@@ -72,15 +69,15 @@ export const LayoutPreview = ({ board, layout, layouts, sourceLayout, apps }: Pr
const appId =
item?.kind === "app" && typeof item.options.appId === "string" ? item.options.appId : null;
const app = appId ? appsById.get(appId) : undefined;
const dynamicSection =
const container =
element.type === "section"
? board.sections.find((candidate) => candidate.id === element.id)
: undefined;
const dynamicSectionLabel =
dynamicSection?.kind === "dynamic" && dynamicSection.options.title
? dynamicSection.options.title
: t("board.setting.section.layout.preview.dynamicSection");
const label = app?.name ?? (item ? t(`widget.${item.kind}.name`) : dynamicSectionLabel);
const containerLabel =
container?.kind === "container" && container.options.title
? container.options.title
: t("section.container.untitled");
const label = app?.name ?? (item ? t(`widget.${item.kind}.name`) : containerLabel);
const WidgetIcon = item ? widgetCatalogIcons[item.kind] : IconLayoutGrid;
return (
@@ -88,7 +85,7 @@ export const LayoutPreview = ({ board, layout, layouts, sourceLayout, apps }: Pr
<Box
role="img"
aria-label={label}
className={`${classes.tile} ${element.type === "section" ? classes.dynamicTile : ""}`}
className={`${classes.tile} ${element.type === "section" ? classes.containerTile : ""}`}
style={{
gridColumn: `${element.xOffset + 1} / span ${element.width}`,
gridRow: `${element.yOffset + 1} / span ${element.height}`,
@@ -0,0 +1,47 @@
.gutterSettings {
background: color-mix(in srgb, var(--mantine-color-default) 55%, transparent);
}
.gutterPreview {
display: grid;
gap: 6px;
width: 100%;
min-height: 112px;
padding: 8px;
overflow: hidden;
background: var(--mantine-color-body);
border: 1px solid var(--mantine-color-default-border);
border-radius: var(--mantine-radius-md);
transition: grid-template-columns 180ms ease-out;
}
.previewCanvas {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
min-width: 0;
}
.previewCanvas > div,
.previewGutter {
background: var(--mantine-color-default);
border-radius: var(--mantine-radius-sm);
}
.previewCanvas > div:nth-child(1) {
grid-row: span 2;
}
.previewCanvas > div:nth-child(4) {
grid-column: span 2;
}
.previewGutter {
min-width: 12px;
}
@media (prefers-reduced-motion: reduce) {
.gutterPreview {
transition: none;
}
}
@@ -4,14 +4,17 @@ import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
Badge,
Box,
Button,
Fieldset,
Grid,
Group,
Input,
NumberInput,
Paper,
Slider,
Stack,
Switch,
Text,
TextInput,
} from "@mantine/core";
@@ -28,6 +31,7 @@ import { SectionCard } from "~/components/manage/section-card";
import type { Board } from "../../_types";
import { LayoutPreview } from "./_layout-preview";
import type { FormValues } from "./_settings-form";
import classes from "./_layout.module.css";
interface Props {
board: Board;
@@ -130,6 +134,8 @@ export const LayoutSettingsContent = ({ board, form, isSaving, saveSettingsAsync
id: createId(),
name: t("board.setting.section.layout.custom.defaultName"),
columnCount: baseLayout.columnCount,
leftGutterColumnCount: baseLayout.leftGutterColumnCount,
rightGutterColumnCount: baseLayout.rightGutterColumnCount,
breakpoint: nextBreakpoint,
role: "custom",
},
@@ -176,7 +182,14 @@ export const LayoutSettingsContent = ({ board, form, isSaving, saveSettingsAsync
styles={{
markLabel: { color: "light-dark(var(--mantine-color-black), var(--mantine-color-white))" },
}}
{...form.getInputProps(`layouts.${index}.columnCount`)}
value={layout.columnCount}
onChange={(columnCount) => {
const left = Math.min(layout.leftGutterColumnCount, Math.max(0, columnCount - 1));
const right = Math.min(layout.rightGutterColumnCount, Math.max(0, columnCount - left - 1));
form.setFieldValue(`layouts.${index}.columnCount`, columnCount);
form.setFieldValue(`layouts.${index}.leftGutterColumnCount`, left);
form.setFieldValue(`layouts.${index}.rightGutterColumnCount`, right);
}}
/>
</Input.Wrapper>
<NumberInput
@@ -196,6 +209,13 @@ export const LayoutSettingsContent = ({ board, form, isSaving, saveSettingsAsync
}
max={layout.role === "custom" ? baseBreakpoint - 1 : 32767}
/>
<GutterSettings
left={layout.leftGutterColumnCount}
right={layout.rightGutterColumnCount}
columnCount={layout.columnCount}
onLeftChange={(value) => form.setFieldValue(`layouts.${index}.leftGutterColumnCount`, value)}
onRightChange={(value) => form.setFieldValue(`layouts.${index}.rightGutterColumnCount`, value)}
/>
</Stack>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 8 }}>
@@ -282,3 +302,123 @@ const getNextCustomBreakpoint = (layouts: Array<{ breakpoint: number }>) => {
return largestGap ? Math.floor((largestGap.start + largestGap.end) / 2) : null;
};
interface GutterSettingsProps {
left: number;
right: number;
columnCount: number;
onLeftChange: (value: number) => void;
onRightChange: (value: number) => void;
}
const gutterMarks = [
{ value: 1, label: "1" },
{ value: 2, label: "2" },
{ value: 3, label: "3" },
];
const GutterSettings = ({ left, right, columnCount, onLeftChange, onRightChange }: GutterSettingsProps) => {
const t = useI18n();
const maxGutterWidth = Math.min(3, Math.max(1, columnCount - 1));
return (
<Paper className={classes.gutterSettings} p="md">
<Stack gap="md">
<Box>
<Text fw={600}>{t("layout.field.gutters.label")}</Text>
<Text size="sm" c="dimmed">
{t("layout.field.gutters.description")}
</Text>
</Box>
<GutterPreview left={left} right={right} columnCount={columnCount} />
<Grid>
<Grid.Col span={{ base: 12, md: 6 }}>
<GutterControl
side="left"
value={left}
max={Math.min(maxGutterWidth, columnCount - right - 1)}
onChange={onLeftChange}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<GutterControl
side="right"
value={right}
max={Math.min(maxGutterWidth, columnCount - left - 1)}
onChange={onRightChange}
/>
</Grid.Col>
</Grid>
</Stack>
</Paper>
);
};
const GutterControl = ({
side,
value,
max,
onChange,
}: {
side: "left" | "right";
value: number;
max: number;
onChange: (value: number) => void;
}) => {
const t = useI18n();
const enabled = value > 0;
return (
<Stack gap="sm">
<Switch
checked={enabled}
disabled={max < 1}
onChange={(event) => onChange(event.currentTarget.checked ? Math.min(2, max) : 0)}
label={t(`layout.field.gutters.${side}.label`)}
description={t(`layout.field.gutters.${side}.description`)}
/>
{enabled && (
<Input.Wrapper label={t("layout.field.gutters.width.label")}>
<Slider
mt="xs"
min={1}
max={max}
value={Math.min(value, max)}
marks={gutterMarks.filter((mark) => mark.value <= max)}
restrictToMarks
thumbLabel={t(`layout.field.gutters.${side}.thumbLabel`)}
onChange={(nextValue) => onChange(Math.min(nextValue, max))}
/>
</Input.Wrapper>
)}
</Stack>
);
};
const GutterPreview = ({ left, right, columnCount }: { left: number; right: number; columnCount: number }) => {
const t = useI18n();
const safeColumnCount = Math.max(1, columnCount);
const main = Math.max(1, safeColumnCount - left - right);
const tracks = [left > 0 ? `${left}fr` : null, `${main}fr`, right > 0 ? `${right}fr` : null]
.filter((track) => track !== null)
.join(" ");
return (
<Box
className={classes.gutterPreview}
aria-label={t("layout.field.gutters.preview.label")}
style={{ gridTemplateColumns: tracks }}
>
{left > 0 && <Box className={classes.previewGutter} data-side="left" />}
<Box className={classes.previewCanvas}>
<Box />
<Box />
<Box />
<Box />
</Box>
{right > 0 && <Box className={classes.previewGutter} data-side="right" />}
</Box>
);
};
@@ -1,4 +1,5 @@
import type { JSX, PropsWithChildren } from "react";
import { cookies, headers } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { AppShellMain } from "@mantine/core";
import { TRPCError } from "@trpc/server";
@@ -6,7 +7,9 @@ import { TRPCError } from "@trpc/server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
import { auth } from "@homarr/auth/next";
import { constructBoardPermissions } from "@homarr/auth/shared";
import { boardViewportWidthCookieName, getLayoutIdForViewportWidth } from "@homarr/boards/layout-selection";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ModalProvider } from "@homarr/modals";
import { MainHeader } from "~/components/layout/header";
import { BoardLogoWithTitle } from "~/components/layout/logo/board-logo";
@@ -47,6 +50,7 @@ export const createBoardLayout = <TParams extends Params>({
(error: unknown) => ({ status: "rejected", error }) as const,
);
const colorSchemePromise = getCurrentColorSchemeAsync();
const initialViewportWidthPromise = getInitialViewportWidthAsync();
const shouldRunBoardTourPromise = sessionPromise.then(async (session) => {
if (!withTour || !session || env.DEMO_MODE) return false;
@@ -58,11 +62,12 @@ export const createBoardLayout = <TParams extends Params>({
return false;
}
});
const [session, initialBoardResult, colorScheme, shouldRunBoardTour] = await Promise.all([
const [session, initialBoardResult, colorScheme, shouldRunBoardTour, initialViewportWidth] = await Promise.all([
sessionPromise,
initialBoardPromise,
colorSchemePromise,
shouldRunBoardTourPromise,
initialViewportWidthPromise,
]);
if (initialBoardResult.status === "rejected") {
const { error } = initialBoardResult;
@@ -84,22 +89,30 @@ export const createBoardLayout = <TParams extends Params>({
}
const initialBoard = initialBoardResult.board;
const { hasChangeAccess } = constructBoardPermissions(initialBoard, session);
const initialLayoutId = getLayoutIdForViewportWidth(initialBoard.layouts, initialViewportWidth);
return (
<BoardProviders initialBoard={initialBoard} canModify={hasChangeAccess}>
<BoardProviders
initialBoard={initialBoard}
initialLayoutId={initialLayoutId}
initialViewportWidth={initialViewportWidth}
canModify={hasChangeAccess}
>
<BoardReadyProvider>
<BoardMantineProvider defaultColorScheme={colorScheme}>
<CustomCss />
<BoardTourGate enabled={shouldRunBoardTour}>
<ClientShell hasNavigation={false}>
<MainHeader
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
actions={headerActions}
hasNavigation={false}
/>
<AppShellMain>{children}</AppShellMain>
</ClientShell>
</BoardTourGate>
<ModalProvider>
<CustomCss />
<BoardTourGate enabled={shouldRunBoardTour}>
<ClientShell hasNavigation={false}>
<MainHeader
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
actions={headerActions}
hasNavigation={false}
/>
<AppShellMain data-advanced-focus-background>{children}</AppShellMain>
</ClientShell>
</BoardTourGate>
</ModalProvider>
</BoardMantineProvider>
</BoardReadyProvider>
</BoardProviders>
@@ -108,3 +121,22 @@ export const createBoardLayout = <TParams extends Params>({
return Layout;
};
const getInitialViewportWidthAsync = async () => {
const cookieValue = (await cookies()).get(boardViewportWidthCookieName)?.value;
const cookieWidth = Number(cookieValue);
if (Number.isInteger(cookieWidth) && cookieWidth >= 200 && cookieWidth <= 10_000) {
return cookieWidth;
}
const requestHeaders = await headers();
const clientHintWidth = Number(requestHeaders.get("sec-ch-viewport-width"));
if (Number.isInteger(clientHintWidth) && clientHintWidth >= 200 && clientHintWidth <= 10_000) {
return clientHintWidth;
}
const userAgent = requestHeaders.get("user-agent") ?? "";
if (/iPad|Tablet|PlayBook|Silk/i.test(userAgent)) return 1024;
if (/Mobi|Android|iPhone|iPod|IEMobile|Opera Mini/i.test(userAgent)) return 390;
return 1440;
};
@@ -1,14 +1,38 @@
import { describe, expect, test } from "vitest";
import { BoardMockBuilder } from "~/components/board/items/actions/test/mocks/board-mock";
import { DynamicSectionMockBuilder } from "~/components/board/items/actions/test/mocks/dynamic-section-mock";
import { ContainerSectionMockBuilder } from "~/components/board/items/actions/test/mocks/container-section-mock";
import { EmptySectionMockBuilder } from "~/components/board/items/actions/test/mocks/empty-section-mock";
import { ItemMockBuilder } from "~/components/board/items/actions/test/mocks/item-mock";
import { getRepresentativeLayoutWidth, projectBoardLayout } from "./_layout-utils";
const mobile = { id: "mobile", name: "Mobile", columnCount: 3, breakpoint: 0, role: "mobile" as const };
const custom = { id: "tablet", name: "Tablet", columnCount: 6, breakpoint: 480, role: "custom" as const };
const base = { id: "base", name: "Base", columnCount: 12, breakpoint: 768, role: "base" as const };
const mobile = {
id: "mobile",
name: "Mobile",
columnCount: 3,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 0,
role: "mobile" as const,
};
const custom = {
id: "tablet",
name: "Tablet",
columnCount: 6,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 480,
role: "custom" as const,
};
const base = {
id: "base",
name: "Base",
columnCount: 12,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 768,
role: "base" as const,
};
describe("layout representative widths", () => {
test("uses a phone width, activation midpoint, and desktop minimum", () => {
@@ -22,30 +46,30 @@ describe("layout representative widths", () => {
describe("projectBoardLayout", () => {
test("returns exact saved positions without recursively re-projecting the active layout", () => {
const rootSection = new EmptySectionMockBuilder({ id: "root" }).build();
const dynamicSection = new DynamicSectionMockBuilder({ id: "dynamic" })
const container = new ContainerSectionMockBuilder({ id: "container" })
.addLayout({ layoutId: mobile.id, parentSectionId: rootSection.id, width: 3, height: 2 })
.build();
const board = new BoardMockBuilder().addLayout(mobile).addSections([rootSection, dynamicSection]).build();
const board = new BoardMockBuilder().addLayout(mobile).addSections([rootSection, container]).build();
expect(projectBoardLayout(board, mobile, mobile)).toEqual([
expect.objectContaining({ id: dynamicSection.id, sectionId: rootSection.id, width: 3, height: 2 }),
expect.objectContaining({ id: container.id, sectionId: rootSection.id, width: 3, height: 2 }),
]);
});
test("uses production ordering and sizing for items and dynamic sections", () => {
test("uses production ordering and sizing for items and containers", () => {
const rootSection = new EmptySectionMockBuilder({ id: "root" }).build();
const dynamicSection = new DynamicSectionMockBuilder({ id: "dynamic" })
const container = new ContainerSectionMockBuilder({ id: "container" })
.addLayout({ layoutId: base.id, parentSectionId: rootSection.id, width: 6, height: 3, xOffset: 6, yOffset: 0 })
.build();
const rootItem = new ItemMockBuilder({ id: "root-item", kind: "clock" })
.addLayout({ layoutId: base.id, sectionId: rootSection.id, width: 5, height: 2, xOffset: 0, yOffset: 0 })
.build();
const nestedItem = new ItemMockBuilder({ id: "nested-item", kind: "clock" })
.addLayout({ layoutId: base.id, sectionId: dynamicSection.id, width: 4, height: 1, xOffset: 0, yOffset: 0 })
.addLayout({ layoutId: base.id, sectionId: container.id, width: 4, height: 1, xOffset: 0, yOffset: 0 })
.build();
const board = new BoardMockBuilder()
.addLayout(mobile)
.addSections([rootSection, dynamicSection])
.addSections([rootSection, container])
.addItems([rootItem, nestedItem])
.build();
@@ -59,7 +83,7 @@ describe("projectBoardLayout", () => {
yOffset: 0,
sectionId: rootSection.id,
});
expect(projected.find((element) => element.id === dynamicSection.id)).toMatchObject({
expect(projected.find((element) => element.id === container.id)).toMatchObject({
type: "section",
width: 3,
xOffset: 0,
@@ -69,7 +93,7 @@ describe("projectBoardLayout", () => {
expect(projected.find((element) => element.id === nestedItem.id)).toMatchObject({
type: "item",
width: 3,
sectionId: dynamicSection.id,
sectionId: container.id,
});
});
@@ -1,9 +1,12 @@
import { generateResponsiveGridFor } from "@homarr/common";
import type { GridAlgorithmItem } from "@homarr/common";
import type { BoardLane } from "@homarr/definitions";
import { boardLanes, getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
import type { Board } from "./_types";
export type BoardLayout = Board["layouts"][number];
type LayoutGeometry = Pick<BoardLayout, "id" | "columnCount" | "leftGutterColumnCount" | "rightGutterColumnCount">;
export const getRepresentativeLayoutWidth = (layout: BoardLayout, allLayouts: BoardLayout[]) => {
if (layout.role === "mobile") return 390;
@@ -17,28 +20,69 @@ export const getRepresentativeLayoutWidth = (layout: BoardLayout, allLayouts: Bo
return nextLayout ? Math.round((layout.breakpoint + nextLayout.breakpoint) / 2) : Math.max(1280, layout.breakpoint);
};
export const projectBoardLayout = (
board: Board,
sourceLayout: Pick<BoardLayout, "id" | "columnCount">,
targetLayout: Pick<BoardLayout, "id" | "columnCount">,
) => {
export const projectBoardLayout = (board: Board, sourceLayout: LayoutGeometry, targetLayout: LayoutGeometry) => {
const elements = getElementsForLayout(board, sourceLayout.id);
if (sourceLayout.id === targetLayout.id && sourceLayout.columnCount === targetLayout.columnCount) {
if (
sourceLayout.id === targetLayout.id &&
sourceLayout.columnCount === targetLayout.columnCount &&
sourceLayout.leftGutterColumnCount === targetLayout.leftGutterColumnCount &&
sourceLayout.rightGutterColumnCount === targetLayout.rightGutterColumnCount
) {
return elements;
}
return board.sections
.filter((section) => section.kind !== "dynamic")
.flatMap(
(section) =>
generateResponsiveGridFor({
items: elements,
previousWidth: sourceLayout.columnCount,
width: targetLayout.columnCount,
sectionId: section.id,
}).items,
const emptyRoots = board.sections
.filter((section) => section.kind === "empty")
.toSorted((first, second) => first.xOffset - second.xOffset || first.id.localeCompare(second.id));
const rootByLane = new Map<BoardLane, (typeof emptyRoots)[number]>();
for (const root of emptyRoots) {
const lane = getRootSectionLane(root.xOffset);
if (!rootByLane.has(lane)) rootByLane.set(lane, root);
}
const mainRoot = rootByLane.get("main");
if (!mainRoot) return [];
const sourceRootById = new Map(
emptyRoots.map((section) => [section.id, getRootSectionLane(section.xOffset)] as const),
);
const targetLaneBySourceLane = new Map<BoardLane, BoardLane>(
boardLanes.map((lane) => [
lane,
lane !== "main" && getBoardLaneColumnCount(targetLayout, lane) === 0 ? "main" : lane,
]),
);
const remappedElements = elements.map((element) => {
const sourceLane = sourceRootById.get(element.sectionId);
if (!sourceLane) return element;
const targetLane = targetLaneBySourceLane.get(sourceLane) ?? "main";
return { ...element, sectionId: (rootByLane.get(targetLane) ?? mainRoot).id };
});
return boardLanes.flatMap((lane) => {
const root = rootByLane.get(lane);
const width = getBoardLaneColumnCount(targetLayout, lane);
if (!root || width === 0) return [];
const sourceLanes = boardLanes.filter(
(sourceLane) =>
rootByLane.has(sourceLane) &&
getBoardLaneColumnCount(sourceLayout, sourceLane) > 0 &&
targetLaneBySourceLane.get(sourceLane) === lane,
);
const previousWidth =
sourceLanes.length === 1
? getBoardLaneColumnCount(sourceLayout, sourceLanes[0] ?? "main")
: Number.MAX_SAFE_INTEGER;
return generateResponsiveGridFor({
items: remappedElements,
previousWidth,
width,
sectionId: root.id,
}).items;
});
};
const getElementsForLayout = (board: Board, layoutId: string): GridAlgorithmItem[] => [
@@ -59,7 +103,7 @@ const getElementsForLayout = (board: Board, layoutId: string): GridAlgorithmItem
: [];
}),
...board.sections.flatMap((section) => {
if (section.kind !== "dynamic") return [];
if (section.kind !== "container") return [];
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
return layout?.parentSectionId
? [
@@ -11,10 +11,18 @@ import type { Board } from "./_types";
interface Props {
initialBoard: Board;
initialLayoutId: string;
initialViewportWidth: number;
canModify: boolean;
}
export const BoardProviders = ({ children, initialBoard, canModify }: PropsWithChildren<Props>) => {
export const BoardProviders = ({
children,
initialBoard,
initialLayoutId,
initialViewportWidth,
canModify,
}: PropsWithChildren<Props>) => {
const searchParams = useSearchParams();
const isDesktop = useMediaQuery("(min-width: 64em)");
const requestedLayoutId = searchParams.get("layout");
@@ -23,7 +31,12 @@ export const BoardProviders = ({ children, initialBoard, canModify }: PropsWithC
const layoutOverrideId = isLayoutEditRequest && isDesktop ? requestedLayoutId : null;
return (
<BoardProvider initialBoard={initialBoard} layoutOverrideId={layoutOverrideId}>
<BoardProvider
initialBoard={initialBoard}
initialLayoutId={initialLayoutId}
initialViewportWidth={initialViewportWidth}
layoutOverrideId={layoutOverrideId}
>
<EditModeProvider initialOpen={isLayoutEditRequest}>{children}</EditModeProvider>
</BoardProvider>
);
@@ -7,10 +7,9 @@ export type Item = Board["items"][number];
export type ItemLayout = Item["layouts"][number];
export type SectionItem = Omit<Item, "layouts"> & ItemLayout & { type: "item" };
export type CategorySection = Extract<Section, { kind: "category" }>;
export type EmptySection = Extract<Section, { kind: "empty" }>;
export type DynamicSection = Extract<Section, { kind: "dynamic" }>;
export type DynamicSectionLayout = DynamicSection["layouts"][number];
export type DynamicSectionItem = Omit<DynamicSection, "layouts"> & DynamicSectionLayout & { type: "section" };
export type ContainerSection = Extract<Section, { kind: "container" }>;
export type ContainerSectionLayout = ContainerSection["layouts"][number];
export type ContainerSectionItem = Omit<ContainerSection, "layouts"> & ContainerSectionLayout & { type: "section" };
export type ItemOfKind<TKind extends WidgetKind> = Extract<Item, { kind: TKind }>;
@@ -0,0 +1,148 @@
"use client";
import { useEffect, useState } from "react";
import {
Alert,
Button,
Card,
Center,
PasswordInput,
Select,
Stack,
Text,
TextInput,
ThemeIcon,
Title,
} from "@mantine/core";
import { IconCheck, IconKey, IconLock } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
interface RequestDetails {
widgetName: string;
sourceName: string;
kinds: Array<"apiKey" | "username" | "password">;
expiresAt: number;
status: "pending" | "completed";
source: {
baseUrl: string;
networkScope: "public" | "private" | "loopback";
};
}
export function CustomWidgetConfigurationEntry({ token }: { token: string }) {
const t = useScopedI18n("customWidget.secretEntry");
const [details, setDetails] = useState<RequestDetails | null>(null);
const [values, setValues] = useState<Record<string, string>>({});
const [baseUrl, setBaseUrl] = useState("");
const [networkScope, setNetworkScope] = useState<"public" | "private" | "loopback">("public");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
void fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`)
.then(async (response) => {
const body = (await response.json()) as RequestDetails | { error: string };
if (!response.ok || "error" in body) throw new Error("error" in body ? body.error : t("unavailable"));
setDetails(body);
setBaseUrl(body.source.baseUrl);
setNetworkScope(body.source.networkScope);
})
.catch((cause: unknown) => setError(cause instanceof Error ? cause.message : t("unavailable")))
.finally(() => setLoading(false));
}, [t, token]);
const submit = async () => {
setSaving(true);
setError(null);
try {
const response = await fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ baseUrl, networkScope, secrets: values }),
});
const body = (await response.json()) as { status?: string; error?: string };
if (!response.ok) throw new Error(body.error ?? t("saveError"));
setDetails((current) => (current ? { ...current, status: "completed" } : current));
setValues({});
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("saveError"));
} finally {
setSaving(false);
}
};
return (
<Center mih="100dvh" p="md">
<Card withBorder shadow="md" radius="lg" p="xl" w="100%" maw={480}>
<Stack gap="lg">
<ThemeIcon size={48} radius="xl" variant="light">
<IconLock size={24} />
</ThemeIcon>
<Stack gap={4}>
<Title order={1} size="h2">
{t("title")}
</Title>
<Text c="dimmed">{t("description")}</Text>
</Stack>
{loading && <Text c="dimmed">{t("loading")}</Text>}
{error && <Alert color="red">{error}</Alert>}
{details?.status === "completed" && (
<Alert color="green" icon={<IconCheck size={18} />}>
{t("saved")}
</Alert>
)}
{details?.status === "pending" && (
<Stack gap="md">
<Card withBorder bg="var(--mantine-color-default-hover)">
<Text fw={600}>{details.widgetName}</Text>
<Text size="sm" c="dimmed">
{t("source", { name: details.sourceName })}
</Text>
</Card>
<TextInput
label={t("baseUrl")}
type="url"
value={baseUrl}
onChange={(event) => setBaseUrl(event.currentTarget.value)}
required
/>
<Select
label={t("networkScope")}
data={["public", "private", "loopback"]}
value={networkScope}
allowDeselect={false}
onChange={(value) => value && setNetworkScope(value as typeof networkScope)}
/>
{details.kinds.map((kind) => {
const Input = kind === "username" ? TextInput : PasswordInput;
return (
<Input
key={kind}
label={t(`field.${kind}`)}
leftSection={<IconKey size={16} />}
value={values[kind] ?? ""}
onChange={(event) => setValues((current) => ({ ...current, [kind]: event.currentTarget.value }))}
autoComplete="off"
required
/>
);
})}
<Button
loading={saving}
disabled={!URL.canParse(baseUrl) || details.kinds.some((kind) => !values[kind])}
onClick={() => void submit()}
>
{t("save")}
</Button>
<Text size="xs" c="dimmed">
{t("expires", { time: new Date(details.expiresAt).toLocaleTimeString() })}
</Text>
</Stack>
)}
</Stack>
</Card>
</Center>
);
}
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { auth } from "@homarr/auth/next";
import { CustomWidgetConfigurationEntry } from "./configuration-entry";
export const metadata: Metadata = {
title: "Configure custom widget API source",
robots: { index: false, follow: false },
};
export default async function CustomWidgetConfigurationPage({ params }: { params: Promise<{ token: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
const { token } = await params;
return <CustomWidgetConfigurationEntry token={token} />;
}
+14 -3
View File
@@ -13,9 +13,9 @@ import { notFound } from "next/navigation";
import type { DayOfWeek } from "@mantine/dates";
import { NextIntlClientProvider } from "next-intl";
import { env as authEnv } from "@homarr/auth/env";
import { getRscServerSettingsAsync } from "@homarr/api/server-settings-server";
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ModalProvider } from "@homarr/modals";
@@ -24,12 +24,15 @@ import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight";
import type { SupportedLanguage } from "@homarr/translation";
import { isLocaleRTL, isLocaleSupported } from "@homarr/translation";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { Analytics } from "~/components/layout/analytics";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
import { env } from "~/env";
import { SearchEngineOptimization } from "~/components/layout/search-engine-optimization";
import { ServiceWorkerRegistration } from "~/components/layout/service-worker-registration";
import { ViewportHint } from "~/components/layout/viewport-hint";
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
import { DayJsLoader } from "./_client-providers/dayjs-loader";
import { JotaiProvider } from "./_client-providers/jotai";
@@ -54,7 +57,7 @@ export const generateMetadata = async (): Promise<Metadata> => ({
title: "Homarr Dashboard",
description:
"A self-hosted dashboard for the *arr stack and your entire homelab. Integrates with 50+ services, real-time widgets, no config files.",
url: "https://homarr.dev",
url: env.HOMARR_WEBSITE_URL,
siteName: "Homarr",
},
icons: {
@@ -101,10 +104,15 @@ export default async function Layout(props: {
getCurrentColorSchemeAsync(),
]);
const direction = isLocaleRTL(locale) ? "rtl" : "ltr";
const publicUrls = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
const StackedProvider = composeWrappers([
(innerProps) => {
return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />;
return <AuthProvider session={session} logoutUrl={authEnv.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />;
},
(innerProps) => (
<SettingsProvider
@@ -151,11 +159,14 @@ export default async function Layout(props: {
suppressHydrationWarning
>
<head>
<meta name="homarr-website-url" content={publicUrls.homarrWebsiteUrl} />
<meta name="homarr-workshop-api-url" content={publicUrls.workshopApiUrl} />
<SearchEngineOptimization />
<CrowdinLiveTranslation locale={locale} />
</head>
<body className={[fontSans.className, fontSans.variable].join(" ")} suppressHydrationWarning>
<Analytics enabled={serverSettings.analytics.enableGeneral} />
<ViewportHint />
<StackedProvider>
<Notifications pauseResetOnHover="notification" />
<ServiceWorkerRegistration />
@@ -1,18 +1,23 @@
"use client";
import { Alert, Anchor, Text } from "@mantine/core";
import { IconFlask } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
const FEEDBACK_URL = "https://github.com/homarr-labs/homarr/discussions/categories/custom-widgets";
export function CustomWidgetBetaBanner() {
const t = useScopedI18n("customWidget.betaBanner");
return (
<Alert variant="light" color="yellow" title="Custom Widgets are in Beta" icon={<IconFlask />}>
<Alert variant="light" color="yellow" title={t("title")} icon={<IconFlask />}>
<Text size="sm">
This feature is experimental and will probably change a lot in the future. If you encounter bugs, wish it did
more, or find something confusing, then please complain to us as much as possible! Only feedback posted on the{" "}
{t("description")}{" "}
<Anchor href={FEEDBACK_URL} target="_blank" fw={600}>
official discussion thread
{t("discussionLink")}
</Anchor>{" "}
will be taken into account. Happy Hacking!
{t("closing")}
</Text>
</Alert>
);
@@ -0,0 +1,48 @@
"use client";
import type { ComponentProps } from "react";
import { CustomWidgetCodeEditor } from "@homarr/custom-widgets/workbench";
import { useScopedI18n } from "@homarr/translation/client";
type SharedEditorProps = ComponentProps<typeof CustomWidgetCodeEditor>;
type CodeEditorProps = Omit<SharedEditorProps, "messages">;
export function CodeEditor(props: CodeEditorProps) {
const t = useScopedI18n("customWidget.editor");
return (
<CustomWidgetCodeEditor
{...props}
messages={{
languageJsx: t("language.jsx"),
languageJson: t("language.json"),
undo: t("action.undo"),
redo: t("action.redo"),
components: t("action.components"),
componentSearch: t("componentReference.search"),
componentEmpty: t("componentReference.empty"),
componentCount: (count) => t("componentReference.count", { count }),
insertStarter: t("action.insertStarter"),
format: t("action.format"),
copy: t("action.copy"),
copied: t("action.copied"),
schema: t("action.schema"),
schemaTab: t("reference.schema"),
minimalTab: t("reference.minimal"),
fullTab: t("reference.full"),
errors: (count) => t("status.errors", { count }),
warnings: (count) => t("status.warnings", { count }),
ready: t("status.ready"),
position: (cursor) => t("status.position", cursor),
characters: (count, limit) =>
limit ? t("status.charactersWithLimit", { count, limit }) : t("status.characters", { count }),
diagnosticsTitle: t("diagnostics.title"),
diagnostic: (diagnostic) =>
`${diagnostic.line ? `${t("diagnostics.line", { line: diagnostic.line })}: ` : ""}${t(
`diagnostics.${diagnostic.code}` as never,
{ value: diagnostic.value ?? "" } as never,
)}`,
}}
/>
);
}
@@ -0,0 +1,37 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { buildCustomWidgetAiPrompt } from "@homarr/custom-widgets/authoring-prompt";
describe("Copy AI prompt", () => {
it("uses one self-contained prompt without an embedded-skill branch", () => {
const source = readFileSync(
`${process.cwd()}/apps/nextjs/src/app/[locale]/manage/custom-widgets/_copy-ai-prompt-button.tsx`,
"utf8",
);
expect(source).toContain("buildCustomWidgetAiPrompt");
expect(source).not.toContain("embedded-authoring-prompt");
expect(source).not.toContain("Menu");
});
it("copies a complete prompt within the public size limit", () => {
const prompt = buildCustomWidgetAiPrompt(undefined, null, null, "Create a Pokédex");
expect(prompt.length).toBeLessThanOrEqual(12_000);
expect(prompt).toContain("exactly one complete `json` fenced block");
expect(prompt).toContain("Put the complete JSX source directly in the `template` string");
});
it("keeps AI actions and section navigation readable on narrow screens", () => {
const card = readFileSync(
`${process.cwd()}/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-ai-card.tsx`,
"utf8",
);
const styles = readFileSync(
`${process.cwd()}/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form.module.css`,
"utf8",
);
expect(card).toContain("<SimpleGrid cols={{ base: 1, sm: 2 }}>");
expect(styles).toContain(".sectionNav > a");
expect(styles).toContain("flex: 0 0 auto");
});
});
@@ -1,343 +1,50 @@
"use client";
import { Button, Popover, Stack, Text } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconCopy, IconSparkles } from "@tabler/icons-react";
import { Button } from "@mantine/core";
import { IconSparkles } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { buildCustomWidgetAiPrompt } from "@homarr/custom-widgets/authoring-prompt";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
const PROMPT_HEADER = `You are helping configure a Homarr custom widget. Homarr is a self-hosted dashboard that can display data from any API endpoint as a widget.
## Your Task
Generate a valid JSON configuration for a Homarr custom widget based on the user's description and the API response below. If you need clarification, ask specific questions.
## Output Format
- Output the JSON inside a \`\`\`json code block for syntax highlighting. If \`\`\`json is not supported, use a generic \`\`\` code block instead.
- Do NOT include any text before or after the JSON block unless you have clarifying questions.
- If your environment supports structured/JSON output mode, use it.
## JSON Schema
The output must conform to this JSON Schema:
`;
const PROMPT_RULES = `
## Key Rules
- The \`displayConfig.type\` field MUST match the \`displayType\` field exactly
- All \`jsonPath\` fields use JSONPath syntax (e.g. \`$.data.count\`, \`$.items[*].name\`)
- The \`$schema\` field should be \`"homarr-custom-widget-v2"\`
- Do NOT include secrets/passwords in the output — those are configured separately in the UI
- \`url\` must be a full URL including protocol (e.g. \`https://...\`)
- For arrays of items, inspect the API response to find the correct paths
## Display Type Guide
- \`singleValue\`: Show one prominent number/text (e.g. total count, status)
- \`keyValue\`: Show labeled pairs like "CPU: 45%" — use \`mappings\` array
- \`table\`: Show tabular data from an array — needs \`tablePath\` for the array and \`columns\` for headers
- \`statGrid\`: Grid of stat cards with optional colors — great for dashboards (e.g. "Movies: 38, Series: 63")
- \`progressBars\`: Visual progress bars with value/max — for storage, quotas, etc.
- \`statusIndicator\`: Green/red dots based on value matching — for service health checks
- \`countGrid\`: Simple grid of counts — like statGrid but simpler, no colors
- \`raw\`: Raw JSON display — for debugging or complex data
- \`actionButton\`: A button that triggers the API call on click — for POST/PUT actions
- \`customJsx\`: Custom JSX layout using whitelisted Mantine components — full creative control over presentation. Set \`displayConfig.template\` to a JSX string. Access API data via \`{data.fieldName}\` bindings (e.g. \`{data.name}\`, \`{data.items[0].title}\`).
## Custom JSX (\`customJsx\`) — Available Mantine Components
When using \`customJsx\`, the template supports whitelisted Mantine UI components. These are React components from the Mantine v9 library. Use their props as documented below.
### Layout Components
- **Stack** — Vertical flex container. Props: \`gap\` (xs|sm|md|lg|xl or number), \`align\` (stretch|center|flex-start|flex-end), \`justify\`
- **Group** — Horizontal flex container. Props: \`gap\`, \`justify\` (flex-start|center|space-between|space-around|flex-end), \`wrap\` (wrap|nowrap), \`grow\` (boolean)
- **Flex** — Generic flex container. Props: \`direction\` (row|column), \`gap\`, \`align\`, \`justify\`, \`wrap\`
- **Grid** + **Grid.Col** — CSS grid layout. Grid props: \`gutter\` (gap). Grid.Col props: \`span\` (1-12 or "auto"), \`offset\`
- **SimpleGrid** — Auto-column grid. Props: \`cols\` (number), \`spacing\`, \`verticalSpacing\`
- **Center** — Centers content. Props: \`inline\` (boolean)
- **Space** — Empty spacing. Props: \`h\` (height), \`w\` (width)
- **Container** — Max-width wrapper. Props: \`size\` (xs|sm|md|lg|xl), \`fluid\` (boolean)
- **AspectRatio** — Maintains aspect ratio. Props: \`ratio\` (number, e.g. 16/9)
### Typography Components
- **Text** — Body text. Props: \`size\` (xs|sm|md|lg|xl), \`fw\` (font-weight number, e.g. 700), \`c\` (color: "dimmed"|"red"|"blue"|...), \`ta\` (text-align), \`tt\` (text-transform: "capitalize"|"uppercase"|"lowercase"), \`td\` (text-decoration), \`lineClamp\` (number), \`truncate\` (boolean), \`span\` (renders as span)
- **Title** — Heading. Props: \`order\` (1-6, maps to h1-h6), \`size\`, \`c\`, \`ta\`, \`tt\`
- **Code** — Inline code. Props: \`color\`, \`block\` (boolean for code block)
- **Highlight** — Text with highlighted substring. Props: \`highlight\` (string or string[])
- **Mark** — Highlighted text background. Props: \`color\`
- **Kbd** — Keyboard key display
- **Blockquote** — Styled quote. Props: \`color\`, \`cite\`, \`icon\`
- **Anchor** — Link. Props: \`href\`, \`target\`, \`underline\` ("always"|"hover"|"never")
- **NumberFormatter** — Formatted number display. Props: \`value\` (number), \`prefix\` (e.g. "$"), \`suffix\` (e.g. "%"), \`thousandSeparator\` (boolean or string), \`decimalScale\` (number)
### Data Display Components
- **Badge** — Label badge. Props: \`color\`, \`variant\` (filled|light|outline|dot|default), \`size\` (xs|sm|md|lg|xl), \`radius\`, \`tt\`
- **Card** + **Card.Section** — Content card. Card props: \`shadow\` (xs|sm|md|lg|xl), \`padding\`/\`p\`, \`radius\`, \`withBorder\` (boolean). Card.Section props: \`withBorder\`, \`inheritPadding\`
- **Paper** — Surface container. Props: \`shadow\`, \`p\`, \`radius\`, \`withBorder\`
- **Alert** — Notification box. Props: \`color\`, \`variant\` (filled|light|outline), \`title\`, \`icon\`
- **ThemeIcon** — Icon container. Props: \`color\`, \`variant\`, \`size\`, \`radius\`
- **ColorSwatch** — Color preview. Props: \`color\` (CSS color string)
- **Table** + **Table.Thead**, **Table.Tbody**, **Table.Tr**, **Table.Th**, **Table.Td** — HTML table. Table props: \`striped\` (boolean), \`withTableBorder\`, \`withColumnBorders\`, \`highlightOnHover\`
- **List** + **List.Item** — Ordered/unordered list. List props: \`type\` ("ordered"|"unordered"), \`icon\`, \`spacing\`
- **Timeline** + **Timeline.Item** — Vertical timeline. Timeline props: \`active\` (number), \`bulletSize\`. Item props: \`title\`, \`bullet\`
- **Accordion** + **.Item** + **.Control** + **.Panel** — Collapsible sections. Item props: \`value\` (string). Control: clickable header. Panel: content.
- **Indicator** — Dot indicator on content. Props: \`color\`, \`position\`, \`size\`, \`label\`, \`processing\` (boolean)
- **Pill** — Removable tag. Props: \`size\`, \`withRemoveButton\`
- **Spoiler** — Show more/less. Props: \`maxHeight\` (number), \`showLabel\`, \`hideLabel\`
### Feedback Components
- **Progress** + **Progress.Section** — Progress bar. Progress props: \`value\` (0-100), \`color\`, \`size\`, \`radius\`, \`striped\`, \`animated\`. Section props: \`value\`, \`color\`
- **RingProgress** — Circular progress. Props: \`sections\` (array of {value, color}), \`size\`, \`thickness\`, \`label\` (ReactNode)
- **Skeleton** — Loading placeholder. Props: \`height\`, \`width\`, \`radius\`, \`visible\` (boolean)
- **Loader** — Spinner. Props: \`size\`, \`color\`, \`type\` (oval|bars|dots)
### Media Components
- **Image** — Responsive image. Props: \`src\`, \`alt\`, \`w\` (width), \`h\` (height), \`radius\`, \`fit\` (cover|contain|fill)
- **Avatar** + **Avatar.Group** — User avatar. Props: \`src\`, \`alt\`, \`size\` (xs|sm|md|lg|xl or number), \`radius\` (sm|xl), \`color\`
- **BackgroundImage** — Background image container. Props: \`src\`, \`radius\`
- **Tooltip** — Hover tooltip. Props: \`label\` (string), \`position\` (top|bottom|left|right), \`withArrow\`
- **Divider** — Horizontal/vertical rule. Props: \`orientation\` (horizontal|vertical), \`label\`, \`labelPosition\`, \`size\`
- **ScrollArea** — Scrollable container. Props: \`h\` (height), \`type\` (auto|always|scroll|hover)
### Charts (@mantine/charts)
- **AreaChart**, **BarChart**, **LineChart** — Props: \`data\` (array of objects), \`dataKey\` (x-axis key), \`series\` (array of {name, color}), \`h\` (height), \`curveType\` (for Area/Line)
- **DonutChart**, **PieChart** — Props: \`data\` (array of {name, value, color}), \`h\`, \`withLabels\`, \`withLabelsLine\`
- **RadarChart** — Props: \`data\`, \`dataKey\`, \`series\`
- **RadialBarChart** — Props: \`data\` (array of {name, value, color}), \`h\`
- **Sparkline** — Props: \`data\` (flat number array), \`h\`, \`w\`, \`color\`, \`curveType\`
### Common Prop Patterns
- **Spacing/sizing:** Most components accept \`p\` (padding), \`m\` (margin), \`px\`/\`py\`/\`mx\`/\`my\`/\`pt\`/\`pb\`/\`pl\`/\`pr\`/\`mt\`/\`mb\`/\`ml\`/\`mr\` with values xs|sm|md|lg|xl or numbers
- **Colors:** Use Mantine color names: "red", "blue", "green", "orange", "violet", "pink", "cyan", "grape", "teal", "yellow", "lime", "indigo", "gray", "dark". Add shade suffix: "red.6", "blue.4"
- **Styles:** Use \`style={{...}}\` for inline CSS. E.g. \`style={{flex: 1, minWidth: 0}}\`
- **Conditional rendering:** Use ternaries: \`{condition ? <Text>Yes</Text> : <Text>No</Text>}\`
- **Responsive:** Most size/spacing props accept object: \`{{ base: "sm", md: "lg" }}\`
### Interactive Components (built-in, state-managed)
These components manage their own internal state — they provide interactivity without event handlers:
**PaginatedList** — Paginates its children with prev/next buttons.
Props: \`pageSize\` (number, default 6)
Usage: Wrap a \`.map()\` expression to paginate results.
\`\`\`jsx
<PaginatedList pageSize={8}>
{data.results.map(item =>
<Card withBorder p="xs" mb="xs">
<Text>{item.name}</Text>
</Card>
)}
</PaginatedList>
\`\`\`
**TabsContainer + TabPanel** — Tabbed interface with automatic tab switching.
TabsContainer props: \`defaultTab\` (string, optional — defaults to first tab)
TabPanel props: \`value\` (string, required — unique tab ID), \`label\` (string, optional — tab display text)
\`\`\`jsx
<TabsContainer defaultTab="overview">
<TabPanel value="overview" label="Overview">
<Text>{data.description}</Text>
</TabPanel>
<TabPanel value="stats" label="Statistics">
<Text>Total: {data.count}</Text>
</TabPanel>
</TabsContainer>
\`\`\`
**Collapsible** — Expandable/collapsible section with a title.
Props: \`title\` (string, required), \`defaultOpen\` (boolean, default false)
\`\`\`jsx
<Collapsible title="Details" defaultOpen={true}>
<Text>{data.details}</Text>
</Collapsible>
\`\`\`
**StatBar** — A horizontal stat bar with label/value (great for RPG-style stats, progress).
Props: \`value\` (number), \`max\` (number, default 100), \`label\` (string), \`color\` (Mantine color)
\`\`\`jsx
<StatBar label="HP" value={45} max={100} color="red" />
<StatBar label="ATK" value={80} max={255} color="orange" />
\`\`\`
**TypeBadge** — A colored badge that maps common type names to colors (normal, fire, water, electric, grass, ice, fighting, poison, ground, flying, psychic, bug, rock, ghost, dragon, dark, steel, fairy).
Props: \`type\` (string), \`size\` (xs|sm|md|lg|xl, default sm)
\`\`\`jsx
<Group gap="xs">
<TypeBadge type="fire" />
<TypeBadge type="flying" />
</Group>
\`\`\`
**Available bindings in templates:**
- \`data\` — the full API response JSON object
- \`String(v)\`, \`Number(v)\`, \`Boolean(v)\` — type coercion helpers
- \`Math.round\`, \`Math.floor\`, \`Math.ceil\`, \`Math.abs\`, \`Math.min\`, \`Math.max\`, \`Math.pow\`, \`Math.sqrt\`, \`Math.PI\`
- \`JSON.stringify(v)\`, \`Array.isArray(v)\`, \`Object.keys(v)\`, \`Object.values(v)\`, \`Object.entries(v)\`
- Expression arrows for \`.map()\`, \`.filter()\`, \`.slice()\` — e.g. \`{data.items.map(item => <Text>{item.name}</Text>)}\`
- Ternaries for conditionals — e.g. \`{data.count > 0 ? "active" : "idle"}\`
**FORBIDDEN keywords (template will be rejected):** constructor, __proto__, eval, Function, import, require, globalThis, window, document, fetch
**Chart data formats:**
- BarChart/LineChart/AreaChart: \`data={data.items}\` + \`dataKey="month"\` (x-axis key) + \`series={[{ name: "count", color: "blue" }]}\` where series \`name\` matches a numeric key in each data row
- DonutChart/PieChart: \`data={data.items}\` where each item is \`{ name: "Label", value: 42, color: "blue" }\` — NO dataKey or series
- Sparkline: \`data={[1,2,3]}\` — flat number array
- NumberFormatter: \`<NumberFormatter value={data.price} thousandSeparator prefix="$" />\`
### Full Pokémon Card Example (demonstrating TypeBadge, StatBar, TabsContainer, Collapsible)
API: \`https://pokeapi.co/api/v2/pokemon/charizard\`
\`\`\`jsx
<Stack gap="sm" p="xs">
<Group wrap="nowrap">
<Avatar src={data.sprites.front_default} size={80} radius="sm" />
<Stack gap={4} style={{flex: 1}}>
<Title order={3} tt="capitalize">{data.name}</Title>
<Text size="xs" c="dimmed">#{String(data.id).padStart(3, "0")}</Text>
<Group gap="xs">
{data.types.map(t => <TypeBadge type={t.type.name} />)}
</Group>
</Stack>
</Group>
<TabsContainer defaultTab="stats">
<TabPanel value="stats" label="Stats">
<Stack gap="xs" pt="xs">
{data.stats.map(s =>
<StatBar label={s.stat.name} value={s.base_stat} max={255} color={s.base_stat > 100 ? "green" : "red"} />
)}
</Stack>
</TabPanel>
<TabPanel value="abilities" label="Abilities">
<Stack gap="xs" pt="xs">
{data.abilities.map(a =>
<Badge variant={a.is_hidden ? "outline" : "filled"} tt="capitalize">
{a.ability.name}{a.is_hidden ? " (hidden)" : ""}
</Badge>
)}
</Stack>
</TabPanel>
<TabPanel value="moves" label="Moves">
<Collapsible title="Move list">
<Group gap="xs" pt="xs">
{data.moves.slice(0, 20).map(m =>
<Badge size="xs" variant="light" tt="capitalize">{m.move.name}</Badge>
)}
</Group>
</Collapsible>
</TabPanel>
</TabsContainer>
</Stack>
\`\`\`
### Paginated List Example
API: \`https://pokeapi.co/api/v2/pokemon?limit=50\`
\`\`\`jsx
<Stack gap="sm" p="xs">
<Group justify="space-between">
<Title order={3}>Pokédex</Title>
<Badge size="lg" color="red">{data.count} Pokémon</Badge>
</Group>
<PaginatedList pageSize={10}>
{data.results.map((pokemon, i) =>
<Card withBorder p="xs" mb="xs">
<Group wrap="nowrap">
<Avatar
src={"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/" + String(i + 1) + ".png"}
size="lg"
radius="sm"
/>
<Stack gap={0} style={{ flex: 1 }}>
<Text fw={700} tt="capitalize">{pokemon.name}</Text>
<Text size="xs" c="dimmed">#{String(i + 1)}</Text>
</Stack>
</Group>
</Card>
)}
</PaginatedList>
</Stack>
\`\`\`
## API Response
`;
const PROMPT_NO_RESPONSE = `Paste the raw JSON response from your API endpoint below:
\`\`\`json
PASTE_YOUR_API_RESPONSE_HERE
\`\`\`
`;
const PROMPT_FOOTER = `
## Your Request
Describe what you want the widget to show:
`;
function buildAiPrompt(
jsonSchema: unknown,
rawResponse?: string | null,
currentConfig?: Record<string, unknown> | null,
) {
const schemaStr = JSON.stringify(jsonSchema, null, 2);
const responseSection = rawResponse
? `The API returned the following JSON:\n\n\`\`\`json\n${rawResponse}\n\`\`\`\n`
: PROMPT_NO_RESPONSE;
const configSection = currentConfig
? `\n## Current Widget Configuration\nThe widget is currently configured as follows. Use this as a starting point and modify based on the user's request:\n\n\`\`\`json\n${JSON.stringify(currentConfig, null, 2)}\n\`\`\`\n`
: "";
return PROMPT_HEADER + schemaStr + PROMPT_RULES + responseSection + configSection + PROMPT_FOOTER;
}
interface CopyAiPromptButtonProps {
rawResponse?: string | null;
currentConfig?: Record<string, unknown> | null;
request?: string | null;
documentationUrl?: string | null;
}
export const CopyAiPromptButton = ({ rawResponse, currentConfig }: CopyAiPromptButtonProps) => {
export const CopyAiPromptButton = ({
rawResponse,
currentConfig,
request,
documentationUrl,
}: CopyAiPromptButtonProps) => {
const t = useScopedI18n("customWidget");
const [opened, { open, close }] = useDisclosure(false);
const { data: schema, isLoading } = clientApi.customWidget.schema.useQuery();
const handleCopy = async () => {
if (!schema) return;
const prompt = buildAiPrompt(schema, rawResponse, currentConfig);
try {
const prompt = buildCustomWidgetAiPrompt(undefined, rawResponse, currentConfig, request, documentationUrl);
await navigator.clipboard.writeText(prompt);
close();
showSuccessNotification({ title: t("action.copyAiPrompt"), message: t("notification.aiPromptCopied") });
showSuccessNotification({
title: t("action.copyAiPrompt"),
message: t("notification.aiPromptCopiedWithCount", { count: prompt.length }),
});
} catch {
showErrorNotification({ title: t("action.copyAiPrompt"), message: t("notification.aiPromptCopyError") });
}
};
return (
<Popover opened={opened} onClose={close} width={320} position="bottom" shadow="md" withinPortal>
<Popover.Target>
<Button
variant="light"
leftSection={<IconSparkles size={16} />}
onClick={open}
loading={isLoading}
disabled={!schema}
fullWidth
size="sm"
>
{t("action.copyAiPrompt")}
</Button>
</Popover.Target>
<Popover.Dropdown>
<Stack gap="sm">
<Text size="sm">{t("notification.aiPromptDescription")}</Text>
{!rawResponse && (
<Text size="xs" c="dimmed" fs="italic">
{t("notification.aiPromptNoResponse")}
</Text>
)}
<Button leftSection={<IconCopy size={16} />} onClick={() => void handleCopy()} fullWidth>
{t("notification.aiPromptCopy")}
</Button>
</Stack>
</Popover.Dropdown>
</Popover>
<Button
type="button"
variant="light"
leftSection={<IconSparkles size={16} />}
onClick={() => void handleCopy()}
fullWidth
size="sm"
>
{t("action.copyAiPrompt")}
</Button>
);
};
@@ -1,24 +1,29 @@
"use client";
import { useRef } from "react";
import { useRef, useState } from "react";
import { ActionIcon, Menu } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import {
IconBuildingStore,
IconClipboard,
IconCopy,
IconDots,
IconDownload,
IconToggleLeft,
IconToggleRight,
IconSparkles,
IconTrash,
IconUpload,
} from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { formatCustomWidgetImportIssues, parseCustomWidgetClipboardDetailed } from "@homarr/custom-widgets/core";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { useConfirmModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { WorkshopPublishModal } from "~/components/workshop/workshop-publish-modal";
const iconProps = { size: 16, stroke: 1.5 };
@@ -26,6 +31,8 @@ interface WidgetRef {
id: string;
name: string;
enabled: boolean;
valid: boolean;
migrationRequired: boolean;
}
export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
@@ -33,26 +40,71 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
const { openConfirmModal } = useConfirmModal();
const deleteMutation = clientApi.customWidget.delete.useMutation();
const duplicateMutation = clientApi.customWidget.duplicate.useMutation();
const toggleEnabledMutation = clientApi.customWidget.toggleEnabled.useMutation();
const utils = clientApi.useUtils();
const [publishOpened, publishControls] = useDisclosure(false);
const [migrationOpened, migrationControls] = useDisclosure(false);
const migrationFileInputRef = useRef<HTMLInputElement>(null);
const [migratedWidget, setMigratedWidget] = useState<HomarrCustomWidgetV2 | null>(null);
const handleToggleEnabled = () => {
toggleEnabledMutation.mutate(
{ id: widget.id, enabled: !widget.enabled },
{
onSuccess: () => {
void utils.customWidget.all.invalidate();
void utils.widget.customApi.getData.invalidate({ definitionId: widget.id });
void revalidatePathActionAsync("/manage/custom-widgets");
},
onError: () => {
showErrorNotification({
title: widget.enabled ? t("action.disable") : t("action.enable"),
message: t("notification.toggleError"),
});
},
},
);
const copyMigrationPrompt = async () => {
try {
const result = await utils.customWidget.legacyMigrationPrompt.fetch({ id: widget.id });
await navigator.clipboard.writeText(result.prompt);
showSuccessNotification({
title: t("action.copyMigrationPrompt"),
message: t("notification.migrationPromptCopied"),
});
} catch (error) {
showErrorNotification({
title: t("action.copyMigrationPrompt"),
message: error instanceof Error ? error.message : t("notification.migrationPromptCopyError"),
});
}
};
const queueMigratedWidget = (text: string) => {
const result = parseCustomWidgetClipboardDetailed(text);
if (!result.success) {
showErrorNotification({
title: t("action.migrate"),
message: formatCustomWidgetImportIssues(result.issues),
});
return;
}
setMigratedWidget(result.widget);
migrationControls.open();
};
const pasteMigratedWidget = async () => {
try {
queueMigratedWidget(await navigator.clipboard.readText());
} catch {
showErrorNotification({
title: t("action.migrate"),
message: t("notification.migrationError"),
});
}
};
const handleMigrationFile = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.addEventListener("load", (loadEvent) => {
try {
queueMigratedWidget(loadEvent.target?.result as string);
} catch {
showErrorNotification({
title: t("action.migrate"),
message: t("notification.migrationError"),
});
}
});
reader.addEventListener("error", () => {
showErrorNotification({ title: t("action.migrate"), message: t("notification.migrationError") });
});
reader.readAsText(file);
event.target.value = "";
};
const handleExport = async () => {
@@ -79,7 +131,7 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
title: t("action.duplicate"),
message: t("notification.duplicated", { name: result.name }),
});
void utils.customWidget.all.invalidate();
void utils.customWidget.list.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets");
},
onError: () => {
@@ -94,120 +146,104 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
title: t("action.delete"),
children: t("action.deleteConfirm", { name: widget.name }),
onConfirm: () => {
deleteMutation.mutate(
{ id: widget.id },
{
onSuccess: () => {
showSuccessNotification({
title: t("action.delete"),
message: t("notification.deleted", { name: widget.name }),
});
void utils.customWidget.all.invalidate();
void utils.widget.customApi.getData.invalidate({ definitionId: widget.id });
void revalidatePathActionAsync("/manage/custom-widgets");
},
onError: () => {
showErrorNotification({ title: t("action.delete"), message: t("notification.deleteError") });
},
const callbacks = {
onSuccess: () => {
showSuccessNotification({
title: t("action.delete"),
message: t("notification.deleted", { name: widget.name }),
});
void utils.customWidget.list.invalidate();
void utils.customWidget.available.invalidate();
void utils.widget.customApi.getData.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets");
},
);
onError: () => {
showErrorNotification({ title: t("action.delete"), message: t("notification.deleteError") });
},
};
deleteMutation.mutate({ id: widget.id }, callbacks);
},
});
};
return (
<Menu withinPortal position="bottom-end" shadow="md">
<Menu.Target>
<ActionIcon variant="subtle" color="gray" aria-label={t("action.menu")}>
<IconDots {...iconProps} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
onClick={handleToggleEnabled}
leftSection={widget.enabled ? <IconToggleLeft {...iconProps} /> : <IconToggleRight {...iconProps} />}
disabled={toggleEnabledMutation.isPending}
>
{widget.enabled ? t("action.disable") : t("action.enable")}
</Menu.Item>
<Menu.Divider />
<Menu.Item
onClick={handleDuplicate}
leftSection={<IconCopy {...iconProps} />}
disabled={duplicateMutation.isPending}
>
{t("action.duplicate")}
</Menu.Item>
<Menu.Item onClick={() => void handleExport()} leftSection={<IconDownload {...iconProps} />}>
{t("action.export")}
</Menu.Item>
<Menu.Divider />
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
};
export const ImportCustomWidgetButton = () => {
const t = useScopedI18n("customWidget");
const fileInputRef = useRef<HTMLInputElement>(null);
const utils = clientApi.useUtils();
const importMutation = clientApi.customWidget.import.useMutation({
onSuccess: () => {
showSuccessNotification({ title: t("action.import"), message: t("notification.imported") });
void utils.customWidget.all.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets");
},
onError: () => {
showErrorNotification({ title: t("action.import"), message: t("notification.importError") });
},
});
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const json = JSON.parse(e.target?.result as string);
importMutation.mutate(json);
} catch {
showErrorNotification({ title: t("action.import"), message: t("notification.importError") });
}
};
reader.onerror = () => {
showErrorNotification({ title: t("action.import"), message: t("notification.importError") });
};
reader.readAsText(file);
event.target.value = "";
};
return (
<>
<MobileAffixButton
variant="default"
leftSection={<IconUpload size={16} />}
onClick={() => fileInputRef.current?.click()}
loading={importMutation.isPending}
>
{t("action.import")}
</MobileAffixButton>
<input
ref={fileInputRef}
type="file"
accept=".json"
hidden
onChange={handleImport}
aria-label="Import custom widget"
/>
<Menu withinPortal position="bottom-end" shadow="md">
<Menu.Target>
<ActionIcon variant="subtle" color="gray" aria-label={t("action.menu")}>
<IconDots {...iconProps} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
{widget.valid && (
<>
<Menu.Item
onClick={handleDuplicate}
leftSection={<IconCopy {...iconProps} />}
disabled={duplicateMutation.isPending}
>
{t("action.duplicate")}
</Menu.Item>
<Menu.Item onClick={() => void handleExport()} leftSection={<IconDownload {...iconProps} />}>
{t("action.export")}
</Menu.Item>
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
<Menu.Divider />
</>
)}
{widget.migrationRequired && (
<>
<Menu.Item onClick={() => void copyMigrationPrompt()} leftSection={<IconSparkles {...iconProps} />}>
{t("action.copyMigrationPrompt")}
</Menu.Item>
<Menu.Item onClick={() => void pasteMigratedWidget()} leftSection={<IconClipboard {...iconProps} />}>
{t("action.pasteMigration")}
</Menu.Item>
<Menu.Item
onClick={() => migrationFileInputRef.current?.click()}
leftSection={<IconUpload {...iconProps} />}
>
{t("action.importMigration")}
</Menu.Item>
<Menu.Divider />
</>
)}
{!widget.migrationRequired && (
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
)}
</Menu.Dropdown>
</Menu>
{widget.valid && <WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />}
{widget.migrationRequired && (
<>
<input
ref={migrationFileInputRef}
type="file"
accept=".json,.md,text/markdown,application/json"
hidden
onChange={handleMigrationFile}
aria-label={t("action.importMigration")}
/>
<CustomWidgetImportDialog
opened={migrationOpened}
widget={migratedWidget}
legacyId={widget.id}
onClose={() => {
migrationControls.close();
setMigratedWidget(null);
}}
/>
</>
)}
</>
);
};
@@ -0,0 +1,62 @@
"use client";
import { useEffect, useState } from "react";
import { Accordion } from "@mantine/core";
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import { CodeEditor } from "./_code-editor";
import { applyDefinition, parseJson } from "./_custom-widget-form-utils";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
export function CustomWidgetAdvancedManifest({ form }: { form: CustomWidgetWorkbenchForm }) {
const t = useScopedI18n("customWidget.workbench.builder");
const serialized = JSON.stringify(
{
$schema: "homarr-custom-widget-v2",
name: form.values.name,
...(form.values.description ? { description: form.values.description } : {}),
...(form.values.iconUrl ? { iconUrl: form.values.iconUrl } : {}),
sources: parseJson(form.values.sources),
requests: parseJson(form.values.requests),
options: parseJson(form.values.options),
template: form.values.template,
},
null,
2,
);
const [draft, setDraft] = useState(serialized);
const [error, setError] = useState<string>();
useEffect(() => setDraft(serialized), [serialized]);
return (
<Accordion variant="contained">
<Accordion.Item value="manifest">
<Accordion.Control>{t("advancedManifest")}</Accordion.Control>
<Accordion.Panel>
<CodeEditor
id="raw-widget-manifest"
label={t("manifestFilename")}
language="json"
value={draft}
error={error}
onChange={(next) => {
setDraft(next);
try {
const parsed = customWidgetDefinitionSchema.safeParse(JSON.parse(next) as unknown);
if (!parsed.success) {
setError(parsed.error.issues[0]?.message ?? t("invalidWidget"));
return;
}
setError(undefined);
applyDefinition(form, parsed.data);
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("invalidJson"));
}
}}
/>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
);
}
@@ -0,0 +1,57 @@
"use client";
import { Button, Card, Group, SimpleGrid, Stack, Text, TextInput, Textarea } from "@mantine/core";
import { IconSparkles } from "@tabler/icons-react";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import { CopyAiPromptButton } from "./_copy-ai-prompt-button";
interface AiCardProps {
candidate: HomarrCustomWidgetV2 | null;
request: string;
onRequestChange(value: string): void;
documentationUrl: string;
onDocumentationUrlChange(value: string): void;
onPaste(): void;
}
export function CustomWidgetAiCard(props: AiCardProps) {
const t = useScopedI18n("customWidget.workbench.ai");
return (
<Card withBorder p="md">
<Stack gap="sm">
<Group gap="xs">
<IconSparkles size={18} />
<Text fw={600}>{t("title")}</Text>
</Group>
<Text size="sm" c="dimmed">
{t("description")}
</Text>
<Textarea
label={t("request")}
value={props.request}
onChange={(event) => props.onRequestChange(event.currentTarget.value)}
autosize
minRows={2}
/>
<TextInput
label={t("documentationUrl")}
value={props.documentationUrl}
onChange={(event) => props.onDocumentationUrlChange(event.currentTarget.value)}
/>
<SimpleGrid cols={{ base: 1, sm: 2 }}>
<CopyAiPromptButton
currentConfig={props.candidate}
request={props.request}
documentationUrl={props.documentationUrl}
/>
<Button type="button" variant="light" leftSection={<IconSparkles size={16} />} onClick={props.onPaste}>
{t("paste")}
</Button>
</SimpleGrid>
</Stack>
</Card>
);
}
@@ -0,0 +1,38 @@
import type { CustomWidgetFormValues, EditorDiagnostic } from "@homarr/custom-widgets/workbench";
import { isRecord, parseJson, parseSources } from "./_custom-widget-form-utils";
export function createCustomWidgetCompletions(values: CustomWidgetFormValues, requestIds: string[]) {
const options = parseJson(values.options);
const optionKeys = Object.keys(isRecord(options) ? options : {});
return [
...requestIds.flatMap((id) => [
{ label: `data["${id}"]`, type: "variable", detail: `Response from ${id}` },
{ label: `status["${id}"]`, type: "variable", detail: `Status for ${id}` },
{ label: `requestId="${id}"`, type: "property", detail: "Named request" },
]),
...parseSources(values.sources).map(({ id }) => ({ label: id, type: "constant", detail: "Source ID" })),
...optionKeys.map((key) => ({ label: `options.${key}`, type: "variable", detail: "Widget option" })),
{ label: "inputs", type: "variable", detail: "Temporary bound input values" },
];
}
export function getInvalidCustomWidgetSections(
issues: readonly { path: PropertyKey[] }[],
requestDiagnostics: EditorDiagnostic[],
templateDiagnostics: EditorDiagnostic[],
) {
const result = new Set<string>();
for (const issue of issues) {
const field = String(issue.path[0] ?? "");
if (["name", "description", "iconUrl"].includes(field)) result.add("general");
else if (field === "sources") result.add("sources");
else if (field === "requests") result.add("requests");
else if (field === "options") result.add("options");
else if (field === "template") result.add("jsx");
}
if (requestDiagnostics.some((entry) => entry.severity === "error")) result.add("requests");
if (templateDiagnostics.some((entry) => entry.severity === "error")) result.add("jsx");
if (result.size > 0) result.add("preview");
return result;
}
@@ -0,0 +1,85 @@
"use client";
import type { ReactNode } from "react";
import type { Icon } from "@tabler/icons-react";
import { Button, Card, Group, Stack, Text, ThemeIcon } from "@mantine/core";
import { IconAlertTriangle, IconCheck, IconPlayerPlay } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import classes from "./_custom-widget-form.module.css";
export function EditorSection({
id,
title,
icon: SectionIcon,
children,
}: {
id: string;
title: string;
icon: Icon;
children: ReactNode;
}) {
return (
<Card id={id} component="section" withBorder p="lg" className={classes.editorSection}>
<Stack gap="md">
<Group gap="sm">
<ThemeIcon variant="light" size="lg">
<SectionIcon size={18} />
</ThemeIcon>
<Text fw={700} size="lg">
{title}
</Text>
</Group>
{children}
</Stack>
</Card>
);
}
export function SaveActions({
dirty,
savePending,
previewPending,
invalid,
mode,
onPreview,
}: {
dirty: boolean;
savePending: boolean;
previewPending: boolean;
invalid: boolean;
mode: "create" | "edit";
onPreview(): void;
}) {
const t = useScopedI18n("customWidget.workbench");
return (
<Group justify="space-between" wrap="wrap">
<Group gap="xs">
{invalid ? (
<IconAlertTriangle size={16} color="var(--mantine-color-red-6)" />
) : (
<IconCheck size={16} color="var(--mantine-color-green-6)" />
)}
<Text size="sm" fw={600}>
{invalid ? t("status.invalid") : dirty ? t("status.unsaved") : t("status.ready")}
</Text>
</Group>
<Group gap="xs" wrap="wrap">
<Button
type="button"
variant="light"
leftSection={<IconPlayerPlay size={16} />}
onClick={onPreview}
loading={previewPending}
disabled={invalid || savePending}
>
{previewPending ? t("action.previewLoading") : t("action.preview")}
</Button>
<Button type="submit" loading={savePending} disabled={invalid || previewPending}>
{mode === "create" ? t("action.create") : t("action.save")}
</Button>
</Group>
</Group>
);
}
@@ -0,0 +1,18 @@
import {
CUSTOM_WIDGET_OPTIONS_EXAMPLES,
CUSTOM_WIDGET_REQUEST_EXAMPLES,
getCustomWidgetOptionsJsonSchema,
getCustomWidgetRequestsJsonSchema,
} from "@homarr/custom-widgets/core";
export const customWidgetRequestReference = {
schema: getCustomWidgetRequestsJsonSchema(),
minimal: CUSTOM_WIDGET_REQUEST_EXAMPLES.minimal,
full: CUSTOM_WIDGET_REQUEST_EXAMPLES.full,
};
export const customWidgetOptionsSchemaReference = {
schema: getCustomWidgetOptionsJsonSchema(),
minimal: CUSTOM_WIDGET_OPTIONS_EXAMPLES.minimal,
full: CUSTOM_WIDGET_OPTIONS_EXAMPLES.full,
};
@@ -0,0 +1,115 @@
import { describe, expect, it, vi } from "vitest";
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import {
applyCustomWidgetAiResponse,
filterSecretsForSourceAuthentication,
getChangedSecrets,
getCustomWidgetPreviewOptionIssues,
loadPreviewQueries,
parseSources,
} from "./_custom-widget-form-utils";
const previewQuery = vi.hoisted(() => vi.fn());
vi.mock("@homarr/api/client", () => ({ fetchApi: { customWidget: { previewQuery: { query: previewQuery } } } }));
const definition = customWidgetDefinitionSchema.parse({
$schema: "homarr-custom-widget-v2",
name: "Preview options",
sources: { default: { name: "API", baseUrl: "https://example.com", networkScope: "public", auth: "none" } },
requests: { containers: { path: "/endpoints/{option:environmentId}/containers" } },
options: { environmentId: { label: "Environment", control: "number", default: 1 } },
template: "<Text>Preview</Text>",
});
describe("Custom Widget workbench preview options", () => {
it("loads one complete AI response into every editor field, including JSX", () => {
const setValues = vi.fn();
const result = applyCustomWidgetAiResponse(
{
values: {
name: "",
description: "",
iconUrl: "",
sources: "{}",
requests: "{}",
options: "{}",
template: "",
secrets: [],
},
setValues,
} as never,
`\`\`\`json\n${JSON.stringify(definition)}\n\`\`\``,
);
if (!result.success) throw new Error("Expected the complete AI response to be accepted");
expect(setValues).toHaveBeenCalledOnce();
const values = setValues.mock.calls[0]?.[0];
expect(values).toMatchObject({
name: "Preview options",
description: "",
iconUrl: "",
template: "<Text>Preview</Text>",
secrets: [],
});
expect(JSON.parse(values?.sources as string)).toEqual(result.widget.sources);
expect(JSON.parse(values?.requests as string)).toEqual(result.widget.requests);
expect(JSON.parse(values?.options as string)).toEqual(result.widget.options);
});
it("shows the default source first regardless of manifest key order", () => {
expect(
parseSources(
JSON.stringify({
secondary: { baseUrl: "https://secondary.example.com", networkScope: "public", auth: "none" },
default: { baseUrl: "https://default.example.com", networkScope: "public", auth: "none" },
}),
).map(({ id }) => id),
).toEqual(["default", "secondary"]);
});
it("keeps load-query option resolution on the server", async () => {
previewQuery.mockResolvedValueOnce({ ok: true, status: 200, data: [] });
await loadPreviewQueries(definition, "preview-1");
expect(previewQuery).toHaveBeenCalledWith({ sessionId: "preview-1", requestId: "containers", params: {} });
});
it("rejects invalid selected options", () => {
expect(getCustomWidgetPreviewOptionIssues(definition, { environmentId: "wrong" })).toEqual([
{ path: "configuration.environmentId", message: "Expected a number" },
]);
});
it("normalizes only changed secrets", () => {
expect(
getChangedSecrets({
name: "Widget",
description: "",
iconUrl: "",
sources: "{}",
requests: "{}",
options: "{}",
template: "<Text />",
secrets: [
{ sourceId: "default", kind: "apiKey", value: "", hasValue: true },
{ sourceId: "other", kind: "password", value: "replacement" },
],
}),
).toEqual([{ sourceId: "other", kind: "password", value: "replacement" }]);
});
it("drops credentials that do not apply after an authentication transition", () => {
expect(
filterSecretsForSourceAuthentication(
[
{ sourceId: "default", kind: "username", value: "admin", hasValue: true },
{ sourceId: "default", kind: "password", value: "secret", hasValue: true },
{ sourceId: "secondary", kind: "apiKey", value: "unchanged", hasValue: true },
],
"default",
"bearer",
),
).toEqual([{ sourceId: "secondary", kind: "apiKey", value: "unchanged", hasValue: true }]);
});
});
@@ -0,0 +1,128 @@
import { fetchApi } from "@homarr/api/client";
import {
customWidgetDefinitionSchema,
getCustomWidgetDefaultOptions,
getCustomWidgetRequiredSecretKinds,
parseCustomWidgetAiResponse,
validateCustomWidgetOptions,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetSource, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import type { UseFormReturnType } from "@mantine/form";
export type CustomWidgetWorkbenchForm = UseFormReturnType<CustomWidgetFormValues>;
export function buildDefinition(values: CustomWidgetFormValues) {
return customWidgetDefinitionSchema.safeParse({
$schema: "homarr-custom-widget-v2",
name: values.name,
description: values.description || undefined,
iconUrl: values.iconUrl || undefined,
sources: parseJson(values.sources),
requests: parseJson(values.requests),
options: parseJson(values.options),
template: values.template,
});
}
export function getChangedSecrets(values: CustomWidgetFormValues) {
return values.secrets
.filter((secret) => secret.value.trim())
.map(({ sourceId, kind, value }) => ({
sourceId,
kind: kind as "apiKey" | "username" | "password",
value,
}));
}
export function filterSecretsForSourceAuthentication(
secrets: CustomWidgetFormValues["secrets"],
sourceId: string,
authType: Parameters<typeof getCustomWidgetRequiredSecretKinds>[0],
) {
const requiredKinds = new Set<string>(getCustomWidgetRequiredSecretKinds(authType));
return secrets.filter((secret) => secret.sourceId !== sourceId || requiredKinds.has(secret.kind));
}
export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrCustomWidgetV2) {
form.setValues({
...form.values,
name: widget.name,
description: widget.description ?? "",
iconUrl: widget.iconUrl ?? "",
sources: JSON.stringify(widget.sources, null, 2),
requests: JSON.stringify(widget.requests, null, 2),
options: JSON.stringify(widget.options, null, 2),
template: widget.template,
});
}
export function applyCustomWidgetAiResponse(form: CustomWidgetWorkbenchForm, response: string) {
const result = parseCustomWidgetAiResponse(response);
if (result.success) applyDefinition(form, result.widget);
return result;
}
export function parseSources(value: string): Array<CustomWidgetSource & { id: string }> {
const parsed = parseJson(value);
return isRecord(parsed)
? Object.entries(parsed)
.flatMap(([id, entry]) => (isRecord(entry) ? [{ id, ...(entry as CustomWidgetSource) }] : []))
.toSorted((left, right) => Number(right.id === "default") - Number(left.id === "default"))
: [];
}
export function parseJson(value: string): unknown {
try {
return JSON.parse(value) as unknown;
} catch {
return null;
}
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
export function getCustomWidgetPreviewOptionIssues(definition: HomarrCustomWidgetV2, options: Record<string, unknown>) {
return validateCustomWidgetOptions(definition.options, options);
}
export function isRuntimeParams(
value: unknown,
expectedNames: readonly string[],
): value is Record<string, string | number | boolean> {
if (!isRecord(value)) return false;
const names = Object.keys(value).toSorted();
return (
names.length === expectedNames.length &&
names.every((name, index) => name === expectedNames[index]) &&
Object.values(value).every((entry) => ["string", "number", "boolean"].includes(typeof entry))
);
}
export async function loadPreviewQueries(definition: HomarrCustomWidgetV2, sessionId: string) {
const data: Record<string, unknown> = {};
const status: Record<string, unknown> = {};
for (const [requestId] of Object.entries(definition.requests).filter(
([, entry]) => entry.kind === "query" && entry.trigger === "load",
)) {
try {
const result = await fetchApi.customWidget.previewQuery.query({ sessionId, requestId, params: {} });
data[requestId] = result.data;
status[requestId] = { loading: false, ...result };
} catch (error) {
data[requestId] = null;
status[requestId] = {
loading: false,
ok: false,
error: error instanceof Error ? error.message : "Request failed",
};
}
}
return { data, status };
}
export function getDefinitionDefaults(definition: HomarrCustomWidgetV2) {
return getCustomWidgetDefaultOptions(definition.options);
}
@@ -0,0 +1,115 @@
.form {
min-width: 0;
}
.sectionNav {
position: sticky;
top: 0.5rem;
z-index: 20;
display: flex;
gap: 0.25rem;
margin-bottom: var(--mantine-spacing-md);
padding: 0.35rem;
overflow-x: auto;
border: 1px solid var(--mantine-color-default-border);
border-radius: var(--mantine-radius-md);
background: color-mix(in srgb, var(--mantine-color-body) 94%, transparent);
backdrop-filter: blur(10px);
}
.sectionNav > a {
flex: 0 0 auto;
}
.editorSection {
scroll-margin-top: 5rem;
}
.previewCanvas {
display: flex;
justify-content: center;
overflow-x: auto;
padding: var(--mantine-spacing-sm);
border-radius: var(--mantine-radius-md);
background: var(--mantine-color-default-hover);
}
.workbench {
display: grid;
gap: var(--mantine-spacing-xl);
align-items: start;
}
.paneSwitcher {
position: sticky;
top: var(--mantine-spacing-xs);
z-index: 10;
margin-bottom: var(--mantine-spacing-lg);
background: var(--mantine-color-body);
}
@media (max-width: 74.9375em) {
.sectionNav {
top: 3.5rem;
}
.workbench[data-mobile-pane="configure"] .previewPane,
.workbench[data-mobile-pane="preview"] .configuration {
display: none;
}
}
.configuration,
.previewPane {
min-width: 0;
}
.previewPane {
display: flex;
flex-direction: column;
gap: var(--mantine-spacing-md);
}
.actionBar {
position: sticky;
bottom: var(--mantine-spacing-sm);
z-index: 10;
background: var(--mantine-color-body);
}
.mobileSaveBar {
position: sticky;
bottom: var(--mantine-spacing-sm);
z-index: 10;
background: var(--mantine-color-body);
}
@media (min-width: 75em) {
.paneSwitcher {
display: none;
}
.mobileSaveBar {
display: none;
}
.workbench {
grid-template-columns: 1fr 1fr;
}
.previewPane {
position: sticky;
top: 5rem;
}
.actionBar {
top: 5rem;
bottom: auto;
}
}
@media (min-width: 100em) {
.workbench {
grid-template-columns: 0.9fr 1.1fr;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,48 @@
"use client";
import { useEffect, useState } from "react";
import type { CSSProperties, ReactNode } from "react";
import { TextInput } from "@mantine/core";
export function CustomWidgetIdentifierInput({
label,
value,
error,
disabled,
style,
onCommit,
}: {
label: string;
value: string;
error?: ReactNode;
disabled?: boolean;
style?: CSSProperties;
onCommit(value: string): void;
}) {
const [draft, setDraft] = useState(value);
useEffect(() => setDraft(value), [value]);
const commit = () => {
if (draft !== value) onCommit(draft);
};
return (
<TextInput
label={label}
value={draft}
error={error}
disabled={disabled}
style={style}
onChange={(event) => setDraft(event.currentTarget.value)}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.currentTarget.blur();
}
if (event.key === "Escape") {
event.preventDefault();
setDraft(value);
}
}}
/>
);
}
@@ -0,0 +1,30 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const readSource = (path: string) => readFileSync(`${process.cwd()}/${path}`, "utf8");
describe("legacy custom widget migration UI", () => {
it("keeps legacy definitions visible and exposes the redacted LLM workflow", () => {
const list = readSource("apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-list.tsx");
const actions = readSource("apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx");
expect(list).toContain("widget.migrationRequired");
expect(list).toContain('t("page.list.migrationInstructions")');
expect(actions).toContain("legacyMigrationPrompt.fetch");
expect(actions).toContain("navigator.clipboard.writeText(result.prompt)");
expect(actions).toContain("navigator.clipboard.readText()");
expect(actions).toContain('t("action.pasteMigration")');
expect(actions).toContain("parseCustomWidgetClipboardDetailed");
expect(actions).toContain("legacyId={widget.id}");
});
it("replaces the legacy record through migration and refreshes every consumer", () => {
const dialog = readSource("apps/nextjs/src/components/custom-widgets/custom-widget-import-dialog.tsx");
expect(dialog).toContain("customWidget.migrateLegacy.useMutation");
expect(dialog).toContain("migrateMutation.mutate({ id: legacyId, widget: configuredWidget, secrets })");
expect(dialog).toContain("utils.customWidget.list.invalidate()");
expect(dialog).toContain("utils.customWidget.available.invalidate()");
expect(dialog).toContain("utils.widget.customApi.getData.invalidate()");
});
});
@@ -1,32 +1,20 @@
"use client";
import { ActionIcon, Avatar, Badge, Group, Stack, Table, Text } from "@mantine/core";
import { IconApi, IconPencil } from "@tabler/icons-react";
import { ActionIcon, Avatar, Badge, Card, Group, Stack, Switch, Text, Tooltip } from "@mantine/core";
import { IconAlertTriangle, IconApi, IconPencil, IconSparkles } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { NoResults } from "~/components/no-results";
import { CustomWidgetRowActions } from "./_custom-widget-actions";
const displayTypeBadgeColors: Record<string, string> = {
singleValue: "blue",
keyValue: "green",
table: "orange",
statGrid: "violet",
progressBars: "teal",
statusIndicator: "cyan",
countGrid: "indigo",
raw: "gray",
actionButton: "red",
customJsx: "pink",
};
const iconProps = { size: 16, stroke: 1.5 };
interface CustomWidgetListProps {
definitions: RouterOutputs["customWidget"]["all"];
definitions: RouterOutputs["customWidget"]["list"];
}
export const CustomWidgetList = ({ definitions }: CustomWidgetListProps) => {
@@ -43,59 +31,173 @@ export const CustomWidgetList = ({ definitions }: CustomWidgetListProps) => {
}
return (
<Stack gap="md">
<Table striped highlightOnHover withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("table.name")}</Table.Th>
<Table.Th>{t("table.url")}</Table.Th>
<Table.Th>{t("table.display")}</Table.Th>
<Table.Th w={90} />
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{definitions.map((def) => (
<Table.Tr key={def.id} style={{ opacity: def.enabled ? undefined : 0.5 }}>
<Table.Td>
<Group gap="xs" wrap="nowrap">
{def.iconUrl ? (
<Avatar size={20} radius="sm" src={def.iconUrl} styles={{ image: { objectFit: "contain" } }} />
) : (
<IconApi size={16} />
)}
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"} style={{ minWidth: 0 }}>
{def.name}
</Text>
</Group>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed" lineClamp={1}>
{def.url}
</Text>
</Table.Td>
<Table.Td>
<Badge color={displayTypeBadgeColors[def.displayType] ?? "gray"} size="sm">
{t(`displayType.${def.displayType}` as never)}
</Badge>
</Table.Td>
<Table.Td>
<Group gap={4} justify="flex-end" wrap="nowrap">
<ActionIcon
component={Link}
href={`/manage/custom-widgets/edit/${def.id}`}
variant="filled"
color="red"
aria-label={t("action.edit")}
>
<IconPencil {...iconProps} />
</ActionIcon>
<CustomWidgetRowActions widget={{ id: def.id, name: def.name, enabled: def.enabled }} />
</Group>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
<Stack gap="sm">
{definitions.map((def) => (
<CustomWidgetCard key={def.id} widget={def} />
))}
</Stack>
);
};
type WidgetDef = RouterOutputs["customWidget"]["list"][number];
function CustomWidgetCard({ widget }: { widget: WidgetDef }) {
const t = useScopedI18n("customWidget");
const toggleMutation = clientApi.customWidget.toggleEnabled.useMutation();
const utils = clientApi.useUtils();
const handleToggle = () => {
toggleMutation.mutate(
{ id: widget.id, enabled: !widget.enabled },
{
onSuccess: async () => {
await utils.widget.customApi.getData.cancel();
void utils.customWidget.list.invalidate();
void utils.widget.customApi.getData.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets");
},
onError: () => {
showErrorNotification({
title: widget.enabled ? t("action.disable") : t("action.enable"),
message: t("notification.toggleError"),
});
},
},
);
};
return (
<Card
padding="sm"
withBorder={!widget.valid}
bd={
widget.migrationRequired
? "1px solid var(--mantine-color-yellow-6)"
: !widget.valid
? "1px solid var(--mantine-color-red-6)"
: undefined
}
style={{
opacity: widget.valid && !widget.enabled ? 0.55 : 1,
transition: "opacity 150ms ease",
}}
>
<Group justify="space-between" wrap="nowrap" gap="md">
<Group wrap="nowrap" gap="sm" style={{ flex: 1, minWidth: 0 }}>
{widget.iconUrl ? (
<Avatar size={36} radius="sm" src={widget.iconUrl} styles={{ image: { objectFit: "contain" } }} />
) : (
<Avatar size={36} radius="sm" color="red">
<IconApi size={18} />
</Avatar>
)}
<Stack gap={2} style={{ minWidth: 0, flex: 1 }}>
<Text size="sm" fw={600} lineClamp={1} style={{ minWidth: 0 }}>
{widget.name}
</Text>
{widget.migrationRequired ? (
<Text size="xs" c="yellow.8">
{t("page.list.migrationDescription")}
</Text>
) : !widget.valid ? (
<Text size="xs" c="red">
{t("page.list.invalidDefinitionDescription")}
</Text>
) : null}
{widget.sources[0] && (
<Text size="xs" c="dimmed" ff="monospace" lineClamp={1} style={{ wordBreak: "break-all", minWidth: 0 }}>
{widget.sources.map((source) => source.origin).join(" · ")}
</Text>
)}
</Stack>
{widget.migrationRequired ? (
<Tooltip label={t("page.list.migrationInstructions")} multiline maw={420}>
<Badge
color="yellow"
size="sm"
variant="light"
leftSection={<IconSparkles size={12} />}
style={{ flexShrink: 0 }}
>
{t("page.list.migrationRequired")}
</Badge>
</Tooltip>
) : widget.valid ? (
<Badge color="pink" size="sm" variant="light" style={{ flexShrink: 0 }}>
JSX · {widget.requestCount}
</Badge>
) : (
<Tooltip
label={widget.validationIssues
.map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message))
.join("\n")}
multiline
maw={520}
>
<Badge
color="red"
size="sm"
variant="light"
leftSection={<IconAlertTriangle size={12} />}
style={{ flexShrink: 0 }}
>
{t("page.list.invalidDefinition")}
</Badge>
</Tooltip>
)}
{widget.missingSecrets.length > 0 && (
<Tooltip
label={t("page.list.missingCredentialsDescription", { count: widget.missingSecrets.length })}
multiline
maw={320}
>
<Badge
color="yellow"
size="sm"
variant="light"
leftSection={<IconAlertTriangle size={12} />}
style={{ flexShrink: 0 }}
>
{t("page.list.missingCredentials", { count: widget.missingSecrets.length })}
</Badge>
</Tooltip>
)}
</Group>
<Group gap="xs" wrap="nowrap" style={{ flexShrink: 0 }}>
{widget.valid && (
<>
<Tooltip label={widget.enabled ? t("action.disable") : t("action.enable")}>
<Switch
size="sm"
checked={widget.enabled}
onChange={handleToggle}
disabled={toggleMutation.isPending}
aria-label={widget.enabled ? t("action.disable") : t("action.enable")}
/>
</Tooltip>
<ActionIcon
component={Link}
href={`/manage/custom-widgets/edit/${widget.id}`}
variant="subtle"
color="gray"
aria-label={t("action.edit")}
>
<IconPencil size={16} stroke={1.5} />
</ActionIcon>
</>
)}
<CustomWidgetRowActions
widget={{
id: widget.id,
name: widget.name,
enabled: widget.enabled,
valid: widget.valid,
migrationRequired: widget.migrationRequired,
}}
/>
</Group>
</Group>
</Card>
);
}
@@ -0,0 +1,196 @@
"use client";
import { useEffect, useState } from "react";
import { ActionIcon, Button, Group, MultiSelect, NumberInput, Select, Stack, Switch, TextInput } from "@mantine/core";
import { IconPlus, IconTrash } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { CodeEditor } from "./_code-editor";
export function DefaultValueEditor({
id,
control,
value,
choices = [],
onChange,
}: {
id: string;
control: string;
value: unknown;
choices?: Array<{ label: string; value: string | number }>;
onChange: (value: unknown) => void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
if (control === "switch")
return (
<Switch
label={t("default")}
checked={value === true}
onChange={(event) => onChange(event.currentTarget.checked)}
/>
);
if (["number", "slider", "duration"].includes(control))
return <NumberInput label={t("default")} value={typeof value === "number" ? value : 0} onChange={onChange} />;
const choiceData = choices.map((choice) => ({ label: choice.label, value: String(choice.value) }));
if (control === "select" && choices.length > 0)
return (
<Select
label={t("default")}
data={choiceData}
value={value === undefined ? null : String(value)}
onChange={(next) => onChange(coerceChoice(next, choices))}
/>
);
if (control === "multiSelect" && choices.length > 0)
return (
<MultiSelect
label={t("default")}
data={choiceData}
value={Array.isArray(value) ? value.map(String) : []}
onChange={(next) => onChange(next.map((entry) => coerceChoice(entry, choices)))}
/>
);
if (control === "json" || control === "multiSelect")
return <JsonValueEditor id={id} label={t("default")} value={value} onChange={onChange} />;
return (
<TextInput
label={t("default")}
value={typeof value === "string" ? value : ""}
onChange={(event) => onChange(event.currentTarget.value)}
/>
);
}
export function optionForControl(option: Record<string, unknown>, control: string | null): Record<string, unknown> {
const nextControl = control ?? "text";
const next: Record<string, unknown> = { ...option, control: nextControl, default: defaultForControl(nextControl) };
if (!["select", "multiSelect"].includes(nextControl)) {
next.choices = undefined;
next.choicesFrom = undefined;
}
if (!["number", "slider", "duration"].includes(nextControl)) {
next.min = undefined;
next.max = undefined;
next.step = undefined;
}
return next;
}
export function OptionChoicesEditor({
value,
onChange,
}: {
value: Array<{ label: string; value: string | number }>;
onChange(value: Array<{ label: string; value: string | number }>): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
return (
<Stack gap="xs">
{value.map((choice, index) => (
<Group key={index} align="end" wrap="wrap">
<TextInput
style={{ flex: "1 1 10rem" }}
label={t("choiceLabel")}
value={choice.label}
onChange={(event) =>
onChange(
value.map((entry, entryIndex) =>
entryIndex === index ? { ...entry, label: event.currentTarget.value } : entry,
),
)
}
/>
<TextInput
style={{ flex: "1 1 10rem" }}
label={t("choiceValue")}
value={String(choice.value)}
onChange={(event) =>
onChange(
value.map((entry, entryIndex) =>
entryIndex === index ? { ...entry, value: parseChoiceValue(event.currentTarget.value) } : entry,
),
)
}
/>
<ActionIcon
type="button"
color="red"
variant="subtle"
aria-label={t("removeChoice")}
onClick={() => onChange(value.filter((_, entryIndex) => entryIndex !== index))}
>
<IconTrash size={16} />
</ActionIcon>
</Group>
))}
<Button
type="button"
size="compact-sm"
variant="subtle"
leftSection={<IconPlus size={14} />}
onClick={() => onChange([...value, { label: t("newChoice"), value: `choice-${value.length + 1}` }])}
>
{t("addChoice")}
</Button>
</Stack>
);
}
export function JsonValueEditor({
id,
label,
description,
value,
onChange,
}: {
id: string;
label: string;
description?: string;
value: unknown;
onChange(value: unknown): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
const serialized = JSON.stringify(value, null, 2);
const [draft, setDraft] = useState(serialized);
const [error, setError] = useState<string>();
useEffect(() => setDraft(serialized), [serialized]);
return (
<CodeEditor
id={`option-${id}`}
label={label}
description={description}
language="json"
value={draft}
height="140px"
error={error}
onChange={(next) => {
setDraft(next);
try {
onChange(JSON.parse(next) as unknown);
setError(undefined);
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("invalidJson"));
}
}}
/>
);
}
function defaultForControl(control: string | null) {
if (control === "switch") return false;
if (["number", "slider", "duration"].includes(control ?? "")) return 0;
if (control === "multiSelect") return [];
if (control === "json") return {};
return "";
}
function parseChoiceValue(value: string): string | number {
return /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/u.test(value.trim()) ? Number(value) : value;
}
function coerceChoice(value: string | null, choices: Array<{ value: string | number }>) {
if (value === null) return "";
const numeric = choices.find((choice) => typeof choice.value === "number" && String(choice.value) === value);
return numeric?.value ?? value;
}
@@ -0,0 +1,271 @@
"use client";
import {
Accordion,
ActionIcon,
Button,
Fieldset,
Group,
NumberInput,
Select,
Stack,
Switch,
Text,
TextInput,
} from "@mantine/core";
import { IconArrowDown, IconArrowUp, IconPlus, IconTrash } from "@tabler/icons-react";
import { customWidgetOptionControls } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import { isRecord, parseJson } from "./_custom-widget-form-utils";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { DefaultValueEditor, OptionChoicesEditor, optionForControl } from "./_custom-widget-option-fields";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
export function CustomWidgetOptionsEditor({
form,
onRename,
}: {
form: CustomWidgetWorkbenchForm;
onRename(currentName: string, nextName: string): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
const parsed = parseJson(form.values.options);
const entries = isRecord(parsed) ? Object.entries(parsed) : [];
const requests = parseJson(form.values.requests);
const requestIds = isRecord(requests) ? Object.keys(requests) : [];
const commit = (next: Array<[string, unknown]>) =>
form.setFieldValue("options", JSON.stringify(Object.fromEntries(next), null, 2));
const update = (index: number, id: string, option: Record<string, unknown>) =>
commit(entries.map((entry, i) => (i === index ? [id, option] : entry)));
const remove = (index: number) => commit(entries.filter((_, i) => i !== index));
const move = (index: number, direction: -1 | 1) => {
const next = [...entries];
const target = index + direction;
if (!next[index] || !next[target]) return;
[next[index], next[target]] = [next[target], next[index]];
commit(next);
};
const add = () => {
let suffix = entries.length + 1;
while (entries.some(([id]) => id === `option-${suffix}`)) suffix += 1;
commit([...entries, [`option-${suffix}`, { label: `Option ${suffix}`, control: "text", default: "" }]]);
};
return (
<Stack gap="sm">
{entries.map(([id, rawOption], index) => {
const option = isRecord(rawOption) ? rawOption : {};
const control = typeof option.control === "string" ? option.control : "text";
const choicesFrom = isRecord(option.choicesFrom) ? option.choicesFrom : null;
const choices = Array.isArray(option.choices)
? option.choices.flatMap((choice) =>
isRecord(choice) &&
typeof choice.label === "string" &&
(typeof choice.value === "string" || typeof choice.value === "number")
? [{ label: choice.label, value: choice.value }]
: [],
)
: [];
return (
<Fieldset key={index} legend={typeof option.label === "string" ? option.label : id}>
<Stack gap="sm">
<Group grow align="start">
<CustomWidgetIdentifierInput
label={t("optionName")}
value={id}
error={form.errors.options}
onCommit={(value) => onRename(id, value)}
/>
<TextInput
label={t("label")}
value={typeof option.label === "string" ? option.label : ""}
onChange={(event) => update(index, id, { ...option, label: event.currentTarget.value })}
/>
<Select
label={t("control")}
data={[...customWidgetOptionControls]}
value={control}
allowDeselect={false}
onChange={(value) => update(index, id, optionForControl(option, value))}
/>
</Group>
<TextInput
label={t("description")}
value={typeof option.description === "string" ? option.description : ""}
onChange={(event) =>
update(index, id, { ...option, description: event.currentTarget.value || undefined })
}
/>
<DefaultValueEditor
id={`${index}-default`}
control={control}
value={option.default}
choices={choices}
onChange={(value) => update(index, id, { ...option, default: value })}
/>
<Accordion variant="contained">
<Accordion.Item value="advanced">
<Accordion.Control>{t("optionDetails")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="sm">
{["number", "slider", "duration"].includes(control) && (
<Group grow>
<NumberInput
label={t("minimum")}
value={typeof option.min === "number" ? option.min : ""}
onChange={(value) =>
update(index, id, { ...option, min: typeof value === "number" ? value : undefined })
}
/>
<NumberInput
label={t("maximum")}
value={typeof option.max === "number" ? option.max : ""}
onChange={(value) =>
update(index, id, { ...option, max: typeof value === "number" ? value : undefined })
}
/>
<NumberInput
label={t("step")}
value={typeof option.step === "number" ? option.step : ""}
onChange={(value) =>
update(index, id, { ...option, step: typeof value === "number" ? value : undefined })
}
/>
</Group>
)}
{["select", "multiSelect"].includes(control) && (
<OptionChoicesEditor
value={choices}
onChange={(nextChoices) =>
update(index, id, {
...option,
choices: nextChoices.length > 0 ? nextChoices : undefined,
choicesFrom: undefined,
default:
control === "select" &&
!nextChoices.some((choice) => Object.is(choice.value, option.default))
? (nextChoices[0]?.value ?? "")
: option.default,
})
}
/>
)}
{["select", "multiSelect"].includes(control) && (
<Group grow align="start">
<Select
label={t("choicesRequest")}
data={requestIds}
value={typeof choicesFrom?.request === "string" ? choicesFrom.request : null}
clearable
onChange={(value) =>
update(index, id, {
...option,
choices: value ? undefined : option.choices,
choicesFrom: value ? { request: value, valuePath: "id", labelPath: "name" } : undefined,
})
}
/>
{choicesFrom && (
<>
<TextInput
label={t("itemsPath")}
placeholder={t("itemsPathPlaceholder")}
value={String(choicesFrom.itemsPath ?? "")}
onChange={(event) =>
update(index, id, {
...option,
choicesFrom: { ...choicesFrom, itemsPath: event.currentTarget.value || undefined },
})
}
/>
<TextInput
label={t("valuePath")}
value={String(choicesFrom.valuePath ?? "")}
onChange={(event) =>
update(index, id, {
...option,
choicesFrom: { ...choicesFrom, valuePath: event.currentTarget.value },
})
}
/>
<TextInput
label={t("labelPath")}
value={String(choicesFrom.labelPath ?? "")}
onChange={(event) =>
update(index, id, {
...option,
choicesFrom: { ...choicesFrom, labelPath: event.currentTarget.value },
})
}
/>
</>
)}
</Group>
)}
<Group grow>
<TextInput
label={t("group")}
value={typeof option.group === "string" ? option.group : ""}
onChange={(event) =>
update(index, id, { ...option, group: event.currentTarget.value || undefined })
}
/>
<Switch
mt="xl"
label={t("advancedOption")}
checked={option.advanced === true}
onChange={(event) => update(index, id, { ...option, advanced: event.currentTarget.checked })}
/>
</Group>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
<Group justify="space-between">
<Group gap="xs">
<ActionIcon
type="button"
variant="subtle"
aria-label={t("moveOptionUp")}
disabled={index === 0}
onClick={() => move(index, -1)}
>
<IconArrowUp size={16} />
</ActionIcon>
<ActionIcon
type="button"
variant="subtle"
aria-label={t("moveOptionDown")}
disabled={index === entries.length - 1}
onClick={() => move(index, 1)}
>
<IconArrowDown size={16} />
</ActionIcon>
</Group>
<Button
type="button"
color="red"
variant="subtle"
leftSection={<IconTrash size={16} />}
onClick={() => remove(index)}
>
{t("removeOption")}
</Button>
</Group>
</Stack>
</Fieldset>
);
})}
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={add}>
{t("addOption")}
</Button>
{form.errors.options && (
<Text c="red" size="xs">
{form.errors.options}
</Text>
)}
</Stack>
);
}
@@ -0,0 +1,86 @@
"use client";
import { useState } from "react";
import { Button, Fieldset, Stack, Textarea } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { collectCustomWidgetRequestReferences, getCustomWidgetConfirmation } from "@homarr/custom-widgets/core";
import type { CustomJsxRequest } from "@homarr/custom-widgets/core";
import { useConfirmModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { isRuntimeParams, parseJson } from "./_custom-widget-form-utils";
export function PreviewActionControl({
request,
sessionId,
}: {
request: CustomJsxRequest & { id: string };
sessionId?: string;
}) {
const t = useScopedI18n("customWidget.workbench.preview");
const { openConfirmModal } = useConfirmModal();
const actionMutation = clientApi.customWidget.previewAction.useMutation();
const expectedParams = [...collectCustomWidgetRequestReferences(request).params].toSorted();
const initialParams = Object.fromEntries(expectedParams.map((name) => [name, ""]));
const [params, setParams] = useState(JSON.stringify(initialParams, null, 2));
const parsed = parseJson(params);
const validParams = isRuntimeParams(parsed, expectedParams) ? parsed : null;
const confirmation = getCustomWidgetConfirmation(request);
const run = async () => {
if (!sessionId || !validParams) return;
const needsConfirmation = request.confirmation !== undefined || request.method === "DELETE";
if (needsConfirmation) {
const confirmed = await new Promise<boolean>((resolve) => {
openConfirmModal({
title: confirmation?.title ?? request.id,
children: confirmation?.message ?? t("deleteConfirmation"),
labels: { confirm: confirmation?.confirmLabel },
confirmProps: { color: confirmation?.destructive || request.method === "DELETE" ? "red.9" : "blue" },
onConfirm: () => resolve(true),
onCancel: () => resolve(false),
});
});
if (!confirmed) return;
}
actionMutation.mutate(
{ sessionId, requestId: request.id, params: validParams, confirmed: needsConfirmation },
{
onSuccess: (result) =>
showSuccessNotification({
title: request.id,
message: result.simulated ? t("simulated") : t("httpStatus", { status: result.status }),
}),
onError: (error) => showErrorNotification({ title: request.id, message: error.message }),
},
);
};
return (
<Fieldset legend={`${request.id} · ${request.method}`}>
<Stack gap="xs">
{expectedParams.length > 0 && (
<Textarea
label={t("actionParameters")}
autosize
minRows={2}
value={params}
error={validParams ? undefined : t("invalidParameters")}
onChange={(event) => setParams(event.currentTarget.value)}
/>
)}
<Button
type="button"
variant="light"
color={confirmation?.destructive || request.method === "DELETE" ? "red" : undefined}
disabled={!sessionId || !validParams}
loading={actionMutation.isPending}
onClick={() => void run()}
>
{confirmation?.confirmLabel ??
(confirmation?.destructive || request.method === "DELETE" ? t("runDestructive") : t("runAction"))}
</Button>
</Stack>
</Fieldset>
);
}
@@ -0,0 +1,51 @@
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
interface PreviewSnapshot {
data: Record<string, unknown>;
status: Record<string, unknown>;
session: { id: string; liveActions: boolean } | null;
}
export function createPreviewDisplayData({
candidate,
fixture,
preview,
options,
fixtureError,
}: {
candidate: HomarrCustomWidgetV2 | null;
fixture: "live" | "loading" | "empty" | "error";
preview: PreviewSnapshot;
options: Record<string, unknown>;
fixtureError: string;
}): Record<string, unknown> | null {
if (!candidate) return null;
const requests = Object.entries(candidate.requests);
const data = fixture === "empty" ? Object.fromEntries(requests.map(([id]) => [id, []])) : preview.data;
const status =
fixture === "loading"
? Object.fromEntries(requests.map(([id]) => [id, { loading: true }]))
: fixture === "error"
? Object.fromEntries(requests.map(([id]) => [id, { loading: false, ok: false, error: fixtureError }]))
: preview.status;
return {
template: candidate.template,
data,
status,
options,
requestCapabilities: requests.map(([id, { kind, method, trigger, permission, confirmation, invalidates }]) => ({
id,
kind,
method,
trigger,
minimumBoardPermission: permission,
confirmation:
typeof confirmation === "string" ? { title: "Confirm action", message: confirmation } : confirmation,
invalidates,
})),
previewSessionId: preview.session?.id,
previewLiveActions: preview.session?.liveActions ?? false,
queriesDisabled: fixture !== "live",
isEditMode: fixture !== "live",
};
}
@@ -0,0 +1,225 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import { CustomWidgetPreviewPanel } from "./_custom-widget-preview-panel";
vi.mock("@homarr/api/client", () => ({
clientApi: {
customWidget: {
setPreviewLiveActions: { useMutation: () => ({ isPending: false, mutate: vi.fn() }) },
previewJournal: { useQuery: () => ({ data: [] }) },
},
},
}));
vi.mock("@homarr/translation/client", () => ({ useScopedI18n: () => (key: string) => key }));
vi.mock("@homarr/notifications", () => ({ showErrorNotification: vi.fn() }));
const rendererAttempt = vi.hoisted(() => vi.fn());
vi.mock("@homarr/widgets/custom-api/custom-jsx-display", () => ({
default: ({ data }: { data: Record<string, unknown> }) => {
rendererAttempt(data);
if ((data.options as Record<string, unknown> | undefined)?.throwPreview === true) {
throw new Error("authored widget failed");
}
return <div>widget-renderer</div>;
},
}));
vi.mock("./_code-editor", () => ({ CodeEditor: ({ label }: { label: string }) => <div>{label}</div> }));
vi.mock("./_custom-widget-preview-action", () => ({ PreviewActionControl: () => <div>action-control</div> }));
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
unobserve() {}
disconnect() {}
},
);
window.matchMedia = vi.fn().mockImplementation(() => ({
matches: false,
media: "",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
describe("Custom Widget preview panel", () => {
test("contains invalid definitions inside the widget canvas while keeping every inspection tab", async () => {
await act(async () => {
root.render(
<MantineProvider>
<CustomWidgetPreviewPanel
candidate={null}
validationIssues={[{ path: "sources.0.baseUrl", message: "Enter a complete URL." }]}
preview={{ data: { previous: true }, status: {}, session: null, outcome: "idle" }}
size="standard"
onSizeChange={vi.fn()}
theme="dark"
onThemeChange={vi.fn()}
optionsSnapshot={{}}
onOptionsChange={vi.fn()}
onLiveActionsChange={vi.fn()}
/>
</MantineProvider>,
);
});
const previewCanvas = host.querySelector('[class*="previewCanvas"]');
expect(previewCanvas?.textContent).toContain("invalid");
for (const tab of ["widget", "data", "options", "actions", "diagnostics"]) {
expect(host.textContent).toContain(`tab.${tab}`);
}
const dataTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.data"),
);
await act(async () => dataTab?.click());
expect(host.textContent).toContain("requestData");
expect(host.textContent).not.toContain("invalid");
const optionsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.options"),
);
await act(async () => optionsTab?.click());
expect(host.textContent).toContain("instanceOptions");
expect(host.textContent).not.toContain("invalid");
const actionsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.actions"),
);
await act(async () => actionsTab?.click());
expect(host.textContent).toContain("liveActions");
expect(host.textContent).not.toContain("invalid");
const diagnosticsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.diagnostics"),
);
expect(diagnosticsTab).toBeDefined();
await act(async () => diagnosticsTab?.click());
expect(host.textContent).toContain("sources.0.baseUrl");
expect(host.textContent).toContain("Enter a complete URL.");
});
test("contains renderer failures inside the widget tab and keeps the inspection tabs usable", async () => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
rendererAttempt.mockClear();
const bundledWidget = BUNDLED_CUSTOM_WIDGETS.at(0);
if (!bundledWidget) throw new Error("Expected at least one bundled Custom Widget");
const candidate = customWidgetDefinitionSchema.parse(bundledWidget.widget);
const preview = { data: {}, status: {}, session: null, outcome: "idle" } as const;
const failingOptions = { throwPreview: true };
await act(async () => {
root.render(
<MantineProvider>
<CustomWidgetPreviewPanel
candidate={{
...candidate,
requests: Object.fromEntries(
Object.entries(candidate.requests).map(([id, request]) => [id, { ...request }]),
),
}}
validationIssues={[]}
preview={preview}
size="standard"
onSizeChange={vi.fn()}
theme="dark"
onThemeChange={vi.fn()}
optionsSnapshot={{ ...failingOptions }}
onOptionsChange={vi.fn()}
onLiveActionsChange={vi.fn()}
/>
</MantineProvider>,
);
});
expect(host.textContent).toContain("title");
expect(host.querySelector('[class*="previewCanvas"]')?.textContent).toContain("title");
for (const tab of ["widget", "data", "options", "actions", "diagnostics"]) {
expect(host.textContent).toContain(`tab.${tab}`);
}
const attemptsAfterFailure = rendererAttempt.mock.calls.length;
await act(async () => {
root.render(
<MantineProvider>
<CustomWidgetPreviewPanel
candidate={candidate}
validationIssues={[]}
preview={preview}
size="standard"
onSizeChange={vi.fn()}
theme="dark"
onThemeChange={vi.fn()}
optionsSnapshot={failingOptions}
onOptionsChange={vi.fn()}
onLiveActionsChange={vi.fn()}
/>
</MantineProvider>,
);
});
expect(rendererAttempt).toHaveBeenCalledTimes(attemptsAfterFailure);
const dataTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.data"),
);
await act(async () => dataTab?.click());
expect(host.textContent).toContain("requestData");
const diagnosticsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.diagnostics"),
);
await act(async () => diagnosticsTab?.click());
expect(host.textContent).toContain("validation.title");
const widgetTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.widget"),
);
await act(async () => widgetTab?.click());
await act(async () => {
root.render(
<MantineProvider>
<CustomWidgetPreviewPanel
candidate={candidate}
validationIssues={[]}
preview={preview}
size="standard"
onSizeChange={vi.fn()}
theme="dark"
onThemeChange={vi.fn()}
optionsSnapshot={{}}
onOptionsChange={vi.fn()}
onLiveActionsChange={vi.fn()}
/>
</MantineProvider>,
);
});
expect(host.textContent).toContain("widget-renderer");
});
});
@@ -0,0 +1,273 @@
"use client";
import { useState } from "react";
import {
Alert,
Badge,
Box,
Card,
Group,
MantineProvider,
Paper,
SegmentedControl,
Stack,
Switch,
Tabs,
Text,
} from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { analyzeCustomWidgetAccessibility, PreviewErrorBoundary } from "@homarr/custom-widgets/workbench";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
import { CodeEditor } from "./_code-editor";
import { getPreviewSummary, PreviewResult, PreviewStatusDot } from "./_custom-widget-preview-status";
import type { PreviewOutcome } from "./_custom-widget-preview-status";
import { PreviewActionControl } from "./_custom-widget-preview-action";
import { createPreviewDisplayData } from "./_custom-widget-preview-data";
import { JsonPreviewEditor } from "./_json-preview-editor";
import classes from "./_custom-widget-form.module.css";
export interface PreviewState {
data: Record<string, unknown>;
status: Record<string, unknown>;
session: { id: string; expiresAt: number; liveActions: boolean } | null;
outcome: PreviewOutcome;
}
interface PreviewPanelProps {
candidate: HomarrCustomWidgetV2 | null;
validationIssues: Array<{ path?: string; message: string }>;
preview: PreviewState;
size: string;
onSizeChange(value: string): void;
theme: "light" | "dark";
onThemeChange(value: "light" | "dark"): void;
optionsSnapshot: Record<string, unknown>;
onOptionsChange(value: Record<string, unknown>): void;
onLiveActionsChange(enabled: boolean): void;
}
export function CustomWidgetPreviewPanel(props: PreviewPanelProps) {
const t = useScopedI18n("customWidget.workbench.preview");
const errorBoundaryMessages = useScopedI18n("customWidget.editor.errorBoundary");
const [fixture, setFixture] = useState<"live" | "loading" | "empty" | "error">("live");
const liveActionsMutation = clientApi.customWidget.setPreviewLiveActions.useMutation();
const journalQuery = clientApi.customWidget.previewJournal.useQuery(
{ sessionId: props.preview.session?.id ?? "" },
{ enabled: Boolean(props.preview.session), refetchInterval: props.preview.session ? 2_000 : false },
);
const widths: Record<string, number> = { compact: 320, standard: 480, wide: 720 };
const candidate = props.candidate;
const accessibilityIssues = candidate ? analyzeCustomWidgetAccessibility(candidate.template) : [];
const displayData = createPreviewDisplayData({
candidate,
fixture,
preview: props.preview,
options: props.optionsSnapshot,
fixtureError: t("fixtureError"),
});
const previewSummary = getPreviewSummary(props.preview.status);
const rendererResetKey = JSON.stringify({
template: candidate?.template,
requests: candidate?.requests,
fixture,
data: props.preview.data,
status: props.preview.status,
sessionId: props.preview.session?.id,
options: props.optionsSnapshot,
});
const previewResult =
props.preview.outcome === "success"
? {
title: t("result.success.title"),
description: t("result.success.description", previewSummary),
}
: props.preview.outcome === "error"
? {
title: t("result.error.title"),
description: t("result.error.description", previewSummary),
}
: props.preview.outcome === "loading"
? { title: t("result.loading.title"), description: t("result.loading.description") }
: { title: "", description: "" };
return (
<Card withBorder p="md">
<Stack gap="md">
<Group grow>
<SegmentedControl
size="xs"
value={props.size}
onChange={props.onSizeChange}
data={[
{ value: "compact", label: t("size.compact") },
{ value: "standard", label: t("size.standard") },
{ value: "wide", label: t("size.wide") },
]}
/>
<SegmentedControl
size="xs"
value={props.theme}
onChange={(value) => props.onThemeChange(value as "light" | "dark")}
data={[
{ value: "light", label: t("theme.light") },
{ value: "dark", label: t("theme.dark") },
]}
/>
</Group>
<SegmentedControl
size="xs"
value={fixture}
disabled={!candidate}
onChange={(value) => setFixture(value as typeof fixture)}
data={[
{ value: "live", label: t("fixture.live") },
{ value: "loading", label: t("fixture.loading") },
{ value: "empty", label: t("fixture.empty") },
{ value: "error", label: t("fixture.error") },
]}
/>
{candidate && (
<PreviewResult
outcome={props.preview.outcome}
title={previewResult.title}
description={previewResult.description}
/>
)}
<Tabs defaultValue="widget" keepMounted={false}>
<Tabs.List grow>
{(["widget", "data", "options", "actions", "diagnostics"] as const).map((tab) => (
<Tabs.Tab key={tab} value={tab}>
<Group gap={6} wrap="nowrap" justify="center">
{t(`tab.${tab}`)}
{tab === "data" && (
<PreviewStatusDot outcome={props.preview.outcome} label={t(`status.${props.preview.outcome}`)} />
)}
</Group>
</Tabs.Tab>
))}
</Tabs.List>
<Tabs.Panel value="widget" pt="sm">
<Box className={classes.previewCanvas}>
<MantineProvider forceColorScheme={props.theme}>
<Paper withBorder p="sm" h={360} w={widths[props.size] ?? 480} maw="100%" style={{ overflow: "auto" }}>
{displayData ? (
<PreviewErrorBoundary
title={errorBoundaryMessages("title")}
description={t("containedFailures")}
retryLabel={errorBoundaryMessages("retry")}
resetKeys={[rendererResetKey]}
>
<CustomJsxDisplay data={displayData} />
</PreviewErrorBoundary>
) : (
<Alert color="yellow">{t("invalid")}</Alert>
)}
</Paper>
</MantineProvider>
</Box>
</Tabs.Panel>
<Tabs.Panel value="data" pt="sm">
<CodeEditor
id="preview-data"
label={t("requestData")}
language="json"
value={JSON.stringify({ data: props.preview.data, status: props.preview.status }, null, 2)}
onChange={() => undefined}
/>
</Tabs.Panel>
<Tabs.Panel value="options" pt="sm">
<JsonPreviewEditor
id="preview-options"
label={t("instanceOptions")}
value={props.optionsSnapshot}
onChange={props.onOptionsChange}
/>
</Tabs.Panel>
<Tabs.Panel value="actions" pt="sm">
<Stack gap="sm">
<Switch
label={t("liveActions")}
description={t("liveActionsDescription")}
checked={props.preview.session?.liveActions ?? false}
disabled={!props.preview.session || liveActionsMutation.isPending}
onChange={(event) => {
if (!props.preview.session) return;
const enabled = event.currentTarget.checked;
liveActionsMutation.mutate(
{ sessionId: props.preview.session.id, enabled },
{
onSuccess: () => props.onLiveActionsChange(enabled),
onError: (error) => showErrorNotification({ title: t("liveActions"), message: error.message }),
},
);
}}
/>
{Object.entries(candidate?.requests ?? {})
.filter(([, request]) => request.kind === "action")
.map(([id, request]) => (
<PreviewActionControl key={id} request={{ id, ...request }} sessionId={props.preview.session?.id} />
))}
{Object.values(candidate?.requests ?? {}).every((request) => request.kind !== "action") && (
<Text size="sm" c="dimmed">
{t("noActions")}
</Text>
)}
</Stack>
</Tabs.Panel>
<Tabs.Panel value="diagnostics" pt="sm">
<Stack gap="xs">
{props.preview.session ? (
<Badge color="green">{t("sessionActive")}</Badge>
) : (
<Badge color="gray">{t("simulationPending")}</Badge>
)}
<Text size="sm" c="dimmed">
{t("containedFailures")}
</Text>
<Text size="sm" fw={600}>
{t("validation.title")}
</Text>
{props.validationIssues.length === 0 ? (
<Alert color="green">{t("validation.ready")}</Alert>
) : (
props.validationIssues.map((issue, index) => (
<Alert key={`${issue.path ?? "widget"}-${index}`} color="red" title={issue.path}>
{issue.message}
</Alert>
))
)}
<Text size="sm" fw={600}>
{t("accessibility.title")}
</Text>
{!candidate ? (
<Alert color="gray">{t("accessibility.pending")}</Alert>
) : accessibilityIssues.length === 0 ? (
<Alert color="green">{t("accessibility.ready")}</Alert>
) : (
accessibilityIssues.map((issue) => (
<Alert key={issue} color="yellow">
{t(`accessibility.${issue}`)}
</Alert>
))
)}
{props.preview.session && (
<CodeEditor
id="preview-journal"
label={t("journal")}
language="json"
value={JSON.stringify(journalQuery.data ?? [], null, 2)}
onChange={() => undefined}
/>
)}
</Stack>
</Tabs.Panel>
</Tabs>
</Stack>
</Card>
);
}
@@ -0,0 +1,54 @@
"use client";
import { Alert, Box, Text, Tooltip } from "@mantine/core";
import { isRecord } from "./_custom-widget-form-utils";
export type PreviewOutcome = "idle" | "loading" | "success" | "error";
export function PreviewResult({
outcome,
title,
description,
}: {
outcome: PreviewOutcome;
title: string;
description: string;
}) {
if (outcome === "idle") return null;
return (
<Alert color={outcome === "error" ? "red" : outcome === "success" ? "green" : "yellow"}>
<Text size="sm" fw={600}>
{title}
</Text>
<Text size="sm">{description}</Text>
</Alert>
);
}
export function PreviewStatusDot({ outcome, label }: { outcome: PreviewOutcome; label: string }) {
const colors = { idle: "gray", loading: "yellow", success: "green", error: "red" } as const;
return (
<Tooltip label={label}>
<Box
component="output"
aria-label={label}
w={8}
h={8}
bg={`var(--mantine-color-${colors[outcome]}-6)`}
style={{ borderRadius: "50%", flexShrink: 0 }}
/>
</Tooltip>
);
}
export function getPreviewSummary(status: Record<string, unknown>) {
return Object.values(status).reduce<{ succeeded: number; failed: number }>(
(summary, value) => {
if (isRecord(value) && value.ok === false) summary.failed += 1;
else summary.succeeded += 1;
return summary;
},
{ succeeded: 0, failed: 0 },
);
}
@@ -1,180 +0,0 @@
"use client";
import { useMemo } from "react";
import { Alert, Badge, Button, Card, Center, Code, Group, Loader, ScrollArea, Stack, Text, Title } from "@mantine/core";
import { IconAlertTriangle, IconExternalLink, IconPlayerPlay } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { extractDisplayData } from "@homarr/widgets/custom-api/extract-display-data";
import { displayComponents } from "@homarr/widgets/custom-api/component";
interface PreviewInput {
url: string;
method: string;
authType: string;
headerName?: string;
requestBody?: string;
displayType: string;
displayConfig: Record<string, unknown>;
secrets: Array<{ kind: string; value: string }>;
definitionId?: string;
}
export interface PreviewFetchResult {
success: boolean;
error?: string;
responseInfo: { status: number; statusText: string } | null;
rawResponse: string | null;
}
interface CustomWidgetPreviewProps {
getFormValues: () => PreviewInput;
formValues: PreviewInput;
fetchResult: PreviewFetchResult | null;
cachedJson: unknown;
onTest: () => void;
isTesting: boolean;
testError?: string | null;
}
export function CustomWidgetPreview({
getFormValues,
formValues,
fetchResult,
cachedJson,
onTest,
isTesting,
testError,
}: CustomWidgetPreviewProps) {
const t = useScopedI18n("customWidget");
const displayData = useMemo((): Record<string, unknown> | null => {
const { displayType, displayConfig } = formValues;
if (displayType === "actionButton") {
return extractDisplayData(null, displayType, displayConfig) as Record<string, unknown>;
}
if (!fetchResult?.success || cachedJson == null) return null;
return extractDisplayData(cachedJson, displayType, displayConfig) as Record<string, unknown>;
}, [fetchResult?.success, cachedJson, formValues]);
const handleTest = () => {
const values = getFormValues();
if (!values.url) return;
onTest();
};
return (
<Card withBorder shadow="sm" p="md">
<Stack gap="sm">
<Group justify="space-between" align="center">
<Title order={5}>{t("preview.title")}</Title>
<Button
size="xs"
variant="light"
leftSection={isTesting ? <Loader size={14} /> : <IconPlayerPlay size={14} />}
onClick={handleTest}
loading={isTesting}
>
{t("preview.test")}
</Button>
</Group>
{testError && (
<Alert color="red" icon={<IconAlertTriangle size={16} />} p="xs">
<Text size="xs">{testError}</Text>
</Alert>
)}
{fetchResult && !fetchResult.success && (
<Alert color="red" icon={<IconAlertTriangle size={16} />} p="xs">
<Text size="xs" fw={500}>
{fetchResult.error}
</Text>
{fetchResult.responseInfo && (
<Badge size="xs" color="red" variant="light" mt={4}>
{fetchResult.responseInfo.status} {fetchResult.responseInfo.statusText}
</Badge>
)}
</Alert>
)}
{displayData && (formValues.displayType === "actionButton" || fetchResult?.success) && (
<Stack gap="xs">
{fetchResult?.success && (
<Group gap="xs">
<Badge size="xs" color="green" variant="light">
{fetchResult.responseInfo?.status} {fetchResult.responseInfo?.statusText}
</Badge>
</Group>
)}
<Card withBorder p="xs" bg="var(--mantine-color-dark-7)" mah={320} style={{ overflow: "auto" }}>
<PreviewDisplay data={displayData} />
</Card>
{fetchResult?.success && fetchResult.rawResponse && (
<Button
size="xs"
variant="subtle"
leftSection={<IconExternalLink size={14} />}
onClick={() => {
const blob = new Blob([fetchResult.rawResponse ?? ""], {
type: "application/json",
});
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl);
setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000);
}}
>
{t("preview.rawResponse")}
</Button>
)}
</Stack>
)}
{!displayData && !testError && !isTesting && (
<Text size="xs" c="dimmed" ta="center">
{t("preview.hint")}
</Text>
)}
</Stack>
</Card>
);
}
function PreviewDisplay({ data }: { data: unknown }) {
const typed = data as Record<string, unknown>;
if (!typed || typeof typed !== "object") {
return (
<Text size="xs" c="dimmed">
No data
</Text>
);
}
const dataType = typed.type as string | undefined;
if (dataType === "actionButton") {
return (
<Center p="sm">
<Button size="sm" color={(typed.buttonColor as string) ?? "blue"} disabled>
{(typed.buttonLabel as string) ?? "Execute"}
</Button>
</Center>
);
}
const Component = dataType ? displayComponents[dataType] : undefined;
if (Component) {
return <Component data={typed} />;
}
return (
<ScrollArea h={100}>
<Code block style={{ fontSize: 11 }}>
{JSON.stringify(data, null, 2)}
</Code>
</ScrollArea>
);
}
@@ -0,0 +1,38 @@
import { renameCustomWidgetOption, renameCustomWidgetRequest } from "@homarr/custom-widgets/workbench";
import { applyDefinition } from "./_custom-widget-form-utils";
import type { buildDefinition, CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
interface RenameHandlersInput {
form: CustomWidgetWorkbenchForm;
candidate: ReturnType<typeof buildDefinition>;
invalidWidgetMessage: string;
}
export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
const renameRequest = (currentId: string, nextId: string) => {
if (!input.candidate.success) {
input.form.setFieldError("requests", input.invalidWidgetMessage);
return;
}
try {
applyDefinition(input.form, renameCustomWidgetRequest(input.candidate.data, currentId, nextId));
input.form.clearFieldError("requests");
} catch (error) {
input.form.setFieldError("requests", error instanceof Error ? error.message : input.invalidWidgetMessage);
}
};
const renameOption = (currentName: string, nextName: string) => {
if (!input.candidate.success) {
input.form.setFieldError("options", input.invalidWidgetMessage);
return;
}
try {
applyDefinition(input.form, renameCustomWidgetOption(input.candidate.data, currentName, nextName));
input.form.clearFieldError("options");
} catch (error) {
input.form.setFieldError("options", error instanceof Error ? error.message : input.invalidWidgetMessage);
}
};
return { renameRequest, renameOption };
}
@@ -0,0 +1,228 @@
"use client";
import { useEffect, useState } from "react";
import { ActionIcon, Button, Group, Select, Stack, Text, TextInput } from "@mantine/core";
import { IconPlus, IconTrash } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { CodeEditor } from "./_code-editor";
import { isRecord } from "./_custom-widget-form-utils";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
export function QueryValuesEditor({
value,
optionNames,
allowParams,
onChange,
}: {
value: Record<string, unknown>;
optionNames: string[];
allowParams: boolean;
onChange(value: Record<string, unknown>): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
const entries = Object.entries(value);
const [nameErrors, setNameErrors] = useState<Record<number, string>>({});
return (
<Stack gap="xs">
<Text size="sm" fw={500}>
{t("queryValues")}
</Text>
{entries.map(([name, bound], index) => {
const kind =
isRecord(bound) && typeof bound.$option === "string"
? "option"
: isRecord(bound) && typeof bound.$param === "string"
? "param"
: "literal";
const current =
kind === "option"
? String((bound as Record<string, unknown>).$option)
: kind === "param"
? String((bound as Record<string, unknown>).$param)
: String(bound ?? "");
const commit = (nextName: string, nextKind: string, nextValue: string) =>
onChange(
Object.fromEntries(
entries.map(([key, child], i) =>
i === index
? [
nextName,
nextKind === "option"
? { $option: nextValue }
: nextKind === "param"
? { $param: nextValue }
: parseLiteral(nextValue),
]
: [key, child],
),
),
);
const sourceChoices = [
{ value: "literal", label: t("literal") },
{ value: "option", label: t("widgetOption") },
...(allowParams ? [{ value: "param", label: t("invocationParameter") }] : []),
];
return (
<Group key={index} align="end" wrap="wrap">
<CustomWidgetIdentifierInput
style={{ flex: "1 1 10rem" }}
label={t("queryKey")}
value={name}
error={nameErrors[index]}
onCommit={(nextName) => {
if (
!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(nextName) ||
entries.some(([entryName], entryIndex) => entryIndex !== index && entryName === nextName)
) {
setNameErrors((currentErrors) => ({ ...currentErrors, [index]: t("queryKeyInvalid") }));
return;
}
setNameErrors((currentErrors) => {
const nextErrors = { ...currentErrors };
delete nextErrors[index];
return nextErrors;
});
commit(nextName, kind, current);
}}
/>
<Select
style={{ flex: "1 1 10rem" }}
label={t("valueSource")}
data={sourceChoices}
value={kind}
allowDeselect={false}
onChange={(nextKind) => commit(name, nextKind ?? "literal", current)}
/>
{kind === "option" ? (
<Select
style={{ flex: "1 1 10rem" }}
label={t("option")}
data={optionNames}
value={current}
searchable
onChange={(next) => commit(name, kind, next ?? "")}
/>
) : (
<TextInput
style={{ flex: "1 1 10rem" }}
label={kind === "param" ? t("parameterName") : t("value")}
value={current}
onChange={(event) => commit(name, kind, event.currentTarget.value)}
/>
)}
<ActionIcon
type="button"
color="red"
variant="subtle"
aria-label={t("removeQueryValue")}
onClick={() => onChange(Object.fromEntries(entries.filter((_, i) => i !== index)))}
>
<IconTrash size={16} />
</ActionIcon>
</Group>
);
})}
<Button
type="button"
size="compact-sm"
variant="subtle"
leftSection={<IconPlus size={14} />}
onClick={() => onChange({ ...value, [`value${entries.length + 1}`]: "" })}
>
{t("addQueryValue")}
</Button>
</Stack>
);
}
export function RequestBodyEditor({
id,
value,
optionNames,
allowParams,
onChange,
}: {
id: string;
value: unknown;
optionNames: string[];
allowParams: boolean;
onChange(value: unknown): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
const serialized = value === undefined ? "" : JSON.stringify(value, null, 2);
const [draft, setDraft] = useState(serialized);
const [error, setError] = useState<string>();
const [optionName, setOptionName] = useState<string | null>(optionNames[0] ?? null);
const [parameterName, setParameterName] = useState("");
const [insertion, setInsertion] = useState({ text: "", key: 0 });
useEffect(() => setDraft(serialized), [serialized]);
return (
<Stack gap="xs">
<CodeEditor
id={`${id}-request-body-editor`}
label={t("jsonBody")}
description={t("jsonBodyDescription")}
language="json"
value={draft}
height="160px"
error={error}
insertText={insertion.text}
insertKey={insertion.key}
onChange={(next) => {
setDraft(next);
try {
onChange(next.trim() ? (JSON.parse(next) as unknown) : undefined);
setError(undefined);
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("invalidJson"));
}
}}
/>
<Group align="end" wrap="wrap">
<Select label={t("option")} data={optionNames} value={optionName} searchable onChange={setOptionName} />
<Button
type="button"
variant="light"
disabled={!optionName}
onClick={() =>
optionName &&
setInsertion((current) => ({ text: JSON.stringify({ $option: optionName }), key: current.key + 1 }))
}
>
{t("insertOptionReference")}
</Button>
{allowParams && (
<>
<TextInput
label={t("parameterName")}
value={parameterName}
onChange={(event) => setParameterName(event.currentTarget.value)}
/>
<Button
type="button"
variant="light"
disabled={!parameterName.trim()}
onClick={() =>
setInsertion((current) => ({
text: JSON.stringify({ $param: parameterName.trim() }),
key: current.key + 1,
}))
}
>
{t("insertParameterReference")}
</Button>
</>
)}
</Group>
</Stack>
);
}
function parseLiteral(value: string): string | number | boolean {
if (value === "true") return true;
if (value === "false") return false;
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/u.test(value.trim())) return Number(value);
return value;
}
@@ -0,0 +1,232 @@
"use client";
import { Accordion, ActionIcon, Button, Fieldset, Group, Select, Stack, Switch, Text, TextInput } from "@mantine/core";
import { IconArrowDown, IconArrowUp, IconPlus, IconTrash } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import { isRecord, parseJson } from "./_custom-widget-form-utils";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { QueryValuesEditor, RequestBodyEditor } from "./_custom-widget-request-value-editors";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
const methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
export function CustomWidgetRequestsEditor({
form,
onRename,
}: {
form: CustomWidgetWorkbenchForm;
onRename(currentId: string, nextId: string): void;
}) {
const t = useScopedI18n("customWidget.workbench.builder");
const parsed = parseJson(form.values.requests);
const entries = isRecord(parsed) ? Object.entries(parsed) : [];
const sources = parseJson(form.values.sources);
const sourceIds = isRecord(sources) ? Object.keys(sources) : ["default"];
const commit = (next: Array<[string, unknown]>) =>
form.setFieldValue("requests", JSON.stringify(Object.fromEntries(next), null, 2));
const update = (index: number, id: string, request: Record<string, unknown>) =>
commit(entries.map((entry, i) => (i === index ? [id, request] : entry)));
const remove = (index: number) => commit(entries.filter((_, i) => i !== index));
const move = (index: number, direction: -1 | 1) => {
const next = [...entries];
const target = index + direction;
if (!next[index] || !next[target]) return;
[next[index], next[target]] = [next[target], next[index]];
commit(next);
};
const add = () => {
let suffix = entries.length + 1;
while (entries.some(([id]) => id === `request-${suffix}`)) suffix += 1;
commit([...entries, [`request-${suffix}`, { path: "/api/data" }]]);
};
return (
<Stack gap="sm">
{entries.map(([id, rawRequest], index) => {
const request = isRecord(rawRequest) ? rawRequest : {};
const kind = request.kind === "action" ? "action" : "query";
const trigger = request.trigger === "manual" ? "manual" : "load";
return (
<Fieldset key={index} legend={id || t("request", { count: index + 1 })}>
<Stack gap="sm">
<Group grow align="start">
<CustomWidgetIdentifierInput
label={t("requestId")}
value={id}
error={form.errors.requests}
onCommit={(value) => onRename(id, value)}
/>
<Select
label={t("type")}
data={["query", "action"]}
value={kind}
allowDeselect={false}
onChange={(value) =>
update(index, id, {
...request,
kind: value,
...(value === "action" ? { trigger: "manual" } : {}),
})
}
/>
<Select
label={t("method")}
data={methods}
value={typeof request.method === "string" ? request.method : "GET"}
allowDeselect={false}
onChange={(value) =>
update(index, id, {
...request,
method: value,
...(value === "DELETE" ? { permission: "full" } : {}),
})
}
/>
</Group>
<Group grow align="start">
<Select
label={t("source")}
data={sourceIds}
value={typeof request.source === "string" ? request.source : "default"}
allowDeselect={false}
onChange={(value) => update(index, id, { ...request, source: value })}
/>
{kind === "query" && (
<Select
label={t("run")}
data={[
{ value: "load", label: t("runLoad") },
{ value: "manual", label: t("runManual") },
]}
value={trigger}
allowDeselect={false}
onChange={(value) => update(index, id, { ...request, trigger: value })}
/>
)}
<Select
label={t("permission")}
data={["view", "modify", "full"]}
value={
typeof request.permission === "string" ? request.permission : kind === "action" ? "modify" : "view"
}
allowDeselect={false}
onChange={(value) => update(index, id, { ...request, permission: value })}
/>
</Group>
<TextInput
label={t("path")}
description={t("pathDescription")}
value={typeof request.path === "string" ? request.path : ""}
onChange={(event) => update(index, id, { ...request, path: event.currentTarget.value })}
/>
<Accordion variant="contained">
<Accordion.Item value="values">
<Accordion.Control>{t("requestDetails")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="sm">
<QueryValuesEditor
value={isRecord(request.query) ? request.query : {}}
optionNames={Object.keys(
isRecord(parseJson(form.values.options))
? (parseJson(form.values.options) as Record<string, unknown>)
: {},
)}
allowParams={trigger === "manual" || kind === "action"}
onChange={(query) => update(index, id, { ...request, query })}
/>
<RequestBodyEditor
id={id}
value={request.body}
optionNames={Object.keys(
isRecord(parseJson(form.values.options))
? (parseJson(form.values.options) as Record<string, unknown>)
: {},
)}
allowParams={trigger === "manual" || kind === "action"}
onChange={(body) => update(index, id, { ...request, body })}
/>
{kind === "action" && (
<TextInput
label={t("confirmation")}
value={typeof request.confirmation === "string" ? request.confirmation : ""}
onChange={(event) =>
update(index, id, { ...request, confirmation: event.currentTarget.value || undefined })
}
/>
)}
{kind === "action" && (
<TextInput
label={t("invalidation")}
description={t("invalidationDescription")}
value={Array.isArray(request.invalidates) ? request.invalidates.join(", ") : ""}
onChange={(event) =>
update(index, id, {
...request,
invalidates: event.currentTarget.value
.split(",")
.map((value) => value.trim())
.filter(Boolean),
})
}
/>
)}
<Switch
label={t("noAuth")}
checked={request.auth === "none"}
onChange={(event) =>
update(index, id, { ...request, auth: event.currentTarget.checked ? "none" : "inherit" })
}
/>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
<Group justify="space-between">
<Group gap="xs">
<ActionIcon
type="button"
variant="subtle"
aria-label={t("moveRequestUp")}
disabled={index === 0}
onClick={() => move(index, -1)}
>
<IconArrowUp size={16} />
</ActionIcon>
<ActionIcon
type="button"
variant="subtle"
aria-label={t("moveRequestDown")}
disabled={index === entries.length - 1}
onClick={() => move(index, 1)}
>
<IconArrowDown size={16} />
</ActionIcon>
</Group>
<Button
type="button"
color="red"
variant="subtle"
leftSection={<IconTrash size={16} />}
onClick={() => remove(index)}
>
{t("removeRequest")}
</Button>
</Group>
</Stack>
</Fieldset>
);
})}
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={add}>
{t("addRequest")}
</Button>
{form.errors.requests && (
<Text c="red" size="xs">
{form.errors.requests}
</Text>
)}
</Stack>
);
}
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { extractCustomWidgetSaveIssues } from "./_custom-widget-save-errors";
describe("extractCustomWidgetSaveIssues", () => {
it("extracts every flattened server validation message", () => {
expect(
extractCustomWidgetSaveIssues({
data: {
zodError: {
fieldErrors: {
template: [
"UNKNOWN_COMPONENT: 'Radio.Group' is not available. Did you mean 'RadioGroup'?",
"UNKNOWN_COMPONENT: 'Radio.Card' is not available. Did you mean 'RadioCard'?",
],
},
},
},
}),
).toEqual([
{ path: "template", message: "UNKNOWN_COMPONENT: 'Radio.Group' is not available. Did you mean 'RadioGroup'?" },
{ path: "template", message: "UNKNOWN_COMPONENT: 'Radio.Card' is not available. Did you mean 'RadioCard'?" },
]);
});
it("extracts paths and messages from a serialized Zod issue list", () => {
const message = JSON.stringify([
{
code: "custom",
message: "UNKNOWN_COMPONENT: 'Radio.Indicator' is not available. Did you mean 'RadioIndicator'?",
path: ["template"],
},
]);
expect(extractCustomWidgetSaveIssues({ message })).toEqual([
{
path: "template",
message: "UNKNOWN_COMPONENT: 'Radio.Indicator' is not available. Did you mean 'RadioIndicator'?",
},
]);
});
it("preserves array indexes in serialized Zod issue paths", () => {
const message = JSON.stringify([
{
code: "custom",
message: "A load parameter requires an explicit binding.",
path: ["requests", "containers", "path"],
},
]);
expect(extractCustomWidgetSaveIssues({ message })).toEqual([
{
path: "requests.containers.path",
message: "A load parameter requires an explicit binding.",
},
]);
});
it("extracts root validation errors from the tRPC error shape", () => {
expect(
extractCustomWidgetSaveIssues({
shape: {
data: {
zodError: {
formErrors: ["The widget definition is invalid."],
fieldErrors: {},
},
},
},
}),
).toEqual([{ message: "The widget definition is invalid." }]);
});
});
@@ -0,0 +1,64 @@
export interface CustomWidgetSaveIssue {
path?: string;
message: string;
}
const MAX_SAVE_ISSUES = 20;
export function extractCustomWidgetSaveIssues(error: unknown): CustomWidgetSaveIssue[] {
const record = asRecord(error);
const data = asRecord(record?.data) ?? asRecord(asRecord(record?.shape)?.data);
const zodError = asRecord(data?.zodError);
const fieldErrors = asRecord(zodError?.fieldErrors);
const flattened = fieldErrors
? Object.entries(fieldErrors).flatMap(([path, value]) =>
Array.isArray(value)
? value.flatMap((message) => (typeof message === "string" ? [{ path, message }] : []))
: [],
)
: [];
const formErrors = Array.isArray(zodError?.formErrors)
? zodError.formErrors.flatMap((message) => (typeof message === "string" ? [{ message }] : []))
: [];
if (flattened.length > 0 || formErrors.length > 0) return uniqueIssues([...formErrors, ...flattened]);
const message = typeof record?.message === "string" ? record.message : null;
if (!message) return [];
const parsed = parseZodIssueMessage(message);
return parsed.length > 0 ? uniqueIssues(parsed) : [{ message }];
}
function parseZodIssueMessage(message: string): CustomWidgetSaveIssue[] {
try {
const parsed = JSON.parse(message) as unknown;
if (!Array.isArray(parsed)) return [];
return parsed.flatMap((candidate) => {
const issue = asRecord(candidate);
if (typeof issue?.message !== "string") return [];
const path = Array.isArray(issue.path)
? issue.path
.filter((part) => typeof part === "string" || typeof part === "number")
.map(String)
.join(".")
: undefined;
return [{ path: path || undefined, message: issue.message }];
});
} catch {
return [];
}
}
function uniqueIssues(issues: CustomWidgetSaveIssue[]) {
return issues
.filter(
(issue, index) =>
issues.findIndex((candidate) => candidate.path === issue.path && candidate.message === issue.message) === index,
)
.slice(0, MAX_SAVE_ISSUES);
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
@@ -0,0 +1,37 @@
"use client";
import { Alert, Button, CopyButton, Text, Textarea } from "@mantine/core";
import { IconAlertCircle, IconCheck, IconCopy } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
export function CustomWidgetSaveIssuesAlert({ issues }: { issues: CustomWidgetSaveIssue[] }) {
const t = useScopedI18n("customWidget.workbench.saveError");
if (issues.length === 0) return null;
const value = issues.map((issue) => `${issue.path ? `${issue.path}: ` : ""}${issue.message}`).join("\n");
return (
<Alert color="red" title={t("title")} icon={<IconAlertCircle size={18} />}>
<Text size="sm" mb="xs">
{t("description")}
</Text>
<Textarea value={value} readOnly autosize minRows={2} maxRows={10} aria-label={t("errors")} mb="xs" />
<CopyButton value={value} timeout={2_000}>
{({ copied, copy }) => (
<Button
type="button"
size="compact-sm"
variant="light"
color={copied ? "green" : "red"}
leftSection={copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
onClick={copy}
>
{copied ? t("copied") : t("copy")}
</Button>
)}
</CopyButton>
</Alert>
);
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { getDependentRequestIds, removeDependentRequests } from "./_custom-widget-source-dependencies";
const requests = JSON.stringify({
status: { source: "default", path: "/status" },
restart: { source: "secondary", path: "/restart", kind: "action" },
logs: { source: "secondary", path: "/logs" },
});
describe("custom widget source dependencies", () => {
it("lists every request that would be removed with a source", () => {
expect(getDependentRequestIds(requests, "secondary")).toEqual(["restart", "logs"]);
});
it("removes only requests that use the selected source", () => {
expect(removeDependentRequests(requests, "secondary")).toEqual({
status: { source: "default", path: "/status" },
});
});
});
@@ -0,0 +1,27 @@
export function getDependentRequestIds(requestsJson: string, sourceId: string) {
const requests = parseRequestRecord(requestsJson);
return Object.entries(requests).flatMap(([requestId, request]) =>
isRecord(request) && request.source === sourceId ? [requestId] : [],
);
}
export function removeDependentRequests(requestsJson: string, sourceId: string) {
return Object.fromEntries(
Object.entries(parseRequestRecord(requestsJson)).filter(
([, request]) => !isRecord(request) || request.source !== sourceId,
),
);
}
function parseRequestRecord(requestsJson: string): Record<string, unknown> {
try {
const requests = JSON.parse(requestsJson) as unknown;
return isRecord(requests) ? requests : {};
} catch {
return {};
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -0,0 +1,155 @@
"use client";
import { Button, Fieldset, Group, PasswordInput, Select, Stack, TextInput } from "@mantine/core";
import { IconKey, IconTrash } from "@tabler/icons-react";
import { getCustomWidgetSourceUrlIssue } from "@homarr/custom-widgets/core";
import type { CustomWidgetSource, CustomWidgetSourceUrlIssue } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
type SecretKind = "apiKey" | "username" | "password";
const secretFields: Record<string, Array<{ kind: SecretKind }>> = {
bearer: [{ kind: "apiKey" }],
basic: [{ kind: "username" }, { kind: "password" }],
apiKeyHeader: [{ kind: "apiKey" }],
apiKeyQuery: [{ kind: "apiKey" }],
};
const sourceUrlErrorKeys: Record<CustomWidgetSourceUrlIssue, `baseUrlError.${CustomWidgetSourceUrlIssue}`> = {
invalid: "baseUrlError.invalid",
protocol: "baseUrlError.protocol",
credentials: "baseUrlError.credentials",
queryOrFragment: "baseUrlError.queryOrFragment",
};
interface CustomWidgetSourceFieldProps {
source: CustomWidgetSource & { id: string };
index: number;
form: CustomWidgetWorkbenchForm;
definitionId?: string;
clearSecretPending: boolean;
onUpdate(index: number, changes: Partial<CustomWidgetSource> & { id?: string }): void;
onSetAuthentication(index: number, type: string): void;
onSetSecret(sourceId: string, kind: string, value: string): void;
onClearSecret(sourceId: string, kind: SecretKind): Promise<void>;
onRemove(index: number): void;
}
export function CustomWidgetSourceField({
source,
index,
form,
definitionId,
clearSecretPending,
onUpdate,
onSetAuthentication,
onSetSecret,
onClearSecret,
onRemove,
}: CustomWidgetSourceFieldProps) {
const t = useScopedI18n("customWidget.workbench.sources");
const baseUrlIssue = getCustomWidgetSourceUrlIssue(source.baseUrl);
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
return (
<Fieldset legend={index === 0 ? t("primary") : source.name}>
<Stack gap="sm">
<Group grow align="start">
<CustomWidgetIdentifierInput
label={t("id")}
value={source.id}
disabled={source.id === "default" || Boolean(definitionId)}
error={form.errors.sources}
onCommit={(value) => onUpdate(index, { id: value })}
/>
<TextInput
label={t("name")}
value={source.name}
onChange={(event) => onUpdate(index, { name: event.currentTarget.value })}
/>
</Group>
<TextInput
label={t("baseUrl")}
type="url"
value={source.baseUrl}
error={baseUrlIssue ? t(sourceUrlErrorKeys[baseUrlIssue]) : undefined}
onChange={(event) => onUpdate(index, { baseUrl: event.currentTarget.value })}
/>
<Group grow align="start">
<Select
label={t("networkScope")}
data={["public", "private", "loopback"]}
value={source.networkScope}
onChange={(value) =>
value && onUpdate(index, { networkScope: value as CustomWidgetSource["networkScope"] })
}
allowDeselect={false}
/>
<Select
label={t("authentication")}
data={["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery"]}
value={authType}
onChange={(value) => onSetAuthentication(index, value ?? "none")}
allowDeselect={false}
/>
</Group>
{typeof source.auth === "object" && source.auth.type === "apiKeyHeader" && (
<TextInput
label={t("headerName")}
value={source.auth.name}
onChange={(event) => onUpdate(index, { auth: { type: "apiKeyHeader", name: event.currentTarget.value } })}
/>
)}
{typeof source.auth === "object" && source.auth.type === "apiKeyQuery" && (
<TextInput
label={t("queryParameter")}
value={source.auth.name}
onChange={(event) => onUpdate(index, { auth: { type: "apiKeyQuery", name: event.currentTarget.value } })}
/>
)}
{(secretFields[authType] ?? []).map(({ kind }) => {
const secret = form.values.secrets.find((entry) => entry.sourceId === source.id && entry.kind === kind);
const Input = kind === "username" ? TextInput : PasswordInput;
return (
<Group key={kind} align="end" wrap="nowrap">
<Input
style={{ flex: 1 }}
label={t(`secret.${kind}`)}
value={secret?.value ?? ""}
placeholder={secret?.hasValue ? t("configured") : undefined}
leftSection={<IconKey size={15} />}
onChange={(event) => onSetSecret(source.id, kind, event.currentTarget.value)}
/>
{definitionId && secret?.hasValue && (
<Button
type="button"
color="red"
variant="subtle"
loading={clearSecretPending}
onClick={() => void onClearSecret(source.id, kind)}
>
{t("clear")}
</Button>
)}
</Group>
);
})}
{index > 0 && (
<Button
type="button"
color="red"
variant="subtle"
leftSection={<IconTrash size={16} />}
onClick={() => onRemove(index)}
>
{t("remove")}
</Button>
)}
</Stack>
</Fieldset>
);
}
@@ -0,0 +1,199 @@
"use client";
import { Accordion, Button, List, Stack, Text } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
import { useConfirmModal } from "@homarr/modals";
import { showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { filterSecretsForSourceAuthentication, isRecord, parseJson, parseSources } from "./_custom-widget-form-utils";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { getDependentRequestIds, removeDependentRequests } from "./_custom-widget-source-dependencies";
import { CustomWidgetSourceField } from "./_custom-widget-source-field";
export function CustomWidgetSourcesEditor({
form,
definitionId,
}: {
form: CustomWidgetWorkbenchForm;
definitionId?: string;
}) {
const t = useScopedI18n("customWidget.workbench.sources");
const w = useScopedI18n("customWidget.workbench");
const { openConfirmModal } = useConfirmModal();
const utils = clientApi.useUtils();
const clearSecretMutation = clientApi.customWidget.secretClear.useMutation();
const sources = parseSources(form.values.sources);
const update = (index: number, changes: Partial<CustomWidgetSource> & { id?: string }) => {
const previousId = sources[index]?.id;
const nextId = changes.id ?? previousId;
if (nextId && sources.some((source, sourceIndex) => sourceIndex !== index && source.id === nextId)) {
form.setFieldError("sources", t("duplicateSourceId"));
return;
}
if (form.errors.sources === t("duplicateSourceId")) form.clearFieldError("sources");
const sourceEntries = sources.map(({ id, ...source }) => [id, source] as const);
form.setFieldValue(
"sources",
JSON.stringify(
Object.fromEntries(
sourceEntries.map(([id, source], i) => [
i === index ? nextId : id,
i === index ? { ...source, ...changes, id: undefined } : source,
]),
),
null,
2,
),
);
if (previousId && nextId && previousId !== nextId) {
const parsedRequests = parseJson(form.values.requests);
const requests = isRecord(parsedRequests)
? Object.fromEntries(
Object.entries(parsedRequests).map(([id, request]) => [
id,
isRecord(request) && request.source === previousId ? { ...request, source: nextId } : request,
]),
)
: {};
form.setFieldValue("requests", JSON.stringify(requests, null, 2));
form.setFieldValue(
"secrets",
form.values.secrets.map((secret) =>
secret.sourceId === previousId ? { ...secret, sourceId: nextId } : secret,
),
);
}
};
const setAuth = (index: number, type: string) => {
const auth =
type === "apiKeyHeader" ? { type, name: "X-API-Key" } : type === "apiKeyQuery" ? { type, name: "api_key" } : type;
update(index, { auth: auth as CustomWidgetSource["auth"] });
form.setFieldValue(
"secrets",
filterSecretsForSourceAuthentication(
form.values.secrets,
sources[index]?.id ?? "",
type as Parameters<typeof filterSecretsForSourceAuthentication>[2],
),
);
};
const setSecret = (sourceId: string, kind: string, value: string) => {
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
const existing = form.values.secrets.find((secret) => secret.sourceId === sourceId && secret.kind === kind);
form.setFieldValue("secrets", [...current, { sourceId, kind, value, hasValue: existing?.hasValue }]);
};
const addSource = () => {
const id = sources.length === 0 ? "default" : `source-${sources.length + 1}`;
form.setFieldValue(
"sources",
JSON.stringify(
Object.fromEntries([
...sources.map(({ id: sourceId, ...source }) => [sourceId, source] as const),
[
id,
{
name: t("newName", { count: sources.length + 1 }),
baseUrl: "https://example.com",
networkScope: sources.length === 0 ? "public" : "private",
auth: "none",
},
],
]),
null,
2,
),
);
};
const removeSourceAndDependents = (index: number) => {
const removedId = sources[index]?.id;
form.setFieldValue(
"sources",
JSON.stringify(
Object.fromEntries(sources.filter((_, i) => i !== index).map(({ id, ...source }) => [id, source])),
null,
2,
),
);
if (!removedId) return;
form.setFieldValue("requests", JSON.stringify(removeDependentRequests(form.values.requests, removedId), null, 2));
form.setFieldValue(
"secrets",
form.values.secrets.filter((secret) => secret.sourceId !== removedId),
);
};
const removeSource = (index: number) => {
const removedId = sources[index]?.id;
if (!removedId) return;
const dependentRequestIds = getDependentRequestIds(form.values.requests, removedId);
if (dependentRequestIds.length === 0) {
removeSourceAndDependents(index);
return;
}
openConfirmModal({
title: t("remove"),
children: (
<Stack gap="xs">
<Text size="sm" fw={500}>
{w("requests.title")} ({dependentRequestIds.length})
</Text>
<List size="sm">
{dependentRequestIds.map((requestId) => (
<List.Item key={requestId}>{requestId}</List.Item>
))}
</List>
</Stack>
),
confirmProps: { children: t("remove") },
onConfirm: () => removeSourceAndDependents(index),
});
};
const clearSecret = async (sourceId: string, kind: "apiKey" | "username" | "password") => {
if (!definitionId) return;
await clearSecretMutation.mutateAsync({ definitionId, sourceId, kind });
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
form.setFieldValue("secrets", [...current, { sourceId, kind, value: "", hasValue: false }]);
await utils.customWidget.get.invalidate({ id: definitionId });
showSuccessNotification({ title: t("credentialRemoved"), message: t("credentialRemovedDescription") });
};
return (
<Stack gap="sm">
{sources.map((source, index) => {
return (
<CustomWidgetSourceField
key={source.id}
source={source}
index={index}
form={form}
definitionId={definitionId}
clearSecretPending={clearSecretMutation.isPending}
onUpdate={update}
onSetAuthentication={setAuth}
onSetSecret={setSecret}
onClearSecret={clearSecret}
onRemove={removeSource}
/>
);
})}
<Accordion variant="contained">
<Accordion.Item value="advanced">
<Accordion.Control>{t("advanced")}</Accordion.Control>
<Accordion.Panel>
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={addSource}>
{t("add")}
</Button>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
{form.errors.sources && (
<Text c="red" size="xs">
{form.errors.sources}
</Text>
)}
</Stack>
);
}
@@ -0,0 +1,54 @@
"use client";
import type { ErrorInfo, ReactNode } from "react";
import { Component } from "react";
import { Alert, Button, Stack, Text } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
interface FormErrorBoundaryState {
error: Error | null;
}
interface FormErrorBoundaryProps {
children: ReactNode;
}
export class FormErrorBoundary extends Component<FormErrorBoundaryProps, FormErrorBoundaryState> {
public state: FormErrorBoundaryState = { error: null };
public static getDerivedStateFromError(error: Error): FormErrorBoundaryState {
return { error };
}
public componentDidCatch(error: Error, _info: ErrorInfo) {
console.error("Custom widget form error:", error);
}
public render() {
if (this.state.error) {
return <FormErrorFallback error={this.state.error} reset={() => this.setState({ error: null })} />;
}
return this.props.children;
}
}
function FormErrorFallback({ error, reset }: { error: Error; reset: () => void }) {
const t = useScopedI18n("customWidget");
return (
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="md">
<Stack gap="xs">
<Text size="sm" fw={600}>
{t("editor.errorBoundary.title")}
</Text>
<Text size="xs" c="dimmed" style={{ fontFamily: "monospace" }}>
{error.message}
</Text>
<Button size="xs" variant="light" color="red" onClick={reset}>
{t("editor.errorBoundary.retry")}
</Button>
</Stack>
</Alert>
);
}
@@ -0,0 +1,104 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useDisclosure } from "@mantine/hooks";
import { IconUpload } from "@tabler/icons-react";
import {
formatCustomWidgetImportIssues,
looksLikeCustomWidgetClipboard,
parseCustomWidgetClipboardDetailed,
} from "@homarr/custom-widgets/core";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
export const ImportCustomWidgetButton = () => {
const t = useScopedI18n("customWidget");
const fileInputRef = useRef<HTMLInputElement>(null);
const [pendingImport, setPendingImport] = useState<HomarrCustomWidgetV2 | null>(null);
const [reviewOpened, { open: openReview, close: closeReview }] = useDisclosure(false);
const queueImport = useCallback(
(value: HomarrCustomWidgetV2) => {
setPendingImport(value);
openReview();
},
[openReview],
);
useEffect(() => {
const handlePaste = (event: ClipboardEvent) => {
if (event.target instanceof Element && event.target.matches("input, textarea, [contenteditable='true']")) return;
const text = event.clipboardData?.getData("text/plain") ?? "";
if (!looksLikeCustomWidgetClipboard(text)) return;
event.preventDefault();
const result = parseCustomWidgetClipboardDetailed(text);
if (!result.success) {
showErrorNotification({
title: t("action.import"),
message: formatCustomWidgetImportIssues(result.issues),
});
return;
}
queueImport(result.widget);
};
window.addEventListener("paste", handlePaste);
return () => window.removeEventListener("paste", handlePaste);
}, [queueImport, t]);
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.addEventListener("load", (loadEvent) => {
try {
const result = parseCustomWidgetClipboardDetailed(loadEvent.target?.result as string);
if (!result.success) throw new Error(formatCustomWidgetImportIssues(result.issues));
queueImport(result.widget);
} catch (error) {
showErrorNotification({
title: t("action.import"),
message: error instanceof Error ? error.message : t("notification.importError"),
});
}
});
reader.addEventListener("error", () => {
showErrorNotification({ title: t("action.import"), message: t("notification.importError") });
});
reader.readAsText(file);
event.target.value = "";
};
return (
<>
<MobileAffixButton
variant="default"
leftSection={<IconUpload size={16} />}
onClick={() => fileInputRef.current?.click()}
title={t("action.pasteImportHint")}
>
{t("action.import")}
</MobileAffixButton>
<input
ref={fileInputRef}
type="file"
accept=".json,.md,text/markdown,application/json"
hidden
onChange={handleImport}
aria-label={t("importReview.fileLabel")}
/>
<CustomWidgetImportDialog
opened={reviewOpened}
widget={pendingImport}
onClose={() => {
closeReview();
setPendingImport(null);
}}
/>
</>
);
};
@@ -0,0 +1,35 @@
"use client";
import { useEffect, useState } from "react";
import { CodeEditor } from "./_code-editor";
import { isRecord, parseJson } from "./_custom-widget-form-utils";
export function JsonPreviewEditor({
id,
label,
value,
onChange,
}: {
id: string;
label: string;
value: Record<string, unknown>;
onChange(value: Record<string, unknown>): void;
}) {
const serialized = JSON.stringify(value, null, 2);
const [draft, setDraft] = useState(serialized);
useEffect(() => setDraft(serialized), [serialized]);
return (
<CodeEditor
id={id}
label={label}
language="json"
value={draft}
onChange={(next) => {
setDraft(next);
const parsed = parseJson(next);
if (isRecord(parsed)) onChange(parsed);
}}
/>
);
}
@@ -0,0 +1,51 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
const cleanups: Array<() => void> = [];
afterEach(() => {
cleanups.splice(0).forEach((cleanup) => cleanup());
document.body.replaceChildren();
window.history.replaceState(null, "", "/en/manage/custom-widgets/edit/widget-1");
});
describe("custom widget unsaved changes guard", () => {
it("blocks client-side link navigation and requests confirmation for a dirty form", () => {
window.history.replaceState(null, "", "/en/manage/custom-widgets/edit/widget-1");
const confirmNavigation = vi.fn();
cleanups.push(registerUnsavedChangesGuard({ isDirty: () => true, confirmNavigation }));
const link = document.createElement("a");
link.href = "/en/manage/custom-widgets";
link.textContent = "Custom widgets";
document.body.append(link);
const event = new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 });
link.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
expect(confirmNavigation).toHaveBeenCalledWith("/en/manage/custom-widgets");
});
it("allows section links and navigation after the form is clean", () => {
window.history.replaceState(null, "", "/en/manage/custom-widgets/edit/widget-1");
let dirty = true;
const confirmNavigation = vi.fn();
cleanups.push(registerUnsavedChangesGuard({ isDirty: () => dirty, confirmNavigation }));
const sectionLink = document.createElement("a");
sectionLink.href = "#sources";
document.body.append(sectionLink);
expect(sectionLink.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }))).toBe(
true,
);
dirty = false;
const listLink = document.createElement("a");
listLink.href = "/en/manage/custom-widgets";
document.body.append(listLink);
expect(listLink.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }))).toBe(true);
expect(confirmNavigation).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,42 @@
interface UnsavedChangesGuardOptions {
isDirty(): boolean;
confirmNavigation(href: string): void;
}
export function registerUnsavedChangesGuard({ isDirty, confirmNavigation }: UnsavedChangesGuardOptions) {
const handleClick = (event: MouseEvent) => {
if (!isDirty() || event.defaultPrevented || event.button !== 0) return;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const eventTarget = event.target instanceof Element ? event.target : null;
const anchor = eventTarget?.closest<HTMLAnchorElement>("a[href]");
if (!anchor || anchor.target === "_blank" || anchor.hasAttribute("download")) return;
const destination = new URL(anchor.href, window.location.href);
const current = new URL(window.location.href);
if (destination.origin !== current.origin) return;
if (
destination.pathname === current.pathname &&
destination.search === current.search &&
destination.hash !== current.hash
) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
confirmNavigation(`${destination.pathname}${destination.search}${destination.hash}`);
};
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (!isDirty()) return;
event.preventDefault();
event.returnValue = true;
};
document.addEventListener("click", handleClick, true);
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
document.removeEventListener("click", handleClick, true);
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}
@@ -0,0 +1,226 @@
"use client";
import { useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { useRouter } from "next/navigation";
import type { UseFormReturnType } from "@mantine/form";
import { clientApi } from "@homarr/api/client";
import { formatCustomWidgetImportIssues } from "@homarr/custom-widgets/core";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { showErrorNotification, showSuccessNotification, showWarningNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import {
applyCustomWidgetAiResponse,
buildDefinition,
getChangedSecrets,
getDefinitionDefaults,
getCustomWidgetPreviewOptionIssues,
isRecord,
loadPreviewQueries,
} from "./_custom-widget-form-utils";
import type { PreviewState } from "./_custom-widget-preview-panel";
import { extractCustomWidgetSaveIssues } from "./_custom-widget-save-errors";
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
interface FormActionsInput {
mode: "create" | "edit";
definitionId?: string;
form: UseFormReturnType<CustomWidgetFormValues>;
candidate: ReturnType<typeof buildDefinition>;
preview: PreviewState;
setPreview: Dispatch<SetStateAction<PreviewState>>;
setMobilePane: Dispatch<SetStateAction<"configure" | "preview">>;
optionsSnapshot: Record<string, unknown>;
setOptionsSnapshot: Dispatch<SetStateAction<Record<string, unknown>>>;
}
export function useCustomWidgetFormActions(input: FormActionsInput) {
const router = useRouter();
const t = useScopedI18n("customWidget");
const w = useScopedI18n("customWidget.workbench");
const utils = clientApi.useUtils();
const createMutation = clientApi.customWidget.create.useMutation();
const updateMutation = clientApi.customWidget.update.useMutation();
const previewMutation = clientApi.customWidget.previewCreate.useMutation();
const [saveIssues, setSaveIssues] = useState<CustomWidgetSaveIssue[]>([]);
const [previewPending, setPreviewPending] = useState(false);
const save = input.form.onSubmit(async (values) => {
clearSaveIssues(input.form, saveIssues);
setSaveIssues([]);
const definition = buildDefinition(values);
if (!definition.success) {
reportSaveIssues(
input.form,
definition.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message })),
setSaveIssues,
t("action.save"),
(count) => w("saveError.more", { count }),
);
return;
}
const changedSecrets = getChangedSecrets(values);
try {
if (input.mode === "create") {
const result = await createMutation.mutateAsync({ ...definition.data, secrets: changedSecrets });
await utils.customWidget.list.invalidate();
showSuccessNotification({
title: t("action.create"),
message: t("notification.created", { name: values.name }),
});
router.push(`/manage/custom-widgets/edit/${result.id}`);
} else if (input.definitionId) {
await updateMutation.mutateAsync({
id: input.definitionId,
...definition.data,
secrets: changedSecrets.length ? changedSecrets : undefined,
});
await Promise.all([
utils.customWidget.list.invalidate(),
utils.customWidget.get.invalidate({ id: input.definitionId }),
utils.widget.customApi.getData.invalidate(),
]);
input.form.setInitialValues(values);
input.form.resetDirty();
showSuccessNotification({
title: t("action.save"),
message: t("notification.updated", { name: values.name }),
});
}
} catch (error) {
const issues = extractCustomWidgetSaveIssues(error);
if (issues.length > 0) {
reportSaveIssues(input.form, issues, setSaveIssues, t("action.save"), (count) =>
w("saveError.more", { count }),
);
} else {
showErrorNotification({ title: t("action.save"), message: t("notification.updateError") });
}
}
});
const runPreview = async () => {
if (previewPending) return;
if (!input.candidate.success) {
showErrorNotification({
title: w("section.preview"),
message: input.candidate.error.issues[0]?.message ?? w("invalidWidget"),
});
return;
}
const optionIssues = getCustomWidgetPreviewOptionIssues(input.candidate.data, input.optionsSnapshot);
if (optionIssues.length > 0) {
const issue = optionIssues[0];
showErrorNotification({
title: w("section.preview"),
message: issue ? `${issue.path}: ${issue.message}` : w("invalidWidget"),
});
return;
}
input.setMobilePane("preview");
input.setPreview({ data: {}, status: {}, session: null, outcome: "loading" });
setPreviewPending(true);
try {
const created = await previewMutation.mutateAsync({
definition: input.candidate.data,
definitionId: input.definitionId,
options: input.optionsSnapshot,
secrets: getChangedSecrets(input.form.values),
});
const snapshot = await loadPreviewQueries(input.candidate.data, created.previewSession.id);
const failed = Object.values(snapshot.status).filter((status) => isRecord(status) && status.ok === false).length;
input.setPreview({
...snapshot,
session: created.previewSession,
outcome: failed > 0 ? "error" : "success",
});
if (failed > 0) {
showWarningNotification({
title: w("preview.result.error.title"),
message: w("preview.result.error.description", {
succeeded: Object.keys(snapshot.status).length - failed,
failed,
}),
});
} else {
showSuccessNotification({
title: w("preview.result.success.title"),
message: w("preview.result.success.description", {
succeeded: Object.keys(snapshot.status).length,
failed: 0,
}),
});
}
} catch {
input.setPreview((current) => ({ ...current, outcome: "error" }));
showErrorNotification({ title: w("section.preview"), message: t("notification.previewError") });
} finally {
setPreviewPending(false);
}
};
const pasteAiResponse = async () => {
try {
const result = applyCustomWidgetAiResponse(input.form, await navigator.clipboard.readText());
if (!result.success) {
throw new Error(formatCustomWidgetImportIssues(result.issues));
}
input.setOptionsSnapshot(getDefinitionDefaults(result.widget));
input.setPreview({ data: {}, status: {}, session: null, outcome: "idle" });
showSuccessNotification({
title: w("ai.response"),
message:
result.warnings.length > 0
? `${w("ai.loaded")} ${formatCustomWidgetImportIssues(result.warnings)}`
: w("ai.loaded"),
});
} catch (error) {
showErrorNotification({
title: w("ai.response"),
message:
error instanceof Error ? w("ai.invalidResponseDetail", { message: error.message }) : w("ai.invalidResponse"),
});
}
};
return {
save,
runPreview,
pasteAiResponse,
saveIssues,
savePending: createMutation.isPending || updateMutation.isPending,
previewPending,
};
}
function reportSaveIssues(
form: UseFormReturnType<CustomWidgetFormValues>,
issues: CustomWidgetSaveIssue[],
setIssues: Dispatch<SetStateAction<CustomWidgetSaveIssue[]>>,
title: string,
getRemainingLabel: (count: number) => string,
) {
setIssues(issues);
const messagesByPath = new Map<string, string[]>();
for (const issue of issues) {
if (!issue.path) continue;
const field = issue.path.split(".")[0] ?? issue.path;
messagesByPath.set(field, [...(messagesByPath.get(field) ?? []), issue.message]);
}
for (const [path, messages] of messagesByPath) {
form.setFieldError(path, messages.join(" "));
}
const remaining = issues.length - 1;
showErrorNotification({
title,
message: `${issues[0]?.message ?? ""}${remaining > 0 ? ` ${getRemainingLabel(remaining)}` : ""}`,
});
}
function clearSaveIssues(form: UseFormReturnType<CustomWidgetFormValues>, issues: CustomWidgetSaveIssue[]) {
for (const path of new Set(issues.flatMap((issue) => (issue.path ? [issue.path.split(".")[0] ?? issue.path] : [])))) {
form.clearFieldError(path);
}
}
@@ -0,0 +1,34 @@
"use client";
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useConfirmModal } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
export function useUnsavedChangesGuard(isDirty: boolean) {
const t = useI18n();
const router = useRouter();
const { openConfirmModal } = useConfirmModal();
const dirtyRef = useRef(isDirty);
const confirmNavigationRef = useRef<(href: string) => void>(() => undefined);
dirtyRef.current = isDirty;
confirmNavigationRef.current = (href) => {
openConfirmModal({
title: t("board.action.edit.confirmLeave.title"),
children: t("board.action.edit.confirmLeave.message"),
confirmProps: { children: t("common.action.discard") },
onConfirm: () => router.push(href),
});
};
useEffect(
() =>
registerUnsavedChangesGuard({
isDirty: () => dirtyRef.current,
confirmNavigation: (href) => confirmNavigationRef.current(href),
}),
[],
);
}
@@ -8,141 +8,7 @@ import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
import { CustomWidgetBetaBanner } from "../../_beta-banner";
import { CustomWidgetForm } from "../../_custom-widget-form";
const authTypeExpectedSecrets: Record<string, string[]> = {
bearer: ["apiKey"],
basic: ["username", "password"],
apiKeyHeader: ["apiKey"],
apiKeyQuery: ["apiKey"],
};
function buildInitialSecrets(authType: string, dbSecrets: Array<{ kind: string; hasValue?: boolean }>) {
const expected = authTypeExpectedSecrets[authType] ?? [];
const existingKinds = new Set(dbSecrets.map((s) => s.kind));
const result = dbSecrets.map((s) => ({ kind: s.kind, value: "", hasValue: s.hasValue ?? false }));
for (const kind of expected) {
if (!existingKinds.has(kind)) {
result.push({ kind, value: "", hasValue: false });
}
}
return result;
}
function buildDisplayInitialValues(displayType: string, config: Record<string, unknown>) {
const base = {
displayType,
jsonPath: "$",
label: "",
unit: "",
valueSize: "lg",
labelPosition: "below",
mappings: [{ label: "", jsonPath: "$", unit: "" }],
kvLayout: "list",
kvColumns: 2,
tablePath: "$",
columns: [{ header: "", jsonPath: "$" }],
striped: true,
compact: false,
statGridItems: [{ label: "", jsonPath: "$", unit: "", color: "blue" }],
statGridColumns: 2,
cardStyle: "filled",
progressBars: [{ label: "", valuePath: "$", maxPath: "", unit: "", color: "blue" }],
showPercentage: true,
barSize: "md",
statusItems: [{ label: "", jsonPath: "$", goodValues: "online,true" }],
statusLayout: "list",
dotSize: "md",
countGridItems: [{ label: "", jsonPath: "$", unit: "" }],
countGridColumns: 2,
countValueSize: "md",
rawJsonPath: "$",
rawMaxHeight: 300,
buttonLabel: "Execute",
buttonColor: "blue",
confirmText: "",
successMessage: "",
template: "",
};
const typeOverrides: Record<string, () => Record<string, unknown>> = {
singleValue: () => ({
jsonPath: (config.jsonPath as string) ?? "$",
label: (config.label as string) ?? "",
unit: (config.unit as string) ?? "",
valueSize: (config.valueSize as string) ?? "lg",
labelPosition: (config.labelPosition as string) ?? "below",
}),
keyValue: () => ({
mappings: (config.mappings as Array<{ label: string; jsonPath: string; unit: string }>) ?? base.mappings,
kvLayout: (config.layout as string) ?? "list",
kvColumns: (config.columns as number) ?? 2,
}),
table: () => ({
tablePath: (config.tablePath as string) ?? "$",
columns: (config.columns as Array<{ header: string; jsonPath: string }>) ?? base.columns,
striped: (config.striped as boolean) ?? true,
compact: (config.compact as boolean) ?? false,
}),
statGrid: () => ({
statGridItems: (
(config.items as Array<{ label: string; jsonPath: string; unit: string; color?: string }>) ?? []
).map((item) => ({
label: item.label,
jsonPath: item.jsonPath,
unit: item.unit,
color: item.color ?? "blue",
})),
statGridColumns: (config.columns as number) ?? 2,
cardStyle: (config.cardStyle as string) ?? "filled",
}),
progressBars: () => ({
progressBars: (
(config.bars as Array<{ label: string; valuePath: string; maxPath?: string; unit: string; color?: string }>) ??
[]
).map((bar) => ({
label: bar.label,
valuePath: bar.valuePath,
maxPath: bar.maxPath ?? "",
unit: bar.unit,
color: bar.color ?? "blue",
})),
showPercentage: (config.showPercentage as boolean) ?? true,
barSize: (config.barSize as string) ?? "md",
}),
statusIndicator: () => ({
statusItems: ((config.items as Array<{ label: string; jsonPath: string; goodValues: string[] }>) ?? []).map(
(item) => ({
label: item.label,
jsonPath: item.jsonPath,
goodValues: item.goodValues.join(", "),
}),
),
statusLayout: (config.layout as string) ?? "list",
dotSize: (config.dotSize as string) ?? "md",
}),
countGrid: () => ({
countGridItems: (config.items as Array<{ label: string; jsonPath: string; unit: string }>) ?? base.countGridItems,
countGridColumns: (config.columns as number) ?? 2,
countValueSize: (config.valueSize as string) ?? "md",
}),
raw: () => ({
rawJsonPath: (config.jsonPath as string) ?? "$",
rawMaxHeight: (config.maxHeight as number) ?? 300,
}),
actionButton: () => ({
buttonLabel: (config.buttonLabel as string) ?? "Execute",
buttonColor: (config.buttonColor as string) ?? "blue",
confirmText: (config.confirmText as string) ?? "",
successMessage: (config.successMessage as string) ?? "",
}),
customJsx: () => ({
template: (config.template as string) ?? "",
}),
};
const overrides = typeOverrides[displayType]?.() ?? {};
return { ...base, ...overrides };
}
import { FormErrorBoundary } from "../../_form-error-boundary";
interface EditCustomWidgetPageProps {
params: Promise<{ id: string }>;
@@ -153,12 +19,8 @@ export default async function EditCustomWidgetPage(props: EditCustomWidgetPagePr
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
const params = await props.params;
const definition = await api.customWidget.byId({ id: params.id }).catch(catchTrpcNotFound);
const displayConfig = definition.displayConfig as Record<string, unknown>;
const displayValues = buildDisplayInitialValues(definition.displayType, displayConfig);
const definition = await api.customWidget.get({ id: params.id }).catch(catchTrpcNotFound);
return (
<>
@@ -167,22 +29,27 @@ export default async function EditCustomWidgetPage(props: EditCustomWidgetPagePr
<Stack>
<Title>{definition.name}</Title>
<CustomWidgetBetaBanner />
<CustomWidgetForm
mode="edit"
definitionId={params.id}
initialValues={{
name: definition.name,
description: definition.description ?? "",
iconUrl: definition.iconUrl ?? "",
url: definition.url,
authType: definition.authType,
headerName: definition.headerName ?? "",
method: definition.method,
requestBody: definition.requestBody ?? "",
...displayValues,
secrets: buildInitialSecrets(definition.authType, definition.secrets),
}}
/>
<FormErrorBoundary>
<CustomWidgetForm
mode="edit"
definitionId={params.id}
initialValues={{
name: definition.name,
description: definition.description ?? "",
iconUrl: definition.iconUrl ?? "",
sources: JSON.stringify(definition.sources, null, 2),
requests: JSON.stringify(definition.requests, null, 2),
options: JSON.stringify(definition.options, null, 2),
template: definition.template,
secrets: definition.secrets.map((secret) => ({
sourceId: secret.sourceId,
kind: secret.kind,
value: "",
hasValue: true,
})),
}}
/>
</FormErrorBoundary>
</Stack>
</Container>
</>
@@ -7,13 +7,13 @@ import { getScopedI18n } from "@homarr/translation/server";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { CustomWidgetBetaBanner } from "../_beta-banner";
import { CustomWidgetForm } from "../_custom-widget-form";
import { FormErrorBoundary } from "../_form-error-boundary";
export default async function NewCustomWidgetPage() {
const session = await auth();
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
const t = await getScopedI18n("customWidget");
return (
@@ -28,7 +28,9 @@ export default async function NewCustomWidgetPage() {
</Text>
</div>
<CustomWidgetBetaBanner />
<CustomWidgetForm mode="create" />
<FormErrorBoundary>
<CustomWidgetForm mode="create" />
</FormErrorBoundary>
</Stack>
</Container>
</>
@@ -1,6 +1,6 @@
import { redirect } from "next/navigation";
import { Group } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import { IconExternalLink, IconPlus } from "@tabler/icons-react";
import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
@@ -10,7 +10,8 @@ import { Link } from "@homarr/ui";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
import { CustomWidgetBetaBanner } from "./_beta-banner";
import { ImportCustomWidgetButton } from "./_custom-widget-actions";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { ImportCustomWidgetButton } from "./_import-custom-widget-button";
import { CustomWidgetList } from "./_custom-widget-list";
export default async function CustomWidgetsPage() {
@@ -19,8 +20,7 @@ export default async function CustomWidgetsPage() {
if (!session || !session.user.permissions.includes("admin")) {
redirect(session ? "/" : "/auth/login");
}
const definitions = await api.customWidget.all();
const definitions = await api.customWidget.list();
const t = await getScopedI18n("customWidget");
return (
@@ -28,6 +28,17 @@ export default async function CustomWidgetsPage() {
title={t("page.list.title")}
primaryAction={
<Group gap="xs">
<MobileAffixButton
component="a"
href="https://www.skills.sh/homarr-labs/homarr/homarr-custom-widget"
target="_blank"
rel="noopener noreferrer"
leftSection={<IconExternalLink size={16} />}
variant="default"
>
{t("action.downloadSkill")}
</MobileAffixButton>
<WorkshopInstallButton />
<ImportCustomWidgetButton />
<MobileAffixButton component={Link} href="/manage/custom-widgets/new" leftSection={<IconPlus size={16} />}>
{t("action.create")}
@@ -0,0 +1,66 @@
import { notFound, redirect } from "next/navigation";
import { Badge, Box, Container, Group, Paper, Stack, Text, Title } from "@mantine/core";
import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
export default async function CustomWidgetPreviewPage({ params }: { params: Promise<{ id: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("admin")) redirect("/");
const { id } = await params;
const preview = await api.customWidget.previewGet({ sessionId: id }).catch(() => null);
if (!preview) notFound();
const loadRequests = preview.requests.filter((request) => request.kind === "query" && request.trigger === "load");
const results = await Promise.all(
loadRequests.map(async (request) => {
const result = await api.customWidget
.previewQuery({ sessionId: id, requestId: request.id, params: {} })
.catch((cause: unknown) => ({
ok: false,
status: 0,
statusText: "Error",
data: null,
error: cause instanceof Error ? cause.message : "Request failed",
}));
return [request.id, result] as const;
}),
);
const data = Object.fromEntries(results.map(([requestId, result]) => [requestId, result.data]));
const status = Object.fromEntries(
results.map(([requestId, result]) => [
requestId,
{ loading: false, ok: result.ok, status: result.status, error: result.error },
]),
);
return (
<Container size="xl" py="xl">
<Stack gap="lg">
<Group justify="space-between" align="end">
<Box>
<Text size="sm" c="dimmed" fw={600}>
CUSTOM WIDGET PREVIEW
</Text>
<Title>{preview.name}</Title>
</Box>
<Badge variant="light">Expires {new Date(preview.expiresAt).toLocaleTimeString()}</Badge>
</Group>
<Paper withBorder radius="lg" p="md" mih={360} style={{ overflow: "auto" }}>
<CustomJsxDisplay
data={{
template: preview.template,
data,
status,
options: preview.options,
requestCapabilities: preview.requests,
previewSessionId: preview.id,
previewLiveActions: preview.liveActions,
}}
/>
</Paper>
</Stack>
</Container>
);
}
@@ -5,6 +5,7 @@ import {
IconApi,
IconBook2,
IconBox,
IconBuildingStore,
IconBrandDiscord,
IconBrandDocker,
IconBrandGithub,
@@ -100,6 +101,12 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
label: t("items.customWidgets"),
hidden: !session?.user.permissions.includes("admin"),
},
{
icon: IconBuildingStore,
href: "/manage/workshop",
label: t("items.workshop"),
hidden: !session?.user.permissions.includes("admin"),
},
{
icon: IconSearch,
href: "/manage/search-engines",
@@ -0,0 +1,42 @@
import { redirect } from "next/navigation";
import { Button } from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { WorkshopInstaller } from "~/components/workshop/workshop-installer";
import { env } from "~/env";
export default async function WorkshopPage() {
const session = await auth();
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
const t = await getScopedI18n("workshop");
const { workshopWebUrl } = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
return (
<ManagePageLayout
title={t("title")}
size="xl"
primaryAction={
<Button
component="a"
href={workshopWebUrl}
target="_blank"
rel="noopener noreferrer"
variant="default"
leftSection={<IconExternalLink size={16} />}
>
{t("openCommunity")}
</Button>
}
>
<WorkshopInstaller />
</ManagePageLayout>
);
}
@@ -0,0 +1,42 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
import { getCustomWidgetComponentCatalog, getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { adminRoute } from "../admin";
interface RouteContext {
params: Promise<{ resource: string }>;
}
const resources = new Map<string, () => unknown>([
["schema", getCustomWidgetJsonSchema],
["components", getCustomWidgetComponentCatalog],
["skill", getCustomWidgetSkill],
[
"authoring-prompt",
() => ({
version: 2,
prompt: CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
resources: [
"homarr://custom-widgets/schema",
"homarr://custom-widgets/components",
"homarr://custom-widgets/skill",
],
httpResources: ["/api/custom-widgets/schema", "/api/custom-widgets/components", "/api/custom-widgets/skill"],
}),
],
]);
const getAuthoringResource = async (_request: NextRequest, context: RouteContext): Promise<Response> => {
const { resource } = await context.params;
const loadResource = resources.get(resource);
if (!loadResource) {
return NextResponse.json({ error: "Custom Widget authoring resource not found." }, { status: 404 });
}
return NextResponse.json(loadResource());
};
export const GET = adminRoute(getAuthoringResource);
@@ -0,0 +1,37 @@
// @vitest-environment node
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auth: vi.fn(),
}));
vi.mock("@homarr/auth/next", () => ({ auth: mocks.auth }));
import { adminRoute } from "./admin";
beforeEach(() => {
mocks.auth.mockResolvedValue({ user: { permissions: ["admin"] } });
});
describe("Custom Widget HTTP resource access", () => {
test("allows authenticated administrators", async () => {
const handler = vi.fn(async () => Response.json({ ok: true }));
const response = await adminRoute(handler)();
expect(response.status).toBe(200);
expect(handler).toHaveBeenCalledOnce();
});
test.each([
["anonymous users", null],
["authenticated non-admins", { user: { permissions: ["board-modify-all"] } }],
])("denies %s", async (_label, session) => {
mocks.auth.mockResolvedValue(session);
const handler = vi.fn(async () => Response.json({ ok: true }));
const response = await adminRoute(handler)();
expect(response.status).toBe(403);
expect(handler).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
import { auth } from "@homarr/auth/next";
type RouteHandler<Arguments extends unknown[]> = (...args: Arguments) => Response | Promise<Response>;
export const adminRoute =
<Arguments extends unknown[]>(handler: RouteHandler<Arguments>) =>
async (...args: Arguments): Promise<Response> => {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
return NextResponse.json({ error: "Administrator access is required." }, { status: 403 });
}
return handler(...args);
};
@@ -0,0 +1,130 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import {
claimCustomWidgetConfigurationRequest,
completeCustomWidgetConfigurationRequest,
configureCustomWidgetSourceFromRequest,
configurePreviewSessionSource,
getCustomWidgetConfigurationRequest,
releaseCustomWidgetConfigurationRequest,
} from "@homarr/api/custom-widget-configuration";
import { customWidgetSourceSchema } from "@homarr/custom-widgets/core";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { db } from "@homarr/db";
import { adminRoute } from "../../admin";
import { readConfigurationRequestBody } from "../body";
interface RouteContext {
params: Promise<{ token: string }>;
}
const getConfigurationRequest = async (_request: NextRequest, context: RouteContext): Promise<Response> => {
const { token } = await context.params;
const request = await getCustomWidgetConfigurationRequest(token);
if (!request)
return NextResponse.json({ error: "This source configuration request is invalid or expired." }, { status: 404 });
return NextResponse.json(
{
widgetName: request.widgetName,
sourceName: request.sourceName,
kinds: request.kinds,
source: request.source,
expiresAt: request.expiresAt,
status: request.status,
},
{ headers: { "Cache-Control": "no-store" } },
);
};
const completeConfigurationRequest = async (request: NextRequest, context: RouteContext): Promise<Response> => {
const { token } = await context.params;
const pending = await getCustomWidgetConfigurationRequest(token);
if (!pending || pending.status !== "pending") {
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
}
const parsedBody = await readConfigurationRequestBody(request);
if (parsedBody.status === "too-large") {
return NextResponse.json({ error: "The configuration payload is too large." }, { status: 413 });
}
if (parsedBody.status !== "ok") {
return NextResponse.json({ error: "Enter a valid source configuration." }, { status: 400 });
}
const body = parsedBody.data;
const sourceResult = customWidgetSourceSchema.safeParse({
...pending.source,
baseUrl: body.baseUrl,
networkScope: body.networkScope,
});
if (!sourceResult.success) {
return NextResponse.json(
{ error: sourceResult.error.issues[0]?.message ?? "Enter a valid server URL." },
{ status: 400 },
);
}
const secrets = pending.kinds.flatMap((kind) => {
const value = body.secrets[kind];
return typeof value === "string" && value.length > 0 && value.length <= 8192
? [{ sourceId: pending.sourceId, kind, value }]
: [];
});
if (secrets.length !== pending.kinds.length) {
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
}
const claimed = await claimCustomWidgetConfigurationRequest(token);
if (!claimed) {
return NextResponse.json(
{ error: "This source configuration request is already being completed." },
{ status: 409 },
);
}
try {
if (claimed.target.type === "preview") {
await configurePreviewSessionSource(
claimed.target.id,
claimed.userId,
claimed.sourceId,
sourceResult.data,
secrets,
);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
} else {
const result = await configureCustomWidgetSourceFromRequest(db, {
definitionId: claimed.target.id,
sourceId: claimed.sourceId,
baseUrl: sourceResult.data.baseUrl,
networkScope: sourceResult.data.networkScope,
secrets,
expectedSource: claimed.source,
});
if (result.status === "definition-not-found") {
return NextResponse.json({ error: "The custom widget no longer exists." }, { status: 404 });
}
if (result.status === "source-not-found") {
return NextResponse.json(
{ error: "This API source changed after the setup link was created. Request a new setup link." },
{ status: 409 },
);
}
if (result.status === "binding-changed") {
return NextResponse.json(
{
error: "This API source authentication changed after the setup link was created. Request a new setup link.",
},
{ status: 409 },
);
}
}
await completeCustomWidgetConfigurationRequest(token);
return NextResponse.json({ status: "completed" }, { headers: { "Cache-Control": "no-store" } });
} finally {
await releaseCustomWidgetConfigurationRequest(token);
}
};
export const GET = adminRoute(getConfigurationRequest);
export const POST = adminRoute(completeConfigurationRequest);
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import { MAX_CONFIGURATION_REQUEST_BODY_BYTES, readConfigurationRequestBody } from "./body";
describe("custom widget configuration request body", () => {
it("rejects a streaming payload once it exceeds the byte budget", async () => {
const request = new Request("http://localhost/configure", {
method: "POST",
body: JSON.stringify({
baseUrl: "https://example.com",
networkScope: "public",
secrets: { apiKey: "x".repeat(MAX_CONFIGURATION_REQUEST_BODY_BYTES) },
}),
});
await expect(readConfigurationRequestBody(request)).resolves.toEqual({ status: "too-large" });
});
it("strictly parses a bounded configuration object", async () => {
const body = { baseUrl: "https://example.com", networkScope: "public", secrets: { apiKey: "secret" } };
await expect(
readConfigurationRequestBody(
new Request("http://localhost/configure", { method: "POST", body: JSON.stringify(body) }),
),
).resolves.toEqual({ status: "ok", data: body });
await expect(
readConfigurationRequestBody(
new Request("http://localhost/configure", {
method: "POST",
body: JSON.stringify({ ...body, unexpected: true }),
}),
),
).resolves.toEqual({ status: "invalid" });
});
});
@@ -0,0 +1,52 @@
import { z } from "zod/v4";
export const MAX_CONFIGURATION_REQUEST_BODY_BYTES = 24 * 1024;
const configurationRequestBodySchema = z.strictObject({
baseUrl: z.string(),
networkScope: z.enum(["public", "private", "loopback"]),
secrets: z.record(z.string(), z.string()),
});
export async function readConfigurationRequestBody(
request: Request,
): Promise<
{ status: "ok"; data: z.infer<typeof configurationRequestBodySchema> } | { status: "invalid" | "too-large" }
> {
const contentLength = request.headers.get("content-length");
if (contentLength && Number(contentLength) > MAX_CONFIGURATION_REQUEST_BODY_BYTES) {
return { status: "too-large" };
}
if (!request.body) return { status: "invalid" };
const reader = request.body.getReader();
const chunks: Uint8Array[] = [];
let byteLength = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
byteLength += value.byteLength;
if (byteLength > MAX_CONFIGURATION_REQUEST_BODY_BYTES) {
await reader.cancel();
return { status: "too-large" };
}
chunks.push(value);
}
} catch {
return { status: "invalid" };
}
const bytes = new Uint8Array(byteLength);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
try {
const candidate = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
const result = configurationRequestBodySchema.safeParse(candidate);
return result.success ? { status: "ok", data: result.data } : { status: "invalid" };
} catch {
return { status: "invalid" };
}
}
@@ -0,0 +1,275 @@
// @vitest-environment node
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
authenticate: vi.fn(),
ipAddress: vi.fn(() => "127.0.0.1"),
toolProcedure: vi.fn(),
loggerWarn: vi.fn(),
buildPrompt: vi.fn((request?: string, documentationUrl?: string) =>
[`Request: ${request ?? ""}`, `Documentation: ${documentationUrl ?? ""}`].join("\n"),
),
getComponent: vi.fn((name: string) => (name === "Text Input" ? { name, safety: "allowed" } : null)),
}));
vi.mock("next/server", () => ({ userAgent: () => ({ ua: "MCP route test" }) }));
vi.mock("@homarr/api/mcp", () => ({
createTRPCContext: vi.fn(() => ({})),
mcpRouter: { createCaller: vi.fn(() => ({ board: { getAllBoards: mocks.toolProcedure } })) },
}));
vi.mock("@homarr/auth/api-key", () => ({
API_KEY_HEADER_NAME: "ApiKey",
getSessionFromApiKeyAsync: mocks.authenticate,
}));
vi.mock("@homarr/common", () => ({ extractBaseUrlFromHeaders: () => "http://localhost" }));
vi.mock("@homarr/common/server", () => ({ ipAddressFromHeaders: mocks.ipAddress }));
vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => ({ info: vi.fn(), warn: mocks.loggerWarn, error: vi.fn() }),
}));
vi.mock("@homarr/custom-widgets/authoring-prompt", () => ({ buildCustomWidgetMcpPrompt: mocks.buildPrompt }));
vi.mock("@homarr/custom-widgets/authoring-resources", () => ({
getCustomWidgetComponent: mocks.getComponent,
getCustomWidgetComponentCatalog: () => ({ components: [{ name: "Text Input" }] }),
getCustomWidgetSkillContent: () => "# Custom Widget Skill",
}));
vi.mock("@homarr/custom-widgets/core", () => ({
customJsxExamples: [{ id: "status-card", title: "Status card", template: "<Text>Status</Text>" }],
getCustomWidgetJsonSchema: () => ({ type: "object", title: "Custom Widget" }),
}));
vi.mock("@homarr/db", () => ({ db: {} }));
vi.mock("~/versions/package-reader", () => ({ getPackageVersion: () => "test-version" }));
vi.mock("../_extract-tools", () => ({
extractMcpTools: () => [
{
name: "board_getAllBoards",
description: "List boards",
pathInRouter: ["board", "getAllBoards"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_list",
description: "List Custom Widgets",
pathInRouter: ["customWidget", "list"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_workshopSearch",
description: "Search Workshop",
pathInRouter: ["customWidget", "workshopSearch"],
inputSchema: { type: "object", properties: {} },
},
],
}));
import { POST } from "./route";
interface JsonRpcResponse {
jsonrpc: "2.0";
id: number | null;
result?: Record<string, unknown>;
error?: { code: number; message: string };
}
beforeEach(() => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["admin"] } });
mocks.buildPrompt.mockClear();
mocks.getComponent.mockClear();
mocks.ipAddress.mockClear();
mocks.ipAddress.mockReturnValue("127.0.0.1");
mocks.toolProcedure.mockReset();
mocks.toolProcedure.mockResolvedValue([]);
mocks.loggerWarn.mockClear();
});
async function callMcp(method: string, params: Record<string, unknown> = {}, id = 1) {
const request = new Request("http://localhost/api/mcp/mcp", {
method: "POST",
headers: {
Accept: "application/json, text/event-stream",
ApiKey: "key.secret",
"Content-Type": "application/json",
"X-Forwarded-For": "198.51.100.10",
"X-Real-IP": "127.0.0.1",
},
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
});
const response = await POST(request as never);
const text = await response.text();
const data = response.headers.get("content-type")?.includes("text/event-stream")
? text
.split("\n")
.find((line) => line.startsWith("data: "))
?.slice("data: ".length)
: text;
if (!data) throw new Error(`MCP response did not contain JSON-RPC data: ${text}`);
return { response, body: JSON.parse(data) as JsonRpcResponse };
}
describe("authenticated MCP prompt protocol", () => {
test("initializes and advertises prompt and resource capabilities", async () => {
const { response, body } = await callMcp("initialize", {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "route-test", version: "1.0.0" },
});
expect(response.status).toBe(200);
expect(body.error).toBeUndefined();
expect(body.result).toMatchObject({
protocolVersion: expect.any(String),
capabilities: { prompts: {}, resources: {} },
serverInfo: { name: "homarr", version: "test-version" },
});
expect(mocks.authenticate).toHaveBeenCalledWith({}, "key.secret", "127.0.0.1", "MCP route test");
expect(mocks.ipAddress).toHaveBeenCalledWith(expect.any(Headers));
});
test("lists and interpolates the custom-widget authoring prompt", async () => {
const listed = await callMcp("prompts/list");
expect(listed.body.result).toEqual({
prompts: [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
],
});
const rendered = await callMcp("prompts/get", {
name: "homarr-custom-widget-author",
arguments: { request: "Build a status card", documentationUrl: "https://docs.example.test/api" },
});
expect(rendered.body.result).toMatchObject({
description: "Current Homarr Custom Widget authoring workflow.",
messages: [
{
role: "user",
content: {
type: "text",
text: "Request: Build a status card\nDocumentation: https://docs.example.test/api",
},
},
],
});
expect(mocks.buildPrompt).toHaveBeenCalledWith("Build a status card", "https://docs.example.test/api");
});
});
describe("authenticated MCP resource protocol", () => {
test("lists concrete resources and URI templates with reviewed MIME types", async () => {
const listed = await callMcp("resources/list");
expect(listed.body.result).toEqual({
resources: [
{ uri: "homarr://custom-widgets/schema", name: "Custom Widget schema", mimeType: "application/schema+json" },
{ uri: "homarr://custom-widgets/components", name: "Custom Widget components", mimeType: "application/json" },
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
{
uri: "homarr://custom-widgets/examples/status-card",
name: "Custom Widget example: Status card",
mimeType: "application/json",
},
],
});
const templates = await callMcp("resources/templates/list");
expect(templates.body.result).toEqual({
resourceTemplates: [
expect.objectContaining({
uriTemplate: "homarr://custom-widgets/components/{name}",
mimeType: "application/json",
}),
expect.objectContaining({
uriTemplate: "homarr://custom-widgets/examples/{name}",
mimeType: "application/json",
}),
],
});
});
test.each([
["homarr://custom-widgets/schema", "application/schema+json", { type: "object", title: "Custom Widget" }],
["homarr://custom-widgets/components", "application/json", { components: [{ name: "Text Input" }] }],
["homarr://custom-widgets/skill", "text/markdown", "# Custom Widget Skill"],
[
"homarr://custom-widgets/examples/status-card",
"application/json",
{ id: "status-card", title: "Status card", template: "<Text>Status</Text>" },
],
["homarr://custom-widgets/components/Text%20Input", "application/json", { name: "Text Input", safety: "allowed" }],
])("dispatches %s with its MIME type", async (uri, mimeType, expected) => {
const { body } = await callMcp("resources/read", { uri });
const contents = body.result?.contents as Array<{ uri: string; mimeType: string; text: string }> | undefined;
const content = contents?.[0];
expect(content).toMatchObject({ uri, mimeType });
expect(mimeType === "text/markdown" ? content?.text : JSON.parse(content?.text ?? "null")).toEqual(expected);
});
});
describe("non-admin MCP discovery", () => {
test("does not list or expose Custom Widget tools, prompts or resources", async () => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["board-view-all"] } });
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
]);
const prompts = await callMcp("prompts/list");
expect(prompts.body.result).toEqual({ prompts: [] });
const resources = await callMcp("resources/list");
expect(resources.body.result).toEqual({ resources: [] });
const templates = await callMcp("resources/templates/list");
expect(templates.body.result).toEqual({ resourceTemplates: [] });
const prompt = await callMcp("prompts/get", { name: "homarr-custom-widget-author" });
expect(prompt.body.result).toBeUndefined();
expect(prompt.body.error).toBeDefined();
const resource = await callMcp("resources/read", { uri: "homarr://custom-widgets/schema" });
expect(resource.body.result).toBeUndefined();
expect(resource.body.error).toBeDefined();
});
});
describe("MCP protocol errors", () => {
test.each([
["prompts/get", { name: "unknown" }],
["resources/read", { uri: "homarr://custom-widgets/unknown" }],
])("returns JSON-RPC errors for unknown %s targets", async (method, params) => {
const { body } = await callMcp(method, params);
expect(body.result).toBeUndefined();
expect(body.error).toEqual(expect.objectContaining({ code: expect.any(Number), message: expect.any(String) }));
});
test("returns a protocol error for a malformed resource request", async () => {
const { body } = await callMcp("resources/read", {});
expect(body.result).toBeUndefined();
expect(body.error).toEqual(expect.objectContaining({ code: -32603, message: expect.any(String) }));
});
test("does not log sensitive tool error messages", async () => {
const failure = Object.assign(new Error("request to https://user:secret@example.test/private failed"), {
code: "BAD_GATEWAY",
});
mocks.toolProcedure.mockRejectedValue(failure);
const { body } = await callMcp("tools/call", { name: "board_getAllBoards", arguments: {} });
expect(JSON.stringify(body)).not.toContain("user:secret");
expect(mocks.loggerWarn).toHaveBeenCalledWith("MCP tool execution failed", {
tool: "board_getAllBoards",
errorName: "Error",
errorCode: "BAD_GATEWAY",
});
const metadata = mocks.loggerWarn.mock.calls.at(-1)?.[1] as Record<string, unknown>;
expect(metadata).not.toHaveProperty("error");
expect(metadata).not.toHaveProperty("message");
});
});
+151 -10
View File
@@ -3,13 +3,28 @@ import type { NextRequest } from "next/server";
import { userAgent } from "next/server";
import { createMcpHandler } from "mcp-handler";
import type { McpTool } from "trpc-to-mcp";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import {
CallToolRequestSchema,
GetPromptRequestSchema,
ListPromptsRequestSchema,
ListResourcesRequestSchema,
ListResourceTemplatesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { createTRPCContext, mcpRouter } from "@homarr/api/mcp";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { extractBaseUrlFromHeaders } from "@homarr/common";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-prompt";
import {
getCustomWidgetComponent,
getCustomWidgetComponentCatalog,
getCustomWidgetSkillContent,
} from "@homarr/custom-widgets/authoring-resources";
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { db } from "@homarr/db";
import { getPackageVersion } from "~/versions/package-reader";
@@ -70,7 +85,12 @@ function clearAuthFailures(ip: string | null) {
authFailures.delete(ip ?? "unknown");
}
const callerStorage = new AsyncLocalStorage<ReturnType<typeof mcpRouter.createCaller>>();
interface McpCallerContext {
caller: ReturnType<typeof mcpRouter.createCaller>;
isAdmin: boolean;
}
const callerStorage = new AsyncLocalStorage<McpCallerContext>();
const emptyObjectSchema = {
type: "object" as const,
@@ -98,6 +118,20 @@ function getTools() {
return toolsCache;
}
function getVisibleTools() {
const tools = getTools();
if (!isCustomWidgetMcpEnabled()) {
return tools.filter((tool) => !tool.name.startsWith("customWidget_"));
}
return tools;
}
function requireCustomWidgetMcpAdmin() {
if (!isCustomWidgetMcpEnabled()) throw new Error("Resource not found");
}
const isCustomWidgetMcpEnabled = () => Boolean(callerStorage.getStore()?.isAdmin);
const SAFE_ERROR_MESSAGES: Record<string, string> = {
UNAUTHORIZED: "You do not have permission to perform this action",
FORBIDDEN: "Access denied",
@@ -168,13 +202,116 @@ If \`hasUseAccess\` is false, the API key owner lacks permission for that integr
const mcpHandler = createMcpHandler(
(server) => {
server.server.setRequestHandler(ListPromptsRequestSchema, () => ({
prompts: isCustomWidgetMcpEnabled()
? [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
]
: [],
}));
server.server.setRequestHandler(GetPromptRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
if (request.params.name !== "homarr-custom-widget-author") throw new Error("Prompt not found");
return {
description: "Current Homarr Custom Widget authoring workflow.",
messages: [
{
role: "user" as const,
content: {
type: "text" as const,
text: buildCustomWidgetMcpPrompt(
request.params.arguments?.request,
request.params.arguments?.documentationUrl,
),
},
},
],
};
});
server.server.setRequestHandler(ListResourcesRequestSchema, () => ({
resources: isCustomWidgetMcpEnabled()
? [
{
uri: "homarr://custom-widgets/schema",
name: "Custom Widget schema",
mimeType: "application/schema+json",
},
{
uri: "homarr://custom-widgets/components",
name: "Custom Widget components",
mimeType: "application/json",
},
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
...customJsxExamples.map((example) => ({
uri: `homarr://custom-widgets/examples/${example.id}`,
name: `Custom Widget example: ${example.title}`,
mimeType: "application/json",
})),
]
: [],
}));
server.server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
resourceTemplates: isCustomWidgetMcpEnabled()
? [
{
uriTemplate: "homarr://custom-widgets/components/{name}",
name: "Custom Widget component",
description: "Metadata for one installed Custom Widget component.",
mimeType: "application/json",
},
{
uriTemplate: "homarr://custom-widgets/examples/{name}",
name: "Custom Widget example",
description: "One canonical Custom Widget example.",
mimeType: "application/json",
},
]
: [],
}));
server.server.setRequestHandler(ReadResourceRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
const { uri } = request.params;
let text: string;
let mimeType = "application/json";
if (uri === "homarr://custom-widgets/schema") {
text = JSON.stringify(getCustomWidgetJsonSchema());
mimeType = "application/schema+json";
} else if (uri === "homarr://custom-widgets/components") text = JSON.stringify(getCustomWidgetComponentCatalog());
else if (uri === "homarr://custom-widgets/skill") {
text = getCustomWidgetSkillContent();
mimeType = "text/markdown";
} else if (uri.startsWith("homarr://custom-widgets/components/")) {
const name = decodeURIComponent(uri.slice("homarr://custom-widgets/components/".length));
const component = getCustomWidgetComponent(name);
if (!component) throw new Error("Component resource not found");
text = JSON.stringify(component);
} else if (uri.startsWith("homarr://custom-widgets/examples/")) {
const name = decodeURIComponent(uri.slice("homarr://custom-widgets/examples/".length));
const example = customJsxExamples.find((candidate) => candidate.id === name);
if (!example) throw new Error("Example resource not found");
text = JSON.stringify(example);
} else throw new Error("Resource not found");
return { contents: [{ uri, mimeType, text }] };
});
server.server.setRequestHandler(ListToolsRequestSchema, () => ({
tools: getTools(),
tools: getVisibleTools(),
}));
server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const tools = getTools();
const tools = getVisibleTools();
const tool = tools.find((t) => t.name === name);
if (!tool) {
@@ -184,8 +321,8 @@ const mcpHandler = createMcpHandler(
};
}
const caller = callerStorage.getStore();
if (!caller) {
const callerContext = callerStorage.getStore();
if (!callerContext) {
return {
content: [{ type: "text" as const, text: "Authentication context not available" }],
isError: true,
@@ -193,7 +330,7 @@ const mcpHandler = createMcpHandler(
}
try {
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], caller);
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], callerContext.caller);
if (typeof procedure !== "function") {
return {
content: [{ type: "text" as const, text: `Tool "${name}" is not callable` }],
@@ -209,7 +346,9 @@ const mcpHandler = createMcpHandler(
const message = sanitizeErrorMessage(error);
logger.warn("MCP tool execution failed", {
tool: name,
error: error instanceof Error ? error.message : String(error),
errorName: error instanceof Error ? error.name : "UnknownError",
errorCode:
error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined,
});
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }],
@@ -219,7 +358,7 @@ const mcpHandler = createMcpHandler(
});
},
{
capabilities: { tools: {} },
capabilities: { tools: {}, prompts: {}, resources: {} },
instructions: SERVER_INSTRUCTIONS,
serverInfo: {
name: "homarr",
@@ -296,7 +435,9 @@ const handler = async (req: NextRequest) => {
const ctx = createTRPCContext({ session, headers: req.headers });
const caller = mcpRouter.createCaller(ctx);
return callerStorage.run(caller, () => mcpHandler(req as unknown as Request));
return callerStorage.run({ caller, isAdmin: session.user.permissions.includes("admin") }, () =>
mcpHandler(req as unknown as Request),
);
};
export { handler as GET, handler as POST, handler as DELETE };
@@ -0,0 +1,126 @@
.backdrop {
pointer-events: none;
animation: focus-backdrop-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.manualBackdrop {
pointer-events: auto;
}
.surface {
position: fixed;
z-index: 1;
pointer-events: auto;
overflow: hidden;
background: var(--mantine-color-body);
box-shadow: var(--mantine-shadow-md);
overscroll-behavior: contain;
animation: focus-surface-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
transform-origin: top left;
}
.manualSurface {
position: fixed;
max-width: none;
max-height: none;
overflow: visible;
background: transparent;
box-shadow: none;
overscroll-behavior: contain;
animation: focus-surface-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
transform-origin: top left;
}
.manualSurface > div {
width: 100%;
height: 100%;
max-height: none !important;
overflow: visible;
}
.backdropClosing {
animation: focus-backdrop-out 180ms ease-in forwards;
}
.surfaceClosing {
animation: focus-surface-out 180ms ease-in forwards;
}
.sourcePlaceholder {
pointer-events: none;
}
.surfaceHost {
width: 100%;
height: 100%;
}
.surfacePortalTarget,
.manualSurfaceMount {
width: 100%;
height: 100%;
min-height: 0;
}
.manualSurfaceMount {
overflow: hidden;
border-radius: inherit;
}
.surfaceHostAdvanced {
position: fixed;
inset: 0;
z-index: var(--homarr-z-index-widget-focus);
width: auto;
height: auto;
pointer-events: none;
}
.closeButton {
position: absolute;
z-index: 2;
pointer-events: auto;
}
@keyframes focus-backdrop-in {
from {
opacity: 0;
}
}
@keyframes focus-surface-in {
from {
transform: translate(var(--focus-translate-x), var(--focus-translate-y))
scale(var(--focus-scale-x), var(--focus-scale-y));
opacity: 0.72;
}
}
@keyframes focus-backdrop-out {
to {
opacity: 0;
}
}
@keyframes focus-surface-out {
to {
transform: translate(var(--focus-translate-x), var(--focus-translate-y))
scale(var(--focus-scale-x), var(--focus-scale-y));
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
.backdrop,
.surface,
.manualSurface {
animation: none;
}
}
@media (forced-colors: active) {
.backdrop {
background: Canvas;
opacity: 0.4;
}
}
@@ -0,0 +1,275 @@
"use client";
import type { PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { Overlay, Portal } from "@mantine/core";
import { useIsomorphicEffect } from "@mantine/hooks";
import { useEditMode } from "@homarr/boards/edit-mode";
import classes from "./advanced-focus.module.css";
import { isEscapeOwnedByNestedOverlay } from "./escape";
import type { FocusRect } from "./geometry";
interface ActiveFocus {
itemId: string;
source: HTMLElement;
sourceRect: FocusRect;
activation: "preview" | "manual";
autofocusClose: boolean;
restorePreviewFocus: boolean;
phase: "visible" | "closing";
}
interface OpenAdvancedFocusOptions {
activation?: ActiveFocus["activation"];
autofocusClose?: boolean;
}
interface AdvancedFocusContextValue {
active: ActiveFocus | null;
open: (itemId: string, source: HTMLElement, options?: OpenAdvancedFocusOptions) => void;
close: (restoreFocus?: boolean) => void;
dismiss: (itemId: string) => void;
hover: (itemId: string, source: HTMLElement) => void;
leave: (itemId: string) => void;
}
const AdvancedFocusContext = createContext<AdvancedFocusContextValue | null>(null);
const HOVER_DELAY_MS = 150;
const CLOSE_DURATION_MS = 180;
const interactiveSelector =
"a[href], button, input, textarea, select, [contenteditable='true'], [role='button'], [role='link'], [role='menuitem'], [role='option']";
const isEditableTarget = (target: EventTarget | null) =>
target instanceof HTMLElement &&
(target.matches("input, textarea, select, [contenteditable='true']") || target.isContentEditable);
export const BoardAdvancedFocusProvider = ({ children }: PropsWithChildren) => {
const [isEditMode] = useEditMode();
const [active, setActive] = useState<ActiveFocus | null>(null);
const activeRef = useRef<ActiveFocus | null>(null);
const hoveredRef = useRef<{ itemId: string; source: HTMLElement } | null>(null);
const shiftHeldRef = useRef(false);
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const cancelHoverTimer = useCallback(() => {
if (hoverTimerRef.current === null) return;
clearTimeout(hoverTimerRef.current);
hoverTimerRef.current = null;
}, []);
const updateActive = useCallback((next: ActiveFocus | null) => {
activeRef.current = next;
setActive(next);
}, []);
const cancelCloseTimer = useCallback(() => {
if (closeTimerRef.current === null) return;
clearTimeout(closeTimerRef.current);
closeTimerRef.current = null;
}, []);
const open = useCallback(
(itemId: string, source: HTMLElement, options: OpenAdvancedFocusOptions = {}) => {
if (isEditMode) return;
cancelHoverTimer();
cancelCloseTimer();
const rect = source.getBoundingClientRect();
updateActive({
itemId,
source,
sourceRect: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
activation: options.activation ?? "manual",
autofocusClose: options.autofocusClose ?? false,
restorePreviewFocus: options.activation === "preview" && document.activeElement === source,
phase: "visible",
});
},
[cancelCloseTimer, cancelHoverTimer, isEditMode, updateActive],
);
const close = useCallback(
(restoreFocus = true) => {
cancelHoverTimer();
const current = activeRef.current;
if (!current || current.phase === "closing") return;
updateActive({ ...current, phase: "closing" });
const closeDuration = window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : CLOSE_DURATION_MS;
closeTimerRef.current = setTimeout(() => {
closeTimerRef.current = null;
updateActive(null);
if (restoreFocus && current.source.isConnected) requestAnimationFrame(() => current.source.focus());
}, closeDuration);
},
[cancelHoverTimer, updateActive],
);
const startHoverTimer = useCallback(() => {
cancelHoverTimer();
const hovered = hoveredRef.current;
if (!hovered || !shiftHeldRef.current || activeRef.current) return;
hoverTimerRef.current = setTimeout(
() => open(hovered.itemId, hovered.source, { activation: "preview" }),
HOVER_DELAY_MS,
);
}, [cancelHoverTimer, open]);
const hover = useCallback(
(itemId: string, source: HTMLElement) => {
hoveredRef.current = { itemId, source };
const current = activeRef.current;
if (current?.activation === "preview" && current.itemId !== itemId) {
cancelCloseTimer();
updateActive(null);
if (current.restorePreviewFocus && current.source.isConnected) current.source.focus({ preventScroll: true });
}
startHoverTimer();
},
[cancelCloseTimer, startHoverTimer, updateActive],
);
useEffect(() => {
const handlePointerMove = (event: PointerEvent) => {
const current = activeRef.current;
if (!shiftHeldRef.current || current?.activation !== "preview") return;
if (
event.target instanceof Element &&
event.target.closest(interactiveSelector)?.closest("[data-advanced-focus-surface]")
)
return;
const underlyingSource = document
.elementsFromPoint(event.clientX, event.clientY)
.map((element) =>
element instanceof HTMLElement
? element.matches("[data-advanced-focus-source]")
? element
: element.closest<HTMLElement>("[data-advanced-focus-source]")
: null,
)
.find((source) => source !== null && source !== current.source);
const itemId = underlyingSource?.dataset.itemId;
if (!underlyingSource || !itemId) return;
if (underlyingSource.hasAttribute("aria-keyshortcuts")) {
hover(itemId, underlyingSource);
return;
}
hoveredRef.current = null;
cancelHoverTimer();
cancelCloseTimer();
updateActive(null);
};
window.addEventListener("pointermove", handlePointerMove, { capture: true });
return () => window.removeEventListener("pointermove", handlePointerMove, { capture: true });
}, [cancelCloseTimer, cancelHoverTimer, hover, updateActive]);
const leave = useCallback(
(itemId: string) => {
if (hoveredRef.current?.itemId === itemId) hoveredRef.current = null;
cancelHoverTimer();
},
[cancelHoverTimer],
);
const dismiss = useCallback(
(itemId: string) => {
if (activeRef.current?.itemId !== itemId) return;
cancelHoverTimer();
cancelCloseTimer();
updateActive(null);
},
[cancelCloseTimer, cancelHoverTimer, updateActive],
);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && activeRef.current) {
const advancedSurface = document.querySelector("[data-advanced-focus-surface]");
if (event.defaultPrevented || event.isComposing || isEscapeOwnedByNestedOverlay(event.target, advancedSurface))
return;
event.preventDefault();
close();
return;
}
if (isEditMode) return;
if (event.key !== "Shift" || event.repeat || isEditableTarget(event.target)) return;
if (activeRef.current?.activation === "manual") return;
shiftHeldRef.current = true;
startHoverTimer();
};
const handleKeyUp = (event: KeyboardEvent) => {
if (event.key !== "Shift") return;
shiftHeldRef.current = false;
cancelHoverTimer();
if (activeRef.current?.activation === "preview") close(false);
};
const handleBlur = () => {
shiftHeldRef.current = false;
cancelHoverTimer();
if (activeRef.current?.activation === "preview") close(false);
};
window.addEventListener("keydown", handleKeyDown, { capture: true });
window.addEventListener("keyup", handleKeyUp);
window.addEventListener("blur", handleBlur);
return () => {
window.removeEventListener("keydown", handleKeyDown, { capture: true });
window.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("blur", handleBlur);
cancelHoverTimer();
cancelCloseTimer();
};
}, [cancelCloseTimer, cancelHoverTimer, close, isEditMode, startHoverTimer]);
useEffect(() => {
if (isEditMode && activeRef.current) close(false);
}, [close, isEditMode]);
useIsomorphicEffect(() => {
if (active?.activation !== "manual") return;
const background = document.querySelectorAll<HTMLElement>("[data-advanced-focus-background]");
background.forEach((element) => {
element.inert = true;
});
return () => {
background.forEach((element) => {
element.inert = false;
});
};
}, [active?.activation]);
const value = useMemo(
() => ({ active, open, close, dismiss, hover, leave }),
[active, close, dismiss, hover, leave, open],
);
return (
<AdvancedFocusContext.Provider value={value}>
{children}
{active?.activation === "preview" && (
<Portal>
<Overlay
fixed
data-advanced-focus-overlay
backgroundOpacity={0.38}
blur={0}
zIndex="var(--homarr-z-index-widget-preview-backdrop)"
className={`${classes.backdrop} ${active.phase === "closing" ? classes.backdropClosing : ""}`}
aria-hidden
/>
</Portal>
)}
</AdvancedFocusContext.Provider>
);
};
export const useAdvancedFocus = () => {
const context = useContext(AdvancedFocusContext);
if (!context) throw new Error("useAdvancedFocus must be used within BoardAdvancedFocusProvider");
return context;
};
@@ -0,0 +1,72 @@
import { describe, expect, test } from "vitest";
import { isEscapeOwnedByNestedOverlay } from "./escape";
describe("isEscapeOwnedByNestedOverlay", () => {
test("allows Escape from the advanced surface itself", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "dialog");
const button = document.createElement("button");
surface.append(button);
expect(isEscapeOwnedByNestedOverlay(button, surface)).toBe(false);
});
test("leaves Escape to a nested Mantine modal", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
const modal = document.createElement("section");
modal.setAttribute("role", "dialog");
const input = document.createElement("input");
modal.append(input);
expect(isEscapeOwnedByNestedOverlay(input, surface)).toBe(true);
});
test.each(["menu", "listbox"])("leaves Escape to a nested %s overlay", (role) => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
const overlay = document.createElement("div");
overlay.setAttribute("role", role);
const target = document.createElement("button");
overlay.append(target);
expect(isEscapeOwnedByNestedOverlay(target, surface)).toBe(true);
});
test("honors Mantine's stop-propagation marker for menus and comboboxes", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
const target = document.createElement("button");
target.setAttribute("data-mantine-stop-propagation", "true");
surface.append(target);
expect(isEscapeOwnedByNestedOverlay(target, surface)).toBe(true);
});
test("leaves Escape to a visible portalled menu when focus stays in the advanced surface", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "dialog");
const target = document.createElement("button");
surface.append(target);
document.body.append(surface);
const menu = document.createElement("div");
menu.setAttribute("role", "menu");
menu.getClientRects = () => [{ width: 100, height: 100 }] as unknown as DOMRectList;
document.body.append(menu);
expect(isEscapeOwnedByNestedOverlay(target, surface)).toBe(true);
menu.remove();
surface.remove();
});
test("does not mistake the compact widget source for a nested overlay", () => {
const surface = document.createElement("section");
surface.setAttribute("role", "region");
const source = document.createElement("button");
expect(isEscapeOwnedByNestedOverlay(source, surface)).toBe(false);
});
});
@@ -0,0 +1,19 @@
const escapeOwnerSelector = [
'[data-mantine-stop-propagation="true"]',
'[role="dialog"]',
'[role="menu"]',
'[role="listbox"]',
].join(", ");
export const isEscapeOwnedByNestedOverlay = (target: EventTarget | null, advancedSurface: Element | null) => {
const escapeOwner = target instanceof Element ? target.closest(escapeOwnerSelector) : null;
if (escapeOwner !== null && escapeOwner !== advancedSurface) return true;
return Array.from(document.querySelectorAll(escapeOwnerSelector)).some(
(owner) =>
owner !== advancedSurface &&
owner.getAttribute("aria-hidden") !== "true" &&
owner.closest('[aria-hidden="true"]') === null &&
owner.getClientRects().length > 0,
);
};
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { getAdvancedFocusClosePosition, getAdvancedFocusRect } from "./geometry";
describe("getAdvancedFocusRect", () => {
it("expands around the widget instead of centering a modal", () => {
const rect = getAdvancedFocusRect({ left: 450, top: 300, width: 300, height: 200 }, { width: 1200, height: 800 });
expect(rect).toEqual({ left: 200, top: 120, width: 800, height: 560 });
expect(rect.left + rect.width / 2).toBe(600);
expect(rect.top + rect.height / 2).toBe(400);
});
it("uses the available viewport on small screens", () => {
expect(getAdvancedFocusRect({ left: 0, top: 0, width: 400, height: 500 }, { width: 390, height: 700 })).toEqual({
left: 8,
top: 68,
width: 374,
height: 624,
});
});
it("keeps controls below the fixed board header on short screens", () => {
const rect = getAdvancedFocusRect({ left: 1200, top: 700, width: 500, height: 500 }, { width: 1366, height: 768 });
expect(rect.left).toBeGreaterThanOrEqual(16);
expect(rect.left + rect.width).toBeLessThanOrEqual(1350);
expect(rect.top).toBeGreaterThanOrEqual(76);
expect(rect.top + rect.height).toBeLessThanOrEqual(752);
});
});
describe("getAdvancedFocusClosePosition", () => {
it("keeps the close control outside the surface when the right side has room", () => {
expect(getAdvancedFocusClosePosition({ left: 16, top: 76, width: 800, height: 560 }, 1280)).toEqual({
left: 824,
top: 76,
});
});
it("uses the left side when the surface is anchored to the right edge", () => {
expect(getAdvancedFocusClosePosition({ left: 464, top: 76, width: 800, height: 560 }, 1280)).toEqual({
left: 412,
top: 76,
});
});
it("falls back to the inside corner on narrow screens", () => {
expect(getAdvancedFocusClosePosition({ left: 8, top: 68, width: 374, height: 624 }, 390)).toEqual({
left: 330,
top: 76,
});
});
});
@@ -0,0 +1,54 @@
import { appShellHeaderHeight } from "../../layout/constants";
export interface FocusRect {
left: number;
top: number;
width: number;
height: number;
}
export interface FocusClosePosition {
left: number;
top: number;
}
const closeButtonSize = 44;
const closeButtonGap = 8;
export const getAdvancedFocusRect = (source: FocusRect, viewport: { width: number; height: number }): FocusRect => {
const margin = viewport.width < 640 ? 8 : 16;
const availableWidth = Math.max(0, viewport.width - margin * 2);
const availableHeight = Math.max(0, viewport.height - appShellHeaderHeight - margin * 2);
const preferredWidth = viewport.width < 640 ? availableWidth : Math.min(800, availableWidth);
const preferredHeight = viewport.width < 640 ? availableHeight : Math.min(560, availableHeight);
const width = Math.min(availableWidth, Math.max(source.width, preferredWidth));
const height = Math.min(availableHeight, Math.max(source.height, preferredHeight));
const minimumTop = appShellHeaderHeight + margin;
const maximumLeft = Math.max(margin, viewport.width - margin - width);
const maximumTop = Math.max(minimumTop, viewport.height - margin - height);
return {
left: Math.min(maximumLeft, Math.max(margin, source.left - (width - source.width) / 2)),
top: Math.min(maximumTop, Math.max(minimumTop, source.top - (height - source.height) / 2)),
width,
height,
};
};
export const getAdvancedFocusClosePosition = (surface: FocusRect, viewportWidth: number): FocusClosePosition => {
const outsideOffset = closeButtonSize + closeButtonGap;
const surfaceRight = surface.left + surface.width;
if (viewportWidth - surfaceRight >= outsideOffset) {
return { left: surfaceRight + closeButtonGap, top: surface.top };
}
if (surface.left >= outsideOffset) {
return { left: surface.left - outsideOffset, top: surface.top };
}
return {
left: Math.max(0, Math.min(viewportWidth - closeButtonSize, surfaceRight - outsideOffset)),
top: surface.top + closeButtonGap,
};
};
@@ -0,0 +1,107 @@
// @vitest-environment jsdom
import { act, createElement, Fragment, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
import { afterEach, describe, expect, test, vi } from "vitest";
import { AdvancedFocusManualSurface } from "./manual-surface";
const sourceRect = { left: 100, top: 120, width: 240, height: 160 };
const rect = { left: 40, top: 80, width: 640, height: 480 };
const closePosition = { left: 688, top: 80 };
describe("AdvancedFocusManualSurface", () => {
let host: HTMLDivElement | undefined;
let root: ReturnType<typeof createRoot> | undefined;
afterEach(async () => {
if (root) await act(async () => root?.unmount());
host?.remove();
document.querySelectorAll("[data-portal]").forEach((portal) => portal.remove());
vi.unstubAllGlobals();
});
test("portals dialog semantics, traps focus, closes from the backdrop, and restores focus", async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal(
"matchMedia",
vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
);
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
const Harness = () => {
const [opened, setOpened] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
return createElement(
Fragment,
null,
createElement("button", { type: "button", onClick: () => setOpened(true) }, "Open advanced view"),
createElement(
AdvancedFocusManualSurface,
{
opened,
phase: "visible",
id: "advanced-focus-test",
label: "Test widget advanced view",
closeLabel: "Close advanced view",
rect,
closePosition,
sourceRect,
radius: "md",
contentRef,
onClose: () => setOpened(false),
},
createElement("button", { type: "button" }, "First widget action"),
createElement("button", { type: "button" }, "Last widget action"),
),
);
};
await act(async () => root?.render(createElement(MantineProvider, null, createElement(Harness))));
const trigger = document.querySelector<HTMLButtonElement>("button");
expect(trigger).not.toBeNull();
trigger?.focus();
await act(async () => trigger?.click());
await act(async () => await new Promise((resolve) => setTimeout(resolve, 20)));
const dialog = document.querySelector<HTMLElement>("[role='dialog']");
const closeButton = dialog?.querySelector<HTMLButtonElement>("[aria-label='Close advanced view']");
const actions = dialog?.querySelectorAll<HTMLButtonElement>("button");
expect(dialog?.id).toBe("advanced-focus-test");
expect(dialog?.getAttribute("aria-modal")).toBe("true");
expect(dialog?.closest("[data-portal]")).not.toBeNull();
expect(dialog?.closest("[data-grid-item-id]")).toBeNull();
expect(document.getElementById(dialog?.getAttribute("aria-labelledby") ?? "")?.textContent).toBe(
"Test widget advanced view",
);
expect(document.activeElement).toBe(closeButton);
const lastAction = actions?.item((actions?.length ?? 1) - 1);
lastAction?.focus();
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
expect(document.activeElement).toBe(closeButton);
closeButton?.focus();
document.dispatchEvent(
new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, cancelable: true }),
);
expect(document.activeElement).toBe(lastAction);
const backdrop = document.querySelector<HTMLElement>("[data-advanced-focus-overlay]");
await act(async () => backdrop?.click());
await act(async () => await new Promise((resolve) => setTimeout(resolve, 20)));
expect(document.activeElement).toBe(trigger);
});
});
@@ -0,0 +1,101 @@
"use client";
import type { CSSProperties, PropsWithChildren, Ref } from "react";
import { Modal, VisuallyHidden } from "@mantine/core";
import { useReducedMotion } from "@mantine/hooks";
import classes from "./advanced-focus.module.css";
import type { FocusClosePosition, FocusRect } from "./geometry";
interface AdvancedFocusManualSurfaceProps extends PropsWithChildren {
opened: boolean;
phase: "visible" | "closing";
id: string;
label: string;
closeLabel: string;
rect: FocusRect;
closePosition: FocusClosePosition;
sourceRect: FocusRect;
radius: string | number;
contentRef: Ref<HTMLDivElement>;
onClose: () => void;
}
export const AdvancedFocusManualSurface = ({
opened,
phase,
id,
label,
closeLabel,
rect,
closePosition,
sourceRect,
radius,
contentRef,
onClose,
children,
}: AdvancedFocusManualSurfaceProps) => {
const reduceMotion = useReducedMotion();
const transitionDuration = reduceMotion ? 0 : 180;
const geometryStyle = {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
"--focus-translate-x": `${sourceRect.left - rect.left}px`,
"--focus-translate-y": `${sourceRect.top - rect.top}px`,
"--focus-scale-x": rect.width > 0 ? sourceRect.width / rect.width : 1,
"--focus-scale-y": rect.height > 0 ? sourceRect.height / rect.height : 1,
} as CSSProperties;
const relativeClosePosition = {
left: closePosition.left - rect.left,
top: closePosition.top - rect.top,
};
return (
<Modal.Root
opened={opened}
onClose={onClose}
radius={radius}
padding={0}
shadow="none"
zIndex="var(--homarr-z-index-widget-focus)"
closeOnEscape={false}
closeOnClickOutside
lockScroll
trapFocus
returnFocus
removeScrollProps={{ allowPinchZoom: true }}
transitionProps={{ duration: transitionDuration, transition: "fade" }}
>
<Modal.Overlay
data-advanced-focus-overlay
backgroundOpacity={0.38}
blur={0}
className={`${classes.backdrop} ${classes.manualBackdrop} ${
phase === "closing" ? classes.backdropClosing : ""
}`}
/>
<Modal.Content
ref={contentRef}
id={id}
data-advanced-focus-surface
className={`${classes.manualSurface} ${phase === "closing" ? classes.surfaceClosing : ""}`}
style={geometryStyle}
>
<Modal.Title>
<VisuallyHidden>{label}</VisuallyHidden>
</Modal.Title>
<Modal.CloseButton
className={classes.closeButton}
variant="default"
size={44}
aria-label={closeLabel}
aria-controls={id}
style={relativeClosePosition}
/>
{children}
</Modal.Content>
</Modal.Root>
);
};
@@ -0,0 +1,26 @@
const isVerticalScrollContainer = (element: Element) => {
if (element.scrollHeight <= element.clientHeight) return false;
const overflowY = getComputedStyle(element).overflowY;
return overflowY === "auto" || overflowY === "scroll";
};
const canScrollVertically = (element: Element, delta: number) => {
return delta < 0 ? element.scrollTop > 0 : element.scrollTop + element.clientHeight < element.scrollHeight;
};
export const redirectShiftWheel = (root: HTMLElement, target: EventTarget | null, delta: number) => {
if (delta === 0) return false;
let current = target instanceof Element ? target : null;
while (current && root.contains(current)) {
const isCurrentScrollContainer = isVerticalScrollContainer(current);
if (isCurrentScrollContainer && canScrollVertically(current, delta)) {
current.scrollTop += delta;
return true;
}
if (current === root) break;
current = current.parentElement;
}
return false;
};
@@ -1,10 +1,12 @@
import { getBoardLayouts } from "@homarr/boards/context";
import { createId } from "@homarr/common";
import type { Modify } from "@homarr/common/types";
import { getRootSectionLane } from "@homarr/definitions";
import type { WidgetKind } from "@homarr/definitions";
import { widgetDefaultSizes } from "@homarr/definitions";
import type { Board, EmptySection, Item, ItemLayout } from "~/app/[locale]/boards/_types";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { getFirstEmptyPosition } from "./empty-position";
import { getSectionElements } from "./section-elements";
@@ -19,17 +21,21 @@ export const createItemCallback =
({ id, kind, options = {}, integrationIds = [] }: CreateItemInput) =>
(previous: Board): Board => {
const firstSection = previous.sections
.filter((section): section is EmptySection => section.kind === "empty")
.filter(
(section): section is EmptySection =>
section.kind === "empty" && getRootSectionLane(section.xOffset) === "main",
)
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) return previous;
const itemLayouts = createItemLayouts(previous, firstSection, kind);
const widget = {
id: id ?? createId(),
kind,
options,
layouts: createItemLayouts(previous, firstSection, kind),
layouts: itemLayouts,
integrationIds,
advancedOptions: {
title: null,
@@ -60,13 +66,14 @@ const createItemLayouts = (board: Board, currentSection: EmptySection, kind: Wid
return layouts.map((layoutId) => {
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
const sizeForLayout = {
...itemSize,
width: Math.min(boardLayout?.columnCount ?? itemSize.width, itemSize.width),
const columnCount = boardLayout ? getBoardLaneColumnCount(boardLayout, "main") : itemSize.width;
const size = {
width: Math.min(itemSize.width, columnCount),
height: itemSize.height,
};
const emptyPosition = boardLayout
? getFirstEmptyPosition(elements, boardLayout.columnCount, 9999, sizeForLayout)
? getFirstEmptyPosition(elements, columnCount, undefined, size)
: { xOffset: 0, yOffset: 0 };
if (!emptyPosition) {
@@ -74,8 +81,8 @@ const createItemLayouts = (board: Board, currentSection: EmptySection, kind: Wid
}
return {
width: sizeForLayout.width,
height: sizeForLayout.height,
width: size.width,
height: size.height,
...emptyPosition,
sectionId: currentSection.id,
layoutId,
@@ -1,6 +1,8 @@
import { createId } from "@homarr/common";
import { getRootSectionLane } from "@homarr/definitions";
import type { Board, EmptySection, ItemLayout, Section } from "~/app/[locale]/boards/_types";
import { getBoardLaneColumnCount } from "~/components/board/layout";
import { getFirstEmptyPosition } from "./empty-position";
import { getSectionElements } from "./section-elements";
@@ -15,16 +17,17 @@ export const duplicateItemCallback =
if (!itemToDuplicate) return previous;
const clonedItem = structuredClone(itemToDuplicate);
const clonedLayouts = clonedItem.layouts.map((layout) => ({
...layout,
...getNextPosition(previous, layout),
}));
return {
...previous,
items: previous.items.concat({
...clonedItem,
id: createId(),
layouts: clonedItem.layouts.map((layout) => ({
...layout,
...getNextPosition(previous, layout),
})),
layouts: clonedLayouts,
}),
};
};
@@ -42,8 +45,10 @@ const getNextPosition = (board: Board, layout: ItemLayout): { xOffset: number; y
}
const firstSection = board.sections
.filter((section): section is EmptySection => section.kind === "empty")
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.filter(
(section): section is EmptySection => section.kind === "empty" && getRootSectionLane(section.xOffset) === "main",
)
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
.at(0);
if (!firstSection) {
@@ -67,18 +72,21 @@ const getEmptySectionPosition = (
layout: ItemLayout,
section: Section,
): { xOffset: number; yOffset: number } | undefined => {
const boardLayout = board.layouts.find((boardLayout) => boardLayout.id === layout.layoutId);
const boardLayout = board.layouts.find((candidate) => candidate.id === layout.layoutId);
if (!boardLayout) return;
const sectionElements = getSectionElements(board, { sectionId: layout.sectionId, layoutId: layout.layoutId });
if (section.kind !== "dynamic") {
return getFirstEmptyPosition(sectionElements, boardLayout.columnCount, undefined, {
const sectionElements = getSectionElements(board, { sectionId: section.id, layoutId: layout.layoutId });
if (section.kind === "empty") {
const columnCount = getBoardLaneColumnCount(boardLayout, getRootSectionLane(section.xOffset));
const size = {
width: layout.width,
height: layout.height,
});
};
return getFirstEmptyPosition(sectionElements, columnCount, undefined, size);
}
const sectionLayout = section.layouts.find((sectionLayout) => sectionLayout.layoutId === layout.layoutId);
const sectionLayout = section.layouts.find((candidate) => candidate.layoutId === layout.layoutId);
if (!sectionLayout) return;
return getFirstEmptyPosition(sectionElements, sectionLayout.width, sectionLayout.height, {
@@ -7,7 +7,7 @@ export const getFirstEmptyPosition = (
size: { width: number; height: number } = { width: 1, height: 1 },
) => {
for (let yOffset = 0; yOffset < rowCount + 1 - size.height; yOffset++) {
for (let xOffset = 0; xOffset < columnCount; xOffset++) {
for (let xOffset = 0; xOffset < columnCount + 1 - size.width; xOffset++) {
const isOccupied = elements.some(
(element) =>
element.yOffset < yOffset + size.height &&
@@ -1,8 +1,8 @@
import type { Board } from "~/app/[locale]/boards/_types";
export const getSectionElements = (board: Board, { sectionId, layoutId }: { sectionId: string; layoutId: string }) => {
const dynamicSectionsOfFirstSection = board.sections
.filter((section) => section.kind === "dynamic")
const containersOfSection = board.sections
.filter((section) => section.kind === "container")
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.map(({ layouts, ...section }) => ({ ...section, ...layouts.find((layout) => layout.layoutId === layoutId)! }))
.filter((section) => section.parentSectionId === sectionId);
@@ -14,5 +14,5 @@ export const getSectionElements = (board: Board, { sectionId, layoutId }: { sect
}))
.filter((item) => item.sectionId === sectionId);
return [...items, ...dynamicSectionsOfFirstSection];
return [...items, ...containersOfSection];
};
@@ -1,15 +1,19 @@
import { describe, expect, test, vi } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import * as boardContext from "@homarr/boards/context";
import { createItemCallback } from "../create-item";
import * as emptyPositionModule from "../empty-position";
import { BoardMockBuilder } from "./mocks/board-mock";
import { DynamicSectionMockBuilder } from "./mocks/dynamic-section-mock";
import { ContainerSectionMockBuilder } from "./mocks/container-section-mock";
import { ItemMockBuilder } from "./mocks/item-mock";
import { LayoutMockBuilder } from "./mocks/layout-mock";
describe("item actions create-item", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("clips oversized widgets to each layout's column count", () => {
const board = new BoardMockBuilder()
.addLayout({ id: "mobile", name: "Mobile", role: "mobile", columnCount: 3, breakpoint: 0 })
@@ -66,9 +70,9 @@ describe("item actions create-item", () => {
],
}),
);
expect(emptyPositionSpy).toHaveBeenCalledWith([], layout.columnCount, 9999, { height: 1, width: 1 });
expect(emptyPositionSpy).toHaveBeenCalledWith([], layout.columnCount, undefined, { height: 1, width: 1 });
});
test("should correctly pass dynamic section and items to getFirstEmptyPosition", () => {
test("should correctly pass containers and items to getFirstEmptyPosition", () => {
// Arrange
const itemKind = "clock";
const emptyPosition = { xOffset: 5, yOffset: 5 };
@@ -77,21 +81,21 @@ describe("item actions create-item", () => {
const itemAndSectionPosition = { height: 2, width: 3, yOffset: 2, xOffset: 1 };
const layout = new LayoutMockBuilder({ id: layoutId, columnCount: 4 }).build();
const dynamicSectionInFirstSection = new DynamicSectionMockBuilder({ id: "4" })
const containerInFirstSection = new ContainerSectionMockBuilder({ id: "4" })
.addLayout({ ...itemAndSectionPosition, layoutId, parentSectionId: firstSectionId })
.build();
const itemInFirstSection = new ItemMockBuilder({ id: "12" })
.addLayout({ ...itemAndSectionPosition, layoutId, sectionId: firstSectionId })
.build();
const otherDynamicSection = new DynamicSectionMockBuilder({ id: "5" }).addLayout({ layoutId }).build();
const otherContainer = new ContainerSectionMockBuilder({ id: "5" }).addLayout({ layoutId }).build();
const otherItem = new ItemMockBuilder({ id: "13" }).addLayout({ layoutId }).build();
const board = new BoardMockBuilder()
.addLayout(layout)
.addEmptySection({ id: "1", yOffset: 2 })
.addEmptySection({ id: firstSectionId, yOffset: 0 })
.addEmptySection({ id: "3", yOffset: 1 })
.addSection(dynamicSectionInFirstSection)
.addSection(otherDynamicSection)
.addSection(containerInFirstSection)
.addSection(otherContainer)
.addItem(itemInFirstSection)
.addItem(otherItem)
.build();
@@ -108,8 +112,10 @@ describe("item actions create-item", () => {
// Assert
expect(result.items.length).toBe(3);
const item = result.items.find((item) => item.id !== itemInFirstSection.id && item.id !== otherItem.id);
expect(item).toEqual(
const createdItem = result.items.find(
(candidate) => candidate.id !== itemInFirstSection.id && candidate.id !== otherItem.id,
);
expect(createdItem).toEqual(
expect.objectContaining({
kind: itemKind,
layouts: [{ ...emptyPosition, height: 1, width: 1, sectionId: firstSectionId, layoutId }],
@@ -118,8 +124,35 @@ describe("item actions create-item", () => {
expect(spy).toHaveBeenCalledWith(
[expect.objectContaining(itemAndSectionPosition), expect.objectContaining(itemAndSectionPosition)],
layout.columnCount,
9999,
undefined,
{ height: 1, width: 1 },
);
});
test("clamps wide defaults and places below a full automatic canvas", () => {
const board = new BoardMockBuilder().addEmptySection({ id: "canvas", yOffset: 0 }).build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 1;
board.items.push(
new ItemMockBuilder({ id: "existing" })
.addLayout({ layoutId: layout.id, sectionId: "canvas", width: 1, height: 1 })
.build(),
);
const result = createItemCallback({ id: "created", kind: "mediaMissing" })(board);
const created = result.items.find((item) => item.id === "created");
expect(created?.layouts).toEqual([
expect.objectContaining({
layoutId: layout.id,
sectionId: "canvas",
width: 1,
height: 3,
xOffset: 0,
yOffset: 1,
}),
]);
});
});
@@ -1,4 +1,4 @@
import { describe, expect, test, vi } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import { duplicateItemCallback } from "../duplicate-item";
import * as emptyPositionModule from "../empty-position";
@@ -7,6 +7,10 @@ import { ItemMockBuilder } from "./mocks/item-mock";
import { LayoutMockBuilder } from "./mocks/layout-mock";
describe("item actions duplicate-item", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("should copy it in the same section", () => {
// Arrange
const itemKind = "minecraftServerStatus";
@@ -61,4 +65,28 @@ describe("item actions duplicate-item", () => {
}),
);
});
test("uses the next automatic canvas row when it is the first available space", () => {
const board = new BoardMockBuilder().addEmptySection({ id: "canvas", yOffset: 0 }).build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected a board layout");
layout.id = "layout";
layout.columnCount = 1;
const currentItem = new ItemMockBuilder({ id: "source" })
.addLayout({ layoutId: layout.id, sectionId: "canvas", width: 1, height: 1 })
.build();
board.items.push(currentItem);
const result = duplicateItemCallback({ itemId: currentItem.id })(board);
const duplicated = result.items.find((item) => item.id !== currentItem.id);
expect(duplicated?.layouts[0]).toEqual(
expect.objectContaining({
layoutId: layout.id,
sectionId: "canvas",
xOffset: 0,
yOffset: 1,
}),
);
});
});
@@ -107,7 +107,6 @@ describe("get first empty position", () => {
expect(result).toEqual(expectedX !== undefined ? { xOffset: expectedX, yOffset: expectedY } : undefined);
});
});
const createElementsFromLayout = (layout: string[][]) => {
const elements: (Pick<Item["layouts"][number], "xOffset" | "yOffset" | "width" | "height"> & { char: string })[] = [];
for (let yOffset = 0; yOffset < layout.length; yOffset++) {
@@ -0,0 +1,123 @@
import { describe, expect, test } from "vitest";
import { getMoveTargets } from "../../item-move-modal";
import { BoardMockBuilder } from "./mocks/board-mock";
import { ContainerSectionMockBuilder } from "./mocks/container-section-mock";
import { EmptySectionMockBuilder } from "./mocks/empty-section-mock";
import { ItemMockBuilder } from "./mocks/item-mock";
describe("item move targets", () => {
test("offers the canvas, enabled gutters, and nested sections", () => {
const board = new BoardMockBuilder().build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected the board mock to contain a layout");
layout.id = "layout";
layout.columnCount = 6;
layout.leftGutterColumnCount = 1;
layout.rightGutterColumnCount = 1;
board.sections.push(
new EmptySectionMockBuilder({ id: "canvas", xOffset: 0 }).build(),
new EmptySectionMockBuilder({ id: "left-gutter", xOffset: -1 }).build(),
new EmptySectionMockBuilder({ id: "right-gutter", xOffset: 1 }).build(),
new ContainerSectionMockBuilder({
id: "container",
options: {
title: "",
customCssClasses: [],
borderColor: "",
showLabel: true,
collapsible: false,
showOpenAll: false,
},
})
.addLayout({
layoutId: layout.id,
parentSectionId: "canvas",
width: 2,
height: 2,
})
.build(),
);
const targets = getMoveTargets(
board,
layout.id,
{
id: "weather",
type: "item",
xOffset: 0,
yOffset: 0,
width: 1,
height: 1,
},
{
canvas: "Dashboard canvas",
container: "New section",
leftRail: "Left dashboard rail",
rightRail: "Right dashboard rail",
numbered: (name, index) => `${name}, destination ${index}`,
located: (name, location, index) => `${name}, ${location}, destination ${index}`,
},
);
expect(targets.map((target) => target.label)).toEqual([
"Dashboard canvas, destination 1",
"Left dashboard rail, destination 2",
"Right dashboard rail, destination 3",
"New section, destination 4",
]);
expect(new Set(targets.map((target) => target.label))).toHaveLength(targets.length);
});
test("does not offer canvases that are narrower than a nested section's contents", () => {
const board = new BoardMockBuilder().build();
const layout = board.layouts[0];
if (!layout) throw new Error("Expected the board mock to contain a layout");
layout.id = "layout";
layout.columnCount = 5;
layout.leftGutterColumnCount = 2;
const section = new ContainerSectionMockBuilder({ id: "source" })
.addLayout({
layoutId: layout.id,
parentSectionId: "canvas",
width: 4,
height: 2,
})
.build();
board.sections.push(
new EmptySectionMockBuilder({ id: "canvas" }).build(),
new EmptySectionMockBuilder({ id: "left-gutter", xOffset: -1 }).build(),
section,
);
board.items.push(
new ItemMockBuilder({ id: "nested" })
.addLayout({
layoutId: layout.id,
sectionId: section.id,
xOffset: 2,
width: 2,
})
.build(),
);
const sourceLayout = section.layouts[0];
if (!sourceLayout) throw new Error("Expected the source section to contain a layout");
const targets = getMoveTargets(
board,
layout.id,
{ ...sourceLayout, id: section.id, type: "section" },
{
canvas: "Canvas",
container: "Section",
leftRail: "Left",
rightRail: "Right",
numbered: (name, index) => `${name} ${index}`,
located: (name, location, index) => `${name} ${location} ${index}`,
},
);
expect(targets).toEqual([]);
});
});
@@ -1,7 +1,7 @@
import { createId } from "@homarr/common";
import type { Board, DynamicSection, EmptySection, Item, Section } from "~/app/[locale]/boards/_types";
import { DynamicSectionMockBuilder } from "./dynamic-section-mock";
import type { Board, ContainerSection, EmptySection, Item, Section } from "~/app/[locale]/boards/_types";
import { ContainerSectionMockBuilder } from "./container-section-mock";
import { EmptySectionMockBuilder } from "./empty-section-mock";
import { ItemMockBuilder } from "./item-mock";
import { LayoutMockBuilder } from "./layout-mock";
@@ -45,6 +45,8 @@ export class BoardMockBuilder {
id: createId(),
name: "Base",
columnCount: 12,
leftGutterColumnCount: 0,
rightGutterColumnCount: 0,
breakpoint: 768,
role: "base",
},
@@ -57,8 +59,8 @@ export class BoardMockBuilder {
return this.addSection(new EmptySectionMockBuilder(emptySection).build());
}
public addDynamicSection(dynamicSection?: Partial<DynamicSection>): BoardMockBuilder {
return this.addSection(new DynamicSectionMockBuilder(dynamicSection).build());
public addContainer(container?: Partial<ContainerSection>): BoardMockBuilder {
return this.addSection(new ContainerSectionMockBuilder(container).build());
}
public addSection(section: Section): BoardMockBuilder {
@@ -1,23 +0,0 @@
import { createId } from "@homarr/common";
import type { CategorySection } from "~/app/[locale]/boards/_types";
export class CategorySectionMockBuilder {
private readonly section: CategorySection;
constructor(section?: Partial<CategorySection>) {
this.section = {
id: createId(),
kind: "category",
xOffset: 0,
yOffset: 0,
name: "Category",
collapsed: false,
...section,
} satisfies CategorySection;
}
public build(): CategorySection {
return this.section;
}
}
Loaded 100 of 1155 files, more files were not shown because too many files have changed in this diff. Show more