Simplify Custom JSX v2 authoring

This commit is contained in:
Thomas Camlong committed 2026-07-21 08:19:22 +02:00
1 parent 1faaf29c3b
commit 05dbad8069
177 files changed
+4775 -43426

No files matched your search

@@ -124,7 +124,7 @@ const AddMenu = () => {
return (
<Menu position="bottom-end">
<Menu.Target>
<HeaderButton w="auto" px={4}>
<HeaderButton w="auto" px={4} aria-label={t("item.action.create")}>
<Group gap={4} wrap="nowrap">
<IconPlus stroke={1.5} />
<IconChevronDown color="gray" size={16} />
@@ -163,6 +163,7 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const board = useRequiredBoard();
const utils = clientApi.useUtils();
const t = useScopedI18n("board.action.edit");
const commonT = useI18n();
const { mutate: saveBoard, isPending } = clientApi.board.saveBoard.useMutation({
onSuccess() {
showSuccessNotification({
@@ -199,7 +200,11 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
return (
<OnboardingTour.Target id="board-edit-mode">
<HeaderButton onClick={toggle} loading={isPending}>
<HeaderButton
onClick={toggle}
loading={isPending}
aria-label={isEditMode ? commonT("common.action.save") : commonT("common.action.edit")}
>
{isEditMode ? <IconPencilOff stroke={1.5} /> : <IconPencil stroke={1.5} />}
</HeaderButton>
</OnboardingTour.Target>
@@ -1,145 +1,23 @@
// @vitest-environment jsdom
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { buildCustomWidgetAiPrompt } from "@homarr/custom-widgets/authoring-prompt";
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 { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "@homarr/custom-widgets/authoring-prompt";
import { showSuccessNotification } from "@homarr/notifications";
import { CopyAiPromptButton } from "./_copy-ai-prompt-button";
vi.mock("@homarr/translation/client", () => ({
useScopedI18n: () => (key: string, values?: { count?: number }) =>
values?.count === undefined ? key : `${key}:${values.count}`,
}));
vi.mock("@homarr/notifications", () => ({
showErrorNotification: vi.fn(),
showSuccessNotification: vi.fn(),
}));
let root: Root;
let host: HTMLDivElement;
let writeText: ReturnType<typeof vi.fn>;
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(),
}));
writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(() => root.unmount());
host.remove();
vi.unstubAllGlobals();
vi.clearAllMocks();
});
describe("CopyAiPromptButton", () => {
test("keeps the normal prompt lightweight and the embedded module lazy", async () => {
const source = await readFile(
resolve(process.cwd(), "apps/nextjs/src/app/[locale]/manage/custom-widgets/_copy-ai-prompt-button.tsx"),
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('from "@homarr/custom-widgets/authoring-prompt"');
expect(source).toContain('await import("@homarr/custom-widgets/embedded-authoring-prompt")');
expect(source).not.toMatch(/^import .*@homarr\/custom-widgets\/embedded-authoring-prompt/mu);
await act(async () => {
root.render(
<MantineProvider>
<CopyAiPromptButton request="Create a Pokédex" />
</MantineProvider>,
);
});
const copyButton = [...host.querySelectorAll<HTMLButtonElement>("button")].find(
(button) => button.textContent === "action.copyAiPrompt",
);
expect(copyButton).toBeDefined();
await act(async () => copyButton?.click());
await vi.waitFor(() => expect(writeText).toHaveBeenCalledOnce());
const prompt = writeText.mock.calls[0]?.[0] as string;
expect(prompt.length).toBeLessThanOrEqual(8_000);
expect(prompt).not.toContain("--- BEGIN SKILL FILE:");
expect(showSuccessNotification).toHaveBeenCalledWith({
title: "action.copyAiPrompt",
message: `notification.aiPromptCopiedWithCount:${prompt.length}`,
});
expect(source).toContain("buildCustomWidgetAiPrompt");
expect(source).not.toContain("embedded-authoring-prompt");
expect(source).not.toContain("Menu");
});
test("copies the complete embedded skill and reports its exact character count", async () => {
await act(async () => {
root.render(
<MantineProvider>
<CopyAiPromptButton request="Create a Pokédex" />
</MantineProvider>,
);
});
const menuTarget = host.querySelector<HTMLButtonElement>('[aria-label="action.copyAiPromptWithSkill"]');
expect(menuTarget).not.toBeNull();
await act(async () => {
menuTarget?.click();
await new Promise((resolve) => window.setTimeout(resolve, 20));
});
const embeddedSkillItem = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((element) =>
element.textContent?.includes("action.copyAiPromptWithSkill"),
);
expect(embeddedSkillItem).toBeDefined();
await act(async () => embeddedSkillItem?.click());
await vi.waitFor(() => expect(writeText).toHaveBeenCalledOnce());
const prompt = writeText.mock.calls[0]?.[0] as string;
expect(prompt.startsWith("Please create this Homarr Custom JSX v2 widget:\n\nCreate a Pokédex")).toBe(true);
expect(prompt).toContain("# Homarr Custom Widget offline authoring bundle");
expect(prompt).toContain("--- BEGIN SKILL FILE: SKILL.md ---");
expect(prompt).toContain("--- BEGIN SKILL FILE: references/widget-schema.json ---");
expect(prompt).toContain("--- BEGIN CANONICAL COMPONENT CATALOG ---");
expect(prompt).toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
expect(prompt.length).toBeGreaterThan(500_000);
expect(prompt.length).toBeLessThanOrEqual(1_700_000);
expect(prompt.endsWith(`${CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL}\nCharacters: ${prompt.length}`)).toBe(true);
expect(showSuccessNotification).toHaveBeenCalledWith({
title: "action.copyAiPrompt",
message: `notification.aiPromptCopiedWithCount:${prompt.length}`,
});
});
test("places the AI authoring card before General information", async () => {
const source = await readFile(
resolve(process.cwd(), "apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form.tsx"),
"utf8",
);
expect(source.indexOf("<CustomWidgetAiCard")).toBeLessThan(source.indexOf('<EditorSection id="general"'));
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("one complete `jsx` fenced block");
});
});
@@ -1,7 +1,7 @@
"use client";
import { Button, Menu } from "@mantine/core";
import { IconChevronDown, IconFileText, IconSparkles } from "@tabler/icons-react";
import { Button } from "@mantine/core";
import { IconSparkles } from "@tabler/icons-react";
import { buildCustomWidgetAiPrompt } from "@homarr/custom-widgets/authoring-prompt";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
@@ -22,20 +22,9 @@ export const CopyAiPromptButton = ({
}: CopyAiPromptButtonProps) => {
const t = useScopedI18n("customWidget");
const handleCopy = async (includeSkill = false) => {
const handleCopy = async () => {
try {
const prompt = includeSkill
? await import("@homarr/custom-widgets/embedded-authoring-prompt").then(
({ buildCustomWidgetAiPromptWithEmbeddedSkill }) =>
buildCustomWidgetAiPromptWithEmbeddedSkill(
undefined,
rawResponse,
currentConfig,
request,
documentationUrl,
),
)
: buildCustomWidgetAiPrompt(undefined, rawResponse, currentConfig, request, documentationUrl);
const prompt = buildCustomWidgetAiPrompt(undefined, rawResponse, currentConfig, request, documentationUrl);
await navigator.clipboard.writeText(prompt);
showSuccessNotification({
title: t("action.copyAiPrompt"),
@@ -47,32 +36,15 @@ export const CopyAiPromptButton = ({
};
return (
<Button.Group w="100%">
<Button
type="button"
variant="light"
leftSection={<IconSparkles size={16} />}
onClick={() => void handleCopy()}
fullWidth
size="sm"
>
{t("action.copyAiPrompt")}
</Button>
<Menu position="bottom-end" withinPortal={false}>
<Menu.Target>
<Button type="button" variant="light" px="xs" aria-label={t("action.copyAiPromptWithSkill")}>
<IconChevronDown size={16} />
</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item leftSection={<IconSparkles size={16} />} onClick={() => void handleCopy()}>
{t("action.copyAiPrompt")}
</Menu.Item>
<Menu.Item leftSection={<IconFileText size={16} />} onClick={() => void handleCopy(true)}>
{t("action.copyAiPromptWithSkill")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
</Button.Group>
<Button
type="button"
variant="light"
leftSection={<IconSparkles size={16} />}
onClick={() => void handleCopy()}
fullWidth
size="sm"
>
{t("action.copyAiPrompt")}
</Button>
);
};
@@ -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>
);
}
@@ -3,8 +3,8 @@ import type { CustomWidgetFormValues, EditorDiagnostic } from "@homarr/custom-wi
import { isRecord, parseJson, parseSources } from "./_custom-widget-form-utils";
export function createCustomWidgetCompletions(values: CustomWidgetFormValues, requestIds: string[]) {
const schema = parseJson(values.optionsSchema);
const optionKeys = Object.keys(isRecord(schema) && isRecord(schema.properties) ? schema.properties : {});
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}` },
@@ -28,7 +28,7 @@ export function getInvalidCustomWidgetSections(
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 (["optionsSchema", "defaultOptions"].includes(field)) result.add("options");
else if (field === "options") result.add("options");
else if (field === "template") result.add("jsx");
}
if (requestDiagnostics.some((entry) => entry.severity === "error")) result.add("requests");
@@ -54,7 +54,7 @@ export function SaveActions({
}) {
const t = useScopedI18n("customWidget.workbench");
return (
<Group justify="space-between" wrap="nowrap">
<Group justify="space-between" wrap="wrap">
<Group gap="xs">
{invalid ? (
<IconAlertTriangle size={16} color="var(--mantine-color-red-6)" />
@@ -62,10 +62,10 @@ export function SaveActions({
<IconCheck size={16} color="var(--mantine-color-green-6)" />
)}
<Text size="sm" fw={600}>
{dirty ? t("status.unsaved") : invalid ? t("status.invalid") : t("status.ready")}
{invalid ? t("status.invalid") : dirty ? t("status.unsaved") : t("status.ready")}
</Text>
</Group>
<Group gap="xs" wrap="nowrap">
<Group gap="xs" wrap="wrap">
<Button
type="button"
variant="light"
@@ -1,7 +1,6 @@
import {
CUSTOM_WIDGET_OPTIONS_EXAMPLES,
CUSTOM_WIDGET_REQUEST_EXAMPLES,
getCustomWidgetDefaultOptionsJsonSchema,
getCustomWidgetOptionsJsonSchema,
getCustomWidgetRequestsJsonSchema,
} from "@homarr/custom-widgets/core";
@@ -14,12 +13,6 @@ export const customWidgetRequestReference = {
export const customWidgetOptionsSchemaReference = {
schema: getCustomWidgetOptionsJsonSchema(),
minimal: CUSTOM_WIDGET_OPTIONS_EXAMPLES.minimal.schema,
full: CUSTOM_WIDGET_OPTIONS_EXAMPLES.full.schema,
};
export const customWidgetDefaultOptionsReference = {
schema: getCustomWidgetDefaultOptionsJsonSchema(),
minimal: CUSTOM_WIDGET_OPTIONS_EXAMPLES.minimal.defaults,
full: CUSTOM_WIDGET_OPTIONS_EXAMPLES.full.defaults,
minimal: CUSTOM_WIDGET_OPTIONS_EXAMPLES.minimal,
full: CUSTOM_WIDGET_OPTIONS_EXAMPLES.full,
};
@@ -1,80 +1,59 @@
import { describe, expect, it, vi } from "vitest";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import { getChangedSecrets, getCustomWidgetPreviewOptionIssues, loadPreviewQueries } from "./_custom-widget-form-utils";
import {
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 } } } }));
vi.mock("@homarr/api/client", () => ({
fetchApi: { customWidget: { previewQuery: { query: previewQuery } } },
}));
const definition: HomarrCustomWidgetV2 = {
const definition = customWidgetDefinitionSchema.parse({
$schema: "homarr-custom-widget-v2",
name: "Preview options",
sources: [
{
id: "default",
name: "API",
baseUrl: "https://example.com",
networkScope: "public",
auth: { type: "none" },
},
],
requests: [
{
id: "containers",
sourceId: "default",
kind: "query",
method: "GET",
pathTemplate: "/endpoints/{endpointId}/containers",
parameters: { endpointId: "number" },
optionsBinding: { endpointId: { $option: "environmentId" } },
auth: "inherit",
minimumBoardPermission: "view",
trigger: "load",
},
],
optionsSchema: {
type: "object",
properties: { environmentId: { type: "number" } },
required: ["environmentId"],
additionalProperties: false,
},
defaultOptions: { environmentId: 1 },
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("passes the selected options to load-query bindings without replacing them with defaults", async () => {
previewQuery.mockResolvedValueOnce({ ok: true, status: 200, data: [] });
await loadPreviewQueries(definition, "preview-1", { environmentId: 7 });
expect(previewQuery).toHaveBeenCalledWith({
sessionId: "preview-1",
requestId: "containers",
params: { endpointId: 7 },
});
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("rejects invalid selected options before creating a preview session", () => {
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 number" },
{ path: "configuration.environmentId", message: "Expected a number" },
]);
});
it("normalizes only changed secrets for save and preview", () => {
it("normalizes only changed secrets", () => {
expect(
getChangedSecrets({
name: "Widget",
description: "",
iconUrl: "",
sources: "[]",
requests: "[]",
optionsSchema: "{}",
defaultOptions: "{}",
sources: "{}",
requests: "{}",
options: "{}",
template: "<Text />",
secrets: [
{ sourceId: "default", kind: "apiKey", value: "", hasValue: true },
@@ -1,7 +1,7 @@
import { fetchApi } from "@homarr/api/client";
import {
customWidgetDefinitionSchema,
resolveCustomWidgetOptionsBinding,
getCustomWidgetDefaultOptions,
validateCustomWidgetOptions,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetSource, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
@@ -18,8 +18,7 @@ export function buildDefinition(values: CustomWidgetFormValues) {
iconUrl: values.iconUrl || undefined,
sources: parseJson(values.sources),
requests: parseJson(values.requests),
optionsSchema: parseJson(values.optionsSchema),
defaultOptions: parseJson(values.defaultOptions),
options: parseJson(values.options),
template: values.template,
});
}
@@ -42,24 +41,20 @@ export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrC
iconUrl: widget.iconUrl ?? "",
sources: JSON.stringify(widget.sources, null, 2),
requests: JSON.stringify(widget.requests, null, 2),
optionsSchema: JSON.stringify(widget.optionsSchema, null, 2),
defaultOptions: JSON.stringify(widget.defaultOptions, null, 2),
options: JSON.stringify(widget.options, null, 2),
template: widget.template,
});
}
export function parseSources(value: string): CustomWidgetSource[] {
export function parseSources(value: string): Array<CustomWidgetSource & { id: string }> {
const parsed = parseJson(value);
return Array.isArray(parsed)
? parsed.filter((entry): entry is CustomWidgetSource => isRecord(entry) && typeof entry.id === "string")
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 parseJsonArray(value: string): unknown[] {
const parsed = parseJson(value);
return Array.isArray(parsed) ? parsed : [];
}
export function parseJson(value: string): unknown {
try {
return JSON.parse(value) as unknown;
@@ -73,33 +68,35 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
}
export function getCustomWidgetPreviewOptionIssues(definition: HomarrCustomWidgetV2, options: Record<string, unknown>) {
return validateCustomWidgetOptions(definition.optionsSchema, options);
return validateCustomWidgetOptions(definition.options, options);
}
export function isRuntimeParams(
value: unknown,
schema: Record<string, "string" | "number" | "boolean">,
expectedNames: readonly string[],
): value is Record<string, string | number | boolean> {
if (!isRecord(value)) return false;
return Object.entries(schema).every(([name, type]) => typeof value[name] === type);
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,
options: Record<string, unknown>,
) {
export async function loadPreviewQueries(definition: HomarrCustomWidgetV2, sessionId: string) {
const data: Record<string, unknown> = {};
const status: Record<string, unknown> = {};
for (const request of definition.requests.filter((entry) => entry.kind === "query" && entry.trigger === "load")) {
for (const [requestId] of Object.entries(definition.requests).filter(
([, entry]) => entry.kind === "query" && entry.trigger === "load",
)) {
try {
const params = resolveCustomWidgetOptionsBinding(request, options);
const result = await fetchApi.customWidget.previewQuery.query({ sessionId, requestId: request.id, params });
data[request.id] = result.data;
status[request.id] = { loading: false, ...result };
const result = await fetchApi.customWidget.previewQuery.query({ sessionId, requestId, params: {} });
data[requestId] = result.data;
status[requestId] = { loading: false, ...result };
} catch (error) {
data[request.id] = null;
status[request.id] = {
data[requestId] = null;
status[requestId] = {
loading: false,
ok: false,
error: error instanceof Error ? error.message : "Request failed",
@@ -108,3 +105,7 @@ export async function loadPreviewQueries(
}
return { data, status };
}
export function getDefinitionDefaults(definition: HomarrCustomWidgetV2) {
return getCustomWidgetDefaultOptions(definition.options);
}
@@ -45,6 +45,10 @@
}
@media (max-width: 74.9375em) {
.sectionNav {
top: 3.5rem;
}
.workbench[data-mobile-pane="configure"] .previewPane,
.workbench[data-mobile-pane="preview"] .configuration {
display: none;
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Box, Button, Paper, SegmentedControl, Stack, TextInput, Textarea } from "@mantine/core";
import { Accordion, Box, Button, Paper, SegmentedControl, Stack, TextInput, Textarea } from "@mantine/core";
import {
IconAlertCircle,
IconApi,
@@ -17,8 +17,8 @@ import {
analyzeRequestManifest,
customWidgetFormSchema,
DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
renameCustomWidgetRequest,
} from "@homarr/custom-widgets/workbench";
import { customWidgetOptionsSchema, getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { useZodForm } from "@homarr/form";
import { IconPicker } from "@homarr/forms-collection";
@@ -26,17 +26,16 @@ import { useScopedI18n } from "@homarr/translation/client";
import { CodeEditor } from "./_code-editor";
import { CustomWidgetAiCard } from "./_custom-widget-ai-card";
import { CustomWidgetAdvancedManifest } from "./_custom-widget-advanced-manifest";
import { createCustomWidgetCompletions, getInvalidCustomWidgetSections } from "./_custom-widget-form-analysis";
import { EditorSection, SaveActions } from "./_custom-widget-form-layout";
import {
customWidgetDefaultOptionsReference,
customWidgetOptionsSchemaReference,
customWidgetRequestReference,
} from "./_custom-widget-form-references";
import { applyDefinition, buildDefinition, isRecord, parseJsonArray } from "./_custom-widget-form-utils";
import { customWidgetOptionsSchemaReference, customWidgetRequestReference } from "./_custom-widget-form-references";
import { buildDefinition, getDefinitionDefaults, isRecord, parseJson } from "./_custom-widget-form-utils";
import { CustomWidgetOptionsEditor } from "./_custom-widget-options-editor";
import { CustomWidgetPreviewPanel } from "./_custom-widget-preview-panel";
import type { PreviewState } from "./_custom-widget-preview-panel";
import { CustomWidgetRequestTools } from "./_custom-widget-request-tools";
import { CustomWidgetRequestsEditor } from "./_custom-widget-requests-editor";
import { createCustomWidgetRenameHandlers } from "./_custom-widget-rename-handlers";
import { CustomWidgetSaveIssuesAlert } from "./_custom-widget-save-issues-alert";
import { CustomWidgetSourcesEditor } from "./_custom-widget-sources-editor";
import { useCustomWidgetFormActions } from "./_use-custom-widget-form-actions";
@@ -70,17 +69,20 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
const [previewTheme, setPreviewTheme] = useState<"light" | "dark">("dark");
const [optionsSnapshot, setOptionsSnapshot] = useState<Record<string, unknown>>(() => {
const initialDefinition = buildDefinition(formInitialValues);
return initialDefinition.success ? initialDefinition.data.defaultOptions : {};
return initialDefinition.success ? getDefinitionDefaults(initialDefinition.data) : {};
});
const [revealedRequest, setRevealedRequest] = useState({ text: "", key: 0 });
const dirtyRef = useRef(false);
dirtyRef.current = form.isDirty();
const candidate = useMemo(() => buildDefinition(form.values), [form.values]);
const parsedOptions = useMemo(
() => customWidgetOptionsSchema.safeParse(parseJson(form.values.options)),
[form.values.options],
);
const requestIds = useMemo(
() =>
parseJsonArray(form.values.requests).flatMap((entry) =>
isRecord(entry) && typeof entry.id === "string" ? [entry.id] : [],
Object.keys(
isRecord(parseJson(form.values.requests)) ? (parseJson(form.values.requests) as Record<string, unknown>) : {},
),
[form.values.requests],
);
@@ -122,16 +124,16 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
window.addEventListener("beforeunload", beforeUnload);
return () => window.removeEventListener("beforeunload", beforeUnload);
}, []);
useEffect(() => {
if (parsedOptions.success) setOptionsSnapshot(getCustomWidgetDefaultOptions(parsedOptions.data));
}, [parsedOptions]);
const invalid = hasDiagnostics || !candidate.success;
const renameRequest = (currentId: string, nextId: string) => {
if (!candidate.success) throw new Error(w("invalidWidget"));
applyDefinition(form, renameCustomWidgetRequest(candidate.data, currentId, nextId));
setRevealedRequest((current) => ({ text: `"id": "${nextId}"`, key: current.key + 1 }));
};
const revealRequest = (requestId: string) => {
setRevealedRequest((current) => ({ text: `"id": "${requestId}"`, key: current.key + 1 }));
};
const { renameRequest, renameOption } = createCustomWidgetRenameHandlers({
form,
candidate,
invalidWidgetMessage: w("invalidWidget"),
});
return (
<form onSubmit={save} className={classes.form}>
<SegmentedControl
@@ -173,6 +175,7 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
onDocumentationUrlChange={setDocumentationUrl}
onPaste={() => void pasteAiResponse()}
/>
<CustomWidgetAdvancedManifest form={form} />
<EditorSection id="general" title={w("generalInformation")} icon={IconSettings}>
<TextInput label={t("field.name")} required {...form.getInputProps("name")} />
<Textarea label={t("field.description")} autosize minRows={2} {...form.getInputProps("description")} />
@@ -182,41 +185,45 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
<CustomWidgetSourcesEditor form={form} definitionId={definitionId} />
</EditorSection>
<EditorSection id="requests" title={w("requests.title")} icon={IconDatabase}>
<CustomWidgetRequestTools requestIds={requestIds} onGoTo={revealRequest} onRename={renameRequest} />
<CodeEditor
id="requests-editor"
label={w("requests.label")}
description={w("requests.description")}
language="json"
value={form.values.requests}
onChange={(value) => form.setFieldValue("requests", value)}
diagnostics={requestDiagnostics}
error={form.errors.requests}
revealText={revealedRequest.text}
revealKey={revealedRequest.key}
reference={customWidgetRequestReference}
required
/>
<CustomWidgetRequestsEditor form={form} onRename={renameRequest} />
<Accordion variant="contained">
<Accordion.Item value="raw">
<Accordion.Control>{w("builder.advancedJson")}</Accordion.Control>
<Accordion.Panel>
<CodeEditor
id="requests-editor"
label={w("requests.label")}
description={w("requests.description")}
language="json"
value={form.values.requests}
onChange={(value) => form.setFieldValue("requests", value)}
diagnostics={requestDiagnostics}
error={form.errors.requests}
reference={customWidgetRequestReference}
required
/>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</EditorSection>
<EditorSection id="options" title={w("options.title")} icon={IconBraces}>
<CodeEditor
id="options-schema"
label={w("options.schema")}
language="json"
value={form.values.optionsSchema}
onChange={(value) => form.setFieldValue("optionsSchema", value)}
error={form.errors.optionsSchema}
reference={customWidgetOptionsSchemaReference}
/>
<CodeEditor
id="default-options"
label={w("options.defaults")}
language="json"
value={form.values.defaultOptions}
onChange={(value) => form.setFieldValue("defaultOptions", value)}
error={form.errors.defaultOptions}
reference={customWidgetDefaultOptionsReference}
/>
<CustomWidgetOptionsEditor form={form} onRename={renameOption} />
<Accordion variant="contained">
<Accordion.Item value="raw">
<Accordion.Control>{w("builder.advancedJson")}</Accordion.Control>
<Accordion.Panel>
<CodeEditor
id="options"
label={w("options.title")}
language="json"
value={form.values.options}
onChange={(value) => form.setFieldValue("options", value)}
error={form.errors.options}
reference={customWidgetOptionsSchemaReference}
/>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</EditorSection>
<EditorSection id="jsx" title={w("jsx.title")} icon={IconCode}>
<CodeEditor
@@ -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);
}
}}
/>
);
}
@@ -50,7 +50,8 @@ function CustomWidgetCard({ widget }: { widget: WidgetDef }) {
toggleMutation.mutate(
{ id: widget.id, enabled: !widget.enabled },
{
onSuccess: () => {
onSuccess: async () => {
await utils.widget.customApi.getData.cancel();
void utils.customWidget.list.invalidate();
void utils.widget.customApi.getData.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets");
@@ -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>
);
}
@@ -4,7 +4,8 @@ import { useState } from "react";
import { Button, Fieldset, Stack, Textarea } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
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";
@@ -15,31 +16,28 @@ export function PreviewActionControl({
request,
sessionId,
}: {
request: HomarrCustomWidgetV2["requests"][number];
request: CustomJsxRequest & { id: string };
sessionId?: string;
}) {
const t = useScopedI18n("customWidget.workbench.preview");
const { openConfirmModal } = useConfirmModal();
const actionMutation = clientApi.customWidget.previewAction.useMutation();
const initialParams = Object.fromEntries(
Object.entries(request.parameters).map(([name, type]) => [
name,
type === "number" ? 0 : type === "boolean" ? false : "",
]),
);
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, request.parameters) ? parsed : null;
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: request.confirmation?.title ?? request.id,
children: request.confirmation?.message ?? t("deleteConfirmation"),
labels: { confirm: request.confirmation?.confirmLabel },
confirmProps: { color: request.confirmation?.destructive || request.method === "DELETE" ? "red.9" : "blue" },
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),
});
@@ -61,7 +59,7 @@ export function PreviewActionControl({
return (
<Fieldset legend={`${request.id} · ${request.method}`}>
<Stack gap="xs">
{Object.keys(request.parameters).length > 0 && (
{expectedParams.length > 0 && (
<Textarea
label={t("actionParameters")}
autosize
@@ -74,13 +72,13 @@ export function PreviewActionControl({
<Button
type="button"
variant="light"
color={request.confirmation?.destructive || request.method === "DELETE" ? "red" : undefined}
color={confirmation?.destructive || request.method === "DELETE" ? "red" : undefined}
disabled={!sessionId || !validParams}
loading={actionMutation.isPending}
onClick={() => void run()}
>
{request.confirmation?.confirmLabel ??
(request.confirmation?.destructive || request.method === "DELETE" ? t("runDestructive") : t("runAction"))}
{confirmation?.confirmLabel ??
(confirmation?.destructive || request.method === "DELETE" ? t("runDestructive") : t("runAction"))}
</Button>
</Stack>
</Fieldset>
@@ -20,32 +20,29 @@ export function createPreviewDisplayData({
fixtureError: string;
}): Record<string, unknown> | null {
if (!candidate) return null;
const data =
fixture === "empty" ? Object.fromEntries(candidate.requests.map((entry) => [entry.id, []])) : preview.data;
const requests = Object.entries(candidate.requests);
const data = fixture === "empty" ? Object.fromEntries(requests.map(([id]) => [id, []])) : preview.data;
const status =
fixture === "loading"
? Object.fromEntries(candidate.requests.map((entry) => [entry.id, { loading: true }]))
? Object.fromEntries(requests.map(([id]) => [id, { loading: true }]))
: fixture === "error"
? Object.fromEntries(
candidate.requests.map((entry) => [entry.id, { loading: false, ok: false, error: fixtureError }]),
)
? Object.fromEntries(requests.map(([id]) => [id, { loading: false, ok: false, error: fixtureError }]))
: preview.status;
return {
template: candidate.template,
data,
status,
options,
requestCapabilities: candidate.requests.map(
({ id, kind, method, trigger, minimumBoardPermission, confirmation, invalidates }) => ({
id,
kind,
method,
trigger,
minimumBoardPermission,
confirmation,
invalidates,
}),
),
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",
@@ -6,7 +6,7 @@ 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 } from "@homarr/custom-widgets/core";
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import { CustomWidgetPreviewPanel } from "./_custom-widget-preview-panel";
@@ -131,7 +131,7 @@ describe("Custom Widget preview panel", () => {
rendererAttempt.mockClear();
const bundledWidget = BUNDLED_CUSTOM_WIDGETS.at(0);
if (!bundledWidget) throw new Error("Expected at least one bundled Custom Widget");
const candidate = bundledWidget.widget;
const candidate = customWidgetDefinitionSchema.parse(bundledWidget.widget);
const preview = { data: {}, status: {}, session: null, outcome: "idle" } as const;
const failingOptions = { throwPreview: true };
@@ -141,7 +141,9 @@ describe("Custom Widget preview panel", () => {
<CustomWidgetPreviewPanel
candidate={{
...candidate,
requests: candidate.requests.map((request) => ({ ...request })),
requests: Object.fromEntries(
Object.entries(candidate.requests).map(([id, request]) => [id, { ...request }]),
),
}}
validationIssues={[]}
preview={preview}
@@ -207,12 +207,12 @@ export function CustomWidgetPreviewPanel(props: PreviewPanelProps) {
);
}}
/>
{candidate?.requests
.filter((request) => request.kind === "action")
.map((request) => (
<PreviewActionControl key={request.id} request={request} sessionId={props.preview.session?.id} />
{Object.entries(candidate?.requests ?? {})
.filter(([, request]) => request.kind === "action")
.map(([id, request]) => (
<PreviewActionControl key={id} request={{ id, ...request }} sessionId={props.preview.session?.id} />
))}
{candidate?.requests.every((request) => request.kind !== "action") && (
{Object.values(candidate?.requests ?? {}).every((request) => request.kind !== "action") && (
<Text size="sm" c="dimmed">
{t("noActions")}
</Text>
@@ -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 };
}
@@ -1,75 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { Button, Group, Select, TextInput } from "@mantine/core";
import { IconEdit, IconTargetArrow } from "@tabler/icons-react";
import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
export function CustomWidgetRequestTools({
requestIds,
onGoTo,
onRename,
}: {
requestIds: string[];
onGoTo(requestId: string): void;
onRename(currentId: string, nextId: string): void;
}) {
const t = useScopedI18n("customWidget.workbench.requests");
const [selected, setSelected] = useState(requestIds[0] ?? "");
const [nextId, setNextId] = useState(requestIds[0] ?? "");
useEffect(() => {
if (!requestIds.includes(selected)) {
setSelected(requestIds[0] ?? "");
setNextId(requestIds[0] ?? "");
}
}, [requestIds, selected]);
if (requestIds.length === 0) return null;
const rename = () => {
try {
onRename(selected, nextId);
setSelected(nextId);
} catch (error) {
showErrorNotification({
title: t("rename"),
message: error instanceof Error ? error.message : t("renameFailed"),
});
}
};
return (
<Group align="end" grow wrap="wrap">
<Select
label={t("selected")}
data={requestIds}
value={selected}
onChange={(value) => {
setSelected(value ?? "");
setNextId(value ?? "");
}}
searchable
/>
<Button
type="button"
variant="light"
leftSection={<IconTargetArrow size={16} />}
onClick={() => onGoTo(selected)}
>
{t("goTo")}
</Button>
<TextInput label={t("newId")} value={nextId} onChange={(event) => setNextId(event.currentTarget.value)} />
<Button
type="button"
variant="light"
leftSection={<IconEdit size={16} />}
disabled={!nextId || nextId === selected}
onClick={rename}
>
{t("rename")}
</Button>
</Group>
);
}
@@ -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>
);
}
@@ -45,13 +45,13 @@ describe("extractCustomWidgetSaveIssues", () => {
{
code: "custom",
message: "A load parameter requires an explicit binding.",
path: ["requests", 0, "optionsBinding", "endpointId"],
path: ["requests", "containers", "path"],
},
]);
expect(extractCustomWidgetSaveIssues({ message })).toEqual([
{
path: "requests.0.optionsBinding.endpointId",
path: "requests.containers.path",
message: "A load parameter requires an explicit binding.",
},
]);
@@ -9,8 +9,9 @@ import type { CustomWidgetSource, CustomWidgetSourceUrlIssue } from "@homarr/cus
import { showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { isRecord, parseJsonArray, parseSources } from "./_custom-widget-form-utils";
import { isRecord, parseJson, parseSources } from "./_custom-widget-form-utils";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
const secretFields: Record<string, Array<{ kind: "apiKey" | "username" | "password" }>> = {
bearer: [{ kind: "apiKey" }],
@@ -37,21 +38,38 @@ export function CustomWidgetSourcesEditor({
const utils = clientApi.useUtils();
const clearSecretMutation = clientApi.customWidget.secretClear.useMutation();
const sources = parseSources(form.values.sources);
const update = (index: number, changes: Partial<CustomWidgetSource>) => {
const update = (index: number, changes: Partial<CustomWidgetSource> & { id?: string }) => {
const previousId = sources[index]?.id;
const nextId = changes.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(
sources.map((source, i) => (i === index ? { ...source, ...changes } : source)),
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 requests = parseJsonArray(form.values.requests).map((request) =>
isRecord(request) && request.sourceId === previousId ? { ...request, sourceId: nextId } : request,
);
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",
@@ -63,11 +81,7 @@ export function CustomWidgetSourcesEditor({
};
const setAuth = (index: number, type: string) => {
const auth =
type === "apiKeyHeader"
? { type, headerName: "X-API-Key" }
: type === "apiKeyQuery"
? { type, parameterName: "api_key" }
: { type };
type === "apiKeyHeader" ? { type, name: "X-API-Key" } : type === "apiKeyQuery" ? { type, name: "api_key" } : type;
update(index, { auth: auth as CustomWidgetSource["auth"] });
};
const setSecret = (sourceId: string, kind: string, value: string) => {
@@ -76,20 +90,22 @@ export function CustomWidgetSourcesEditor({
form.setFieldValue("secrets", [...current, { sourceId, kind, value, hasValue: existing?.hasValue }]);
};
const addSource = () => {
const id = `source-${sources.length + 1}`;
const id = sources.length === 0 ? "default" : `source-${sources.length + 1}`;
form.setFieldValue(
"sources",
JSON.stringify(
[
...sources,
{
Object.fromEntries([
...sources.map(({ id: sourceId, ...source }) => [sourceId, source] as const),
[
id,
name: t("newName", { count: sources.length + 1 }),
baseUrl: "https://example.com",
networkScope: "private",
auth: { type: "none" },
},
],
{
name: t("newName", { count: sources.length + 1 }),
baseUrl: "https://example.com",
networkScope: sources.length === 0 ? "public" : "private",
auth: "none",
},
],
]),
null,
2,
),
@@ -100,7 +116,7 @@ export function CustomWidgetSourcesEditor({
form.setFieldValue(
"sources",
JSON.stringify(
sources.filter((_, i) => i !== index),
Object.fromEntries(sources.filter((_, i) => i !== index).map(({ id, ...source }) => [id, source])),
null,
2,
),
@@ -109,7 +125,13 @@ export function CustomWidgetSourcesEditor({
form.setFieldValue(
"requests",
JSON.stringify(
parseJsonArray(form.values.requests).filter((request) => !isRecord(request) || request.sourceId !== removedId),
Object.fromEntries(
Object.entries(
isRecord(parseJson(form.values.requests))
? (parseJson(form.values.requests) as Record<string, unknown>)
: {},
).filter(([, request]) => !isRecord(request) || request.source !== removedId),
),
null,
2,
),
@@ -136,11 +158,12 @@ export function CustomWidgetSourcesEditor({
<Fieldset key={index} legend={index === 0 ? t("primary") : source.name}>
<Stack gap="sm">
<Group grow align="start">
<TextInput
<CustomWidgetIdentifierInput
label={t("id")}
value={source.id}
disabled={Boolean(definitionId)}
onChange={(event) => update(index, { id: event.currentTarget.value })}
disabled={source.id === "default" || Boolean(definitionId)}
error={form.errors.sources}
onCommit={(value) => update(index, { id: value })}
/>
<TextInput
label={t("name")}
@@ -168,30 +191,30 @@ export function CustomWidgetSourcesEditor({
<Select
label={t("authentication")}
data={["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery"]}
value={source.auth.type}
value={typeof source.auth === "string" ? source.auth : source.auth.type}
onChange={(value) => setAuth(index, value ?? "none")}
allowDeselect={false}
/>
</Group>
{source.auth.type === "apiKeyHeader" && (
{typeof source.auth === "object" && source.auth.type === "apiKeyHeader" && (
<TextInput
label={t("headerName")}
value={source.auth.headerName}
value={source.auth.name}
onChange={(event) =>
update(index, { auth: { type: "apiKeyHeader", headerName: event.currentTarget.value } })
update(index, { auth: { type: "apiKeyHeader", name: event.currentTarget.value } })
}
/>
)}
{source.auth.type === "apiKeyQuery" && (
{typeof source.auth === "object" && source.auth.type === "apiKeyQuery" && (
<TextInput
label={t("queryParameter")}
value={source.auth.parameterName}
value={source.auth.name}
onChange={(event) =>
update(index, { auth: { type: "apiKeyQuery", parameterName: event.currentTarget.value } })
update(index, { auth: { type: "apiKeyQuery", name: event.currentTarget.value } })
}
/>
)}
{(secretFields[source.auth.type] ?? []).map((field) => {
{(secretFields[typeof source.auth === "string" ? source.auth : source.auth.type] ?? []).map((field) => {
const secret = form.values.secrets.find(
(entry) => entry.sourceId === source.id && entry.kind === field.kind,
);
@@ -19,6 +19,7 @@ import {
applyDefinition,
buildDefinition,
getChangedSecrets,
getDefinitionDefaults,
getCustomWidgetPreviewOptionIssues,
isRecord,
loadPreviewQueries,
@@ -132,7 +133,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
options: input.optionsSnapshot,
secrets: getChangedSecrets(input.form.values),
});
const snapshot = await loadPreviewQueries(input.candidate.data, created.previewSession.id, input.optionsSnapshot);
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,
@@ -171,7 +172,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
throw new Error(formatCustomWidgetImportIssues(result.issues));
}
applyDefinition(input.form, customWidgetDefinitionSchema.parse(result.widget));
input.setOptionsSnapshot(result.widget.defaultOptions);
input.setOptionsSnapshot(getDefinitionDefaults(result.widget));
input.setPreview({ data: {}, status: {}, session: null, outcome: "idle" });
showSuccessNotification({
title: w("ai.response"),
@@ -38,8 +38,7 @@ export default async function EditCustomWidgetPage(props: EditCustomWidgetPagePr
iconUrl: definition.iconUrl ?? "",
sources: JSON.stringify(definition.sources, null, 2),
requests: JSON.stringify(definition.requests, null, 2),
optionsSchema: JSON.stringify(definition.optionsSchema, null, 2),
defaultOptions: JSON.stringify(definition.defaultOptions, null, 2),
options: JSON.stringify(definition.options, null, 2),
template: definition.template,
secrets: definition.secrets.map((secret) => ({
sourceId: secret.sourceId,
@@ -3,7 +3,6 @@ import { Badge, Box, Container, Group, Paper, Stack, Text, Title } from "@mantin
import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import { resolveCustomWidgetOptionsBinding } from "@homarr/custom-widgets/core";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
export default async function CustomWidgetPreviewPage({ params }: { params: Promise<{ id: string }> }) {
@@ -16,11 +15,8 @@ export default async function CustomWidgetPreviewPage({ params }: { params: Prom
const loadRequests = preview.requests.filter((request) => request.kind === "query" && request.trigger === "load");
const results = await Promise.all(
loadRequests.map(async (request) => {
const result = await Promise.resolve()
.then(() => resolveCustomWidgetOptionsBinding(request, preview.options))
.then((requestParams) =>
api.customWidget.previewQuery({ sessionId: id, requestId: request.id, params: requestParams }),
)
const result = await api.customWidget
.previewQuery({ sessionId: id, requestId: request.id, params: {} })
.catch((cause: unknown) => ({
ok: false,
status: 0,
@@ -22,7 +22,7 @@ import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-pro
import {
getCustomWidgetComponent,
getCustomWidgetComponentCatalog,
getCustomWidgetOfflineBundle,
getCustomWidgetSkillContent,
} from "@homarr/custom-widgets/authoring-resources";
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { db } from "@homarr/db";
@@ -252,7 +252,7 @@ const mcpHandler = createMcpHandler(
if (uri === "homarr://custom-widgets/schema") text = JSON.stringify(getCustomWidgetJsonSchema());
else if (uri === "homarr://custom-widgets/components") text = JSON.stringify(getCustomWidgetComponentCatalog());
else if (uri === "homarr://custom-widgets/skill") {
text = getCustomWidgetOfflineBundle();
text = getCustomWidgetSkillContent();
mimeType = "text/markdown";
} else if (uri.startsWith("homarr://custom-widgets/components/")) {
const name = decodeURIComponent(uri.slice("homarr://custom-widgets/components/".length));
@@ -26,7 +26,7 @@ export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }
const utils = clientApi.useUtils();
const [values, setValues] = useState<Record<string, string>>({});
const review = useMemo(() => getImportReview(widget), [widget]);
const requirements = useMemo(() => getCustomWidgetSecretRequirements(widget?.sources ?? []), [widget]);
const requirements = useMemo(() => getCustomWidgetSecretRequirements(widget?.sources ?? {}), [widget]);
const mutation = clientApi.customWidget.import.useMutation({
onSuccess: (result) => {
showSuccessNotification({ title: t("action.import"), message: t("notification.imported") });
@@ -391,8 +391,8 @@ function CapabilitySummary({ widget }: { widget: HomarrCustomWidgetV2 }) {
{t("sources")}
</Text>
<Stack gap={6}>
{widget.sources.map((source) => (
<Box key={source.id}>
{Object.entries(widget.sources).map(([sourceId, source]) => (
<Box key={sourceId}>
<Text size="sm" fw={500}>
{source.name}
</Text>
@@ -404,7 +404,7 @@ function CapabilitySummary({ widget }: { widget: HomarrCustomWidgetV2 }) {
{source.networkScope}
</Badge>
<Badge size="xs" variant="outline">
{source.auth.type}
{typeof source.auth === "string" ? source.auth : source.auth.type}
</Badge>
</Group>
</Box>
@@ -415,16 +415,16 @@ function CapabilitySummary({ widget }: { widget: HomarrCustomWidgetV2 }) {
<Text fw={600} size="sm" mb="xs">
{t("requests")}
</Text>
{widget.requests.length === 0 ? (
{Object.keys(widget.requests).length === 0 ? (
<Text size="xs" c="dimmed">
{t("noRequests")}
</Text>
) : (
<Stack gap={6}>
{widget.requests.map((request) => (
<Group key={request.id} justify="space-between" wrap="nowrap">
{Object.entries(widget.requests).map(([requestId, request]) => (
<Group key={requestId} justify="space-between" wrap="nowrap">
<Text size="xs" ff="monospace" truncate>
{request.id}
{requestId}
</Text>
<Group gap={4} wrap="nowrap">
<Badge size="xs">{request.kind}</Badge>
@@ -432,7 +432,7 @@ function CapabilitySummary({ widget }: { widget: HomarrCustomWidgetV2 }) {
{request.method}
</Badge>
<Badge size="xs" variant="outline">
{request.minimumBoardPermission}
{request.permission}
</Badge>
</Group>
</Group>