feat(custom-widgets): full Mantine v9 + SubFetch support for custom JSX
Massively expands the custom JSX widget system to support virtually all Mantine v9 components and adds in-widget HTTP request capabilities via a server-proxied SubFetch system. - Whitelist ~100 Mantine components (core, all 16 charts, dates) - Add SubFetch, SubData, ActionButton, ToggleSwitch, RefreshButton - Add server-side subFetch tRPC mutation with same-origin + auth - Show HTTP method warning badges in widget and admin preview - Remove `fetch` from forbidden keywords, increase template to 50KB - Expand bindings: Date.*, parseInt, parseFloat, Array.from, etc. - Update AI prompt with full component reference + demo templates
This commit is contained in:
12 files changed
+1164
-257
No files matched your search
@@ -479,7 +479,10 @@ function CustomApiWidgetInner({ definitionId, refreshInterval }: { definitionId:
|
||||
|
||||
const Component = dataType ? displayComponents[dataType] : undefined;
|
||||
if (Component) {
|
||||
const enrichedData = dataType === "actionButton" ? { ...widgetData, widgetDefinitionId: definitionId } : widgetData;
|
||||
const enrichedData =
|
||||
dataType === "actionButton" || dataType === "customJsx"
|
||||
? { ...widgetData, widgetDefinitionId: definitionId }
|
||||
: widgetData;
|
||||
return <Component data={enrichedData} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import JsxParser from "react-jsx-parser";
|
||||
import { Alert, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
import { Alert, Badge, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle, IconNetwork } from "@tabler/icons-react";
|
||||
|
||||
import { WHITELISTED_COMPONENTS, SAFE_BINDINGS } from "./jsx-whitelist";
|
||||
import { WidgetDefinitionProvider } from "./widget-definition-context";
|
||||
|
||||
const MAX_PARSE_ERRORS = 5;
|
||||
|
||||
@@ -15,11 +16,40 @@ function appendParseError(prev: string[], message: string): string[] {
|
||||
return [...prev, message];
|
||||
}
|
||||
|
||||
const METHOD_PATTERN = /(?:method|method)\s*=\s*["'](\w+)["']/gi;
|
||||
const SUBFETCH_PATTERN = /<(?:SubFetch|ActionButton|ToggleSwitch)\b/g;
|
||||
|
||||
export function extractHttpMethods(template: string): string[] {
|
||||
const methods = new Set<string>();
|
||||
if (SUBFETCH_PATTERN.test(template)) {
|
||||
SUBFETCH_PATTERN.lastIndex = 0;
|
||||
let match = METHOD_PATTERN.exec(template);
|
||||
while (match) {
|
||||
methods.add(match[1].toUpperCase());
|
||||
match = METHOD_PATTERN.exec(template);
|
||||
}
|
||||
if (/<ActionButton\b/.test(template) && methods.size === 0) methods.add("POST");
|
||||
if (/<ToggleSwitch\b/.test(template) && methods.size === 0) methods.add("POST");
|
||||
if (/<SubFetch\b/.test(template) && methods.size === 0) methods.add("GET");
|
||||
}
|
||||
return [...methods].sort();
|
||||
}
|
||||
|
||||
const METHOD_COLORS: Record<string, string> = {
|
||||
GET: "blue",
|
||||
POST: "orange",
|
||||
PUT: "yellow",
|
||||
DELETE: "red",
|
||||
PATCH: "grape",
|
||||
};
|
||||
|
||||
export default function CustomJsxDisplay({ data }: { data: Record<string, unknown> }) {
|
||||
const template = String(data.template ?? "");
|
||||
const apiData = data.data;
|
||||
const definitionId = String(data.widgetDefinitionId ?? "");
|
||||
const [parseErrors, setParseErrors] = useState<string[]>([]);
|
||||
const bindings = useMemo(() => SAFE_BINDINGS(apiData), [apiData]);
|
||||
const httpMethods = useMemo(() => extractHttpMethods(template), [template]);
|
||||
|
||||
useEffect(() => {
|
||||
setParseErrors([]);
|
||||
@@ -40,35 +70,51 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap={0} h="100%">
|
||||
<JsxParser
|
||||
jsx={template}
|
||||
components={WHITELISTED_COMPONENTS as never}
|
||||
bindings={bindings}
|
||||
disableKeyGeneration
|
||||
componentsOnly
|
||||
allowUnknownElements={false}
|
||||
blacklistedAttrs={[/^on.+/i, /^dangerously/i]}
|
||||
blacklistedTags={["script", "iframe", "object", "embed", "form", "style", "link", "meta", "base"]}
|
||||
onError={handleError}
|
||||
renderError={({ error }) => (
|
||||
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs">{String(error)}</Text>
|
||||
<WidgetDefinitionProvider definitionId={definitionId}>
|
||||
<Stack gap={0} h="100%">
|
||||
{httpMethods.length > 0 && (
|
||||
<Alert color="yellow" variant="light" p={4} mb={4} icon={<IconNetwork size={14} />}>
|
||||
<Group gap={4} align="center">
|
||||
<Text size="xs" c="dimmed">
|
||||
HTTP:
|
||||
</Text>
|
||||
{httpMethods.map((m) => (
|
||||
<Badge key={m} size="xs" color={METHOD_COLORS[m] ?? "gray"} variant="filled">
|
||||
{m}
|
||||
</Badge>
|
||||
))}
|
||||
</Group>
|
||||
</Alert>
|
||||
)}
|
||||
/>
|
||||
{parseErrors.length > 0 && (
|
||||
<Alert color="yellow" variant="light" p="xs" mt="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{parseErrors.length} template warning(s):
|
||||
</Text>
|
||||
{parseErrors.map((msg) => (
|
||||
<Text key={msg} size="xs" c="dimmed" style={{ fontFamily: "monospace" }}>
|
||||
{msg}
|
||||
<JsxParser
|
||||
jsx={template}
|
||||
components={WHITELISTED_COMPONENTS as never}
|
||||
bindings={bindings}
|
||||
disableKeyGeneration
|
||||
componentsOnly
|
||||
allowUnknownElements={false}
|
||||
blacklistedAttrs={[/^on.+/i, /^dangerously/i]}
|
||||
blacklistedTags={["script", "iframe", "object", "embed", "form", "style", "link", "meta", "base"]}
|
||||
onError={handleError}
|
||||
renderError={({ error }) => (
|
||||
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs">{String(error)}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
/>
|
||||
{parseErrors.length > 0 && (
|
||||
<Alert color="yellow" variant="light" p="xs" mt="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{parseErrors.length} template warning(s):
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
{parseErrors.map((msg) => (
|
||||
<Text key={msg} size="xs" c="dimmed" style={{ fontFamily: "monospace" }}>
|
||||
{msg}
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</WidgetDefinitionProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
"use client";
|
||||
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Badge, Button, Code, Skeleton, Switch, Text, Title } from "@mantine/core";
|
||||
import {
|
||||
IconAlertTriangle,
|
||||
IconCheck,
|
||||
IconPlayerPlay,
|
||||
IconPower,
|
||||
IconRefresh,
|
||||
IconTrash,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useConfirmModal } from "@homarr/modals";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
|
||||
import { useWidgetDefinitionId } from "./widget-definition-context";
|
||||
|
||||
const MAX_CALLS_PER_MINUTE = 10;
|
||||
const RATE_WINDOW_MS = 60_000;
|
||||
const callTimestamps = new Map<string, number[]>();
|
||||
|
||||
const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
|
||||
type HttpMethod = (typeof HTTP_METHODS)[number];
|
||||
|
||||
type SubFetchResult =
|
||||
| { ok: true; status: number; data: unknown }
|
||||
| { ok: false; status: number; data: unknown; error?: string };
|
||||
|
||||
const ICON_MAP: Record<string, ComponentType<{ size?: number | string }>> = {
|
||||
play: IconPlayerPlay,
|
||||
check: IconCheck,
|
||||
refresh: IconRefresh,
|
||||
power: IconPower,
|
||||
trash: IconTrash,
|
||||
};
|
||||
|
||||
const SubFetchDataContext = createContext<unknown>(undefined);
|
||||
|
||||
function checkRateLimit(definitionId: string): boolean {
|
||||
const now = Date.now();
|
||||
const calls = callTimestamps.get(definitionId) ?? [];
|
||||
const recent = calls.filter((t) => now - t < RATE_WINDOW_MS);
|
||||
if (recent.length >= MAX_CALLS_PER_MINUTE) return false;
|
||||
recent.push(now);
|
||||
callTimestamps.set(definitionId, recent);
|
||||
return true;
|
||||
}
|
||||
|
||||
function parseBool(value: unknown, defaultValue = false): boolean {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
function parseMethod(method?: string): HttpMethod {
|
||||
const upper = (method ?? "GET").toUpperCase();
|
||||
if (HTTP_METHODS.includes(upper as HttpMethod)) return upper as HttpMethod;
|
||||
return "GET";
|
||||
}
|
||||
|
||||
function parseJsonRecord(str?: string): Record<string, string> | undefined {
|
||||
if (!str?.trim()) return undefined;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(str);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
|
||||
const result: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(parsed)) {
|
||||
result[key] = String(value);
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function getByPath(obj: unknown, path?: string): unknown {
|
||||
if (!path?.trim()) return obj;
|
||||
return path.split(".").reduce<unknown>((acc, key) => {
|
||||
if (acc == null || typeof acc !== "object") return undefined;
|
||||
return (acc as Record<string, unknown>)[key];
|
||||
}, obj);
|
||||
}
|
||||
|
||||
function formatDisplayValue(value: unknown): string {
|
||||
if (value == null) return "—";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function useSubFetchExecutor() {
|
||||
const definitionId = useWidgetDefinitionId();
|
||||
const mutation = clientApi.widget.customApi.subFetch.useMutation();
|
||||
|
||||
const execute = useCallback(
|
||||
async (params: { url: string; method?: string; body?: string; headers?: string }): Promise<SubFetchResult> => {
|
||||
if (!definitionId) {
|
||||
return { ok: false as const, status: 0, data: null, error: "Widget definition not available" };
|
||||
}
|
||||
if (!checkRateLimit(definitionId)) {
|
||||
return { ok: false as const, status: 0, data: null, error: "Rate limit exceeded (10 calls/minute)" };
|
||||
}
|
||||
|
||||
return mutation.mutateAsync({
|
||||
definitionId,
|
||||
url: params.url,
|
||||
method: parseMethod(params.method),
|
||||
body: params.body,
|
||||
headers: parseJsonRecord(params.headers),
|
||||
});
|
||||
},
|
||||
[definitionId, mutation],
|
||||
);
|
||||
|
||||
return { execute, isPending: mutation.isPending };
|
||||
}
|
||||
|
||||
export interface SubFetchProps {
|
||||
url: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
headers?: string;
|
||||
trigger?: "auto" | "manual";
|
||||
label?: string;
|
||||
color?: string;
|
||||
variant?: string;
|
||||
children?: ReactNode;
|
||||
loadingText?: string;
|
||||
errorText?: string;
|
||||
display?: "json" | "text";
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export function SubFetch({
|
||||
url,
|
||||
method,
|
||||
body,
|
||||
headers,
|
||||
trigger = "auto",
|
||||
label = "Fetch",
|
||||
color = "blue",
|
||||
variant = "filled",
|
||||
children,
|
||||
loadingText = "Loading...",
|
||||
errorText,
|
||||
display,
|
||||
path,
|
||||
}: SubFetchProps) {
|
||||
const { execute, isPending } = useSubFetchExecutor();
|
||||
const [subData, setSubData] = useState<unknown>(undefined);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [fetched, setFetched] = useState(false);
|
||||
|
||||
const runFetch = useCallback(async () => {
|
||||
setError(null);
|
||||
const result = await execute({ url, method, body, headers });
|
||||
if (result.ok) {
|
||||
setSubData(result.data);
|
||||
setFetched(true);
|
||||
} else {
|
||||
setError(result.error ?? errorText ?? `Request failed (${result.status})`);
|
||||
setFetched(true);
|
||||
}
|
||||
}, [execute, url, method, body, headers, errorText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (trigger === "auto") {
|
||||
void runFetch();
|
||||
}
|
||||
}, [trigger, runFetch]);
|
||||
|
||||
if (trigger === "manual" && !fetched && !isPending) {
|
||||
return (
|
||||
<Button color={color} variant={variant as never} onClick={() => void runFetch()} loading={isPending}>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div>
|
||||
<Skeleton height={8} radius="xl" mb="xs" />
|
||||
<Text size="xs" c="dimmed">
|
||||
{loadingText}
|
||||
</Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs">{error}</Text>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
const contextValue = subData;
|
||||
|
||||
if (display === "json") {
|
||||
return (
|
||||
<SubFetchDataContext.Provider value={contextValue}>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{JSON.stringify(subData, null, 2)}
|
||||
</Code>
|
||||
</SubFetchDataContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
if (display === "text" && path) {
|
||||
return (
|
||||
<SubFetchDataContext.Provider value={contextValue}>
|
||||
<Text size="sm">{formatDisplayValue(getByPath(subData, path))}</Text>
|
||||
</SubFetchDataContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
if (!children) {
|
||||
return (
|
||||
<SubFetchDataContext.Provider value={contextValue}>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{JSON.stringify(subData, null, 2)}
|
||||
</Code>
|
||||
</SubFetchDataContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
return <SubFetchDataContext.Provider value={contextValue}>{children}</SubFetchDataContext.Provider>;
|
||||
}
|
||||
|
||||
export interface SubDataProps {
|
||||
path?: string;
|
||||
as?: string;
|
||||
order?: number;
|
||||
size?: string;
|
||||
color?: string;
|
||||
variant?: string;
|
||||
fw?: number;
|
||||
c?: string;
|
||||
}
|
||||
|
||||
|
||||
export function SubData({ path, as = "Text", ...props }: SubDataProps) {
|
||||
const subData = useContext(SubFetchDataContext);
|
||||
const value = getByPath(subData, path);
|
||||
|
||||
if (value === undefined && path) {
|
||||
return (
|
||||
<Text size="xs" c="dimmed">
|
||||
—
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
const displayValue = as === "Code" ? JSON.stringify(value, null, 2) : formatDisplayValue(value);
|
||||
|
||||
if (as === "Title") {
|
||||
return (
|
||||
<Title order={(props.order as 1 | 2 | 3 | 4 | 5 | 6) ?? 3} c={props.c}>
|
||||
{displayValue}
|
||||
</Title>
|
||||
);
|
||||
}
|
||||
|
||||
if (as === "Badge") {
|
||||
return (
|
||||
<Badge color={props.color} variant={props.variant as never} size={props.size as never}>
|
||||
{displayValue}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (as === "Code") {
|
||||
return <Code block>{displayValue}</Code>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Text size={props.size as never} fw={props.fw} c={props.c}>
|
||||
{displayValue}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ActionButtonProps {
|
||||
url: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
headers?: string;
|
||||
label: string;
|
||||
color?: string;
|
||||
variant?: string;
|
||||
size?: string;
|
||||
confirmMessage?: string;
|
||||
successMessage?: string;
|
||||
icon?: string;
|
||||
fullWidth?: boolean | string;
|
||||
disabled?: boolean | string;
|
||||
}
|
||||
|
||||
export function ActionButton({
|
||||
url,
|
||||
method = "POST",
|
||||
body,
|
||||
headers,
|
||||
label,
|
||||
color = "blue",
|
||||
variant = "filled",
|
||||
size = "sm",
|
||||
confirmMessage,
|
||||
successMessage,
|
||||
icon,
|
||||
fullWidth,
|
||||
disabled,
|
||||
}: ActionButtonProps) {
|
||||
const { execute, isPending } = useSubFetchExecutor();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const Icon = icon ? ICON_MAP[icon.toLowerCase()] : undefined;
|
||||
|
||||
const runAction = async () => {
|
||||
const result = await execute({ url, method, body, headers });
|
||||
if (result.ok) {
|
||||
if (successMessage) {
|
||||
showSuccessNotification({ title: label, message: successMessage });
|
||||
}
|
||||
} else {
|
||||
showErrorNotification({ title: label, message: result.error ?? `Request failed (${result.status})` });
|
||||
}
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
if (confirmMessage) {
|
||||
openConfirmModal({
|
||||
title: label,
|
||||
children: confirmMessage,
|
||||
onConfirm: () => void runAction(),
|
||||
});
|
||||
} else {
|
||||
void runAction();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
color={color}
|
||||
variant={variant as never}
|
||||
size={size as never}
|
||||
onClick={handleClick}
|
||||
loading={isPending}
|
||||
leftSection={Icon ? <Icon size={16} /> : undefined}
|
||||
fullWidth={parseBool(fullWidth)}
|
||||
disabled={parseBool(disabled)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ToggleSwitchProps {
|
||||
url: string;
|
||||
method?: string;
|
||||
onBody?: string;
|
||||
offBody?: string;
|
||||
initialValue?: boolean | string;
|
||||
label?: string;
|
||||
color?: string;
|
||||
size?: string;
|
||||
disabled?: boolean | string;
|
||||
}
|
||||
|
||||
export function ToggleSwitch({
|
||||
url,
|
||||
method = "POST",
|
||||
onBody,
|
||||
offBody,
|
||||
initialValue = false,
|
||||
label,
|
||||
color = "blue",
|
||||
size = "sm",
|
||||
disabled,
|
||||
}: ToggleSwitchProps) {
|
||||
const { execute, isPending } = useSubFetchExecutor();
|
||||
const [checked, setChecked] = useState(parseBool(initialValue));
|
||||
const pendingRef = useRef(false);
|
||||
|
||||
const handleChange = async (next: boolean) => {
|
||||
if (pendingRef.current) return;
|
||||
pendingRef.current = true;
|
||||
const prev = checked;
|
||||
setChecked(next);
|
||||
|
||||
const result = await execute({
|
||||
url,
|
||||
method,
|
||||
body: next ? onBody : offBody,
|
||||
});
|
||||
|
||||
pendingRef.current = false;
|
||||
if (!result.ok) {
|
||||
setChecked(prev);
|
||||
showErrorNotification({ title: label ?? "Toggle", message: result.error ?? "Request failed" });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Switch
|
||||
label={label}
|
||||
color={color}
|
||||
size={size as never}
|
||||
checked={checked}
|
||||
onChange={(event) => void handleChange(event.currentTarget.checked)}
|
||||
disabled={parseBool(disabled) || isPending}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export interface RefreshButtonProps {
|
||||
label?: string;
|
||||
color?: string;
|
||||
variant?: string;
|
||||
size?: string;
|
||||
}
|
||||
|
||||
export function RefreshButton({
|
||||
label = "Refresh",
|
||||
color = "blue",
|
||||
variant = "light",
|
||||
size = "sm",
|
||||
}: RefreshButtonProps) {
|
||||
const definitionId = useWidgetDefinitionId();
|
||||
const utils = clientApi.useUtils();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleRefresh = async () => {
|
||||
if (!definitionId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await utils.widget.customApi.getData.invalidate({ definitionId });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
color={color}
|
||||
variant={variant as never}
|
||||
size={size as never}
|
||||
leftSection={<IconRefresh size={16} />}
|
||||
onClick={() => void handleRefresh()}
|
||||
loading={loading}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,60 +1,99 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { createElement } from "react";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, useState } from "react";
|
||||
import {
|
||||
Stack,
|
||||
Group,
|
||||
Flex,
|
||||
Grid,
|
||||
SimpleGrid,
|
||||
Center,
|
||||
Space,
|
||||
Container,
|
||||
AspectRatio,
|
||||
Text,
|
||||
Title,
|
||||
Code,
|
||||
Highlight,
|
||||
Mark,
|
||||
Kbd,
|
||||
Blockquote,
|
||||
Anchor,
|
||||
NumberFormatter,
|
||||
Badge,
|
||||
Card,
|
||||
Paper,
|
||||
Alert,
|
||||
ThemeIcon,
|
||||
ColorSwatch,
|
||||
Table,
|
||||
List,
|
||||
Timeline,
|
||||
Accordion,
|
||||
Indicator,
|
||||
Pill,
|
||||
Spoiler,
|
||||
Progress,
|
||||
RingProgress,
|
||||
Skeleton,
|
||||
Loader,
|
||||
Image,
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Anchor,
|
||||
AspectRatio,
|
||||
Avatar,
|
||||
BackgroundImage,
|
||||
Tooltip,
|
||||
Badge,
|
||||
Blockquote,
|
||||
Box,
|
||||
Breadcrumbs,
|
||||
Burger,
|
||||
Button,
|
||||
Card,
|
||||
Center,
|
||||
Chip,
|
||||
CloseButton,
|
||||
Code,
|
||||
Collapse,
|
||||
ColorSwatch,
|
||||
Container,
|
||||
CopyButton,
|
||||
DataList,
|
||||
Divider,
|
||||
EmptyState,
|
||||
Fieldset,
|
||||
Flex,
|
||||
Grid,
|
||||
Group,
|
||||
Highlight,
|
||||
HoverCard,
|
||||
Image,
|
||||
Indicator,
|
||||
Kbd,
|
||||
List,
|
||||
Loader,
|
||||
Mark,
|
||||
Marquee,
|
||||
Menu,
|
||||
NavLink,
|
||||
Notification,
|
||||
NumberFormatter,
|
||||
Overlay,
|
||||
Pagination,
|
||||
Paper,
|
||||
Pill,
|
||||
Progress,
|
||||
Rating,
|
||||
RingProgress,
|
||||
RollingNumber,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
SemiCircleProgress,
|
||||
SimpleGrid,
|
||||
Skeleton,
|
||||
Slider,
|
||||
Space,
|
||||
Spoiler,
|
||||
Stack,
|
||||
Stepper,
|
||||
Switch,
|
||||
Table,
|
||||
Tabs,
|
||||
Text,
|
||||
ThemeIcon,
|
||||
Timeline,
|
||||
Title,
|
||||
Tooltip,
|
||||
Transition,
|
||||
Tree,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
AreaChart,
|
||||
BarChart,
|
||||
LineChart,
|
||||
BarsList,
|
||||
BubbleChart,
|
||||
CompositeChart,
|
||||
DonutChart,
|
||||
FunnelChart,
|
||||
Heatmap,
|
||||
LineChart,
|
||||
PieChart,
|
||||
RadarChart,
|
||||
RadialBarChart,
|
||||
SankeyChart,
|
||||
ScatterChart,
|
||||
Sparkline,
|
||||
Treemap,
|
||||
} from "@mantine/charts";
|
||||
import { Calendar, DatePicker, MiniCalendar, TimeValue } from "@mantine/dates";
|
||||
|
||||
import { PaginatedList, TabsContainer, TabPanel, Collapsible, StatBar, TypeBadge } from "./jsx-interactive-components";
|
||||
import { SubFetch, SubData, ActionButton, ToggleSwitch, RefreshButton } from "./jsx-sub-fetch";
|
||||
|
||||
const SAFE_URL_PATTERN = /^https?:\/\//i;
|
||||
|
||||
@@ -63,13 +102,112 @@ function isSafeUrl(url: unknown): boolean {
|
||||
return SAFE_URL_PATTERN.test(url) || url.startsWith("/") || url.startsWith("#");
|
||||
}
|
||||
|
||||
function stripEventHandlers(props: Record<string, unknown>): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (/^on[A-Z]/.test(key)) continue;
|
||||
safe[key] = value;
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
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 });
|
||||
return createElement(Anchor as never, { ...stripEventHandlers(props), href: safeHref });
|
||||
}
|
||||
|
||||
function SafeNavLink(props: Record<string, unknown>) {
|
||||
const href = props.href;
|
||||
const safeHref = href && isSafeUrl(href) ? href : undefined;
|
||||
return createElement(NavLink as never, { ...stripEventHandlers(props), href: safeHref });
|
||||
}
|
||||
|
||||
function SafeButton(props: Record<string, unknown>) {
|
||||
return createElement(Button as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeActionIcon(props: Record<string, unknown>) {
|
||||
return createElement(ActionIcon as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeBurger(props: Record<string, unknown>) {
|
||||
return createElement(Burger as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeCloseButton(props: Record<string, unknown>) {
|
||||
return createElement(CloseButton as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeChip(props: Record<string, unknown>) {
|
||||
return createElement(Chip as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeNotification(props: Record<string, unknown>) {
|
||||
return createElement(Notification as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeRating(props: Record<string, unknown>) {
|
||||
return createElement(Rating as never, { ...stripEventHandlers(props), readOnly: true });
|
||||
}
|
||||
|
||||
function SafeSlider(props: Record<string, unknown>) {
|
||||
return createElement(Slider as never, { ...stripEventHandlers(props), readOnly: true });
|
||||
}
|
||||
|
||||
function SafeSwitch(props: Record<string, unknown>) {
|
||||
return createElement(Switch as never, { ...stripEventHandlers(props), readOnly: true });
|
||||
}
|
||||
|
||||
function SafeSegmentedControl(props: Record<string, unknown>) {
|
||||
return createElement(SegmentedControl as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafePagination(props: Record<string, unknown>) {
|
||||
return createElement(Pagination as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeStepper(props: Record<string, unknown>) {
|
||||
return createElement(Stepper as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeCalendar(props: Record<string, unknown>) {
|
||||
return createElement(Calendar as never, { ...stripEventHandlers(props), static: true });
|
||||
}
|
||||
|
||||
function SafeMiniCalendar(props: Record<string, unknown>) {
|
||||
return createElement(MiniCalendar as never, { ...stripEventHandlers(props), static: true });
|
||||
}
|
||||
|
||||
function SafeTree(props: Record<string, unknown>) {
|
||||
return createElement(Tree as never, stripEventHandlers(props));
|
||||
}
|
||||
|
||||
function SafeDatePicker(props: Record<string, unknown>) {
|
||||
return createElement(DatePicker as never, { ...stripEventHandlers(props), static: true });
|
||||
}
|
||||
|
||||
function SafeCopyButton({ value }: { value?: string; children?: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleCopy = () => {
|
||||
if (!value) return;
|
||||
void navigator.clipboard.writeText(value).then(() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
});
|
||||
};
|
||||
return createElement(Button as never, {
|
||||
size: "xs",
|
||||
variant: copied ? "filled" : "light",
|
||||
color: copied ? "teal" : "blue",
|
||||
onClick: handleCopy,
|
||||
children: copied ? "Copied!" : "Copy",
|
||||
});
|
||||
}
|
||||
|
||||
export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
// Layout
|
||||
Box,
|
||||
Stack,
|
||||
Group,
|
||||
Flex,
|
||||
@@ -80,6 +218,10 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
Space,
|
||||
Container,
|
||||
AspectRatio,
|
||||
Overlay,
|
||||
ScrollArea,
|
||||
|
||||
// Typography & text
|
||||
Text,
|
||||
Title,
|
||||
Code,
|
||||
@@ -89,6 +231,10 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
Blockquote,
|
||||
Anchor: SafeAnchor,
|
||||
NumberFormatter,
|
||||
Marquee,
|
||||
RollingNumber,
|
||||
|
||||
// Data display
|
||||
Badge,
|
||||
Card,
|
||||
"Card.Section": Card.Section,
|
||||
@@ -99,6 +245,8 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
Table,
|
||||
"Table.Thead": Table.Thead,
|
||||
"Table.Tbody": Table.Tbody,
|
||||
"Table.Tfoot": Table.Tfoot,
|
||||
"Table.Caption": Table.Caption,
|
||||
"Table.Tr": Table.Tr,
|
||||
"Table.Th": Table.Th,
|
||||
"Table.Td": Table.Td,
|
||||
@@ -116,6 +264,7 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
Progress,
|
||||
"Progress.Section": Progress.Section,
|
||||
RingProgress,
|
||||
SemiCircleProgress,
|
||||
Skeleton,
|
||||
Loader,
|
||||
Image,
|
||||
@@ -124,7 +273,59 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
BackgroundImage,
|
||||
Tooltip,
|
||||
Divider,
|
||||
ScrollArea,
|
||||
DataList,
|
||||
"DataList.Item": DataList.Item,
|
||||
"DataList.ItemLabel": DataList.ItemLabel,
|
||||
"DataList.ItemValue": DataList.ItemValue,
|
||||
EmptyState,
|
||||
"EmptyState.Indicator": EmptyState.Indicator,
|
||||
"EmptyState.Title": EmptyState.Title,
|
||||
"EmptyState.Description": EmptyState.Description,
|
||||
"EmptyState.Actions": EmptyState.Actions,
|
||||
Fieldset,
|
||||
Notification: SafeNotification,
|
||||
Rating: SafeRating,
|
||||
|
||||
// Navigation & structure
|
||||
Breadcrumbs,
|
||||
NavLink: SafeNavLink,
|
||||
Stepper: SafeStepper,
|
||||
"Stepper.Step": Stepper.Step,
|
||||
Tabs,
|
||||
"Tabs.List": Tabs.List,
|
||||
"Tabs.Tab": Tabs.Tab,
|
||||
"Tabs.Panel": Tabs.Panel,
|
||||
Tree: SafeTree,
|
||||
|
||||
// Interactive display (handlers stripped — wired via SubFetch separately)
|
||||
Button: SafeButton,
|
||||
ActionIcon: SafeActionIcon,
|
||||
Burger: SafeBurger,
|
||||
CloseButton: SafeCloseButton,
|
||||
Chip: SafeChip,
|
||||
"Chip.Group": Chip.Group,
|
||||
Pagination: SafePagination,
|
||||
SegmentedControl: SafeSegmentedControl,
|
||||
Slider: SafeSlider,
|
||||
Switch: SafeSwitch,
|
||||
|
||||
// Hover overlays & menus
|
||||
HoverCard,
|
||||
"HoverCard.Target": HoverCard.Target,
|
||||
"HoverCard.Dropdown": HoverCard.Dropdown,
|
||||
Menu,
|
||||
"Menu.Target": Menu.Target,
|
||||
"Menu.Dropdown": Menu.Dropdown,
|
||||
"Menu.Item": Menu.Item,
|
||||
"Menu.Label": Menu.Label,
|
||||
"Menu.Divider": Menu.Divider,
|
||||
|
||||
// Utility
|
||||
CopyButton: SafeCopyButton,
|
||||
Collapse,
|
||||
Transition,
|
||||
|
||||
// Charts
|
||||
AreaChart,
|
||||
BarChart,
|
||||
LineChart,
|
||||
@@ -133,12 +334,35 @@ export const WHITELISTED_COMPONENTS: Record<string, ComponentType<never>> = {
|
||||
RadarChart,
|
||||
RadialBarChart,
|
||||
Sparkline,
|
||||
BubbleChart,
|
||||
CompositeChart,
|
||||
FunnelChart,
|
||||
Heatmap,
|
||||
ScatterChart,
|
||||
SankeyChart,
|
||||
Treemap,
|
||||
BarsList,
|
||||
|
||||
// Dates
|
||||
Calendar: SafeCalendar,
|
||||
MiniCalendar: SafeMiniCalendar,
|
||||
DatePicker: SafeDatePicker,
|
||||
TimeValue,
|
||||
|
||||
// Custom interactive components (own state management)
|
||||
PaginatedList,
|
||||
TabsContainer,
|
||||
TabPanel,
|
||||
Collapsible,
|
||||
StatBar,
|
||||
TypeBadge,
|
||||
|
||||
// SubFetch — server-proxied HTTP from within templates
|
||||
SubFetch,
|
||||
SubData,
|
||||
ActionButton,
|
||||
ToggleSwitch,
|
||||
RefreshButton,
|
||||
};
|
||||
|
||||
function sanitizeData(obj: unknown): unknown {
|
||||
@@ -172,6 +396,7 @@ Object.freeze(safeJSON);
|
||||
|
||||
const safeArray: Record<string, unknown> = Object.create(null);
|
||||
safeArray.isArray = (v: unknown) => Array.isArray(v);
|
||||
safeArray.from = <T>(v: ArrayLike<T> | Iterable<T>) => Array.from(v);
|
||||
Object.freeze(safeArray);
|
||||
|
||||
const safeObject: Record<string, unknown> = Object.create(null);
|
||||
@@ -180,6 +405,20 @@ safeObject.values = (v: object) => Object.values(v);
|
||||
safeObject.entries = (v: object) => Object.entries(v);
|
||||
Object.freeze(safeObject);
|
||||
|
||||
const safeDate: Record<string, unknown> = Object.create(null);
|
||||
safeDate.now = () => Date.now();
|
||||
safeDate.create = (v?: string | number) => (v != null ? new Date(v) : new Date());
|
||||
safeDate.toISOString = (v: string | number) => new Date(v).toISOString();
|
||||
safeDate.toLocaleDateString = (v: string | number, locale?: string) =>
|
||||
new Date(v).toLocaleDateString(locale ?? "en-US");
|
||||
safeDate.toLocaleTimeString = (v: string | number, locale?: string) =>
|
||||
new Date(v).toLocaleTimeString(locale ?? "en-US");
|
||||
safeDate.getTime = (v: string | number) => new Date(v).getTime();
|
||||
safeDate.getYear = (v: string | number) => new Date(v).getFullYear();
|
||||
safeDate.getMonth = (v: string | number) => new Date(v).getMonth();
|
||||
safeDate.getDay = (v: string | number) => new Date(v).getDate();
|
||||
Object.freeze(safeDate);
|
||||
|
||||
export const SAFE_BINDINGS = (apiData: unknown) => ({
|
||||
data: sanitizeData(apiData),
|
||||
String: (v: unknown) => String(v),
|
||||
@@ -189,4 +428,11 @@ export const SAFE_BINDINGS = (apiData: unknown) => ({
|
||||
JSON: safeJSON,
|
||||
Array: safeArray,
|
||||
Object: safeObject,
|
||||
Date: safeDate,
|
||||
parseInt: (v: string, radix?: number) => parseInt(v, radix),
|
||||
parseFloat: (v: string) => parseFloat(v),
|
||||
encodeURIComponent: (v: string) => encodeURIComponent(v),
|
||||
decodeURIComponent: (v: string) => decodeURIComponent(v),
|
||||
isNaN: (v: unknown) => Number.isNaN(Number(v)),
|
||||
isFinite: (v: unknown) => Number.isFinite(Number(v)),
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
const WidgetDefinitionContext = createContext<string>("");
|
||||
|
||||
export function WidgetDefinitionProvider({
|
||||
definitionId,
|
||||
children,
|
||||
}: {
|
||||
definitionId: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return <WidgetDefinitionContext.Provider value={definitionId}>{children}</WidgetDefinitionContext.Provider>;
|
||||
}
|
||||
|
||||
export function useWidgetDefinitionId(): string {
|
||||
return useContext(WidgetDefinitionContext);
|
||||
}
|
||||
Reference in new issue
Block a user