feat: modernize widget experience
This commit is contained in:
198 files changed
+4209
-2295
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import type { ComponentType } from "react";
|
||||
import {
|
||||
ActionIcon,
|
||||
@@ -32,6 +32,8 @@ import { showErrorNotification, showSuccessNotification } from "@homarr/notifica
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { useWidgetRuntimeActions } from "../runtime-hooks";
|
||||
import { getUsableWidgetQueryData } from "../common/query-state";
|
||||
import actionTargetClasses from "../common/action-target.module.css";
|
||||
|
||||
const CustomJsxDisplay = dynamic(() => import("./custom-jsx-display"), { ssr: false });
|
||||
@@ -383,18 +385,21 @@ function ActionButtonDisplay({ data, width, height }: CustomDisplayProps) {
|
||||
const confirmText = (data.confirmText as string) || "";
|
||||
const successMessage = (data.successMessage as string) || t("executeSuccess");
|
||||
const definitionId = data.widgetDefinitionId as string | undefined;
|
||||
const boardId = data.boardId as string | undefined;
|
||||
const itemId = data.itemId as string | undefined;
|
||||
const canExecute = data.canExecute === true;
|
||||
|
||||
const handleExecute = async () => {
|
||||
if (!definitionId) return;
|
||||
if (!definitionId || !boardId || !itemId || !canExecute) return;
|
||||
setLastSuccess(false);
|
||||
try {
|
||||
const result = await executeMutation.mutateAsync({ definitionId });
|
||||
const result = await executeMutation.mutateAsync({ boardId, itemId, definitionId });
|
||||
if (result.success) {
|
||||
setLastSuccess(true);
|
||||
showSuccessNotification({ title: buttonLabel, message: successMessage });
|
||||
setTimeout(() => setLastSuccess(false), 3000);
|
||||
} else {
|
||||
showErrorNotification({ title: buttonLabel, message: result.error ?? t("executeFailed") });
|
||||
showErrorNotification({ title: buttonLabel, message: t("executeFailed") });
|
||||
}
|
||||
} catch {
|
||||
showErrorNotification({ title: buttonLabel, message: t("executeFailed") });
|
||||
@@ -420,6 +425,7 @@ function ActionButtonDisplay({ data, width, height }: CustomDisplayProps) {
|
||||
color={buttonColor}
|
||||
onClick={handleClick}
|
||||
loading={executeMutation.isPending}
|
||||
disabled={!canExecute || !boardId || !itemId || !definitionId}
|
||||
leftSection={lastSuccess ? <IconCheck size={18} /> : <IconPlayerPlay size={18} />}
|
||||
variant={lastSuccess ? "light" : "filled"}
|
||||
maw="calc(100% - var(--mantine-spacing-sm) * 2)"
|
||||
@@ -460,10 +466,12 @@ const displayTypeTranslationKeys = {
|
||||
|
||||
export default function CustomApiWidget({
|
||||
options,
|
||||
boardId,
|
||||
itemId,
|
||||
width,
|
||||
height,
|
||||
displayMode = "compact",
|
||||
widgetStateRef,
|
||||
widgetRuntimeRef,
|
||||
}: WidgetComponentProps<"customApi">) {
|
||||
const t = useScopedI18n("widget.customApi");
|
||||
const { definitionId, refreshInterval } = options;
|
||||
@@ -481,40 +489,48 @@ export default function CustomApiWidget({
|
||||
);
|
||||
}
|
||||
|
||||
if (!boardId || !itemId) return null;
|
||||
|
||||
return (
|
||||
<CustomApiWidgetInner
|
||||
boardId={boardId}
|
||||
itemId={itemId}
|
||||
definitionId={definitionId}
|
||||
refreshInterval={refreshInterval as number}
|
||||
width={width}
|
||||
height={height}
|
||||
displayMode={displayMode}
|
||||
widgetStateRef={widgetStateRef}
|
||||
widgetRuntimeRef={widgetRuntimeRef}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomApiWidgetInner({
|
||||
boardId,
|
||||
itemId,
|
||||
definitionId,
|
||||
refreshInterval,
|
||||
width,
|
||||
height,
|
||||
displayMode,
|
||||
widgetStateRef,
|
||||
widgetRuntimeRef,
|
||||
}: {
|
||||
boardId: string;
|
||||
itemId: string;
|
||||
definitionId: string;
|
||||
refreshInterval: number;
|
||||
width: number;
|
||||
height: number;
|
||||
displayMode: "compact" | "advanced";
|
||||
widgetStateRef?: WidgetComponentProps<"customApi">["widgetStateRef"];
|
||||
widgetRuntimeRef?: WidgetComponentProps<"customApi">["widgetRuntimeRef"];
|
||||
}) {
|
||||
const t = useScopedI18n("widget.customApi");
|
||||
const tCustomWidget = useScopedI18n("customWidget");
|
||||
const safeInterval = Number.isFinite(refreshInterval) ? refreshInterval : 30;
|
||||
const intervalMs = Math.max(1000, safeInterval * 1000);
|
||||
const [pollingPaused, setPollingPaused] = useState(false);
|
||||
const { data, isLoading, error, refetch, isFetching } = clientApi.widget.customApi.getData.useQuery(
|
||||
{ definitionId },
|
||||
const query = clientApi.widget.customApi.getData.useQuery(
|
||||
{ boardId, itemId, definitionId },
|
||||
{
|
||||
refetchInterval: (query) => {
|
||||
const result = query.state.data as Record<string, unknown> | undefined;
|
||||
@@ -527,6 +543,8 @@ function CustomApiWidgetInner({
|
||||
},
|
||||
},
|
||||
);
|
||||
const data = getUsableWidgetQueryData(query);
|
||||
const { isLoading, refetch, isFetching } = query;
|
||||
|
||||
const widgetData = (data ?? {}) as Record<string, unknown>;
|
||||
const dataType = widgetData.type as string | undefined;
|
||||
@@ -536,19 +554,7 @@ function CustomApiWidgetInner({
|
||||
setPollingPaused((value) => !value);
|
||||
}, [pollingPaused, refetch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!widgetStateRef) return;
|
||||
if (canTogglePolling) {
|
||||
widgetStateRef.current = { ...widgetStateRef.current, togglePolling };
|
||||
} else if (widgetStateRef.current) {
|
||||
delete widgetStateRef.current.togglePolling;
|
||||
}
|
||||
return () => {
|
||||
if (widgetStateRef.current?.togglePolling === togglePolling) {
|
||||
delete widgetStateRef.current.togglePolling;
|
||||
}
|
||||
};
|
||||
}, [canTogglePolling, togglePolling, widgetStateRef]);
|
||||
useWidgetRuntimeActions(widgetRuntimeRef, canTogglePolling ? { togglePolling } : {});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -558,28 +564,6 @@ function CustomApiWidgetInner({
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
const isNotFound = error.data?.code === "NOT_FOUND";
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Stack align="center" gap="xs">
|
||||
<IconAlertTriangle size={32} color={`var(--mantine-color-${isNotFound ? "yellow" : "red"}-6)`} />
|
||||
{isNotFound ? (
|
||||
<Text c="dimmed" size="sm" ta="center">
|
||||
{t("definitionNotFound")}
|
||||
</Text>
|
||||
) : (
|
||||
<Tooltip label={error.message} multiline>
|
||||
<Text c="dimmed" size="sm" ta="center" tabIndex={0} aria-label={`${t("fetchFailed")}. ${error.message}`}>
|
||||
{t("fetchFailed")}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
if (dataType === "disabled") {
|
||||
@@ -596,7 +580,8 @@ function CustomApiWidgetInner({
|
||||
if (Component) {
|
||||
const displayTypeKey = displayTypeTranslationKeys[dataType as keyof typeof displayTypeTranslationKeys];
|
||||
const pollingLabel = pollingPaused ? t("actions.resumePolling") : t("actions.pausePolling");
|
||||
const enrichedData = dataType === "actionButton" ? { ...widgetData, widgetDefinitionId: definitionId } : widgetData;
|
||||
const enrichedData =
|
||||
dataType === "actionButton" ? { ...widgetData, boardId, itemId, widgetDefinitionId: definitionId } : widgetData;
|
||||
const content = <Component data={enrichedData} displayMode={displayMode} width={width} height={height} />;
|
||||
if (displayMode === "compact") return content;
|
||||
return (
|
||||
|
||||
@@ -64,6 +64,16 @@ describe("CustomJsxDisplay", () => {
|
||||
expect(container.textContent).toContain("Safe");
|
||||
});
|
||||
|
||||
it("does not expose parser failures in rendered or accessible text", async () => {
|
||||
await renderDisplay({
|
||||
template: "<Text>http://admin:password@nas.internal/private/path?token=secret",
|
||||
data: {},
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toMatch(/admin|password|nas\.internal|private\/path|token|secret/i);
|
||||
expect(container.innerHTML).not.toMatch(/admin|password|nas\.internal|private\/path|token|secret/i);
|
||||
});
|
||||
|
||||
describe("safe bindings security", () => {
|
||||
it("exposes wrapper functions, not native constructors", () => {
|
||||
const bindings = SAFE_BINDINGS({ value: 7 });
|
||||
|
||||
@@ -7,27 +7,17 @@ import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { WHITELISTED_COMPONENTS, SAFE_BINDINGS } from "./jsx-whitelist";
|
||||
|
||||
const MAX_PARSE_ERRORS = 5;
|
||||
|
||||
function appendParseError(prev: string[], message: string): string[] {
|
||||
if (prev.length >= MAX_PARSE_ERRORS) return prev;
|
||||
if (prev.includes(message)) return prev;
|
||||
return [...prev, message];
|
||||
}
|
||||
|
||||
export default function CustomJsxDisplay({ data }: { data: Record<string, unknown> }) {
|
||||
const template = String(data.template ?? "");
|
||||
const apiData = data.data;
|
||||
const [parseErrors, setParseErrors] = useState<string[]>([]);
|
||||
const [hasParseError, setHasParseError] = useState(false);
|
||||
const bindings = useMemo(() => SAFE_BINDINGS(apiData), [apiData]);
|
||||
|
||||
useEffect(() => {
|
||||
setParseErrors([]);
|
||||
setHasParseError(false);
|
||||
}, [template, bindings]);
|
||||
|
||||
const handleError = useCallback((error: Error) => {
|
||||
setParseErrors((prev) => appendParseError(prev, error.message));
|
||||
}, []);
|
||||
const handleError = useCallback(() => setHasParseError(true), []);
|
||||
|
||||
if (!template.trim()) {
|
||||
return (
|
||||
@@ -51,22 +41,17 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
||||
blacklistedAttrs={[/^on.+/i, /^dangerously/i]}
|
||||
blacklistedTags={["script", "iframe", "object", "embed", "form", "style", "link", "meta", "base"]}
|
||||
onError={handleError}
|
||||
renderError={({ error }) => (
|
||||
renderError={() => (
|
||||
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs">{String(error)}</Text>
|
||||
<Text size="xs">Invalid widget template</Text>
|
||||
</Alert>
|
||||
)}
|
||||
/>
|
||||
{parseErrors.length > 0 && (
|
||||
{hasParseError && (
|
||||
<Alert color="yellow" variant="light" p="xs" mt="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{parseErrors.length} template warning(s):
|
||||
Invalid widget template
|
||||
</Text>
|
||||
{parseErrors.map((msg) => (
|
||||
<Text key={msg} size="xs" c="dimmed" style={{ fontFamily: "monospace" }}>
|
||||
{msg}
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
@@ -4,34 +4,34 @@ import { z } from "zod/v4";
|
||||
import { createWidgetDefinition, widgetQueryInputMatches } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
const createOptions = () =>
|
||||
optionsBuilder.from((factory) => ({
|
||||
definitionId: factory.customWidgetSelect({ defaultValue: "" }),
|
||||
refreshInterval: factory.slider({
|
||||
defaultValue: 30,
|
||||
validate: z.number().min(1).max(3600),
|
||||
step: 1,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("customApi", {
|
||||
icon: IconApi,
|
||||
queryKey: [["widget", "customApi", "getData"]],
|
||||
queryMatcher: ({ input }, scope) => widgetQueryInputMatches(input, { definitionId: scope.options.definitionId }),
|
||||
contextActions({ options, widgetStateRef }) {
|
||||
contextActions: ({ options, widgetRuntimeRef }) => {
|
||||
return [
|
||||
{
|
||||
key: "togglePolling",
|
||||
label: (t) => t("widget.customApi.actions.togglePolling"),
|
||||
label: "widget.customApi.actions.togglePolling",
|
||||
icon: IconPlayerPause,
|
||||
hidden: typeof options.definitionId !== "string" || options.definitionId.trim() === "",
|
||||
disabled: typeof widgetStateRef?.current?.togglePolling !== "function",
|
||||
disabled: typeof widgetRuntimeRef.current.actions.togglePolling !== "function",
|
||||
onClick: () => {
|
||||
const action = widgetStateRef?.current?.togglePolling;
|
||||
if (typeof action === "function") action();
|
||||
widgetRuntimeRef.current.actions.togglePolling?.();
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
definitionId: factory.customWidgetSelect({ defaultValue: "" }),
|
||||
refreshInterval: factory.slider({
|
||||
defaultValue: 30,
|
||||
validate: z.number().min(1).max(3600),
|
||||
step: 1,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
createOptions,
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -54,19 +54,19 @@ import {
|
||||
Sparkline,
|
||||
} from "@mantine/charts";
|
||||
|
||||
import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "../common/application-url";
|
||||
import { PaginatedList, TabsContainer, TabPanel, Collapsible, StatBar, TypeBadge } from "./jsx-interactive-components";
|
||||
|
||||
const SAFE_URL_PATTERN = /^https?:\/\//i;
|
||||
|
||||
function isSafeUrl(url: unknown): boolean {
|
||||
if (typeof url !== "string") return false;
|
||||
return SAFE_URL_PATTERN.test(url) || url.startsWith("/") || url.startsWith("#");
|
||||
}
|
||||
|
||||
function SafeAnchor(props: Record<string, unknown>) {
|
||||
const href = props.href;
|
||||
const safeHref = href && isSafeUrl(href) ? href : undefined;
|
||||
return createElement(Anchor as never, { ...props, href: safeHref });
|
||||
const safeHref = getSafeApplicationUrl(props.href);
|
||||
const target = safeHref ? props.target : undefined;
|
||||
return createElement(Anchor as never, {
|
||||
...props,
|
||||
component: safeHref ? "a" : "span",
|
||||
href: safeHref,
|
||||
target,
|
||||
rel: target === "_blank" ? SAFE_NEW_TAB_REL : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
|
||||
Reference in new issue
Block a user