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

@@ -1,11 +1,10 @@
"use client";
import { useEffect, useId, useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import {
Accordion,
Alert,
ColorInput,
Fieldset,
MultiSelect,
NumberInput,
Select,
@@ -21,16 +20,16 @@ import { IconAlertTriangle } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useOptionalBoard } from "@homarr/boards/context";
import { resolveCustomWidgetOptionsBinding, validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
import type { CustomWidgetOption } from "@homarr/custom-widgets/core";
import { validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
import { CustomWidgetCodeEditor } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetEditorMessages } from "@homarr/custom-widgets/workbench";
import { IconPicker } from "@homarr/forms-collection";
import { useScopedI18n } from "@homarr/translation/client";
import type { CommonWidgetInputProps } from "./common";
import { useFormContext } from "./form";
type Schema = Record<string, unknown>;
export const WidgetCustomWidgetConfigurationInput = ({
property,
}: CommonWidgetInputProps<"customWidgetConfiguration">) => {
@@ -45,10 +44,10 @@ export const WidgetCustomWidgetConfigurationInput = ({
{ enabled: board !== null && Boolean(definitionId) },
);
const definition = available.data?.find((candidate) => candidate.id === definitionId);
const schema = isRecord(definition?.optionsSchema) ? definition.optionsSchema : null;
const options = isRecord(definition?.options) ? (definition.options as Record<string, CustomWidgetOption>) : null;
const issues = useMemo(
() => (schema ? validateCustomWidgetOptions(schema, configuration) : []),
[configuration, schema],
() => (options ? validateCustomWidgetOptions(options, configuration) : []),
[configuration, options],
);
useEffect(() => {
@@ -57,50 +56,41 @@ export const WidgetCustomWidgetConfigurationInput = ({
else form.clearFieldError(path);
}, [form, issues, property]);
if (!definitionId || !schema) return null;
const properties = getEffectiveProperties(schema, configuration);
const required = getEffectiveRequired(schema, configuration);
const entries = sortOptionEntries(properties);
const regular = entries.filter(([, child]) => !isAdvancedOption(child));
const advanced = entries.filter(([, child]) => isAdvancedOption(child));
if (!definitionId || !options) return null;
const entries = Object.entries(options);
const regular = entries.filter(([, option]) => !option.advanced);
const advanced = entries.filter(([, option]) => option.advanced);
return (
<Stack gap="md">
{issues.length > 0 && (
{issues[0] && (
<Alert color="yellow" variant="light" icon={<IconAlertTriangle size={16} />}>
<Text size="sm">{labels("needsAttention", { message: issues[0]?.message ?? "" })}</Text>
<Text size="sm">{labels("needsAttention", { message: issues[0].message })}</Text>
</Alert>
)}
{regular.map(([name, candidate]) =>
isRecord(candidate) ? (
<OptionField
key={name}
name={name}
schema={candidate}
path={`options.${property}.${name}`}
configuration={configuration}
required={required.has(name)}
/>
) : null,
)}
{regular.map(([name, option]) => (
<OptionField
key={name}
option={option}
path={`options.${property}.${name}`}
configuration={configuration}
definitionId={definitionId}
/>
))}
{advanced.length > 0 && (
<Accordion variant="contained">
<Accordion.Item value="advanced-options">
<Accordion.Control>{labels("advancedOptions")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="sm">
{advanced.map(([name, candidate]) =>
isRecord(candidate) ? (
<OptionField
key={name}
name={name}
schema={candidate}
path={`options.${property}.${name}`}
configuration={configuration}
required={required.has(name)}
/>
) : null,
)}
{advanced.map(([name, option]) => (
<OptionField
key={name}
option={option}
path={`options.${property}.${name}`}
configuration={configuration}
definitionId={definitionId}
/>
))}
</Stack>
</Accordion.Panel>
</Accordion.Item>
@@ -111,506 +101,228 @@ export const WidgetCustomWidgetConfigurationInput = ({
};
function OptionField({
name,
schema,
option,
path,
configuration,
required = false,
definitionId,
}: {
name: string;
schema: Schema;
option: CustomWidgetOption;
path: string;
configuration: Record<string, unknown>;
required?: boolean;
definitionId: string;
}) {
const form = useFormContext();
const presentation = isRecord(schema["x-homarr"]) ? schema["x-homarr"] : {};
const label = typeof schema.title === "string" ? schema.title : humanize(name);
const description = typeof schema.description === "string" ? schema.description : undefined;
const placeholder = typeof presentation.placeholder === "string" ? presentation.placeholder : undefined;
const control = typeof presentation.control === "string" ? presentation.control : inferControl(schema);
const input = form.getInputProps(path, { type: control === "switch" ? "checkbox" : "input" });
if (control === "json") {
const input = form.getInputProps(path, { type: option.control === "switch" ? "checkbox" : "input" });
const common = { label: option.label, description: option.description };
if (option.choicesFrom)
return <DynamicOptionField option={option} path={path} configuration={configuration} definitionId={definitionId} />;
if (option.control === "switch") return <Switch {...common} {...input} />;
if (["number", "duration"].includes(option.control))
return <NumberInput {...common} min={option.min} max={option.max} step={option.step} {...input} />;
if (option.control === "slider")
return (
<JsonValueInput
label={label}
description={description}
required={required}
<Stack gap={4}>
<Text size="sm" fw={500}>
{option.label}
</Text>
{option.description && (
<Text size="xs" c="dimmed">
{option.description}
</Text>
)}
<Slider min={option.min ?? 0} max={option.max ?? 100} step={option.step ?? 1} {...input} />
</Stack>
);
const choices = option.choices?.map((choice) => ({ label: choice.label, value: String(choice.value) })) ?? [];
if (option.control === "select")
return (
<Select
{...common}
data={choices}
value={input.value == null ? null : String(input.value)}
onChange={(value) => form.setFieldValue(path, coerceChoice(value, option))}
/>
);
if (option.control === "multiSelect")
return (
<MultiSelect
{...common}
data={choices}
value={Array.isArray(input.value) ? input.value.map(String) : []}
onChange={(value) =>
form.setFieldValue(
path,
value.map((entry) => coerceChoice(entry, option)),
)
}
/>
);
if (option.control === "textarea") return <Textarea {...common} autosize minRows={3} {...input} />;
if (option.control === "color") return <ColorInput {...common} {...input} />;
if (option.control === "date") return <DateInput {...common} valueFormat="YYYY-MM-DD" {...input} />;
if (option.control === "time") return <TimeInput {...common} {...input} />;
if (option.control === "icon") return <IconPicker withAsterisk={false} {...input} />;
if (option.control === "timeZone")
return <Select {...common} searchable data={Intl.supportedValuesOf("timeZone")} {...input} />;
if (option.control === "json")
return (
<JsonOption
label={option.label}
description={option.description}
value={input.value}
onChange={(value) => form.setFieldValue(path, value)}
/>
);
}
if (schema.type === "object" && isRecord(schema.properties)) {
const value = isRecord(input.value) ? input.value : {};
const properties = getEffectiveProperties(schema, value);
const nestedRequired = getEffectiveRequired(schema, value);
return (
<Fieldset legend={`${label}${required ? " *" : ""}`}>
<Stack gap="sm">
{sortOptionEntries(properties).map(([childName, child]) =>
isRecord(child) ? (
<OptionField
key={childName}
name={childName}
schema={child}
path={`${path}.${childName}`}
configuration={configuration}
required={nestedRequired.has(childName)}
/>
) : null,
)}
</Stack>
</Fieldset>
);
}
const choices = getChoices(control === "multi-select" && isRecord(schema.items) ? schema.items : schema);
if (isRecord(presentation.optionsSource)) {
return (
<DynamicOptionsSelect
label={label}
description={description}
source={presentation.optionsSource}
configuration={configuration}
path={path}
numeric={
control === "multi-select" && isRecord(schema.items)
? schema.items.type === "number" || schema.items.type === "integer"
: schema.type === "number" || schema.type === "integer"
}
multiple={control === "multi-select"}
placeholder={placeholder}
required={required}
/>
);
}
return (
<StaticOptionControl
control={control}
schema={schema}
path={path}
label={label}
description={description}
placeholder={placeholder}
required={required}
choices={choices}
/>
);
return <TextInput {...common} type={option.control === "url" ? "url" : "text"} {...input} />;
}
function StaticOptionControl({
control,
schema,
function DynamicOptionField({
option,
path,
label,
description,
placeholder,
required,
choices,
}: {
control: string;
schema: Schema;
path: string;
label: string;
description?: string;
placeholder?: string;
required: boolean;
choices: Array<{ value: string; label: string }>;
}) {
const form = useFormContext();
const input = form.getInputProps(path, { type: control === "switch" ? "checkbox" : "input" });
switch (control) {
case "switch":
return <Switch label={label} description={description} required={required} {...input} />;
case "number":
return <NumberInput label={label} description={description} required={required} {...input} />;
case "duration":
return <NumberInput label={label} description={description} required={required} suffix=" s" min={0} {...input} />;
case "slider":
return (
<Stack gap={4}>
<Text size="sm" fw={500}>
{label}
{required ? " *" : ""}
</Text>
{description && (
<Text size="xs" c="dimmed">
{description}
</Text>
)}
<Slider
min={typeof schema.minimum === "number" ? schema.minimum : 0}
max={typeof schema.maximum === "number" ? schema.maximum : 100}
step={typeof schema.multipleOf === "number" ? schema.multipleOf : 1}
{...input}
/>
</Stack>
);
case "select": {
const numeric = schema.type === "number" || schema.type === "integer";
return (
<Select
label={label}
description={description}
placeholder={placeholder}
data={choices}
searchable
required={required}
value={input.value === undefined || input.value === null ? null : String(input.value)}
onBlur={input.onBlur}
onChange={(value) => form.setFieldValue(path, numeric && value !== null ? Number(value) : value)}
/>
);
}
case "multi-select": {
const itemSchema = isRecord(schema.items) ? schema.items : {};
const numeric = itemSchema.type === "number" || itemSchema.type === "integer";
return (
<MultiSelect
label={label}
description={description}
placeholder={placeholder}
data={choices}
searchable
required={required}
value={Array.isArray(input.value) ? input.value.map(String) : []}
onBlur={input.onBlur}
onChange={(value) => form.setFieldValue(path, numeric ? value.map(Number) : value)}
/>
);
}
case "date":
return (
<DateInput label={label} description={description} required={required} valueFormat="YYYY-MM-DD" {...input} />
);
case "time":
return <TimeInput label={label} description={description} required={required} {...input} />;
case "color":
return <ColorInput label={label} description={description} required={required} {...input} />;
case "icon":
return (
<Stack gap={4}>
<IconPicker label={label} withAsterisk={required} {...input} />
{description && (
<Text size="xs" c="dimmed">
{description}
</Text>
)}
</Stack>
);
case "timeZone":
return (
<Select
label={label}
description={description}
data={Intl.supportedValuesOf("timeZone")}
searchable
required={required}
{...input}
/>
);
case "textarea":
return (
<Textarea
label={label}
description={description}
placeholder={placeholder}
required={required}
autosize
minRows={3}
{...input}
/>
);
default:
return (
<TextInput
label={label}
description={description}
placeholder={placeholder}
required={required}
type={control === "url" ? "url" : "text"}
{...input}
/>
);
}
}
function DynamicOptionsSelect({
label,
description,
source,
configuration,
path,
numeric,
multiple,
placeholder,
required,
definitionId,
}: {
label: string;
description?: string;
source: Schema;
configuration: Record<string, unknown>;
option: CustomWidgetOption;
path: string;
numeric: boolean;
multiple: boolean;
placeholder?: string;
required: boolean;
configuration: Record<string, unknown>;
definitionId: string;
}) {
const form = useFormContext();
const board = useOptionalBoard();
const definitionId = typeof form.values.options.definitionId === "string" ? form.values.options.definitionId : "";
const input = form.getInputProps(path);
const available = clientApi.customWidget.available.useQuery(
{ boardId: board?.id ?? "", currentId: definitionId || undefined },
{ enabled: board !== null && Boolean(definitionId) },
);
const definition = available.data?.find((candidate) => candidate.id === definitionId);
const requestId = typeof source.requestId === "string" ? source.requestId : "";
const request = definition?.optionRequests.find((candidate) => candidate.id === requestId);
const params = (() => {
if (!request) return null;
try {
return resolveCustomWidgetOptionsBinding(request, configuration);
} catch {
return null;
}
})();
const source = option.choicesFrom;
if (!source) return null;
const query = clientApi.customWidget.optionRequest.useQuery(
{ boardId: board?.id ?? "", definitionId, requestId, params: params ?? {} },
{ enabled: Boolean(board?.id && definitionId && requestId && request && params) },
{
boardId: board?.id ?? "",
definitionId,
requestId: source.request,
params: primitiveConfiguration(configuration),
},
{ enabled: Boolean(board?.id && definitionId && source.request) },
);
const valuePath = typeof source.valuePath === "string" ? source.valuePath : "$.value";
const labelPath = typeof source.labelPath === "string" ? source.labelPath : "$.label";
const itemsPath = typeof source.itemsPath === "string" ? source.itemsPath : undefined;
const collection = itemsPath ? getByPath(query.data?.data, itemsPath) : query.data?.data;
const rows = Array.isArray(collection) ? collection : [];
const data = rows.flatMap((row) => {
const value = getByPath(row, valuePath);
const optionLabel = getByPath(row, labelPath);
const collection = source.itemsPath ? getByPath(query.data?.data, source.itemsPath) : query.data?.data;
const data = (Array.isArray(collection) ? collection : []).flatMap((row) => {
const value = getByPath(row, source.valuePath);
const label = getByPath(row, source.labelPath);
return typeof value === "string" || typeof value === "number"
? [{ value: String(value), label: String(optionLabel ?? value) }]
? [{ value: String(value), label: String(label ?? value) }]
: [];
});
const commonProps = {
label,
description,
placeholder,
const input = form.getInputProps(path);
const common = {
label: option.label,
description: option.description,
data,
searchable: true,
required,
disabled: !request || query.isError,
disabled: query.isError,
rightSection: query.isFetching ? "…" : undefined,
onBlur: input.onBlur,
};
if (multiple) {
if (option.control === "multiSelect")
return (
<MultiSelect
{...commonProps}
{...common}
value={Array.isArray(input.value) ? input.value.map(String) : []}
onChange={(value) => form.setFieldValue(path, numeric ? value.map(Number) : value)}
onChange={(value) =>
form.setFieldValue(
path,
value.map((entry) => coerceChoice(entry, option)),
)
}
/>
);
}
return (
<Select
{...commonProps}
value={input.value === undefined || input.value === null ? null : String(input.value)}
onChange={(value) => form.setFieldValue(path, numeric && value !== null ? Number(value) : value)}
{...common}
value={input.value == null ? null : String(input.value)}
onChange={(value) => form.setFieldValue(path, coerceChoice(value, option))}
/>
);
}
function JsonValueInput({
const editorMessages: CustomWidgetEditorMessages = {
languageJsx: "JSX",
languageJson: "JSON",
undo: "Undo",
redo: "Redo",
components: "Components",
componentSearch: "Search components",
componentEmpty: "No components",
componentCount: (count) => `${count} components`,
insertStarter: "Insert starter",
format: "Format",
copy: "Copy",
copied: "Copied",
schema: "Schema",
schemaTab: "JSON Schema",
minimalTab: "Minimal",
fullTab: "Full",
errors: (count) => `${count} errors`,
warnings: (count) => `${count} warnings`,
ready: "Ready",
position: ({ line, column }) => `Ln ${line}, Col ${column}`,
characters: (count, limit) => (limit ? `${count} / ${limit}` : `${count} characters`),
diagnosticsTitle: "Diagnostics",
diagnostic: (diagnostic) => diagnostic.value ?? diagnostic.code,
};
function JsonOption({
label,
description,
required,
value,
onChange,
}: {
label: string;
description?: string;
required: boolean;
value: unknown;
onChange(value: unknown): void;
}) {
const labels = useScopedI18n("widget.customApi.configuration");
const [draft, setDraft] = useState(() => JSON.stringify(value ?? null, null, 2));
const [error, setError] = useState<string | null>(null);
useEffect(() => setDraft(JSON.stringify(value ?? null, null, 2)), [value]);
const [error, setError] = useState<string>();
return (
<ConfigurationJsonEditor
<CustomWidgetCodeEditor
id={`${label}-json-option`}
label={label}
description={description}
required={required}
error={error}
language="json"
value={draft}
height="160px"
error={error}
onChange={(next) => {
setDraft(next);
try {
const parsed = JSON.parse(next) as unknown;
setError(null);
onChange(parsed);
onChange(JSON.parse(next) as unknown);
setError(undefined);
} catch (cause) {
setError(cause instanceof Error ? cause.message : labels("invalidJson"));
setError(cause instanceof Error ? cause.message : "Invalid JSON");
}
}}
messages={editorMessages}
/>
);
}
function ConfigurationJsonEditor({
label,
description,
required,
error,
value,
height,
onChange,
}: {
label: string;
description?: string;
required?: boolean;
error?: string | null;
value: string;
height: string;
onChange(value: string): void;
}) {
const t = useScopedI18n("customWidget.editor");
const id = useId();
return (
<CustomWidgetCodeEditor
id={id}
label={label}
description={description}
required={required}
error={error}
value={value}
language="json"
height={height}
onChange={onChange}
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.value ?? diagnostic.code,
}}
/>
function coerceChoice(value: string | null, option: CustomWidgetOption) {
if (value === null) return null;
return typeof option.default === "number" ||
option.choices?.some((choice) => typeof choice.value === "number" && String(choice.value) === value)
? Number(value)
: value;
}
function primitiveConfiguration(value: Record<string, unknown>) {
return Object.fromEntries(
Object.entries(value).filter((entry): entry is [string, string | number | boolean] =>
["string", "number", "boolean"].includes(typeof entry[1]),
),
);
}
function inferControl(schema: Schema) {
if (Array.isArray(schema.enum)) return "select";
if (schema.type === "boolean") return "switch";
if (schema.type === "number" || schema.type === "integer") return "number";
if (schema.format === "date") return "date";
if (schema.format === "time") return "time";
if (schema.format === "color") return "color";
if (schema.format === "uri") return "url";
return "text";
}
function getChoices(schema: Schema) {
return Array.isArray(schema.enum)
? schema.enum.flatMap((value) =>
typeof value === "string" || typeof value === "number" ? [{ value: String(value), label: String(value) }] : [],
)
: [];
}
function getEffectiveProperties(schema: Schema, configuration: Record<string, unknown>): Record<string, unknown> {
const properties = isRecord(schema.properties) ? schema.properties : {};
if (!isRecord(schema.if)) return properties;
const branch = matchesCondition(schema.if, configuration) ? schema.then : schema.else;
return isRecord(branch) && isRecord(branch.properties) ? { ...properties, ...branch.properties } : properties;
}
function getEffectiveRequired(schema: Schema, configuration: Record<string, unknown>) {
const required = new Set(
Array.isArray(schema.required) ? schema.required.filter((value): value is string => typeof value === "string") : [],
);
if (!isRecord(schema.if)) return required;
const branch = matchesCondition(schema.if, configuration) ? schema.then : schema.else;
if (isRecord(branch) && Array.isArray(branch.required)) {
branch.required
.filter((value): value is string => typeof value === "string")
.forEach((value) => required.add(value));
}
return required;
}
function sortOptionEntries(properties: Record<string, unknown>) {
return Object.entries(properties).toSorted((left, right) => optionOrder(left[1]) - optionOrder(right[1]));
}
function optionOrder(value: unknown) {
if (!isRecord(value) || !isRecord(value["x-homarr"])) return 0;
const order = value["x-homarr"].order;
return typeof order === "number" ? order : 0;
}
function isAdvancedOption(value: unknown) {
return isRecord(value) && isRecord(value["x-homarr"]) && value["x-homarr"].advanced === true;
}
function matchesCondition(schema: Schema, configuration: Record<string, unknown>): boolean {
const required = Array.isArray(schema.required)
? schema.required.filter((value): value is string => typeof value === "string")
: [];
if (required.some((key) => configuration[key] === undefined)) return false;
if (!isRecord(schema.properties)) return true;
return Object.entries(schema.properties).every(([key, candidate]) => {
if (!isRecord(candidate)) return true;
const value = configuration[key];
if (candidate.const !== undefined) return Object.is(value, candidate.const);
return !Array.isArray(candidate.enum) || candidate.enum.some((entry) => Object.is(entry, value));
});
}
function humanize(value: string) {
return value
.replaceAll(/[-_]/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/^./, (letter) => letter.toUpperCase());
}
function getByPath(value: unknown, path: string): unknown {
const normalized = path
return path
.replace(/^\$\.?/u, "")
.replaceAll(/\[(\d+)\]/gu, ".$1")
.replaceAll(/\[['"]([^'"]+)['"]\]/gu, ".$1");
return normalized
.split(".")
.filter(Boolean)
.reduce<unknown>((current, segment) => {
if (["__proto__", "prototype", "constructor"].includes(segment.toLowerCase())) return undefined;
if (Array.isArray(current) && /^\d+$/u.test(segment)) return current[Number(segment)];
return isRecord(current) ? current[segment] : undefined;
}, value);
.reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -1,20 +1,7 @@
"use client";
import dynamic from "next/dynamic";
import { useMemo, useState } from "react";
import {
Avatar,
Badge,
Card,
Combobox,
Group,
InputBase,
Loader,
Paper,
Stack,
Text,
useCombobox,
} from "@mantine/core";
import { Avatar, Badge, Combobox, Group, InputBase, Loader, Stack, Text, useCombobox } from "@mantine/core";
import { IconApi } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
@@ -25,8 +12,6 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
const CustomJsxDisplay = dynamic(() => import("../custom-api/custom-jsx-display"), { ssr: false });
export const WidgetCustomWidgetSelectInput = ({
property,
kind,
@@ -59,8 +44,6 @@ export const WidgetCustomWidgetSelectInput = ({
);
const selectedLabel = definitions.find((d) => d.value === currentValue)?.label;
const selected = definitions.find((definition) => definition.value === currentValue);
const combobox = useCombobox({
onDropdownClose: () => {
combobox.resetSelectedOption();
@@ -137,36 +120,6 @@ export const WidgetCustomWidgetSelectInput = ({
</Combobox.Options>
</Combobox.Dropdown>
</Combobox>
{selected && (
<Card withBorder p="sm">
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" fw={600}>
{selected.name}
</Text>
<Badge size="sm" variant="light">
{labels("preview")}
</Badge>
</Group>
<Paper withBorder p="sm" h={180} style={{ overflow: "auto" }}>
<CustomJsxDisplay
data={{
template: selected.template,
data: {},
status: Object.fromEntries(
selected.requestCapabilities.map((request) => [request.id, { loading: true }]),
),
options: selected.defaultOptions,
requestCapabilities: selected.requestCapabilities,
previewSessionId: "widget-picker",
queriesDisabled: true,
isEditMode: true,
}}
/>
</Paper>
</Stack>
</Card>
)}
</Stack>
);
};
+13 -6
View File
@@ -26,9 +26,8 @@ export default function CustomApiWidget({
{ itemId: itemId ?? "" },
{
enabled: Boolean(itemId) && Boolean(definitionId),
refetchInterval: intervalMs,
retry: (failureCount, error) =>
!["NOT_FOUND", "PRECONDITION_FAILED"].includes(error.data?.code ?? "") && failureCount < 3,
refetchInterval: (currentQuery) => (isTerminalDefinitionError(currentQuery.state.error) ? false : intervalMs),
retry: (failureCount, error) => !isTerminalDefinitionError(error) && failureCount < 3,
},
);
@@ -44,17 +43,18 @@ export default function CustomApiWidget({
);
if (query.error) {
const errorCode = query.error.data?.code;
const isUnavailable = errorCode === "NOT_FOUND" || errorCode === "FORBIDDEN";
return (
<Unavailable
message={
errorCode === "NOT_FOUND"
isUnavailable
? t("definitionNotFound")
: errorCode === "PRECONDITION_FAILED"
? t("configurationNeedsRepair")
: tCustomJsx("requestFailed")
}
danger={errorCode !== "NOT_FOUND"}
removeLabel={errorCode === "NOT_FOUND" ? t("removeFromBoard") : undefined}
danger={!isUnavailable}
removeLabel={isUnavailable ? t("removeFromBoard") : undefined}
onRemove={removeItem}
/>
);
@@ -73,6 +73,13 @@ export default function CustomApiWidget({
);
}
function isTerminalDefinitionError(error: unknown): boolean {
if (!error || typeof error !== "object" || !("data" in error)) return false;
const data = error.data;
if (!data || typeof data !== "object" || !("code" in data)) return false;
return data.code === "NOT_FOUND" || data.code === "FORBIDDEN" || data.code === "PRECONDITION_FAILED";
}
function Unavailable({
message,
danger = false,
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
import * as MantineCharts from "@mantine/charts";
import * as MantineCore from "@mantine/core";
import * as MantineDates from "@mantine/dates";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -9,7 +10,12 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type { Root } from "react-dom/client";
import { customJsxComponentRegistry, enabledCustomJsxComponents } from "@homarr/custom-widgets/catalog";
import { customJsxExamples, customJsxTablerIconNames } from "@homarr/custom-widgets/core";
import {
BUNDLED_CUSTOM_WIDGETS,
customJsxExamples,
customJsxTablerIconNames,
getCustomWidgetDefaultOptions,
} from "@homarr/custom-widgets/core";
import { renderSafeJsx, SafeJsxError, sanitizeCustomJsxProps } from "@homarr/custom-widgets/jsx";
import CustomJsxDisplay from "./custom-jsx-display";
@@ -54,6 +60,14 @@ describe("CustomJsxDisplay", () => {
dispatchEvent: () => false,
}),
});
Object.defineProperty(globalThis, "ResizeObserver", {
writable: true,
value: class {
observe() {}
unobserve() {}
disconnect() {}
},
});
});
afterEach(async () => {
@@ -65,8 +79,15 @@ describe("CustomJsxDisplay", () => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root.render(createElement(MantineProvider, null, createElement(CustomJsxDisplay, { data })));
root.render(
createElement(
MantineProvider,
null,
createElement(QueryClientProvider, { client: queryClient }, createElement(CustomJsxDisplay, { data })),
),
);
});
};
@@ -80,6 +101,29 @@ describe("CustomJsxDisplay", () => {
expect(container.textContent).toContain("3");
});
it("keeps runtime components inside an inert provider before a preview session exists", async () => {
await renderDisplay({ template: '<RefreshButton label="Refresh" />', data: {} });
expect(container.textContent).toContain("Refresh");
expect(container.textContent).not.toContain("RUNTIME_RENDER_ERROR");
expect(container.querySelector("button")?.disabled).toBe(true);
});
it("renders the bundled Pokédex list without a widget-wide runtime failure", async () => {
const pokedex = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-pokedex")?.widget;
expect(pokedex).toBeDefined();
await renderDisplay({
template: pokedex?.template,
data: { pokemon: { count: 2, results: [{ name: "bulbasaur" }, { name: "pikachu" }] } },
status: { pokemon: { loading: false, ok: true, status: 200 } },
options: getCustomWidgetDefaultOptions(pokedex?.options ?? {}),
});
expect(container.textContent).toContain("bulbasaur");
expect(container.textContent).toContain("pikachu");
expect(container.textContent).not.toContain("RUNTIME_RENDER_ERROR");
});
it("recovers when preview data arrives after an initial render error", async () => {
const template = "<Stack>{data.items.map((item) => <Text key={item}>{item}</Text>)}</Stack>";
await renderDisplay({ template, data: {} });
@@ -553,7 +597,7 @@ describe("shared Custom JSX examples", () => {
bindings: {
...SAFE_BINDINGS(sampleData),
status: {},
options: example.widget.defaultOptions,
options: getCustomWidgetDefaultOptions(example.widget.options ?? {}),
inputs: {},
},
});
@@ -7,7 +7,7 @@ import type { CustomWidgetPublishedQueryState } from "@homarr/custom-widgets/run
import { CustomJsxRenderer, parseRequestCapabilities } from "@homarr/custom-widgets/runtime";
import { createCustomWidgetComponents, SAFE_BINDINGS } from "./jsx-components";
import { WidgetDefinitionProvider } from "./widget-definition-context";
import { InactiveWidgetDefinitionProvider, WidgetDefinitionProvider } from "./widget-definition-context";
export { CUSTOM_JSX_METHOD_COLORS } from "@homarr/custom-widgets/runtime";
@@ -52,12 +52,21 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
}}
/>
);
const hasRuntime = typeof data.widgetItemId === "string" || typeof data.previewSessionId === "string";
return hasRuntime ? (
const definitionId = typeof data.widgetDefinitionId === "string" ? data.widgetDefinitionId : undefined;
const itemId = typeof data.widgetItemId === "string" ? data.widgetItemId : undefined;
const previewSessionId = typeof data.previewSessionId === "string" ? data.previewSessionId : undefined;
if (!itemId && !previewSessionId) {
return (
<InactiveWidgetDefinitionProvider definitionId={definitionId} isEditMode={data.isEditMode === true}>
{renderer}
</InactiveWidgetDefinitionProvider>
);
}
return (
<WidgetDefinitionProvider
definitionId={String(data.widgetDefinitionId ?? "")}
itemId={typeof data.widgetItemId === "string" ? data.widgetItemId : undefined}
previewSessionId={typeof data.previewSessionId === "string" ? data.previewSessionId : undefined}
definitionId={definitionId}
itemId={itemId}
previewSessionId={previewSessionId}
previewLiveActions={data.previewLiveActions === true}
queriesDisabled={data.queriesDisabled === true}
isEditMode={data.isEditMode === true}
@@ -66,8 +75,6 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
>
{renderer}
</WidgetDefinitionProvider>
) : (
renderer
);
}
@@ -11,6 +11,7 @@ import {
IconBluetooth,
IconBolt,
IconBookmark,
IconBrandDocker,
IconBug,
IconCalendar,
IconCamera,
@@ -64,6 +65,7 @@ import {
IconMusic,
IconNetwork,
IconPhoto,
IconPokeball,
IconPin,
IconPlayerPause,
IconPlayerPlay,
@@ -133,6 +135,7 @@ const TABLER_ICON_IMPORTS = {
IconHeart,
IconStar,
IconBookmark,
IconBrandDocker,
IconFlag,
IconPin,
IconPlayerPlay,
@@ -183,6 +186,7 @@ const TABLER_ICON_IMPORTS = {
IconExternalLink,
IconLink,
IconPhoto,
IconPokeball,
IconCamera,
IconMusic,
IconVideo,
@@ -27,12 +27,17 @@ interface WidgetDefinitionProviderProps {
children: ReactNode;
}
export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
const INACTIVE_PORT: CustomWidgetRuntimePort = {
query: async () => ({ ok: false, status: 0, data: null, error: "Custom widget unavailable" }),
executeAction: async () => ({ ok: false, status: 0, data: null, error: "Custom widget unavailable" }),
invalidate: async () => undefined,
confirm: async () => false,
notify: () => undefined,
};
const useRuntimeMessages = (): CustomWidgetRuntimeMessages => {
const t = useScopedI18n("widget.customApi.customJsx");
const utils = clientApi.useUtils();
const queryClient = useQueryClient();
const { openConfirmModal } = useConfirmModal();
const messages: CustomWidgetRuntimeMessages = {
return {
requestIdRequired: t("requestIdRequired"),
unsavedPreview: t("unsavedPreview"),
invalidParams: t("invalidParams"),
@@ -48,6 +53,32 @@ export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
toggle: t("toggle"),
refresh: t("refresh"),
};
};
export function InactiveWidgetDefinitionProvider({
definitionId,
isEditMode,
children,
}: Pick<WidgetDefinitionProviderProps, "definitionId" | "isEditMode" | "children">) {
const messages = useRuntimeMessages();
return (
<CustomWidgetRuntimeProvider
definitionId={definitionId}
isEditMode={isEditMode ?? false}
requestCapabilities={[]}
port={INACTIVE_PORT}
messages={messages}
>
{children}
</CustomWidgetRuntimeProvider>
);
}
export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
const utils = clientApi.useUtils();
const queryClient = useQueryClient();
const { openConfirmModal } = useConfirmModal();
const messages = useRuntimeMessages();
const port: CustomWidgetRuntimePort = {
query: async (input, signal) => {
if (input.itemId) {