feat(custom-widgets): add extensible widget platform
This commit is contained in:
1 parent
6cca757493
commit
8f152f1929
317 files changed
+32326
-1788
No files matched your search
@@ -18,10 +18,13 @@
|
||||
"./inputs/json-path-tree-picker": "./src/_inputs/json-path-tree-picker.tsx",
|
||||
"./custom-api/component": "./src/custom-api/component.tsx",
|
||||
"./custom-api/custom-jsx-display": "./src/custom-api/custom-jsx-display.tsx",
|
||||
"./custom-api/trusted-widget-preview": "./src/custom-api/trusted-widget-preview.tsx",
|
||||
"./custom-api/package-option-fields": "./src/custom-api/package-option-fields.tsx",
|
||||
"./custom-api/extract-display-data": "./src/custom-api/extract-display-data.ts",
|
||||
"./assistant/context": "./src/assistant/context.tsx",
|
||||
"./catalog": "./src/catalog.ts",
|
||||
"./definition": "./src/definition.ts",
|
||||
"./native-reference-starters": "./src/native-reference-starters.ts",
|
||||
"./errors": "./src/errors/component.tsx",
|
||||
"./manifest": "./src/manifest.ts",
|
||||
"./options": "./src/options.ts",
|
||||
@@ -64,6 +67,7 @@
|
||||
"@homarr/translation": "workspace:^0.1.0",
|
||||
"@homarr/ui": "workspace:^0.1.0",
|
||||
"@homarr/validation": "workspace:^0.1.0",
|
||||
"@homarr/widget-sdk": "workspace:^0.1.0",
|
||||
"@mantine/charts": "catalog:",
|
||||
"@mantine/core": "catalog:",
|
||||
"@mantine/dates": "catalog:",
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
Alert,
|
||||
ColorInput,
|
||||
MultiSelect,
|
||||
NumberInput,
|
||||
Select,
|
||||
Slider,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
Textarea,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { DateInput, TimeInput } from "@mantine/dates";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Accordion, Alert, MultiSelect, Select, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import type { CustomWidgetOption } from "@homarr/custom-widgets/core";
|
||||
import { normalizeCustomWidgetOptions, 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 { customWidgetPackageSchema } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { PackageOptionField, PackageOptionFields } from "../custom-api/package-option-fields";
|
||||
import { PackageConnectionBindings } from "../custom-api/package-connection-bindings";
|
||||
export { JsonOption } from "../custom-api/package-json-option";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
@@ -46,9 +35,19 @@ export const WidgetCustomWidgetConfigurationInput = ({
|
||||
);
|
||||
const definition = available.data?.find((candidate) => candidate.id === definitionId);
|
||||
const options = isRecord(definition?.options) ? (definition.options as Record<string, CustomWidgetOption>) : null;
|
||||
const packageDefinition = useMemo(() => {
|
||||
const entry: unknown = definition;
|
||||
if (!isRecord(entry) || entry.packageVersion !== 3) return;
|
||||
const connections = customWidgetPackageSchema.shape.connections.safeParse(entry.connections);
|
||||
const bindings = z.record(z.string(), z.string()).safeParse(entry.installationBindings);
|
||||
if (!connections.success || !bindings.success) return;
|
||||
return { connections: connections.data, installationBindings: bindings.data };
|
||||
}, [definition]);
|
||||
const isPackage = Boolean(packageDefinition);
|
||||
const definitionVersion = definition?.updatedAt instanceof Date ? definition.updatedAt.getTime() : undefined;
|
||||
const configurationVersion = form.values.options.configurationVersion;
|
||||
const needsDefinitionRepair = definitionVersion !== undefined && configurationVersion !== definitionVersion;
|
||||
const needsDefinitionRepair =
|
||||
!isPackage && definitionVersion !== undefined && configurationVersion !== definitionVersion;
|
||||
const effectiveConfiguration = useMemo(
|
||||
() => (options && needsDefinitionRepair ? normalizeCustomWidgetOptions(options, configuration) : configuration),
|
||||
[configuration, needsDefinitionRepair, options],
|
||||
@@ -71,6 +70,26 @@ export const WidgetCustomWidgetConfigurationInput = ({
|
||||
}, [form, issues, property]);
|
||||
|
||||
if (!definitionId || !options) return null;
|
||||
if (packageDefinition)
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<PackageConnectionBindings
|
||||
connections={packageDefinition.connections}
|
||||
installationBindings={packageDefinition.installationBindings}
|
||||
value={
|
||||
isRecord(form.values.options.connectionBindings)
|
||||
? (form.values.options.connectionBindings as Record<string, string>)
|
||||
: {}
|
||||
}
|
||||
onChange={(value) => form.setFieldValue("options.connectionBindings", value)}
|
||||
/>
|
||||
<PackageOptionFields
|
||||
schema={options}
|
||||
value={effectiveConfiguration}
|
||||
onChange={(value) => form.setFieldValue(`options.${property}`, value)}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
const entries = Object.entries(options);
|
||||
const regular = entries.filter(([, option]) => !option.advanced);
|
||||
const advanced = entries.filter(([, option]) => option.advanced);
|
||||
@@ -126,70 +145,16 @@ function OptionField({
|
||||
definitionId: string;
|
||||
}) {
|
||||
const form = useFormContext();
|
||||
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 (
|
||||
<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
|
||||
identity={`${definitionId}:${path}`}
|
||||
editorId={`${definitionId}-${path}-json-option`}
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
value={input.value}
|
||||
onChange={(value) => form.setFieldValue(path, value)}
|
||||
/>
|
||||
);
|
||||
return <TextInput {...common} type={option.control === "url" ? "url" : "text"} {...input} />;
|
||||
return (
|
||||
<PackageOptionField
|
||||
identity={`${definitionId}:${path}`}
|
||||
option={option}
|
||||
value={form.getInputProps(path).value}
|
||||
onChange={(value) => form.setFieldValue(path, value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DynamicOptionField({
|
||||
@@ -255,84 +220,6 @@ function DynamicOptionField({
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
export function JsonOption({
|
||||
identity,
|
||||
editorId,
|
||||
label,
|
||||
description,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
identity: string;
|
||||
editorId: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
value: unknown;
|
||||
onChange(value: unknown): void;
|
||||
}) {
|
||||
const serializedValue = JSON.stringify(value ?? null, null, 2);
|
||||
const [draft, setDraft] = useState(serializedValue);
|
||||
const [error, setError] = useState<string>();
|
||||
const synchronizedValueRef = useRef(serializedValue);
|
||||
const identityRef = useRef(identity);
|
||||
useEffect(() => {
|
||||
if (identityRef.current === identity && synchronizedValueRef.current === serializedValue) return;
|
||||
identityRef.current = identity;
|
||||
synchronizedValueRef.current = serializedValue;
|
||||
setDraft(serializedValue);
|
||||
setError(undefined);
|
||||
}, [identity, serializedValue]);
|
||||
return (
|
||||
<CustomWidgetCodeEditor
|
||||
id={editorId}
|
||||
label={label}
|
||||
description={description}
|
||||
language="json"
|
||||
value={draft}
|
||||
height="160px"
|
||||
error={error}
|
||||
onChange={(next) => {
|
||||
setDraft(next);
|
||||
try {
|
||||
const parsed = JSON.parse(next) as unknown;
|
||||
synchronizedValueRef.current = JSON.stringify(parsed ?? null, null, 2);
|
||||
onChange(parsed);
|
||||
setError(undefined);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Invalid JSON");
|
||||
}
|
||||
}}
|
||||
messages={editorMessages}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function coerceChoice(value: string | null, option: CustomWidgetOption) {
|
||||
if (value === null) return null;
|
||||
return typeof option.default === "number" ||
|
||||
|
||||
@@ -77,6 +77,7 @@ export const WidgetCustomWidgetSelectInput = ({
|
||||
if (!definition || definition.migrationRequired) return;
|
||||
form.setFieldValue(`options.${property}`, val);
|
||||
form.setFieldValue("options.configuration", definition?.defaultOptions ?? {});
|
||||
form.setFieldValue("options.connectionBindings", {});
|
||||
form.setFieldValue(
|
||||
"options.configurationVersion",
|
||||
definition?.updatedAt instanceof Date ? definition.updatedAt.getTime() : Date.now(),
|
||||
@@ -132,12 +133,21 @@ export const WidgetCustomWidgetSelectInput = ({
|
||||
{labels("migrationRequired")}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge size="xs" variant="light">
|
||||
{labels("sources", { count: def.sources.length })}
|
||||
</Badge>
|
||||
<Badge size="xs" variant="light" color="gray">
|
||||
{labels("requests", { count: def.requestCapabilities.length })}
|
||||
</Badge>
|
||||
{"packageVersion" in def && def.packageVersion === 3 && (
|
||||
<Badge size="xs" variant="light" color="violet">
|
||||
{labels("trustedPackage")}
|
||||
</Badge>
|
||||
)}
|
||||
{!("packageVersion" in def) && (
|
||||
<Badge size="xs" variant="light">
|
||||
{labels("sources", { count: def.sources.length })}
|
||||
</Badge>
|
||||
)}
|
||||
{!("packageVersion" in def) && (
|
||||
<Badge size="xs" variant="light" color="gray">
|
||||
{labels("requests", { count: def.requestCapabilities.length })}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
@@ -1,27 +1,13 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useWidgetNow } from "@homarr/widget-sdk";
|
||||
|
||||
export const useCurrentTime = ({ showSeconds }: { showSeconds: boolean }) => {
|
||||
const [time, setTime] = useState<Date | null>(null);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval>>(null);
|
||||
const intervalMultiplier = useMemo(() => (showSeconds ? 1 : 60), [showSeconds]);
|
||||
|
||||
useEffect(() => {
|
||||
setTime(new Date());
|
||||
timeoutRef.current = setTimeout(
|
||||
() => {
|
||||
setTime(new Date());
|
||||
intervalRef.current = setInterval(() => setTime(new Date()), intervalMultiplier * 1000);
|
||||
},
|
||||
intervalMultiplier * 1000 - (1000 * (showSeconds ? 0 : dayjs().second()) + dayjs().millisecond()),
|
||||
);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [intervalMultiplier, showSeconds]);
|
||||
|
||||
return time;
|
||||
let interval = 60_000;
|
||||
if (showSeconds) interval = 1000;
|
||||
const timestamp = useWidgetNow(interval);
|
||||
return useMemo(() => {
|
||||
if (timestamp === null) return null;
|
||||
return new Date(timestamp);
|
||||
}, [timestamp]);
|
||||
};
|
||||
@@ -1,95 +0,0 @@
|
||||
.homarr-data-table,
|
||||
.homarr-data-table .mantine-datatable-table,
|
||||
.homarr-data-table .mantine-datatable-table thead,
|
||||
.homarr-data-table .mantine-datatable-table tbody,
|
||||
.homarr-data-table .mantine-datatable-table tfoot,
|
||||
.homarr-data-table th,
|
||||
.homarr-data-table td {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-table tr {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-table {
|
||||
width: 100% !important;
|
||||
max-width: 100%;
|
||||
table-layout: fixed !important;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-table tbody tr:hover {
|
||||
background-color: color-mix(in srgb, var(--mantine-color-default-hover) 40%, transparent) !important;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-scroll-area-scrollbar[data-state="visible"]:hover {
|
||||
@mixin light {
|
||||
background-color: var(--mantine-color-gray-0);
|
||||
}
|
||||
|
||||
@mixin dark {
|
||||
background-color: var(--mantine-color-dark-8);
|
||||
}
|
||||
}
|
||||
|
||||
.homarr-data-table th {
|
||||
padding: 0;
|
||||
white-space: nowrap;
|
||||
background-color: color-mix(in srgb, var(--mantine-color-body) 60%, transparent) !important;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.homarr-data-table td {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Lets a cell's content (e.g. an oversized action icon) visually overflow its own box without
|
||||
growing it - used to make a per-row icon look bigger without inflating row height, since the
|
||||
icon is pulled out of flow via absolute positioning rather than actually being a bigger cell. */
|
||||
.homarr-data-table td.docker-actions-cell {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.homarr-data-table td .mantine-Text-root,
|
||||
.homarr-data-table td .mantine-Group-root {
|
||||
white-space: nowrap;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-header-cell-sortable-icon,
|
||||
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon {
|
||||
opacity: 0;
|
||||
transition: opacity 150ms ease-out;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-header-cell-sortable-group {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-header-cell-sortable-unsorted-icon {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon svg,
|
||||
.homarr-data-table .mantine-datatable-header-cell-sortable-text svg,
|
||||
.homarr-data-table .mantine-datatable-header-cell-sortable-icon svg {
|
||||
width: var(--mantine-font-size-md);
|
||||
height: var(--mantine-font-size-md);
|
||||
}
|
||||
|
||||
.homarr-data-table th:hover .mantine-datatable-header-cell-sortable-icon,
|
||||
.homarr-data-table th:hover .mantine-datatable-header-cell-draggable-action-icon,
|
||||
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon:focus-visible,
|
||||
.homarr-data-table .mantine-datatable-header-cell-drag-over .mantine-datatable-header-cell-draggable-action-icon {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.homarr-data-table-row-cursor-default .mantine-datatable-context-menu-cursor {
|
||||
cursor: default;
|
||||
}
|
||||
@@ -1,161 +1 @@
|
||||
"use client";
|
||||
|
||||
import "./homarr-data-table.css";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { DataTableColumn, DataTableProps } from "mantine-datatable";
|
||||
import { DataTable } from "mantine-datatable";
|
||||
|
||||
import { scrollAreaDefaultProps } from "@homarr/ui";
|
||||
|
||||
const fallbackColumnWidth = 60;
|
||||
|
||||
const getColumnWidth = (width: string | number | undefined): number => {
|
||||
if (typeof width === "number" && Number.isFinite(width) && width > 0) return width;
|
||||
if (typeof width === "string") {
|
||||
const parsedWidth = Number.parseFloat(width);
|
||||
if (Number.isFinite(parsedWidth) && parsedWidth > 0) return parsedWidth;
|
||||
}
|
||||
return fallbackColumnWidth;
|
||||
};
|
||||
|
||||
type HomarrDataTableProps<T> = DataTableProps<T> & {
|
||||
columns: DataTableColumn<T>[];
|
||||
groups?: never;
|
||||
isEditMode: boolean;
|
||||
cellPadding: string;
|
||||
rowCursor?: "auto" | "default";
|
||||
};
|
||||
|
||||
export function HomarrDataTable<T>({
|
||||
isEditMode,
|
||||
cellPadding,
|
||||
rowCursor = "auto",
|
||||
className,
|
||||
columns,
|
||||
defaultColumnProps,
|
||||
onMouseDownCapture,
|
||||
scrollAreaProps,
|
||||
style,
|
||||
...props
|
||||
}: HomarrDataTableProps<T>) {
|
||||
const [resizePreviewWidths, setResizePreviewWidths] = useState<Record<string, number>>();
|
||||
const removeResizeListeners = useRef<() => void>(() => undefined);
|
||||
useEffect(() => () => removeResizeListeners.current(), []);
|
||||
|
||||
const handleMouseDownCapture = useCallback(
|
||||
(event: React.MouseEvent<HTMLTableElement>) => {
|
||||
onMouseDownCapture?.(event);
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
|
||||
const handle = target.closest(".mantine-datatable-header-resizable-handle");
|
||||
const currentCell = handle?.closest<HTMLTableCellElement>("th[data-accessor]");
|
||||
const headerRow = currentCell?.parentElement;
|
||||
if (!currentCell || !headerRow) return;
|
||||
|
||||
const cells = Array.from(headerRow.querySelectorAll<HTMLTableCellElement>("th[data-accessor]"));
|
||||
const currentIndex = cells.indexOf(currentCell);
|
||||
const nextCell = cells[currentIndex + 1];
|
||||
const currentAccessor = currentCell.dataset.accessor;
|
||||
const nextAccessor = nextCell?.dataset.accessor;
|
||||
if (!nextCell || !currentAccessor || !nextAccessor) return;
|
||||
|
||||
const widths = Object.fromEntries(
|
||||
cells.flatMap((cell) => {
|
||||
const accessor = cell.dataset.accessor;
|
||||
if (!accessor) return [];
|
||||
return [[accessor, cell.getBoundingClientRect().width]];
|
||||
}),
|
||||
);
|
||||
const currentWidth = widths[currentAccessor];
|
||||
const nextWidth = widths[nextAccessor];
|
||||
if (currentWidth === undefined || nextWidth === undefined) return;
|
||||
|
||||
const visualScale = currentCell.getBoundingClientRect().width / currentCell.offsetWidth;
|
||||
const minimumWidth = fallbackColumnWidth * visualScale;
|
||||
const startX = event.clientX;
|
||||
|
||||
removeResizeListeners.current();
|
||||
const handleMouseMove = (moveEvent: MouseEvent) => {
|
||||
const delta = Math.min(
|
||||
nextWidth - minimumWidth,
|
||||
Math.max(minimumWidth - currentWidth, moveEvent.clientX - startX),
|
||||
);
|
||||
setResizePreviewWidths({
|
||||
...widths,
|
||||
[currentAccessor]: currentWidth + delta,
|
||||
[nextAccessor]: nextWidth - delta,
|
||||
});
|
||||
};
|
||||
const handleResizeEnd = () => {
|
||||
removeResizeListeners.current();
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => setResizePreviewWidths(undefined)));
|
||||
};
|
||||
removeResizeListeners.current = () => {
|
||||
window.removeEventListener("mousemove", handleMouseMove);
|
||||
window.removeEventListener("mouseup", handleResizeEnd);
|
||||
window.removeEventListener("blur", handleResizeEnd);
|
||||
};
|
||||
window.addEventListener("mousemove", handleMouseMove);
|
||||
window.addEventListener("mouseup", handleResizeEnd);
|
||||
window.addEventListener("blur", handleResizeEnd);
|
||||
},
|
||||
[onMouseDownCapture],
|
||||
);
|
||||
|
||||
const mergedClassName = [
|
||||
"homarr-data-table",
|
||||
rowCursor === "default" ? "homarr-data-table-row-cursor-default" : undefined,
|
||||
className,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
const fittedColumns = useMemo(() => {
|
||||
const visibleColumns = columns.filter(({ hidden }) => !hidden);
|
||||
const getRenderedWidth = (column: DataTableColumn<T>) =>
|
||||
resizePreviewWidths?.[String(column.accessor)] ?? getColumnWidth(column.width);
|
||||
const totalWidth = visibleColumns.reduce((total, column) => total + getRenderedWidth(column), 0);
|
||||
if (totalWidth <= 0) return columns;
|
||||
|
||||
return columns.map((column) => {
|
||||
if (column.hidden) return column;
|
||||
|
||||
const width = `${(getRenderedWidth(column) / totalWidth) * 100}%`;
|
||||
const fittedWidth = { width, minWidth: width, maxWidth: width };
|
||||
const cellsStyle = column.cellsStyle ?? defaultColumnProps?.cellsStyle;
|
||||
return {
|
||||
...column,
|
||||
titleStyle: [column.titleStyle, fittedWidth],
|
||||
cellsStyle: (record: T, index: number) => [cellsStyle?.(record, index), fittedWidth, { padding: cellPadding }],
|
||||
};
|
||||
});
|
||||
}, [cellPadding, columns, defaultColumnProps?.cellsStyle, resizePreviewWidths]);
|
||||
|
||||
return (
|
||||
<DataTable<T>
|
||||
withTableBorder={false}
|
||||
borderRadius={0}
|
||||
highlightOnHover
|
||||
highlightOnHoverColor={{ dark: "dark.5", light: "gray.1" }}
|
||||
verticalAlign="center"
|
||||
loaderBackgroundBlur={2}
|
||||
textSelectionDisabled
|
||||
height="100%"
|
||||
{...props}
|
||||
striped={false}
|
||||
columns={fittedColumns}
|
||||
onMouseDownCapture={handleMouseDownCapture}
|
||||
className={mergedClassName}
|
||||
style={[{ pointerEvents: isEditMode ? "none" : undefined }, style]}
|
||||
defaultColumnProps={{
|
||||
...defaultColumnProps,
|
||||
noWrap: defaultColumnProps?.noWrap ?? true,
|
||||
draggable: true,
|
||||
resizable: true,
|
||||
cellsStyle: defaultColumnProps?.cellsStyle ?? (() => ({ padding: cellPadding })),
|
||||
}}
|
||||
scrollAreaProps={{ ...scrollAreaDefaultProps, ...scrollAreaProps }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export { HomarrDataTable } from "@homarr/widget-sdk/table";
|
||||
@@ -1,146 +1 @@
|
||||
"use client";
|
||||
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
interface StoredWidgetState {
|
||||
version: number;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
interface UseLocalWidgetStateOptions<T> {
|
||||
key: string | undefined;
|
||||
version: number;
|
||||
defaultValue: T | (() => T);
|
||||
validate?: (value: unknown) => value is T;
|
||||
migrate?: (value: unknown, storedVersion: number) => T | undefined;
|
||||
}
|
||||
|
||||
const resolveDefaultValue = <T>(value: T | (() => T)): T =>
|
||||
typeof value === "function" ? (value as () => T)() : value;
|
||||
|
||||
export const serializeLocalWidgetState = <T>(version: number, value: T): string => JSON.stringify({ version, value });
|
||||
|
||||
export const parseLocalWidgetState = <T>(
|
||||
serialized: string,
|
||||
version: number,
|
||||
validate?: (value: unknown) => value is T,
|
||||
migrate?: (value: unknown, storedVersion: number) => T | undefined,
|
||||
): T | undefined => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(serialized);
|
||||
if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("value" in parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stored = parsed as StoredWidgetState;
|
||||
if (typeof stored.version !== "number") return undefined;
|
||||
if (stored.version !== version) {
|
||||
const migrated = migrate?.(stored.value, stored.version);
|
||||
if (migrated === undefined || (validate && !validate(migrated))) return undefined;
|
||||
return migrated;
|
||||
}
|
||||
if (validate && !validate(stored.value)) return undefined;
|
||||
return stored.value as T;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const useLocalWidgetState = <T>({
|
||||
key,
|
||||
version,
|
||||
defaultValue,
|
||||
validate,
|
||||
migrate,
|
||||
}: UseLocalWidgetStateOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void] => {
|
||||
const defaultValueRef = useRef(defaultValue);
|
||||
const validateRef = useRef(validate);
|
||||
const migrateRef = useRef(migrate);
|
||||
defaultValueRef.current = defaultValue;
|
||||
validateRef.current = validate;
|
||||
migrateRef.current = migrate;
|
||||
|
||||
const createDefaultValue = useCallback(() => resolveDefaultValue(defaultValueRef.current), []);
|
||||
const [value, setValueState] = useState<T>(createDefaultValue);
|
||||
const valueRef = useRef(value);
|
||||
|
||||
const setMemoryValue = useCallback((nextValue: T) => {
|
||||
valueRef.current = nextValue;
|
||||
setValueState(nextValue);
|
||||
}, []);
|
||||
|
||||
const removeStoredValue = useCallback(() => {
|
||||
if (!key) return;
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Storage can be unavailable in private or restricted browser contexts.
|
||||
}
|
||||
}, [key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const serialized = window.localStorage.getItem(key);
|
||||
if (serialized === null) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
const parsed = parseLocalWidgetState(serialized, version, validateRef.current, migrateRef.current);
|
||||
if (parsed === undefined) {
|
||||
window.localStorage.removeItem(key);
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
setMemoryValue(parsed);
|
||||
} catch {
|
||||
setMemoryValue(createDefaultValue());
|
||||
}
|
||||
}, [createDefaultValue, key, setMemoryValue, version]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.storageArea !== window.localStorage || event.key !== key) return;
|
||||
if (event.newValue === null) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parseLocalWidgetState(event.newValue, version, validateRef.current, migrateRef.current);
|
||||
if (parsed !== undefined) setMemoryValue(parsed);
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
return () => window.removeEventListener("storage", handleStorage);
|
||||
}, [createDefaultValue, key, setMemoryValue, version]);
|
||||
|
||||
const setValue: Dispatch<SetStateAction<T>> = useCallback(
|
||||
(nextValue) => {
|
||||
const resolved =
|
||||
typeof nextValue === "function" ? (nextValue as (previous: T) => T)(valueRef.current) : nextValue;
|
||||
if (Object.is(resolved, valueRef.current)) return;
|
||||
setMemoryValue(resolved);
|
||||
if (key) {
|
||||
try {
|
||||
window.localStorage.setItem(key, serializeLocalWidgetState(version, resolved));
|
||||
} catch {
|
||||
// Keep the in-memory state usable when persistence is unavailable.
|
||||
}
|
||||
}
|
||||
},
|
||||
[key, setMemoryValue, version],
|
||||
);
|
||||
|
||||
const resetValue = useCallback(() => {
|
||||
removeStoredValue();
|
||||
setMemoryValue(createDefaultValue());
|
||||
}, [createDefaultValue, removeStoredValue, setMemoryValue]);
|
||||
|
||||
return [value, setValue, resetValue];
|
||||
};
|
||||
export { parseLocalWidgetState, serializeLocalWidgetState, useLocalWidgetState } from "@homarr/widget-sdk";
|
||||
@@ -1,235 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import type { DataTableColumn } from "mantine-datatable";
|
||||
import { useDataTableColumns } from "mantine-datatable";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
interface TableLayoutOptions extends Record<string, unknown> {
|
||||
columnOrder?: string;
|
||||
columnWidths?: string;
|
||||
}
|
||||
|
||||
interface PendingTableLayout {
|
||||
layout: TableLayoutOptions;
|
||||
onLayoutChange: (layout: TableLayoutOptions) => void;
|
||||
storeKey: string;
|
||||
}
|
||||
|
||||
interface UseTableLayoutPersistenceProps {
|
||||
boardId: string | undefined;
|
||||
hasChangeAccess: boolean;
|
||||
itemId: string | undefined;
|
||||
saveItemOptions: (input: { boardId: string; itemId: string; newOptions: TableLayoutOptions }) => void;
|
||||
setOptions: (input: { newOptions: TableLayoutOptions }) => void;
|
||||
}
|
||||
|
||||
interface UsePersistedTableLayoutProps<T> {
|
||||
columns: DataTableColumn<T>[];
|
||||
columnAccessors: readonly string[];
|
||||
columnOrder: string;
|
||||
columnWidths: string;
|
||||
itemId: string | undefined;
|
||||
storeKeyPrefix: string;
|
||||
onLayoutChange: (layout: TableLayoutOptions) => void;
|
||||
}
|
||||
|
||||
const layoutSaveDelay = 350;
|
||||
|
||||
export const useTableLayoutPersistence = ({
|
||||
boardId,
|
||||
hasChangeAccess,
|
||||
itemId,
|
||||
saveItemOptions,
|
||||
setOptions,
|
||||
}: UseTableLayoutPersistenceProps) =>
|
||||
useCallback(
|
||||
(newOptions: TableLayoutOptions) => {
|
||||
setOptions({ newOptions });
|
||||
if (hasChangeAccess && boardId && itemId) saveItemOptions({ boardId, itemId, newOptions });
|
||||
},
|
||||
[boardId, hasChangeAccess, itemId, saveItemOptions, setOptions],
|
||||
);
|
||||
|
||||
const toPixelWidth = (width: string | number): number | undefined => {
|
||||
if (typeof width === "number" && Number.isFinite(width) && width > 0) return width;
|
||||
if (typeof width !== "string" || !width.endsWith("px")) return undefined;
|
||||
|
||||
const parsedWidth = Number.parseInt(width, 10);
|
||||
return Number.isFinite(parsedWidth) && parsedWidth > 0 ? parsedWidth : undefined;
|
||||
};
|
||||
|
||||
const getColumnWidthMap = (
|
||||
columnsWidth: Record<string, string | number>[],
|
||||
visibleAccessorSet: ReadonlySet<string>,
|
||||
): Record<string, number> => {
|
||||
const widths: Record<string, number> = {};
|
||||
for (const entry of columnsWidth) {
|
||||
for (const [accessor, width] of Object.entries(entry)) {
|
||||
if (!visibleAccessorSet.has(accessor)) continue;
|
||||
const pixelWidth = toPixelWidth(width);
|
||||
if (pixelWidth !== undefined) widths[accessor] = pixelWidth;
|
||||
}
|
||||
}
|
||||
return widths;
|
||||
};
|
||||
|
||||
export const parseColumnOrder = (value: string, columnAccessors: readonly string[]): string[] => {
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
|
||||
const allowed = new Set(columnAccessors);
|
||||
return parsed.filter(
|
||||
(accessor, index): accessor is string =>
|
||||
typeof accessor === "string" && allowed.has(accessor) && parsed.indexOf(accessor) === index,
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const parseColumnWidths = (value: string, columnAccessors: readonly string[]): Record<string, number> => {
|
||||
if (!value) return {};
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!isRecord(parsed)) return {};
|
||||
|
||||
const allowed = new Set(columnAccessors);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed).filter(
|
||||
(entry): entry is [string, number] =>
|
||||
allowed.has(entry[0]) && typeof entry[1] === "number" && Number.isFinite(entry[1]) && entry[1] > 0,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
export const usePersistedTableLayout = <T>({
|
||||
columns,
|
||||
columnAccessors,
|
||||
columnOrder,
|
||||
columnWidths,
|
||||
itemId,
|
||||
storeKeyPrefix,
|
||||
onLayoutChange,
|
||||
}: UsePersistedTableLayoutProps<T>) => {
|
||||
const savedOrder = useMemo(() => parseColumnOrder(columnOrder, columnAccessors), [columnAccessors, columnOrder]);
|
||||
const savedWidths = useMemo(() => parseColumnWidths(columnWidths, columnAccessors), [columnAccessors, columnWidths]);
|
||||
const visibleAccessors = useMemo(() => columns.map(({ accessor }) => String(accessor)), [columns]);
|
||||
const visibleAccessorSet = useMemo(() => new Set(visibleAccessors), [visibleAccessors]);
|
||||
const restoredOrder = useMemo(
|
||||
() => [
|
||||
...savedOrder.filter((accessor) => visibleAccessorSet.has(accessor)),
|
||||
...visibleAccessors.filter((accessor) => !savedOrder.includes(accessor)),
|
||||
],
|
||||
[savedOrder, visibleAccessors, visibleAccessorSet],
|
||||
);
|
||||
const storeKey = `${storeKeyPrefix}-${itemId ?? "preview"}-${[...visibleAccessors].toSorted().join(",")}`;
|
||||
const { effectiveColumns, columnsOrder, columnsWidth, setColumnsOrder, setMultipleColumnWidths } =
|
||||
useDataTableColumns<T>({
|
||||
key: storeKey,
|
||||
columns,
|
||||
});
|
||||
|
||||
const lastStoreKey = useRef(storeKey);
|
||||
const hydrated = useRef(false);
|
||||
const previousOrder = useRef(columnsOrder);
|
||||
const previousWidths = useRef(columnsWidth);
|
||||
useEffect(() => {
|
||||
if (lastStoreKey.current !== storeKey) {
|
||||
lastStoreKey.current = storeKey;
|
||||
hydrated.current = false;
|
||||
}
|
||||
if (hydrated.current) return;
|
||||
|
||||
const orderMatches =
|
||||
columnsOrder.length === restoredOrder.length &&
|
||||
columnsOrder.every((accessor, index) => accessor === restoredOrder[index]);
|
||||
const currentWidths = getColumnWidthMap(columnsWidth, visibleAccessorSet);
|
||||
const visibleWidths = Object.entries(savedWidths).filter(([accessor]) => visibleAccessorSet.has(accessor));
|
||||
const widthsMatch = visibleWidths.every(([accessor, width]) => currentWidths[accessor] === width);
|
||||
|
||||
if (orderMatches && widthsMatch) {
|
||||
previousOrder.current = columnsOrder;
|
||||
previousWidths.current = columnsWidth;
|
||||
hydrated.current = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!orderMatches) setColumnsOrder(restoredOrder);
|
||||
if (!widthsMatch) {
|
||||
setMultipleColumnWidths(visibleWidths.map(([accessor, width]) => ({ accessor, width })));
|
||||
}
|
||||
}, [
|
||||
columnsOrder,
|
||||
columnsWidth,
|
||||
restoredOrder,
|
||||
savedWidths,
|
||||
setColumnsOrder,
|
||||
setMultipleColumnWidths,
|
||||
storeKey,
|
||||
visibleAccessorSet,
|
||||
]);
|
||||
|
||||
const pendingLayout = useRef<PendingTableLayout | undefined>(undefined);
|
||||
const saveTimeout = useRef<number | undefined>(undefined);
|
||||
const flushPendingLayout = useCallback(() => {
|
||||
const pending = pendingLayout.current;
|
||||
pendingLayout.current = undefined;
|
||||
window.clearTimeout(saveTimeout.current);
|
||||
saveTimeout.current = undefined;
|
||||
if (pending) pending.onLayoutChange(pending.layout);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pendingLayout.current && pendingLayout.current.storeKey !== storeKey) flushPendingLayout();
|
||||
}, [flushPendingLayout, storeKey]);
|
||||
useEffect(() => () => flushPendingLayout(), [flushPendingLayout]);
|
||||
useEffect(() => {
|
||||
if (!hydrated.current) return;
|
||||
|
||||
const orderChanged = JSON.stringify(columnsOrder) !== JSON.stringify(previousOrder.current);
|
||||
const widthsChanged = JSON.stringify(columnsWidth) !== JSON.stringify(previousWidths.current);
|
||||
previousOrder.current = columnsOrder;
|
||||
previousWidths.current = columnsWidth;
|
||||
if (!orderChanged && !widthsChanged) return;
|
||||
|
||||
const newLayout: TableLayoutOptions = {};
|
||||
if (orderChanged) {
|
||||
const fullOrder = [...savedOrder, ...columnAccessors.filter((accessor) => !savedOrder.includes(accessor))];
|
||||
const reorderedVisibleColumns = [...columnsOrder];
|
||||
const mergedOrder = fullOrder.map((accessor) =>
|
||||
visibleAccessorSet.has(accessor) ? (reorderedVisibleColumns.shift() ?? accessor) : accessor,
|
||||
);
|
||||
newLayout.columnOrder = JSON.stringify(mergedOrder);
|
||||
}
|
||||
if (widthsChanged) {
|
||||
const widthMap: Record<string, number> = { ...savedWidths };
|
||||
Object.assign(widthMap, getColumnWidthMap(columnsWidth, visibleAccessorSet));
|
||||
newLayout.columnWidths = JSON.stringify(widthMap);
|
||||
}
|
||||
|
||||
if (pendingLayout.current && pendingLayout.current.storeKey !== storeKey) flushPendingLayout();
|
||||
pendingLayout.current = pendingLayout.current
|
||||
? { ...pendingLayout.current, layout: { ...pendingLayout.current.layout, ...newLayout } }
|
||||
: { layout: newLayout, onLayoutChange, storeKey };
|
||||
window.clearTimeout(saveTimeout.current);
|
||||
saveTimeout.current = window.setTimeout(flushPendingLayout, layoutSaveDelay);
|
||||
}, [
|
||||
columnAccessors,
|
||||
columnsOrder,
|
||||
columnsWidth,
|
||||
flushPendingLayout,
|
||||
onLayoutChange,
|
||||
savedOrder,
|
||||
savedWidths,
|
||||
storeKey,
|
||||
visibleAccessorSet,
|
||||
]);
|
||||
|
||||
return { effectiveColumns, storeKey };
|
||||
};
|
||||
export {
|
||||
parseColumnOrder,
|
||||
parseColumnWidths,
|
||||
usePersistedTableLayout,
|
||||
useTableLayoutPersistence,
|
||||
} from "@homarr/widget-sdk/table";
|
||||
@@ -6,20 +6,19 @@ import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link, zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { isLegacyCustomWidgetMigrationError, isTerminalCustomWidgetDefinitionError } from "./migration-state";
|
||||
import { usePackageLifecycle } from "./use-package-lifecycle";
|
||||
|
||||
const CustomJsxDisplay = dynamic(() => import("./custom-jsx-display"), { ssr: false });
|
||||
const TrustedWidgetDisplay = dynamic(() => import("./trusted-widget-display"), { ssr: false });
|
||||
|
||||
export default function CustomApiWidget({
|
||||
options,
|
||||
itemId,
|
||||
isEditMode,
|
||||
removeItem,
|
||||
}: WidgetComponentProps<"customApi">) {
|
||||
export default function CustomApiWidget(props: WidgetComponentProps<"customApi">) {
|
||||
const { options, itemId, isEditMode, removeItem } = props;
|
||||
const t = useI18n("widget.customApi");
|
||||
const tCustomJsx = useI18n("widget.customApi.customJsx");
|
||||
const { data: session } = useSession();
|
||||
@@ -31,12 +30,22 @@ export default function CustomApiWidget({
|
||||
{ itemId: itemId ?? "" },
|
||||
{
|
||||
enabled: Boolean(itemId) && Boolean(definitionId),
|
||||
refetchInterval: (currentQuery) =>
|
||||
isTerminalCustomWidgetDefinitionError(currentQuery.state.error) ? false : intervalMs,
|
||||
refetchInterval: (currentQuery) => {
|
||||
if (isTerminalCustomWidgetDefinitionError(currentQuery.state.error)) return false;
|
||||
const data = currentQuery.state.data;
|
||||
if (isRecord(data) && (data.type === "customWidgetV3" || data.hasLoadQueries === false)) return false;
|
||||
return intervalMs;
|
||||
},
|
||||
retry: (failureCount, error) => !isTerminalCustomWidgetDefinitionError(error) && failureCount < 3,
|
||||
},
|
||||
);
|
||||
const accessError = usePackageLifecycle({
|
||||
itemId,
|
||||
enabled: query.data?.type === "customWidgetV3",
|
||||
refresh: query.refetch,
|
||||
});
|
||||
|
||||
if (accessError) return <Unavailable message={t("definitionNotFound")} />;
|
||||
if (!definitionId) {
|
||||
return <Unavailable message={t("definitionNotFound")} removeLabel={t("removeFromBoard")} onRemove={removeItem} />;
|
||||
}
|
||||
@@ -47,7 +56,7 @@ export default function CustomApiWidget({
|
||||
<Loader size="sm" />
|
||||
</Center>
|
||||
);
|
||||
if (query.error) {
|
||||
if (query.error && (isTerminalCustomWidgetDefinitionError(query.error) || !query.data)) {
|
||||
const errorCode = query.error.data?.code;
|
||||
const migrationRequired = isLegacyCustomWidgetMigrationError(query.error);
|
||||
if (isEditMode && errorCode === "NOT_FOUND") {
|
||||
@@ -75,6 +84,9 @@ export default function CustomApiWidget({
|
||||
);
|
||||
}
|
||||
if (!query.data) return null;
|
||||
if (query.data.type === "customWidgetV3") {
|
||||
return <TrustedWidgetDisplay data={query.data} widget={props} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<CustomJsxDisplay
|
||||
@@ -83,6 +95,18 @@ export default function CustomApiWidget({
|
||||
widgetDefinitionId: definitionId,
|
||||
widgetItemId: itemId,
|
||||
isEditMode,
|
||||
host: {
|
||||
boardId: props.boardId,
|
||||
itemId,
|
||||
width: props.width,
|
||||
height: props.height,
|
||||
displayScale: props.displayScale ?? 1,
|
||||
visibleWidth: props.width * (props.displayScale ?? 1),
|
||||
visibleHeight: props.height * (props.displayScale ?? 1),
|
||||
displayMode: props.displayMode ?? "compact",
|
||||
isEditMode,
|
||||
isPreview: !itemId,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -78,6 +78,7 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
||||
...Object.fromEntries(Object.entries(queryState).map(([id, value]) => [id, value.status])),
|
||||
}}
|
||||
options={isRecord(data.options) ? data.options : {}}
|
||||
host={isRecord(data.host) ? data.host : {}}
|
||||
components={components}
|
||||
createBindings={SAFE_BINDINGS}
|
||||
messages={{
|
||||
|
||||
@@ -6,10 +6,21 @@ import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("customApi", {
|
||||
icon: IconApi,
|
||||
supportsAdvancedFocus: true,
|
||||
contextActions: ({ widgetRuntimeRef }) =>
|
||||
(widgetRuntimeRef.current.commands ?? []).map((command) => ({
|
||||
key: command.id,
|
||||
label: () => command.label,
|
||||
disabled: command.disabled,
|
||||
hidden: command.hidden,
|
||||
color: command.destructive ? "red" : undefined,
|
||||
onClick: () => void command.run(),
|
||||
})),
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
definitionId: factory.customWidgetSelect({ defaultValue: "" }),
|
||||
configuration: factory.customWidgetConfiguration(),
|
||||
connectionBindings: factory.internal({ defaultValue: {} as Record<string, string> }),
|
||||
configurationVersion: factory.internal({ defaultValue: 1 }),
|
||||
refreshInterval: factory.slider({
|
||||
defaultValue: 30,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const LEGACY_MIGRATION_ERROR = "LEGACY_CUSTOM_WIDGET_MIGRATION_REQUIRED";
|
||||
const TERMINAL_DEFINITION_CODES = new Set(["NOT_FOUND", "FORBIDDEN", "PRECONDITION_FAILED"]);
|
||||
const TERMINAL_DEFINITION_CODES = new Set(["NOT_FOUND", "FORBIDDEN", "UNAUTHORIZED", "PRECONDITION_FAILED"]);
|
||||
|
||||
export function isLegacyCustomWidgetMigrationError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "message" in error && error.message === LEGACY_MIGRATION_ERROR);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { Alert, Select, Stack } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export function PackageConnectionBindings({
|
||||
connections,
|
||||
installationBindings,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
connections: CustomWidgetPackage["connections"];
|
||||
installationBindings: Record<string, string>;
|
||||
value: Record<string, string>;
|
||||
onChange(value: Record<string, string>): void;
|
||||
}) {
|
||||
const t = useI18n("widget.customApi.configuration");
|
||||
const { data: session } = useSession();
|
||||
const isAdmin = session?.user.permissions.includes("admin") ?? false;
|
||||
const local = clientApi.customWidget.package.connections.useQuery(undefined, {
|
||||
enabled: isAdmin && Object.keys(connections).length > 0,
|
||||
});
|
||||
if (!isAdmin) return null;
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
{local.isError && <Alert color="red">{t("connectionsError")}</Alert>}
|
||||
{Object.entries(connections).map(([name, connection]) => {
|
||||
const candidates = (local.data ?? []).filter(
|
||||
(row) => isRecord(row.configuration) && isWidgetConnectionCompatible(connection, row.configuration),
|
||||
);
|
||||
const defaults = candidates.find((row) => row.id === installationBindings[name]);
|
||||
const selected = value[name];
|
||||
const choices = candidates.map((row) => ({ value: row.id, label: row.name }));
|
||||
if (selected && !candidates.some((row) => row.id === selected))
|
||||
choices.push({ value: selected, label: t("connectionUnavailable") });
|
||||
let placeholder = t("connectionUnbound");
|
||||
if (defaults) placeholder = t("connectionDefault", { name: defaults.name });
|
||||
let error: string | undefined;
|
||||
if (local.data && !connection.optional && !selected && !defaults) error = t("connectionMissing");
|
||||
if (local.data && selected && !candidates.some((row) => row.id === selected))
|
||||
error = t("connectionUnavailable");
|
||||
return (
|
||||
<Select
|
||||
key={name}
|
||||
label={connection.label}
|
||||
description={connection.description}
|
||||
required={!connection.optional}
|
||||
placeholder={placeholder}
|
||||
clearable
|
||||
searchable
|
||||
data={choices}
|
||||
value={selected ?? null}
|
||||
error={error}
|
||||
disabled={local.isLoading}
|
||||
onChange={(next) => {
|
||||
const bindings = { ...value };
|
||||
if (next) bindings[name] = next;
|
||||
else delete bindings[name];
|
||||
onChange(bindings);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { CustomWidgetCodeEditor } from "@homarr/custom-widgets/workbench";
|
||||
import type { CustomWidgetEditorMessages } from "@homarr/custom-widgets/workbench";
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
export function JsonOption({
|
||||
identity,
|
||||
editorId,
|
||||
label,
|
||||
description,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
identity: string;
|
||||
editorId: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
value: unknown;
|
||||
onChange(value: unknown): void;
|
||||
}) {
|
||||
const serializedValue = JSON.stringify(value ?? null, null, 2);
|
||||
const [draft, setDraft] = useState(serializedValue);
|
||||
const [error, setError] = useState<string>();
|
||||
const synchronizedValueRef = useRef(serializedValue);
|
||||
const identityRef = useRef(identity);
|
||||
useEffect(() => {
|
||||
if (identityRef.current === identity && synchronizedValueRef.current === serializedValue) return;
|
||||
identityRef.current = identity;
|
||||
synchronizedValueRef.current = serializedValue;
|
||||
setDraft(serializedValue);
|
||||
setError(undefined);
|
||||
}, [identity, serializedValue]);
|
||||
return (
|
||||
<CustomWidgetCodeEditor
|
||||
id={editorId}
|
||||
label={label}
|
||||
description={description}
|
||||
language="json"
|
||||
value={draft}
|
||||
height="160px"
|
||||
error={error}
|
||||
onChange={(next) => {
|
||||
setDraft(next);
|
||||
try {
|
||||
const parsed = JSON.parse(next) as unknown;
|
||||
synchronizedValueRef.current = JSON.stringify(parsed ?? null, null, 2);
|
||||
onChange(parsed);
|
||||
setError(undefined);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Invalid JSON");
|
||||
}
|
||||
}}
|
||||
messages={editorMessages}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Accordion,
|
||||
ColorInput,
|
||||
MultiSelect,
|
||||
NumberInput,
|
||||
Select,
|
||||
Slider,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
Textarea,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { DateInput, TimeInput } from "@mantine/dates";
|
||||
|
||||
import type { CustomWidgetOption, CustomWidgetOptions } from "@homarr/custom-widgets/core";
|
||||
import { IconPicker } from "@homarr/forms-collection";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { JsonOption } from "./package-json-option";
|
||||
|
||||
export function PackageOptionFields({
|
||||
schema,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
schema: CustomWidgetOptions;
|
||||
value: Record<string, unknown>;
|
||||
onChange(value: Record<string, unknown>): void;
|
||||
}) {
|
||||
const t = useI18n("widget.customApi.configuration");
|
||||
const render = ([name, option]: [string, CustomWidgetOption]) => (
|
||||
<PackageOptionField
|
||||
key={name}
|
||||
identity={name}
|
||||
option={option}
|
||||
value={Object.hasOwn(value, name) ? value[name] : option.default}
|
||||
onChange={(next) => onChange({ ...value, [name]: next })}
|
||||
/>
|
||||
);
|
||||
const entries = Object.entries(schema);
|
||||
const advanced = entries.filter(([, option]) => option.advanced);
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{entries.filter(([, option]) => !option.advanced).map(render)}
|
||||
{advanced.length > 0 && (
|
||||
<Accordion variant="contained">
|
||||
<Accordion.Item value="advanced">
|
||||
<Accordion.Control>{t("advancedOptions")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="sm">{advanced.map(render)}</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export function PackageOptionField({
|
||||
identity,
|
||||
option,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
identity: string;
|
||||
option: CustomWidgetOption;
|
||||
value: unknown;
|
||||
onChange(value: unknown): void;
|
||||
}) {
|
||||
const common = { label: option.label, description: option.description };
|
||||
const textValue = typeof value === "string" ? value : "";
|
||||
const numberValue = typeof value === "number" ? value : 0;
|
||||
if (option.control === "switch")
|
||||
return <Switch {...common} checked={value === true} onChange={(event) => onChange(event.currentTarget.checked)} />;
|
||||
if (option.control === "number" || option.control === "duration")
|
||||
return (
|
||||
<NumberInput
|
||||
{...common}
|
||||
min={option.min}
|
||||
max={option.max}
|
||||
step={option.step}
|
||||
value={numberValue}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
if (option.control === "slider")
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
<Text size="sm" fw={500}>
|
||||
{option.label}
|
||||
</Text>
|
||||
{option.description && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{option.description}
|
||||
</Text>
|
||||
)}
|
||||
<Slider
|
||||
aria-label={option.label}
|
||||
min={option.min ?? 0}
|
||||
max={option.max ?? 100}
|
||||
step={option.step ?? 1}
|
||||
value={numberValue}
|
||||
onChange={onChange}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
const choices = option.choices?.map((choice) => ({ label: choice.label, value: String(choice.value) })) ?? [];
|
||||
// V3 dynamic configuration lives in its configuration entrypoint, never in the legacy request executor.
|
||||
if (option.control === "select")
|
||||
return (
|
||||
<Select
|
||||
{...common}
|
||||
data={choices}
|
||||
value={value == null ? null : String(value)}
|
||||
onChange={(next) => onChange(coerceChoice(next, option))}
|
||||
/>
|
||||
);
|
||||
if (option.control === "multiSelect")
|
||||
return (
|
||||
<MultiSelect
|
||||
{...common}
|
||||
data={choices}
|
||||
value={Array.isArray(value) ? value.map(String) : []}
|
||||
onChange={(next) => onChange(next.map((entry) => coerceChoice(entry, option)))}
|
||||
/>
|
||||
);
|
||||
if (option.control === "textarea")
|
||||
return (
|
||||
<Textarea
|
||||
{...common}
|
||||
autosize
|
||||
minRows={3}
|
||||
value={textValue}
|
||||
onChange={(event) => onChange(event.currentTarget.value)}
|
||||
/>
|
||||
);
|
||||
if (option.control === "color") return <ColorInput {...common} value={textValue} onChange={onChange} />;
|
||||
if (option.control === "date")
|
||||
return (
|
||||
<DateInput
|
||||
{...common}
|
||||
valueFormat="YYYY-MM-DD"
|
||||
value={textValue || null}
|
||||
onChange={(next) => onChange(next ?? "")}
|
||||
/>
|
||||
);
|
||||
if (option.control === "time")
|
||||
return <TimeInput {...common} value={textValue} onChange={(event) => onChange(event.currentTarget.value)} />;
|
||||
if (option.control === "icon") return <IconPicker withAsterisk={false} value={textValue} onChange={onChange} />;
|
||||
if (option.control === "timeZone")
|
||||
return (
|
||||
<Select
|
||||
{...common}
|
||||
searchable
|
||||
data={Intl.supportedValuesOf("timeZone")}
|
||||
value={textValue}
|
||||
onChange={(next) => onChange(next ?? "")}
|
||||
/>
|
||||
);
|
||||
if (option.control === "json")
|
||||
return (
|
||||
<JsonOption
|
||||
identity={identity}
|
||||
editorId={`${identity}-json-option`}
|
||||
{...common}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<TextInput
|
||||
{...common}
|
||||
type={option.control === "url" ? "url" : "text"}
|
||||
value={textValue}
|
||||
onChange={(event) => onChange(event.currentTarget.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function coerceChoice(value: string | null, option: CustomWidgetOption) {
|
||||
if (value === null) return null;
|
||||
if (
|
||||
typeof option.default === "number" ||
|
||||
option.choices?.some((choice) => typeof choice.value === "number" && String(choice.value) === value)
|
||||
)
|
||||
return Number(value);
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
"use client";
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Button, Center, Loader, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { TrustedWidgetHost } from "./trusted-widget-host";
|
||||
import { TrustedWidgetErrorBoundary } from "./trusted-widget-error-boundary";
|
||||
import { loadTrustedWidgetModule, retainTrustedWidgetStylesheet } from "./trusted-widget-loader";
|
||||
import type { TrustedWidgetData } from "./trusted-widget-types";
|
||||
|
||||
interface LoadedSurface {
|
||||
url: string;
|
||||
data: TrustedWidgetData;
|
||||
Component: ComponentType;
|
||||
releaseStyles?: () => void;
|
||||
}
|
||||
|
||||
export default function TrustedWidgetDisplay({
|
||||
data,
|
||||
widget,
|
||||
surface: requestedSurface,
|
||||
onOptionsChange,
|
||||
frozen = false,
|
||||
onReady,
|
||||
onLoadError,
|
||||
}: {
|
||||
data: TrustedWidgetData;
|
||||
widget: WidgetComponentProps<"customApi">;
|
||||
surface?: "tile" | "advanced" | "configuration";
|
||||
onOptionsChange?: (options: Record<string, unknown>) => void;
|
||||
frozen?: boolean;
|
||||
onReady?: (previewId: string) => void;
|
||||
onLoadError?: (previewId: string, error: Error) => void;
|
||||
}) {
|
||||
const t = useI18n("widget.customApi.customJsx");
|
||||
let surface: "tile" | "advanced" | "configuration" = "tile";
|
||||
if (widget.displayMode === "advanced" && data.surfaceUrls.advanced) surface = "advanced";
|
||||
if (requestedSurface && data.surfaceUrls[requestedSurface]) surface = requestedSurface;
|
||||
const moduleUrl = data.surfaceUrls[surface] ?? data.surfaceUrls.tile;
|
||||
const cssUrl = data.stylesheetUrls[surface];
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [loaded, setLoaded] = useState<LoadedSurface>();
|
||||
const [failure, setFailure] = useState<Error>();
|
||||
const committed = useRef<LoadedSurface | undefined>(undefined);
|
||||
const styles = useRef(new Set<() => void>());
|
||||
const callbacks = useRef({ onReady, onLoadError });
|
||||
callbacks.current = { onReady, onLoadError };
|
||||
|
||||
useEffect(() => {
|
||||
if (frozen) return;
|
||||
let active = true;
|
||||
let promoted = false;
|
||||
const retained = styles.current;
|
||||
setFailure(undefined);
|
||||
const stylesheet = cssUrl ? retainTrustedWidgetStylesheet(cssUrl) : undefined;
|
||||
if (stylesheet) retained.add(stylesheet.release);
|
||||
void Promise.all([loadTrustedWidgetModule(moduleUrl, attempt), stylesheet?.loaded]).then(
|
||||
([module]) => {
|
||||
if (!active) return;
|
||||
promoted = true;
|
||||
setLoaded({ url: moduleUrl, data, Component: module.default, releaseStyles: stylesheet?.release });
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (!active) return;
|
||||
const reason = error instanceof Error ? error : new Error(String(error));
|
||||
setFailure(reason);
|
||||
if (data.previewId) callbacks.current.onLoadError?.(data.previewId, reason);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
if (!promoted && stylesheet) {
|
||||
stylesheet.release();
|
||||
retained.delete(stylesheet.release);
|
||||
}
|
||||
};
|
||||
}, [attempt, cssUrl, data, frozen, moduleUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
const retained = styles.current;
|
||||
return () => {
|
||||
retained.forEach((release) => release());
|
||||
retained.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const accept = useCallback((entry: LoadedSurface) => {
|
||||
committed.current = entry;
|
||||
for (const release of styles.current) {
|
||||
if (release === entry.releaseStyles) continue;
|
||||
release();
|
||||
styles.current.delete(release);
|
||||
}
|
||||
if (entry.data.previewId) callbacks.current.onReady?.(entry.data.previewId);
|
||||
}, []);
|
||||
|
||||
const renderFailed = (error: Error) => {
|
||||
if (!data.previewId) return;
|
||||
setFailure(error);
|
||||
callbacks.current.onLoadError?.(data.previewId, error);
|
||||
if (!committed.current || loaded === committed.current) return;
|
||||
if (loaded?.releaseStyles) {
|
||||
loaded.releaseStyles();
|
||||
styles.current.delete(loaded.releaseStyles);
|
||||
}
|
||||
setLoaded(committed.current);
|
||||
};
|
||||
|
||||
let content = (
|
||||
<Center h="100%">
|
||||
<Loader size="sm" />
|
||||
</Center>
|
||||
);
|
||||
if (loaded) {
|
||||
const Component = loaded.Component;
|
||||
content = (
|
||||
<>
|
||||
<Component key={loaded.url} />
|
||||
<SurfaceCommitted entry={loaded} onReady={accept} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
let displayData = data;
|
||||
const retainingPrevious = Boolean(loaded && loaded.url !== moduleUrl);
|
||||
if (loaded && retainingPrevious) displayData = loaded.data;
|
||||
|
||||
return (
|
||||
<TrustedWidgetHost
|
||||
data={displayData}
|
||||
widget={widget}
|
||||
onOptionsChange={onOptionsChange}
|
||||
frozen={frozen || retainingPrevious}
|
||||
notice={
|
||||
failure && (
|
||||
<Alert color="red" title={t("requestFailed")}>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{failure.message}</Text>
|
||||
<Button
|
||||
disabled={frozen}
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
onClick={() => setAttempt((current) => current + 1)}
|
||||
>
|
||||
{t("retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
>
|
||||
<TrustedWidgetErrorBoundary
|
||||
key={`${loaded?.url ?? moduleUrl}:${attempt}`}
|
||||
title={t("requestFailed")}
|
||||
retryLabel={t("retry")}
|
||||
onRetry={() => setAttempt((current) => current + 1)}
|
||||
onError={renderFailed}
|
||||
>
|
||||
{(!failure || loaded) && content}
|
||||
</TrustedWidgetErrorBoundary>
|
||||
</TrustedWidgetHost>
|
||||
);
|
||||
}
|
||||
|
||||
function SurfaceCommitted({ entry, onReady }: { entry: LoadedSurface; onReady(entry: LoadedSurface): void }) {
|
||||
useEffect(() => onReady(entry), [entry, onReady]);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { Component } from "react";
|
||||
import { Alert, Button, Stack, Text } from "@mantine/core";
|
||||
|
||||
export class TrustedWidgetErrorBoundary extends Component<
|
||||
PropsWithChildren<{ title: string; retryLabel: string; onRetry(): void; onError?(error: Error): void }>,
|
||||
{ error: Error | null }
|
||||
> {
|
||||
state = { error: null as Error | null };
|
||||
|
||||
static getDerivedStateFromError(error: unknown) {
|
||||
if (error instanceof Error) return { error };
|
||||
return { error: new Error(String(error)) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error) {
|
||||
this.props.onError?.(error);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error)
|
||||
return (
|
||||
<Alert color="red" title={this.props.title}>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{this.state.error.message}</Text>
|
||||
<Button size="compact-xs" onClick={this.props.onRetry}>
|
||||
{this.props.retryLabel}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren, ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Modal, useComputedColorScheme } from "@mantine/core";
|
||||
import { useReducedMotion } from "@mantine/hooks";
|
||||
import { IconCode } from "@tabler/icons-react";
|
||||
import { hashKey, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { clientApi, fetchApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { getSafeAppHref } from "@homarr/common";
|
||||
import { useConfirmModal } from "@homarr/modals";
|
||||
import { showErrorNotification, showSuccessNotification, showWarningNotification } from "@homarr/notifications";
|
||||
import { useRegisterSpotlightContextActions } from "@homarr/spotlight";
|
||||
import { useCurrentIntlLocale } from "@homarr/translation/client";
|
||||
import { createWidgetStateStore, WidgetHostProvider } from "@homarr/widget-sdk";
|
||||
import type { WidgetCommand, WidgetHostContext, WidgetHostServices, WidgetStateStore } from "@homarr/widget-sdk/shared";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import type { TrustedWidgetData } from "./trusted-widget-types";
|
||||
import { useTrustedWidgetTransport } from "./trusted-widget-transport";
|
||||
|
||||
export function TrustedWidgetHost({
|
||||
data,
|
||||
widget,
|
||||
children,
|
||||
onOptionsChange,
|
||||
frozen = false,
|
||||
notice,
|
||||
}: PropsWithChildren<{
|
||||
data: TrustedWidgetData;
|
||||
widget: WidgetComponentProps<"customApi">;
|
||||
onOptionsChange?: (options: Record<string, unknown>) => void;
|
||||
frozen?: boolean;
|
||||
notice?: ReactNode;
|
||||
}>) {
|
||||
const { data: session } = useSession();
|
||||
const { boardId, itemId, isEditMode, setOptions, openAdvancedFocus, closeAdvancedFocus } = widget;
|
||||
const utils = clientApi.useUtils();
|
||||
const queryClient = useQueryClient();
|
||||
const locale = useCurrentIntlLocale();
|
||||
const colorScheme = useComputedColorScheme("dark");
|
||||
const reducedMotion = useReducedMotion();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const frozenRef = useRef(frozen);
|
||||
frozenRef.current = frozen;
|
||||
const [visible, setVisible] = useState(true);
|
||||
const [commands, setCommands] = useState<readonly WidgetCommand[]>([]);
|
||||
const [detail, setDetail] = useState<{ title: string; content: ReactNode } | null>(null);
|
||||
const registrations = useRef(new Map<symbol, readonly WidgetCommand[]>());
|
||||
const stateRef = useRef<{ key: string; store: WidgetStateStore } | null>(null);
|
||||
const stateKey = `${data.installationId}:${data.manifest.sdkVersion}:${data.manifest.configurationVersion}:${session?.user.id ?? "guest"}`;
|
||||
if (stateRef.current?.key !== stateKey) {
|
||||
const saved = widget.widgetStateRef;
|
||||
if (saved && !saved.current) saved.current = {};
|
||||
const backing = saved?.current ?? {};
|
||||
const key = `custom-widget:${stateKey}`;
|
||||
if (!backing[key] || typeof backing[key] !== "object") backing[key] = {};
|
||||
stateRef.current = { key: stateKey, store: createWidgetStateStore(backing[key] as Record<string, unknown>) };
|
||||
}
|
||||
const state = stateRef.current.store;
|
||||
|
||||
useEffect(() => {
|
||||
let intersects = true;
|
||||
const update = () => setVisible(intersects && document.visibilityState === "visible");
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
intersects = entry?.isIntersecting ?? true;
|
||||
update();
|
||||
});
|
||||
if (root.current) observer.observe(root.current);
|
||||
document.addEventListener("visibilitychange", update);
|
||||
update();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener("visibilitychange", update);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const subscriptionScope = hashKey([session?.user.id, itemId, data.previewId, data.artifactDigest, data.options]);
|
||||
const transport = useTrustedWidgetTransport(data.previewId, subscriptionScope, frozen);
|
||||
useEffect(() => {
|
||||
if (!frozen) return;
|
||||
const identity = widget.itemId ?? data.previewId;
|
||||
void queryClient.cancelQueries({
|
||||
predicate: ({ queryKey: key }) =>
|
||||
(key[0] === "custom-widget-sdk" || key[0] === "custom-widget") && key[2] === identity,
|
||||
});
|
||||
}, [data.previewId, frozen, queryClient, widget.itemId]);
|
||||
|
||||
const registerCommands = useCallback((next: readonly WidgetCommand[]) => {
|
||||
const token = Symbol();
|
||||
registrations.current.set(token, next);
|
||||
setCommands([...registrations.current.values()].flat());
|
||||
return () => {
|
||||
registrations.current.delete(token);
|
||||
setCommands([...registrations.current.values()].flat());
|
||||
};
|
||||
}, []);
|
||||
|
||||
const services = useMemo<WidgetHostServices>(
|
||||
() => ({
|
||||
transport,
|
||||
state,
|
||||
registerCommands,
|
||||
notify: ({ title, message, color }) => {
|
||||
const notification = { title, message: message ?? "" };
|
||||
if (color === "red") showErrorNotification(notification);
|
||||
else if (color === "yellow" || color === "orange") showWarningNotification(notification);
|
||||
else showSuccessNotification(notification);
|
||||
},
|
||||
navigate(href) {
|
||||
if (frozenRef.current) return;
|
||||
const target = getSafeAppHref(href);
|
||||
if (target) window.location.assign(target);
|
||||
},
|
||||
openDetail: (next) => {
|
||||
if (!frozenRef.current) setDetail(next);
|
||||
},
|
||||
closeDetail: () => setDetail(null),
|
||||
openAdvanced: () => {
|
||||
if (!frozenRef.current) openAdvancedFocus?.();
|
||||
},
|
||||
closeAdvanced: () => closeAdvancedFocus?.(),
|
||||
async updateOptions(options) {
|
||||
if (frozenRef.current) throw new Error("Preview the current draft before changing its configuration");
|
||||
if (onOptionsChange) {
|
||||
onOptionsChange(options);
|
||||
return;
|
||||
}
|
||||
if (!boardId || !itemId) throw new Error("This preview cannot save widget options");
|
||||
const newOptions = { configuration: options };
|
||||
if (!isEditMode) {
|
||||
await fetchApi.widget.options.saveItemOptions.mutate({
|
||||
boardId,
|
||||
itemId,
|
||||
newOptions,
|
||||
});
|
||||
}
|
||||
setOptions({ newOptions });
|
||||
await utils.widget.customApi.getData.invalidate({ itemId });
|
||||
},
|
||||
confirm: ({ title, message, destructive }) =>
|
||||
new Promise((resolve) => {
|
||||
if (frozenRef.current) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
openConfirmModal({
|
||||
title,
|
||||
children: message,
|
||||
confirmProps: { color: destructive ? "red" : undefined },
|
||||
onConfirm: () => resolve(true),
|
||||
onCancel: () => resolve(false),
|
||||
});
|
||||
}),
|
||||
}),
|
||||
[
|
||||
onOptionsChange,
|
||||
openConfirmModal,
|
||||
registerCommands,
|
||||
state,
|
||||
transport,
|
||||
utils.widget.customApi.getData,
|
||||
boardId,
|
||||
isEditMode,
|
||||
itemId,
|
||||
setOptions,
|
||||
openAdvancedFocus,
|
||||
closeAdvancedFocus,
|
||||
],
|
||||
);
|
||||
|
||||
const availableCommands = useMemo(
|
||||
() =>
|
||||
commands
|
||||
.filter((command) => !command.hidden)
|
||||
.map((command) => ({
|
||||
...command,
|
||||
disabled: command.disabled || isEditMode || frozen,
|
||||
async run() {
|
||||
if (command.disabled || isEditMode || frozenRef.current) return;
|
||||
try {
|
||||
await command.run();
|
||||
} catch (error) {
|
||||
showErrorNotification({
|
||||
title: command.label,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
},
|
||||
})),
|
||||
[commands, isEditMode, frozen],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const runtime = widget.widgetRuntimeRef?.current;
|
||||
if (!runtime) return;
|
||||
runtime.commands = availableCommands;
|
||||
return () => {
|
||||
if (runtime.commands === availableCommands) runtime.commands = [];
|
||||
};
|
||||
}, [availableCommands, widget.widgetRuntimeRef]);
|
||||
|
||||
useEffect(() => {
|
||||
const runtime = widget.widgetRuntimeRef?.current;
|
||||
if (!runtime) return;
|
||||
const refresh = () => {
|
||||
if (frozen) return Promise.resolve();
|
||||
return queryClient.refetchQueries({
|
||||
queryKey: ["custom-widget-sdk", data.artifactDigest, widget.itemId ?? data.previewId, session?.user.id],
|
||||
type: "active",
|
||||
});
|
||||
};
|
||||
runtime.refresh = refresh;
|
||||
return () => {
|
||||
if (runtime.refresh === refresh) runtime.refresh = undefined;
|
||||
};
|
||||
}, [
|
||||
data.artifactDigest,
|
||||
data.previewId,
|
||||
frozen,
|
||||
queryClient,
|
||||
session?.user.id,
|
||||
widget.itemId,
|
||||
widget.widgetRuntimeRef,
|
||||
]);
|
||||
|
||||
useRegisterSpotlightContextActions(
|
||||
`custom-widget:${widget.itemId ?? data.installationId}`,
|
||||
availableCommands.map((command) => ({
|
||||
id: `${widget.itemId}:${command.id}`,
|
||||
name: command.label,
|
||||
description: command.description,
|
||||
icon: IconCode,
|
||||
disabled: command.disabled,
|
||||
interaction: () => ({ type: "javaScript" as const, onSelect: () => void command.run() }),
|
||||
})),
|
||||
[availableCommands, widget.itemId],
|
||||
);
|
||||
|
||||
const displayScale = widget.displayScale ?? 1;
|
||||
const context: WidgetHostContext = {
|
||||
sdkVersion: "1",
|
||||
itemId: widget.itemId,
|
||||
previewId: data.previewId,
|
||||
boardId: widget.boardId,
|
||||
installationId: data.installationId,
|
||||
revisionId: data.artifactDigest,
|
||||
displayMode: widget.displayMode ?? "compact",
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
displayScale,
|
||||
visibleWidth: widget.width * displayScale,
|
||||
visibleHeight: widget.height * displayScale,
|
||||
isEditMode: widget.isEditMode,
|
||||
isPreview: !widget.itemId,
|
||||
visible: visible && !frozen,
|
||||
executionEnabled: !frozen,
|
||||
refreshIntervalSeconds: widget.options.refreshInterval,
|
||||
locale,
|
||||
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
colorScheme,
|
||||
reducedMotion: reducedMotion ?? false,
|
||||
userId: session?.user.id,
|
||||
};
|
||||
|
||||
return (
|
||||
<WidgetHostProvider context={context} services={services} options={data.options}>
|
||||
<div
|
||||
ref={root}
|
||||
data-custom-widget={data.installationId}
|
||||
data-custom-widget-artifact={data.artifactDigest}
|
||||
data-mantine-color-scheme={colorScheme}
|
||||
style={{ width: "100%", height: "100%", minWidth: 0, minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
{notice}
|
||||
<div inert={frozen} style={{ width: "100%", height: "100%", minWidth: 0, minHeight: 0, flex: 1 }}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
<Modal opened={detail !== null} onClose={() => setDetail(null)} title={detail?.title} size="xl">
|
||||
<div inert={frozen} data-custom-widget-artifact={data.artifactDigest} data-mantine-color-scheme={colorScheme}>
|
||||
{detail?.content}
|
||||
</div>
|
||||
</Modal>
|
||||
</WidgetHostProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { Alert, Stack } from "@mantine/core";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { customWidgetOptionsSchema } from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetOption } from "@homarr/custom-widgets/core";
|
||||
import { useWidgetOptions, useWidgetQuery, useWidgetServices } from "@homarr/widget-sdk";
|
||||
|
||||
import { PackageOptionField } from "./package-option-fields";
|
||||
|
||||
export function LegacyConfiguration({
|
||||
schema,
|
||||
parameterNames = {},
|
||||
}: {
|
||||
schema: unknown;
|
||||
parameterNames?: Record<string, string[]>;
|
||||
}) {
|
||||
const options = useWidgetOptions();
|
||||
const services = useWidgetServices();
|
||||
const parsed = useMemo(() => customWidgetOptionsSchema.parse(schema), [schema]);
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{Object.entries(parsed).map(([name, option]) => (
|
||||
<LegacyOption
|
||||
key={name}
|
||||
name={name}
|
||||
option={option}
|
||||
parameterNames={parameterNames[option.choicesFrom?.request ?? ""] ?? []}
|
||||
value={options[name] ?? option.default}
|
||||
onChange={(value) => {
|
||||
void services
|
||||
.updateOptions({ ...options, [name]: value })
|
||||
.catch((error: unknown) =>
|
||||
services.notify({ title: option.label, message: String(error), color: "red" }),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function LegacyOption({
|
||||
name,
|
||||
option,
|
||||
value,
|
||||
onChange,
|
||||
parameterNames,
|
||||
}: {
|
||||
name: string;
|
||||
option: CustomWidgetOption;
|
||||
value: unknown;
|
||||
onChange(value: unknown): void;
|
||||
parameterNames: string[];
|
||||
}) {
|
||||
const options = useWidgetOptions();
|
||||
const source = option.choicesFrom;
|
||||
const query = useWidgetQuery<{ data: unknown }>(
|
||||
source?.request ?? "",
|
||||
{
|
||||
params: Object.fromEntries(parameterNames.map((key) => [key, options[key]])),
|
||||
optionValues: options,
|
||||
},
|
||||
{ enabled: Boolean(source), staleTime: 30_000 },
|
||||
);
|
||||
let renderedOption = option;
|
||||
if (source) {
|
||||
const rows = source.itemsPath ? getByPath(query.data?.data, source.itemsPath) : query.data?.data;
|
||||
const choices = (Array.isArray(rows) ? rows : []).flatMap((row) => {
|
||||
const entry = getByPath(row, source.valuePath);
|
||||
if (typeof entry !== "string" && typeof entry !== "number") return [];
|
||||
return [{ value: entry, label: String(getByPath(row, source.labelPath) ?? entry) }];
|
||||
});
|
||||
// Preserve the selected value while fetching or when the upstream omits a formerly valid option.
|
||||
for (const entry of Array.isArray(value) ? value : [value]) {
|
||||
if (
|
||||
(typeof entry === "string" || typeof entry === "number") &&
|
||||
!choices.some((choice) => String(choice.value) === String(entry))
|
||||
)
|
||||
choices.push({ value: entry, label: String(entry) });
|
||||
}
|
||||
renderedOption = { ...option, choices, choicesFrom: undefined };
|
||||
}
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
{query.error && <Alert color="red">{query.error.message}</Alert>}
|
||||
<PackageOptionField identity={name} option={renderedOption} value={value} onChange={onChange} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function getByPath(value: unknown, path: string): unknown {
|
||||
return path
|
||||
.replace(/^\$\.?/u, "")
|
||||
.split(".")
|
||||
.filter(Boolean)
|
||||
.reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), value);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useQueries, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
CustomJsxRenderer,
|
||||
CustomWidgetRuntimeProvider,
|
||||
parseRequestCapabilities,
|
||||
} from "@homarr/custom-widgets/runtime";
|
||||
import type {
|
||||
CustomJsxInputState,
|
||||
CustomWidgetPublishedQueryState,
|
||||
CustomWidgetRequestResult,
|
||||
CustomWidgetRuntimePort,
|
||||
} from "@homarr/custom-widgets/runtime";
|
||||
import { useConfirmModal } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { useWidgetHost, useWidgetOptions, useWidgetServices, useWidgetState } from "@homarr/widget-sdk";
|
||||
|
||||
import { createCustomWidgetComponents, SAFE_BINDINGS } from "./jsx-components";
|
||||
import { useRuntimeMessages } from "./widget-definition-context";
|
||||
|
||||
export { LegacyConfiguration } from "./trusted-widget-legacy-configuration";
|
||||
|
||||
export function LegacyWidget({ template, requestCapabilities }: { template: string; requestCapabilities?: unknown }) {
|
||||
const host = useWidgetHost();
|
||||
const services = useWidgetServices();
|
||||
const options = useWidgetOptions();
|
||||
const inputState = useWidgetState<CustomJsxInputState>("legacy-inputs", { values: {}, types: {} });
|
||||
const messages = useRuntimeMessages();
|
||||
const t = useI18n("widget.customApi.customJsx");
|
||||
const actionT = useI18n("common.action");
|
||||
const diagnosticsT = useI18n("customWidget.editor.diagnostics");
|
||||
const capabilities = useMemo(() => parseRequestCapabilities(requestCapabilities), [requestCapabilities]);
|
||||
const load = capabilities.filter((request) => request.kind === "query" && request.trigger === "load");
|
||||
const itemId = host.itemId ?? host.previewId ?? "";
|
||||
const queryCacheKey = `${host.revisionId}:${host.userId ?? "guest"}:${host.scope ?? ""}`;
|
||||
const [accessFailure, setAccessFailure] = useState<{ scope: string; error: unknown }>();
|
||||
const queryClient = useQueryClient();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const [published, setPublished] = useState<Record<string, CustomWidgetPublishedQueryState>>({});
|
||||
const publish = useCallback((name: string, state: CustomWidgetPublishedQueryState | null) => {
|
||||
setPublished((current) => {
|
||||
if (!state) {
|
||||
if (!Object.hasOwn(current, name)) return current;
|
||||
const next = { ...current };
|
||||
delete next[name];
|
||||
return next;
|
||||
}
|
||||
const previous = current[name];
|
||||
if (previous && previous.data === state.data && JSON.stringify(previous.status) === JSON.stringify(state.status))
|
||||
return current;
|
||||
return { ...current, [name]: state };
|
||||
});
|
||||
}, []);
|
||||
const queries = useQueries({
|
||||
queries: load.map((request) => ({
|
||||
queryKey: ["custom-widget-sdk", host.revisionId, itemId, host.userId, "query", host.scope, request.id, {}],
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) =>
|
||||
services.transport.query(
|
||||
{ itemId, name: request.id, input: { params: {} } },
|
||||
signal,
|
||||
) as Promise<CustomWidgetRequestResult>,
|
||||
enabled: Boolean(itemId) && host.visible,
|
||||
refetchInterval: Math.max(1, host.refreshIntervalSeconds ?? 30) * 1000,
|
||||
retry: false,
|
||||
})),
|
||||
});
|
||||
const port: CustomWidgetRuntimePort = {
|
||||
query: async (input, signal) => {
|
||||
try {
|
||||
return (await services.transport.query(
|
||||
{ itemId, name: input.requestId, input: { params: input.params } },
|
||||
signal ?? new AbortController().signal,
|
||||
)) as CustomWidgetRequestResult;
|
||||
} catch (error) {
|
||||
if (isAccessError(error)) {
|
||||
setAccessFailure({ scope: queryCacheKey, error });
|
||||
queryClient.removeQueries({
|
||||
predicate: ({ queryKey: key }) => key[0] === "custom-widget" && key[2] === itemId,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
executeAction: async (input) => {
|
||||
const result = await services.transport.action({
|
||||
itemId,
|
||||
name: input.requestId,
|
||||
input: { params: input.params, confirmed: input.confirmed },
|
||||
});
|
||||
if (result && typeof result === "object" && "simulated" in result && result.simulated)
|
||||
return { ok: true, status: 200, data: null, simulated: true };
|
||||
return result as CustomWidgetRequestResult;
|
||||
},
|
||||
invalidate: async ({ targets }) => {
|
||||
await queryClient.invalidateQueries({
|
||||
predicate: ({ queryKey: key }) => {
|
||||
if (key[0] === "custom-widget-sdk" && key[2] === itemId && key[4] === "query")
|
||||
return targets.includes("*") || targets.includes(String(key[6]));
|
||||
return (
|
||||
key[0] === "custom-widget" &&
|
||||
key[2] === itemId &&
|
||||
(targets.includes("*") || targets.includes(String(key[3])))
|
||||
);
|
||||
},
|
||||
});
|
||||
},
|
||||
confirm: ({ title, message, confirmLabel, destructive }) =>
|
||||
new Promise((resolve) =>
|
||||
openConfirmModal({
|
||||
title,
|
||||
children: message,
|
||||
labels: { confirm: confirmLabel },
|
||||
confirmProps: { color: destructive ? "red" : undefined },
|
||||
onConfirm: () => resolve(true),
|
||||
onCancel: () => resolve(false),
|
||||
}),
|
||||
),
|
||||
notify: ({ kind, title, message }) =>
|
||||
services.notify({ title, message, color: kind === "error" ? "red" : undefined }),
|
||||
};
|
||||
const copy = actionT("copy");
|
||||
const copied = t("copied");
|
||||
const components = useMemo(() => createCustomWidgetComponents({ copy, copied }), [copy, copied]);
|
||||
const data: Record<string, unknown> = {};
|
||||
const status: Record<string, unknown> = {};
|
||||
for (const [index, request] of load.entries()) {
|
||||
const query = queries[index];
|
||||
const response = query?.data;
|
||||
data[request.id] = response?.data ?? null;
|
||||
status[request.id] = {
|
||||
loading: query?.isFetching && !response,
|
||||
ok: response?.ok,
|
||||
status: response?.status,
|
||||
statusText: response?.statusText,
|
||||
error: response?.error ?? query?.error?.message,
|
||||
};
|
||||
}
|
||||
for (const [id, state] of Object.entries(published)) {
|
||||
data[id] = state.data;
|
||||
status[id] = state.status;
|
||||
}
|
||||
// Access failures invalidate any previously published SubFetch data before another render can reveal it.
|
||||
if (queries.some((query) => isAccessError(query.error)))
|
||||
throw queries.find((query) => isAccessError(query.error))?.error;
|
||||
if (accessFailure?.scope === queryCacheKey) throw accessFailure.error;
|
||||
return (
|
||||
<CustomWidgetRuntimeProvider
|
||||
itemId={host.itemId}
|
||||
previewSessionId={host.previewId}
|
||||
definitionId={host.installationId}
|
||||
queryCacheKey={queryCacheKey}
|
||||
isEditMode={host.isEditMode}
|
||||
queriesDisabled={!host.visible}
|
||||
requestCapabilities={capabilities}
|
||||
port={port}
|
||||
messages={messages}
|
||||
setQueryState={publish}
|
||||
>
|
||||
<CustomJsxRenderer
|
||||
inputState={inputState}
|
||||
template={template}
|
||||
data={data}
|
||||
status={status}
|
||||
options={options}
|
||||
host={{ ...host }}
|
||||
components={components}
|
||||
createBindings={SAFE_BINDINGS}
|
||||
messages={{
|
||||
noTemplate: t("noTemplate"),
|
||||
templateWarnings: (count) => t("templateWarnings", { count: String(count) }),
|
||||
bindingTypeConflict: (name, firstType, secondType) =>
|
||||
diagnosticsT("runtimeBindingTypeConflict", { value: name, firstType, secondType }),
|
||||
}}
|
||||
/>
|
||||
</CustomWidgetRuntimeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function isAccessError(error: unknown) {
|
||||
if (!error || typeof error !== "object" || !("data" in error)) return false;
|
||||
const data = error.data;
|
||||
return Boolean(
|
||||
data &&
|
||||
typeof data === "object" &&
|
||||
"code" in data &&
|
||||
["FORBIDDEN", "UNAUTHORIZED", "NOT_FOUND"].includes(String(data.code)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
import { registerTrustedWidgetModules } from "./trusted-widget-modules";
|
||||
|
||||
interface WidgetModule {
|
||||
default: ComponentType;
|
||||
}
|
||||
|
||||
const moduleLoads = new Map<string, Promise<WidgetModule>>();
|
||||
const stylesheets = new Map<string, { element: HTMLLinkElement; references: number; loaded: Promise<void> }>();
|
||||
|
||||
function resolveArtifactUrl(path: string) {
|
||||
const url = new URL(path, window.location.origin);
|
||||
const isArtifact = url.pathname.startsWith("/api/custom-widgets/artifacts/");
|
||||
const isPreview = url.pathname.startsWith("/api/custom-widgets/previews/");
|
||||
if (url.origin !== window.location.origin || (!isArtifact && !isPreview)) {
|
||||
throw new Error("Widget artifacts must be served by this Homarr instance");
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export function loadTrustedWidgetModule(path: string, attempt = 0): Promise<WidgetModule> {
|
||||
const requestedUrl = new URL(resolveArtifactUrl(path));
|
||||
// Browser module maps retain failed evaluations; an explicit Retry gets a fresh module request.
|
||||
if (attempt > 0) requestedUrl.searchParams.set("retry", String(attempt));
|
||||
const url = requestedUrl.href;
|
||||
registerTrustedWidgetModules();
|
||||
const existing = moduleLoads.get(url);
|
||||
if (existing) return existing;
|
||||
const loading = import(/* webpackIgnore: true */ /* turbopackIgnore: true */ url).then((module: unknown) => {
|
||||
if (!module || typeof module !== "object" || !("default" in module)) {
|
||||
throw new Error("A widget surface must export a React component as default");
|
||||
}
|
||||
const component = module.default;
|
||||
const wrappedTypes = [Symbol.for("react.memo"), Symbol.for("react.forward_ref"), Symbol.for("react.lazy")];
|
||||
const isWrappedComponent =
|
||||
component !== null &&
|
||||
typeof component === "object" &&
|
||||
"$$typeof" in component &&
|
||||
wrappedTypes.includes(component.$$typeof as symbol);
|
||||
if (typeof component !== "function" && !isWrappedComponent) {
|
||||
throw new Error("The widget default export is not a React component");
|
||||
}
|
||||
return module as WidgetModule;
|
||||
});
|
||||
moduleLoads.set(url, loading);
|
||||
void loading.catch(() => moduleLoads.delete(url));
|
||||
return loading;
|
||||
}
|
||||
|
||||
export function retainTrustedWidgetStylesheet(path: string) {
|
||||
const url = resolveArtifactUrl(path);
|
||||
let entry = stylesheets.get(url);
|
||||
if (!entry) {
|
||||
const element = document.createElement("link");
|
||||
element.rel = "stylesheet";
|
||||
element.href = url;
|
||||
const loaded = new Promise<void>((resolve, reject) => {
|
||||
element.addEventListener("load", () => resolve(), { once: true });
|
||||
element.addEventListener("error", () => reject(new Error("The widget stylesheet could not be loaded")), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
entry = { element, references: 0, loaded };
|
||||
stylesheets.set(url, entry);
|
||||
document.head.appendChild(element);
|
||||
}
|
||||
entry.references += 1;
|
||||
const retained = entry;
|
||||
let released = false;
|
||||
return {
|
||||
loaded: entry.loaded,
|
||||
release() {
|
||||
if (released) return;
|
||||
released = true;
|
||||
retained.references -= 1;
|
||||
if (retained.references > 0) return;
|
||||
retained.element.remove();
|
||||
stylesheets.delete(url);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import * as React from "react";
|
||||
import * as ReactJsxRuntime from "react/jsx-runtime";
|
||||
import * as ReactJsxDevRuntime from "react/jsx-dev-runtime";
|
||||
|
||||
import * as WidgetSdk from "@homarr/widget-sdk";
|
||||
|
||||
const registryKey = Symbol.for("homarr.widget.modules.v1");
|
||||
const loaders: Record<string, () => Promise<unknown>> = {
|
||||
"react-dom": () => import("react-dom"),
|
||||
"react-dom/client": () => import("react-dom/client"),
|
||||
"@mantine/core": () => import("@mantine/core"),
|
||||
"@mantine/hooks": () => import("@mantine/hooks"),
|
||||
"@mantine/charts": () => import("@mantine/charts"),
|
||||
"@mantine/dates": () => import("@mantine/dates"),
|
||||
// Old artifacts externalized Tabler. New builds bundle only the icons their source imports.
|
||||
"@tabler/icons-react": () => import("@tabler/icons-react"),
|
||||
"@tanstack/react-query": () => import("@tanstack/react-query"),
|
||||
"@homarr/widget-sdk/ui": () => import("@homarr/widget-sdk/ui"),
|
||||
"@homarr/widget-sdk/table": () => import("@homarr/widget-sdk/table"),
|
||||
"@homarr/widget-sdk/legacy": () => import("./trusted-widget-legacy"),
|
||||
};
|
||||
interface WidgetModuleRegistry {
|
||||
prepare(ids?: readonly string[]): Promise<void>;
|
||||
require(id: string): unknown;
|
||||
}
|
||||
|
||||
/** Every artifact uses Homarr's React; optional UI libraries load only when its compiled imports need them. */
|
||||
export function registerTrustedWidgetModules() {
|
||||
const registry = globalThis as typeof globalThis & { [registryKey]?: WidgetModuleRegistry };
|
||||
const modules: Record<string, unknown> = {
|
||||
react: React,
|
||||
"react/jsx-runtime": ReactJsxRuntime,
|
||||
"react/jsx-dev-runtime": ReactJsxDevRuntime,
|
||||
"@homarr/widget-sdk": WidgetSdk,
|
||||
"@homarr/widget-sdk/client": WidgetSdk,
|
||||
};
|
||||
const pending = new Map<string, Promise<void>>();
|
||||
// Refresh module exports after HMR; all SDK copies retain the shared context identity.
|
||||
registry[registryKey] = {
|
||||
async prepare(ids = Object.keys(loaders)) {
|
||||
await Promise.all(
|
||||
ids.map((id) => {
|
||||
if (Object.hasOwn(modules, id)) return;
|
||||
const existing = pending.get(id);
|
||||
if (existing) return existing;
|
||||
const load = loaders[id];
|
||||
if (!load) throw new Error(`Unsupported widget host module: ${id}`);
|
||||
const loading = load().then((value) => {
|
||||
modules[id] = value;
|
||||
});
|
||||
pending.set(id, loading);
|
||||
void loading.catch(() => pending.delete(id));
|
||||
return loading;
|
||||
}),
|
||||
);
|
||||
},
|
||||
require(id) {
|
||||
if (!Object.hasOwn(modules, id)) throw new Error(`Widget host module was not prepared: ${id}`);
|
||||
return modules[id];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { useRef } from "react";
|
||||
|
||||
import { createWidgetRuntimeState } from "../definition";
|
||||
import TrustedWidgetDisplay from "./trusted-widget-display";
|
||||
import type { TrustedWidgetData } from "./trusted-widget-types";
|
||||
|
||||
export type { TrustedWidgetData } from "./trusted-widget-types";
|
||||
|
||||
export default function TrustedWidgetPreview({
|
||||
data,
|
||||
width,
|
||||
height,
|
||||
displayScale = 1,
|
||||
surface = "tile",
|
||||
onOptionsChange,
|
||||
onSurfaceChange,
|
||||
frozen = false,
|
||||
onReady,
|
||||
onLoadError,
|
||||
}: {
|
||||
data: TrustedWidgetData;
|
||||
width: number;
|
||||
height: number;
|
||||
displayScale?: number;
|
||||
surface?: "tile" | "advanced" | "configuration";
|
||||
onOptionsChange?: (options: Record<string, unknown>) => void;
|
||||
onSurfaceChange?: (surface: "tile" | "advanced" | "configuration") => void;
|
||||
frozen?: boolean;
|
||||
onReady?: (previewId: string) => void;
|
||||
onLoadError?: (previewId: string, error: Error) => void;
|
||||
}) {
|
||||
const widgetStateRef = useRef<Record<string, unknown> | null>(null);
|
||||
const widgetRuntimeRef = useRef(createWidgetRuntimeState());
|
||||
let displayMode: "compact" | "advanced" = "compact";
|
||||
if (surface === "advanced") displayMode = "advanced";
|
||||
return (
|
||||
<TrustedWidgetDisplay
|
||||
data={data}
|
||||
surface={surface}
|
||||
onOptionsChange={onOptionsChange}
|
||||
frozen={frozen}
|
||||
onReady={onReady}
|
||||
onLoadError={onLoadError}
|
||||
widget={{
|
||||
options: {
|
||||
definitionId: data.installationId,
|
||||
configuration: data.options,
|
||||
configurationVersion: 1,
|
||||
connectionBindings: {},
|
||||
refreshInterval: 30,
|
||||
},
|
||||
integrationIds: [],
|
||||
itemId: undefined,
|
||||
boardId: undefined,
|
||||
isEditMode: false,
|
||||
displayMode,
|
||||
openAdvancedFocus: () => onSurfaceChange?.("advanced"),
|
||||
closeAdvancedFocus: () => onSurfaceChange?.("tile"),
|
||||
width,
|
||||
height,
|
||||
displayScale,
|
||||
widgetStateRef,
|
||||
widgetRuntimeRef,
|
||||
setOptions: () => undefined,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { WidgetSubscriptionObserver } from "@homarr/widget-sdk/shared";
|
||||
|
||||
interface SharedSubscription {
|
||||
itemId: string;
|
||||
listeners: Set<WidgetSubscriptionObserver>;
|
||||
start(observer: WidgetSubscriptionObserver): () => void;
|
||||
stop(): void;
|
||||
generation: number;
|
||||
latest?: { value: unknown };
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const subscriptions = new Map<string, SharedSubscription>();
|
||||
const focusTransitionGraceMs = 500;
|
||||
|
||||
/** One live connection per viewer, placement, revision and request, with a single retained event. */
|
||||
export function subscribeSharedWidget(
|
||||
key: string,
|
||||
itemId: string,
|
||||
start: SharedSubscription["start"],
|
||||
observer: WidgetSubscriptionObserver,
|
||||
) {
|
||||
let shared = subscriptions.get(key);
|
||||
let created = false;
|
||||
if (!shared) {
|
||||
shared = { itemId, listeners: new Set(), start, stop: () => undefined, generation: 0 };
|
||||
subscriptions.set(key, shared);
|
||||
created = true;
|
||||
}
|
||||
const entry = shared;
|
||||
clearTimeout(entry.timer);
|
||||
entry.timer = undefined;
|
||||
entry.listeners.add(observer);
|
||||
if (entry.latest) observer.next(entry.latest.value);
|
||||
if (created) connect(key, entry);
|
||||
return () => {
|
||||
entry.listeners.delete(observer);
|
||||
if (entry.listeners.size > 0 || subscriptions.get(key) !== entry) return;
|
||||
entry.timer = setTimeout(() => dispose(key, entry), focusTransitionGraceMs);
|
||||
};
|
||||
}
|
||||
|
||||
function connect(key: string, entry: SharedSubscription) {
|
||||
const generation = ++entry.generation;
|
||||
const active = () => subscriptions.get(key) === entry && entry.generation === generation;
|
||||
try {
|
||||
const stop = entry.start({
|
||||
next(value) {
|
||||
if (!active()) return;
|
||||
entry.latest = { value };
|
||||
entry.listeners.forEach((listener) => listener.next(value));
|
||||
},
|
||||
error(error) {
|
||||
if (!active()) return;
|
||||
dispose(key, entry);
|
||||
entry.listeners.forEach((listener) => listener.error(error));
|
||||
entry.listeners.clear();
|
||||
},
|
||||
complete() {
|
||||
if (!active()) return;
|
||||
dispose(key, entry);
|
||||
entry.listeners.forEach((listener) => listener.complete());
|
||||
entry.listeners.clear();
|
||||
},
|
||||
});
|
||||
if (subscriptions.get(key) !== entry) stop();
|
||||
else entry.stop = stop;
|
||||
} catch (error) {
|
||||
dispose(key, entry);
|
||||
const failure = error instanceof Error ? error : new Error(String(error));
|
||||
entry.listeners.forEach((listener) => listener.error(failure));
|
||||
entry.listeners.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function dispose(key: string, entry: SharedSubscription) {
|
||||
entry.generation++;
|
||||
if (subscriptions.get(key) === entry) subscriptions.delete(key);
|
||||
clearTimeout(entry.timer);
|
||||
entry.latest = undefined;
|
||||
entry.stop();
|
||||
entry.stop = () => undefined;
|
||||
}
|
||||
|
||||
/** Binding and activation events discard the retained event and reopen authorized server handlers. */
|
||||
export function refreshSharedWidgetSubscriptions(itemId: string) {
|
||||
for (const [key, entry] of subscriptions) {
|
||||
if (entry.itemId !== itemId) continue;
|
||||
entry.generation++;
|
||||
entry.stop();
|
||||
entry.stop = () => undefined;
|
||||
entry.latest = undefined;
|
||||
if (entry.listeners.size === 0) dispose(key, entry);
|
||||
else connect(key, entry);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSharedWidgetSubscriptions(itemId: string, error: Error) {
|
||||
for (const [key, entry] of subscriptions) {
|
||||
if (entry.itemId !== itemId) continue;
|
||||
dispose(key, entry);
|
||||
entry.listeners.forEach((listener) => listener.error(error));
|
||||
entry.listeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useMemo, useRef } from "react";
|
||||
import { hashKey } from "@tanstack/react-query";
|
||||
import { clientApi, fetchApi } from "@homarr/api/client";
|
||||
import type { WidgetTransport } from "@homarr/widget-sdk/shared";
|
||||
import { subscribeSharedWidget } from "./trusted-widget-subscriptions";
|
||||
|
||||
export function useTrustedWidgetTransport(previewId: string | undefined, subscriptionScope: string, frozen = false) {
|
||||
const client = clientApi.useUtils().client;
|
||||
const frozenRef = useRef(frozen);
|
||||
frozenRef.current = frozen;
|
||||
const assertExecuting = () => {
|
||||
if (frozenRef.current) throw new Error("The retained preview is paused. Preview the current draft to resume.");
|
||||
};
|
||||
const transport = useMemo<WidgetTransport>(
|
||||
() => ({
|
||||
query: (input, signal) => {
|
||||
assertExecuting();
|
||||
if (previewId)
|
||||
return fetchApi.customWidget.package.previewQuery.query(
|
||||
{ previewId: previewId, name: input.name, input: input.input },
|
||||
{ signal },
|
||||
);
|
||||
return fetchApi.widget.customApi.packageQuery.query(input, { signal });
|
||||
},
|
||||
action: (input) => {
|
||||
assertExecuting();
|
||||
if (previewId)
|
||||
return fetchApi.customWidget.package.previewAction.mutate({
|
||||
previewId: previewId,
|
||||
name: input.name,
|
||||
input: input.input,
|
||||
});
|
||||
return fetchApi.widget.customApi.packageAction.mutate(input);
|
||||
},
|
||||
subscribe(input, observer) {
|
||||
if (frozenRef.current) {
|
||||
observer.complete();
|
||||
return () => undefined;
|
||||
}
|
||||
return subscribeSharedWidget(
|
||||
hashKey([subscriptionScope, input]),
|
||||
input.itemId,
|
||||
(sharedObserver) => {
|
||||
if (previewId) {
|
||||
const subscription = client.customWidget.package.previewSubscription.subscribe(
|
||||
{ previewId: previewId, name: input.name, input: input.input },
|
||||
{
|
||||
onData: sharedObserver.next,
|
||||
onError: sharedObserver.error,
|
||||
onComplete: sharedObserver.complete,
|
||||
},
|
||||
);
|
||||
return () => subscription.unsubscribe();
|
||||
}
|
||||
const subscription = client.widget.customApi.packageSubscription.subscribe(input, {
|
||||
onData: sharedObserver.next,
|
||||
onError: sharedObserver.error,
|
||||
onComplete: sharedObserver.complete,
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
},
|
||||
observer,
|
||||
);
|
||||
},
|
||||
storageGet: (input, signal) => {
|
||||
assertExecuting();
|
||||
if (previewId)
|
||||
return fetchApi.customWidget.package.previewStorageGet.query(
|
||||
{ previewId, scope: input.scope, key: input.key },
|
||||
{ signal },
|
||||
);
|
||||
return fetchApi.widget.customApi.packageStorageGet.query(input, { signal });
|
||||
},
|
||||
storageSet: (input) => {
|
||||
assertExecuting();
|
||||
if (previewId)
|
||||
return fetchApi.customWidget.package.previewStorageSet.mutate({
|
||||
previewId,
|
||||
scope: input.scope,
|
||||
key: input.key,
|
||||
value: input.value,
|
||||
});
|
||||
return fetchApi.widget.customApi.packageStorageSet.mutate(input);
|
||||
},
|
||||
}),
|
||||
[client, previewId, subscriptionScope],
|
||||
);
|
||||
|
||||
return transport;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { WidgetPackageManifest } from "@homarr/custom-widgets/package";
|
||||
|
||||
export interface TrustedWidgetData {
|
||||
type: "customWidgetV3";
|
||||
installationId: string;
|
||||
previewId?: string;
|
||||
artifactDigest: string;
|
||||
manifest: WidgetPackageManifest;
|
||||
options: Record<string, unknown>;
|
||||
surfaceUrls: { tile: string; advanced?: string; configuration?: string };
|
||||
stylesheetUrls: { tile: string; advanced?: string; configuration?: string };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
|
||||
import { isTerminalCustomWidgetDefinitionError } from "./migration-state";
|
||||
import { clearSharedWidgetSubscriptions, refreshSharedWidgetSubscriptions } from "./trusted-widget-subscriptions";
|
||||
|
||||
export function usePackageLifecycle({
|
||||
itemId,
|
||||
enabled,
|
||||
refresh,
|
||||
}: {
|
||||
itemId?: string;
|
||||
enabled: boolean;
|
||||
refresh(): Promise<{ error: unknown }>;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [accessError, setAccessError] = useState<Error | null>(null);
|
||||
useEffect(() => setAccessError(null), [itemId]);
|
||||
const belongsToPlacement = (query: { queryKey: readonly unknown[] }) =>
|
||||
query.queryKey[0] === "custom-widget-sdk" && query.queryKey[2] === itemId;
|
||||
clientApi.widget.customApi.packageLifecycle.useSubscription(
|
||||
{ itemId: itemId ?? "" },
|
||||
{
|
||||
enabled: enabled && Boolean(itemId),
|
||||
onData(event) {
|
||||
if (event.kind === "storage") {
|
||||
void queryClient.invalidateQueries({
|
||||
predicate: (query) => belongsToPlacement(query) && query.queryKey[4] === "storage",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.kind === "disabled") {
|
||||
const error = Object.assign(new Error("Widget installation is disabled"), { data: { code: "FORBIDDEN" } });
|
||||
setAccessError(error);
|
||||
if (itemId) clearSharedWidgetSubscriptions(itemId, error);
|
||||
queryClient.removeQueries({ predicate: belongsToPlacement });
|
||||
} else if (itemId) refreshSharedWidgetSubscriptions(itemId);
|
||||
void queryClient.invalidateQueries({ predicate: belongsToPlacement });
|
||||
void refresh().then((result) => {
|
||||
if (!result.error) setAccessError(null);
|
||||
});
|
||||
},
|
||||
onError(error) {
|
||||
if (!isTerminalCustomWidgetDefinitionError(error)) return;
|
||||
setAccessError(new Error(error.message));
|
||||
if (itemId)
|
||||
clearSharedWidgetSubscriptions(itemId, Object.assign(new Error(error.message), { data: error.data }));
|
||||
queryClient.removeQueries({ predicate: belongsToPlacement });
|
||||
void refresh().then((result) => {
|
||||
if (!result.error) setAccessError(null);
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
return accessError;
|
||||
}
|
||||
@@ -36,7 +36,7 @@ const INACTIVE_PORT: CustomWidgetRuntimePort = {
|
||||
notify: () => undefined,
|
||||
};
|
||||
|
||||
const useRuntimeMessages = (): CustomWidgetRuntimeMessages => {
|
||||
export const useRuntimeMessages = (): CustomWidgetRuntimeMessages => {
|
||||
const t = useI18n("widget.customApi.customJsx");
|
||||
const actionT = useI18n("common.action");
|
||||
return {
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { ServerSettings } from "@homarr/server-settings";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
import type { stringOrTranslation } from "@homarr/translation";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
import type { WidgetCommand } from "@homarr/widget-sdk/shared";
|
||||
|
||||
import type { WidgetImports } from "./registry";
|
||||
import type { inferOptionsFromCreator, WidgetOptionsRecord } from "./options";
|
||||
@@ -41,6 +42,8 @@ export interface WidgetRuntimeActions {
|
||||
export interface WidgetRuntimeState {
|
||||
queries: readonly NormalizedWidgetQuery[];
|
||||
actions: WidgetRuntimeActions;
|
||||
commands?: readonly WidgetCommand[];
|
||||
refresh?: () => Promise<void>;
|
||||
}
|
||||
|
||||
export type WidgetRuntimeRef = React.MutableRefObject<WidgetRuntimeState>;
|
||||
@@ -174,6 +177,8 @@ export type WidgetComponentProps<TKind extends WidgetKind> = WidgetProps<TKind>
|
||||
boardId: string | undefined; // undefined when in preview mode
|
||||
isEditMode: boolean;
|
||||
displayMode?: "compact" | "advanced";
|
||||
openAdvancedFocus?: () => void;
|
||||
closeAdvancedFocus?: () => void;
|
||||
setOptions: ({ newOptions }: { newOptions: Partial<inferOptionsFromCreator<WidgetOptionsRecordOf<TKind>>> }) => void;
|
||||
width: number;
|
||||
height: number;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
|
||||
/** Small metadata only: native menus never import package source or the trusted widget runtime. */
|
||||
export function getNativeWidgetReferenceStarter(kind: WidgetKind, integrationKinds: readonly IntegrationKind[] = []) {
|
||||
if (kind === "clock") return "clock";
|
||||
if (kind === "timer") return "timer";
|
||||
if (kind === "downloads") return "downloads";
|
||||
if (kind === "mediaServer") return "media";
|
||||
if (kind === "beszelSystemGrid" || kind === "beszelSystemTable" || kind === "beszelSystemStats") return "beszel";
|
||||
if (
|
||||
(kind === "calendar" || kind === "mediaMissing") &&
|
||||
integrationKinds.length === 1 &&
|
||||
integrationKinds[0] === "sonarr"
|
||||
)
|
||||
return "sonarr";
|
||||
return undefined;
|
||||
}
|
||||
Reference in new issue
Block a user