refactor: consolidate widget workbench modules

This commit is contained in:
ajnart committed 2026-09-12 16:06:18 +02:00
1 parent 29c94be821
commit 84058544a4
50 files changed
+1529 -1597

No files matched your search

@@ -27,7 +27,7 @@ import { useI18n } from "@homarr/translation/client";
import { InlineConfirmMenuItem, Link } from "@homarr/ui";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { downloadJson } from "~/components/custom-widgets/download";
import { downloadJson } from "@homarr/common";
const iconProps = { size: 16, stroke: 1.5 };
@@ -1,52 +0,0 @@
"use client";
import { useState } from "react";
import { Accordion, Select, Stack, Text } from "@mantine/core";
import type { CustomWidgetArtifact } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
import { CodeEditor } from "~/components/custom-widgets/code-editor";
export function PackageArtifactReview({ artifact }: { artifact: CustomWidgetArtifact }) {
const t = useI18n("customWidget.package.artifactReview");
const [selected, setSelected] = useState("dependency-lock.json");
const files: Record<string, string> = { "dependency-lock.json": JSON.stringify(artifact.dependencyLock, null, 2) };
for (const [surface, compiled] of Object.entries(artifact.client)) {
if (!compiled) continue;
files[`${surface}.js`] = compiled.javascript;
if (compiled.css) files[`${surface}.css`] = compiled.css;
}
if (artifact.server) files["server.js"] = artifact.server;
const path = Object.hasOwn(files, selected) ? selected : "dependency-lock.json";
return (
<Accordion>
<Accordion.Item value="artifact">
<Accordion.Control>{t("title")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
<Text size="sm">{t("description")}</Text>
<Text size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
{artifact.digest}
</Text>
<Select
label={t("file")}
value={path}
data={Object.keys(files)}
onChange={(value) => {
if (value) setSelected(value);
}}
/>
<CodeEditor
id={`artifact-${artifact.digest}-${path}`}
label={path}
value={files[path] ?? ""}
language={path.endsWith(".json") ? "json" : path.endsWith(".css") ? "css" : "tsx"}
readOnly
height="320px"
onChange={() => undefined}
/>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
);
}
@@ -1,20 +0,0 @@
import { HOST_WIDGET_MODULES } from "@homarr/custom-widgets/package";
/** Public authoring context only. Local bindings and runtime response data never belong here. */
export const packageAssistantSdkContext = {
schema: "homarr-widget-package-v3",
sdkVersion: "1",
hostModules: HOST_WIDGET_MODULES,
package:
"widget.json contains $schema, manifest, dependencies, connections, options; files are edited separately. manifest requires id, name, version (exact semver), sdkVersion:'1', entrypoints:{tile,advanced?,configuration?,server?}. Each client surface default-exports a React component. Local relative modules and CSS imports work. dependencies maps npm names to exact versions. No request, connection or server file is required for static widgets. Declare connections as named {label,kind:'http'|'integration'|'service',optional?}; service requirements also declare serviceType. Owners bind local settings and encrypted secrets. Never embed credentials, local addresses or connection IDs in portable source.",
styling:
"Use normal TSX, React hooks, imported Mantine components, CSS and reusable modules. manifest.styles defaults to scoped CSS; 'global' is an explicit package choice. Build dashboard tiles and advanced views; there is no standalone application route. Respect host.visibleWidth/visibleHeight, colorScheme, locale, reducedMotion and isEditMode. Entry points may reuse the same component and branch on displayMode.",
client:
"Import @homarr/widget-sdk. useWidgetHost() returns displayMode:'compact'|'advanced',width,height,visibleWidth,visibleHeight,displayScale,visible,isPreview,isEditMode,locale,timeZone,colorScheme,reducedMotion. useWidgetOptions<T>() returns option values. useWidgetState<T>(key,initial) shares instance state between tile and advanced. useWidgetClock(intervalMs=1000) returns epoch milliseconds or null, pauses when hidden. useWidgetQuery<T>(name,input?,{enabled?,refetchInterval?,staleTime?}) returns query state. useWidgetAction<Output,Input>(name) returns mutation (mutate/mutateAsync). useWidgetSubscription<T>(name,input?,{enabled?,maximumEvents?}) returns data,events,error,connected,reconnect. useWidgetStorage<T>('user'|'instance'|'installation',key,initial) returns data,set,saving,saveError. useWidgetCommands([{id,label,run,disabled?,destructive?}]) registers native menu commands. WidgetScope name/handlerPrefix/options isolates composed components.",
services:
"useWidgetServices() exposes notify({title,message?,color?}), navigate(href), openAdvanced(), closeAdvanced(), openDetail({title,content:ReactNode}), closeDetail(), confirm({title,message,destructive?}):Promise<boolean>, updateOptions(record):Promise<void>. Use updateOptions from an authored configuration surface. Managed storage is isolated memory in preview. Query results and local options are not part of Assistant context.",
server:
"Optional server.ts imports @homarr/widget-sdk/server and default-exports defineWidgetServer({handler:async(input,context)=>value}). Declare every handler in manifest.handlers with kind:'query'|'action'|'subscription'|'migration', permission:'view'|'modify'|'full', inputSchema? (JSON Schema), guestAccess?; actions default to modify. fetchWidgetConnection<T>(context,{connection:'slot',path,method?,query?,body?,responseType?}) returns {data,ok,status,contentType,durationMs,updatedAt}. getWidgetConnection<TSettings>(context,{connection,serviceType?}) returns {configuration:{kind,serviceType?,settings?:TSettings,...},secrets:Record<string,string>} only to trusted server code for Node SQL, MQTT, SSH, files or other service clients; never return secrets to browser queries. getWidgetServerContext(context) returns options,installationId,bindingNames,bindingLabels,isPreview. Declare connections with multiple:true for a repeatable group, and integrationKind (for example sonarr) to filter compatible native integrations. getWidgetConnectionGroup(context,slot) returns all {connection,label} members for queries and actions; do not hard-code first/second server slots. callWidgetIntegration(context,{connection,capability,input?}) invokes native adapters; subscribeWidgetIntegration yields native stream events. callWidgetRunner and subscribeWidgetRunner address owner-managed remote runners. Server modules have trusted Node capabilities. Secrets stay in owner-bound connections. Do not invent integration capabilities: use reference packages or declared capability docs.",
lifecycle:
"Proposals only change the visible draft after explicit review; they never save, trust, run or activate code. The owner saves the draft, reviews dependencies and trust, runs exact-candidate Preview, then explicitly activates the saved release for all placements. SDK actions are simulated in default previews, but arbitrary trusted browser/Node code still executes. A preview session proves compilation/session creation only, not successful UI rendering, live action success or all application behavior. Any source/options/binding edit invalidates preview evidence.",
};
@@ -2,10 +2,25 @@
import { Alert, Button, Divider, Group, Popover, Stack, Text, Textarea } from "@mantine/core";
import { IconSparkles } from "@tabler/icons-react";
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
import { createId } from "@homarr/common";
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { packageDraftToolContracts } from "~/components/assistant/assistant-package-draft-contracts";
import type {
PackageDraftReview,
ProposePackageChangesArgs,
} from "~/components/assistant/assistant-package-draft-contracts";
import {
notifyPackageDraftChanged,
registerAssistantPackageDraft,
} from "~/components/assistant/assistant-package-draft-registry";
import { packageAssistantSdkContext } from "@homarr/custom-widgets/authoring-prompt";
import { recoveryDocument } from "@homarr/custom-widgets/workbench/package";
import type { PackageDocument } from "@homarr/custom-widgets/workbench/package";
import type { usePackageWorkspace } from "./_use-package-workspace";
export function PackageAssistant() {
const t = useI18n("customWidget.package.assistant");
@@ -91,3 +106,158 @@ export function PackageAssistant() {
</Popover>
);
}
type Workspace = ReturnType<typeof usePackageWorkspace>;
const maximumContextCharacters = 180_000;
export function usePackageAssistant(workspace: Workspace) {
const identity = useRef({ document: workspace.document, revision: createId() });
if (identity.current.document !== workspace.document)
identity.current = { document: workspace.document, revision: createId() };
const revision = identity.current.revision;
const latest = useRef({ workspace, revision });
latest.current = { workspace, revision };
const readState = useRef({ revision: "", paths: new Set<string>(), metadata: false });
useEffect(
() =>
registerAssistantPackageDraft({
read(input) {
const { workspace: state, revision: currentRevision } = latest.current;
const sanitized = recoveryDocument(state.document);
if (readState.current.revision !== currentRevision)
readState.current = { revision: currentRevision, paths: new Set(), metadata: false };
const metadataOmitted = sanitized.metadata.length > 60_000;
if (!metadataOmitted) readState.current.metadata = true;
const files: Record<string, string> = {};
const omittedFiles: string[] = [];
let remaining = maximumContextCharacters;
for (const path of input.paths ?? Object.keys(sanitized.files)) {
const value = sanitized.files[path];
if (value === undefined || value.length > remaining) {
omittedFiles.push(path);
continue;
}
files[path] = value;
remaining -= value.length;
readState.current.paths.add(path);
}
const redactedFiles = Object.keys(sanitized.files).filter(
(path) => sanitized.files[path] !== state.document.files[path],
);
let previewEvidence: unknown = { status: "not-previewed-current-candidate" };
if (state.preview && !state.stale)
previewEvidence = {
status: "compiled-and-preview-session-created",
revision: currentRevision,
artifactDigest: state.preview.displayData.artifactDigest,
browserRenderingVerified: false,
liveActions: state.preview.liveActions,
};
return {
installationId: state.installationId,
saved: !state.editor.dirty,
revision: currentRevision,
name: sanitized.name,
metadata: metadataOmitted ? undefined : sanitized.metadata,
metadataOmitted,
selectedFile: state.selected,
filePaths: Object.keys(sanitized.files),
files,
omittedFiles,
oversizedFiles: Object.entries(sanitized.files)
.filter(([, value]) => value.length > maximumContextCharacters)
.map(([path]) => path),
contextLimits: {
fileCharacters: maximumContextCharacters,
metadataCharacters: 60_000,
oversizedFilesRequireManualEdit: true,
},
redactedFiles,
metadataRedacted: sanitized.metadata !== state.document.metadata,
diagnostics: recoveryDocument({ name: "", metadata: state.error, files: {} }).metadata.slice(0, 4000),
schemaValid: state.parsed.success,
validationIssues: state.parsed.success
? []
: state.parsed.error.issues.map(({ path, message }) => ({ path, message })),
sdk: packageAssistantSdkContext,
reference: input.reference ? widgetReferencePackages[input.reference] : undefined,
previewEvidence,
excluded: [
"local connection bindings",
"connection settings and credentials",
"preview option values",
"runtime response data",
],
};
},
review(input) {
return prepare(input, latest.current, readState.current).review;
},
apply(input) {
const prepared = prepare(input, latest.current, readState.current);
if (!prepared.review.available || !prepared.next) return { applied: false, error: prepared.review.error };
latest.current.workspace.resetExecution();
readState.current = { revision: "", paths: new Set(), metadata: false };
latest.current.workspace.edit(prepared.next);
return { applied: true };
},
}),
[],
);
useEffect(() => {
notifyPackageDraftChanged();
}, [revision, workspace.busy, workspace.preview, workspace.error]);
}
function prepare(
input: ProposePackageChangesArgs,
{ workspace, revision }: { workspace: Workspace; revision: string },
read: { revision: string; paths: Set<string>; metadata: boolean },
): { review: PackageDraftReview; next?: PackageDocument } {
const parsed = packageDraftToolContracts.propose_widget_package_changes.parameters.safeParse(input);
if (!parsed.success) return unavailable("The proposed patch is invalid.");
if (revision !== input.revision || read.revision !== revision)
return unavailable("The draft changed. Ask the Assistant to read the current draft and propose again.");
if (workspace.busy) return unavailable("Wait for the current save or preview to finish.");
const current = workspace.document;
if (input.metadata !== undefined && !read.metadata)
return unavailable(
"The manifest is too large for Assistant context. Edit it directly before proposing a replacement.",
);
const sanitized = recoveryDocument(current);
if (input.metadata !== undefined && sanitized.metadata !== current.metadata)
return unavailable(
"The manifest contains redacted credentials. Move them to a local connection before replacing this file.",
);
if (input.name !== undefined && sanitized.name !== current.name)
return unavailable("The name contains redacted credentials. Edit it directly before proposing a replacement.");
const next = {
name: input.name ?? current.name,
metadata: input.metadata ?? current.metadata,
files: { ...current.files },
};
const changes: PackageDraftReview["changes"] = [];
if (next.name !== current.name) changes.push({ path: "Installation name", before: current.name, after: next.name });
if (next.metadata !== current.metadata)
changes.push({ path: "widget.json", before: current.metadata, after: next.metadata });
for (const [path, value] of Object.entries(input.files)) {
if (Object.hasOwn(current.files, path) && !read.paths.has(path))
return unavailable(`Read '${path}' before proposing changes to it.`);
if (sanitized.files[path] !== current.files[path])
return unavailable(
`'${path}' contains redacted credentials. Move them to local connections before replacing this file.`,
);
if (value === null) delete next.files[path];
else next.files[path] = value;
if (value !== current.files[path]) changes.push({ path, before: current.files[path] ?? "", after: value ?? "" });
}
if (
Object.keys(next.files).length > 256 ||
Object.values(next.files).reduce((size, file) => size + file.length, 0) > 20_000_000
)
return unavailable("The proposed draft exceeds package size limits.");
return { next, review: { available: true, changes } };
}
const unavailable = (error: string) => ({ review: { available: false, error, changes: [] } });
@@ -1,125 +0,0 @@
"use client";
import { useEffect, useRef, useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { Alert, MultiSelect, Select, Stack } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { getWidgetConnectionBindingNames, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
export function PackageBindingPicker({
name,
requirement,
connections,
integrations,
bindings,
onChange,
onPendingChange,
disabled,
}: {
name: string;
requirement: CustomWidgetPackage["connections"][string];
connections: RouterOutputs["customWidget"]["package"]["connections"];
integrations: RouterOutputs["integration"]["all"];
bindings: Record<string, string>;
onChange: Dispatch<SetStateAction<Record<string, string>>>;
onPendingChange(pending: boolean): void;
disabled: boolean;
}) {
const t = useI18n("customWidget.package");
const utils = clientApi.useUtils();
const saveConnection = clientApi.customWidget.package.saveConnection.useMutation();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const preparing = useRef(false);
const mounted = useRef(true);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const ids = [...new Set(getWidgetConnectionBindingNames(name, requirement, bindings).map((key) => bindings[key]!))];
const compatible = connections.filter((connection) => isWidgetConnectionCompatible(requirement, connection.configuration));
const choices = compatible.map((connection) => ({ value: connection.id, label: connection.name }));
if (requirement.kind === "integration") {
for (const integration of integrations) {
if (requirement.integrationKind && integration.kind !== requirement.integrationKind) continue;
if (compatible.some((connection) => connection.integrationId === integration.id)) continue;
choices.push({ value: `integration:${integration.id}`, label: integration.name });
}
}
// Keep unavailable bindings visible so a removed integration can be diagnosed or replaced.
for (const id of ids) {
if (!choices.some((choice) => choice.value === id))
choices.push({ value: id, label: connections.find((connection) => connection.id === id)?.name ?? t("unavailableConnection") });
}
const change = async (values: string[]) => {
if (preparing.current || disabled) return;
preparing.current = true;
setPending(true);
onPendingChange(true);
setError("");
try {
const nextIds: string[] = [];
for (const value of values) {
if (!value.startsWith("integration:")) {
nextIds.push(value);
continue;
}
const integration = integrations.find((entry) => `integration:${entry.id}` === value);
if (!integration) throw new Error(t("unavailableConnection"));
const result = await saveConnection.mutateAsync({
name: integration.name,
integrationId: integration.id,
configuration: { kind: "integration" },
});
nextIds.push(result.id);
}
if (!mounted.current) return;
onChange((current) => {
const next = { ...current };
for (const key of getWidgetConnectionBindingNames(name, requirement, next)) delete next[key];
for (const [index, id] of nextIds.entries()) {
let key = name;
if (index > 0) key = `${name}:${id}`;
next[key] = id;
}
return next;
});
} catch (cause) {
if (mounted.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally {
// Refresh the list independently; a failed refetch must not discard a selection.
if (values.some((value) => value.startsWith("integration:")))
void utils.customWidget.package.connections.invalidate();
preparing.current = false;
if (mounted.current) setPending(false);
onPendingChange(false);
}
};
const common = {
label: requirement.label,
description: requirement.description,
placeholder: t("chooseConnection"),
required: !requirement.optional,
searchable: true,
clearable: true,
disabled: pending || disabled,
data: choices,
nothingFoundMessage: t("noCompatibleConnections"),
};
return (
<Stack gap="xs" flex={1}>
{requirement.multiple ? (
<MultiSelect {...common} value={ids} onChange={(values) => void change(values)} />
) : (
<Select {...common} value={ids[0] ?? null} onChange={(value) => void change(value ? [value] : [])} />
)}
{error && <Alert color="red">{error}</Alert>}
</Stack>
);
}
@@ -1,5 +1,7 @@
"use client";
import { extractErrorMessage } from "@homarr/common";
import { useState } from "react";
import {
Alert,
@@ -13,12 +15,12 @@ import {
Text,
Textarea,
TextInput,
Accordion,
Table,
} from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { PackageHistorySummary } from "./_package-history-summary";
export function PackageCollectors({ itemId, queries }: { itemId: string; queries: string[] }) {
const t = useI18n("customWidget.package");
@@ -61,7 +63,7 @@ export function PackageCollectors({ itemId, queries }: { itemId: string; queries
},
);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
};
return (
@@ -195,3 +197,71 @@ function CollectorRow({
</Paper>
);
}
type History = RouterOutputs["widget"]["customApi"]["packageHistory"];
function PackageHistorySummary({ data }: { data: History }) {
const t = useI18n("customWidget.package.historySummary");
const latest = data.samples.at(-1);
return (
<Stack gap="xs">
{latest && (
<Group justify="space-between">
<Text fw={600}>
{formatCollectedValue(latest.value)} {data.unit}
</Text>
<Text size="xs" c="dimmed">
{t("latest", { time: new Date(latest.timestamp).toLocaleString() })}
</Text>
</Group>
)}
{!latest && (
<Text size="sm" c="dimmed">
{t("empty")}
</Text>
)}
{"lastError" in data && data.lastError && <Alert color="yellow">{data.lastError}</Alert>}
<Accordion multiple>
<Accordion.Item value="samples">
<Accordion.Control>{t("samples", { count: data.samples.length })}</Accordion.Control>
<Accordion.Panel>
<div style={{ maxHeight: 220, overflow: "auto" }}>
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("time")}</Table.Th>
<Table.Th>{t("value")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data.samples.toReversed().map((sample, index) => (
<Table.Tr key={`${sample.timestamp}-${index}`}>
<Table.Td>{new Date(sample.timestamp).toLocaleString()}</Table.Td>
<Table.Td>
{formatCollectedValue(sample.value)} {data.unit}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</div>
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="technical">
<Accordion.Control>{t("details")}</Accordion.Control>
<Accordion.Panel>
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>
{JSON.stringify(data, null, 2)}
</Text>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
function formatCollectedValue(value: unknown): string {
if (typeof value === "number") return value.toLocaleString();
if (typeof value === "string") return value.slice(0, 240);
return (JSON.stringify(value) ?? "—").slice(0, 240);
}
@@ -1,58 +0,0 @@
"use client";
import { Accordion, Alert, Badge, Group, Stack, Text } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { useI18n } from "@homarr/translation/client";
type Diagnostic = RouterOutputs["customWidget"]["package"]["diagnoseConnection"];
export function PackageConnectionDiagnostic({ result }: { result: Diagnostic }) {
const t = useI18n("customWidget.package.diagnostic");
let color = "yellow";
if (["connected", "integration", "fileReadable", "transportReachable"].includes(result.status)) color = "green";
if (["dnsError", "unavailable", "httpError", "serviceUnavailable"].includes(result.status)) color = "red";
return (
<Stack gap="xs">
<Alert color={color} title={t(`status.${result.status}`)}>
<Stack gap="xs">
<Text size="sm">{t(`help.${result.status}`)}</Text>
{"stage" in result && (
<Text size="xs">
{t("phase", { phase: t(`stage.${result.stage as "dns" | "connection" | "tls" | "response"}`) })}
</Text>
)}
{"hostname" in result && (
<Text size="sm" ff="monospace">
{result.hostname}
</Text>
)}
{result.addresses.length > 0 && (
<Group gap="xs">
{result.addresses.map(({ address }) => (
<Badge key={address} variant="outline" tt="none">
{address}
</Badge>
))}
</Group>
)}
{"httpStatus" in result && typeof result.httpStatus === "number" && typeof result.durationMs === "number" && (
<Text size="xs">{t("response", { status: result.httpStatus, milliseconds: result.durationMs })}</Text>
)}
{"sampleFields" in result && Array.isArray(result.sampleFields) && result.sampleFields.length > 0 && (
<Text size="xs">{t("fields", { fields: result.sampleFields.join(", ") })}</Text>
)}
</Stack>
</Alert>
<Accordion>
<Accordion.Item value="details">
<Accordion.Control>{t("details")}</Accordion.Control>
<Accordion.Panel>
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", overflowWrap: "anywhere" }}>
{JSON.stringify(result, null, 2)}
</Text>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
@@ -1,4 +1,6 @@
"use client";
import { extractErrorMessage, isRecord, getConnectionUrlSuggestion } from "@homarr/common";
import { useState } from "react";
import {
Alert,
@@ -15,10 +17,8 @@ import {
} from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { isRecord } from "@homarr/common";
import { useI18n } from "@homarr/translation/client";
import type { WidgetJson } from "@homarr/widget-sdk/shared";
import { getConnectionUrlSuggestion } from "./_package-connection-url";
type Connection = RouterOutputs["customWidget"]["package"]["connections"][number];
type Authentication = "none" | "basic" | "bearer" | "headers" | "cookie" | "query";
const authKinds = ["none", "basic", "bearer", "headers", "cookie", "query"];
@@ -129,7 +129,7 @@ export function ConnectionEditor({ onSaved, connection }: { onSaved(): void; con
setHeaders("{}");
onSaved();
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
};
return (
@@ -1,11 +0,0 @@
import { getSafeApplicationUrl } from "@homarr/common";
/** Offer an explicit prefix; preserve the owner's hostname, port and path text. */
export function getConnectionUrlSuggestion(value: string): string | undefined {
const input = value.trim();
if (!input || input.includes("://") || (input.startsWith("/") && !input.startsWith("//"))) return undefined;
let candidate = `http://${input}`;
if (input.startsWith("//")) candidate = `http:${input}`;
if (!getSafeApplicationUrl(candidate)) return undefined;
return candidate;
}
@@ -1,15 +1,14 @@
"use client";
import { ConnectionEditor } from "./_package-connection-editor";
import { PackageConnectionDiagnostic } from "./_package-connection-diagnostic";
import { PackageBindingPicker } from "./_package-binding-picker";
import type { RouterOutputs } from "@homarr/api";
import { useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { Alert, Button, Group, Paper, Stack, Text } from "@mantine/core";
import { extractErrorMessage } from "@homarr/common";
import { ConnectionEditor } from "./_package-connection-editor";
import type { RouterOutputs } from "@homarr/api";
import { useState, useEffect, useRef } from "react";
import type { Dispatch, SetStateAction } from "react";
import { Alert, Button, Group, Paper, Stack, Text, MultiSelect, Select, Accordion, Badge } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { getWidgetConnectionBindingNames } from "@homarr/custom-widgets/package";
import { getWidgetConnectionBindingNames, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
@@ -144,3 +143,170 @@ export function PackageConnections({
</Stack>
);
}
function PackageBindingPicker({
name,
requirement,
connections,
integrations,
bindings,
onChange,
onPendingChange,
disabled,
}: {
name: string;
requirement: CustomWidgetPackage["connections"][string];
connections: RouterOutputs["customWidget"]["package"]["connections"];
integrations: RouterOutputs["integration"]["all"];
bindings: Record<string, string>;
onChange: Dispatch<SetStateAction<Record<string, string>>>;
onPendingChange(pending: boolean): void;
disabled: boolean;
}) {
const t = useI18n("customWidget.package");
const utils = clientApi.useUtils();
const saveConnection = clientApi.customWidget.package.saveConnection.useMutation();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const preparing = useRef(false);
const mounted = useRef(true);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const ids = [...new Set(getWidgetConnectionBindingNames(name, requirement, bindings).map((key) => bindings[key]!))];
const compatible = connections.filter((connection) => isWidgetConnectionCompatible(requirement, connection.configuration));
const choices = compatible.map((connection) => ({ value: connection.id, label: connection.name }));
if (requirement.kind === "integration") {
for (const integration of integrations) {
if (requirement.integrationKind && integration.kind !== requirement.integrationKind) continue;
if (compatible.some((connection) => connection.integrationId === integration.id)) continue;
choices.push({ value: `integration:${integration.id}`, label: integration.name });
}
}
// Keep unavailable bindings visible so a removed integration can be diagnosed or replaced.
for (const id of ids) {
if (!choices.some((choice) => choice.value === id))
choices.push({ value: id, label: connections.find((connection) => connection.id === id)?.name ?? t("unavailableConnection") });
}
const change = async (values: string[]) => {
if (preparing.current || disabled) return;
preparing.current = true;
setPending(true);
onPendingChange(true);
setError("");
try {
const nextIds: string[] = [];
for (const value of values) {
if (!value.startsWith("integration:")) {
nextIds.push(value);
continue;
}
const integration = integrations.find((entry) => `integration:${entry.id}` === value);
if (!integration) throw new Error(t("unavailableConnection"));
const result = await saveConnection.mutateAsync({
name: integration.name,
integrationId: integration.id,
configuration: { kind: "integration" },
});
nextIds.push(result.id);
}
if (!mounted.current) return;
onChange((current) => {
const next = { ...current };
for (const key of getWidgetConnectionBindingNames(name, requirement, next)) delete next[key];
for (const [index, id] of nextIds.entries()) {
let key = name;
if (index > 0) key = `${name}:${id}`;
next[key] = id;
}
return next;
});
} catch (cause) {
if (mounted.current) setError(extractErrorMessage(cause));
} finally {
// Refresh the list independently; a failed refetch must not discard a selection.
if (values.some((value) => value.startsWith("integration:")))
void utils.customWidget.package.connections.invalidate();
preparing.current = false;
if (mounted.current) setPending(false);
onPendingChange(false);
}
};
const common = {
label: requirement.label,
description: requirement.description,
placeholder: t("chooseConnection"),
required: !requirement.optional,
searchable: true,
clearable: true,
disabled: pending || disabled,
data: choices,
nothingFoundMessage: t("noCompatibleConnections"),
};
return (
<Stack gap="xs" flex={1}>
{requirement.multiple ? (
<MultiSelect {...common} value={ids} onChange={(values) => void change(values)} />
) : (
<Select {...common} value={ids[0] ?? null} onChange={(value) => void change(value ? [value] : [])} />
)}
{error && <Alert color="red">{error}</Alert>}
</Stack>
);
}
type Diagnostic = RouterOutputs["customWidget"]["package"]["diagnoseConnection"];
function PackageConnectionDiagnostic({ result }: { result: Diagnostic }) {
const t = useI18n("customWidget.package.diagnostic");
let color = "yellow";
if (["connected", "integration", "fileReadable", "transportReachable"].includes(result.status)) color = "green";
if (["dnsError", "unavailable", "httpError", "serviceUnavailable"].includes(result.status)) color = "red";
return (
<Stack gap="xs">
<Alert color={color} title={t(`status.${result.status}`)}>
<Stack gap="xs">
<Text size="sm">{t(`help.${result.status}`)}</Text>
{"stage" in result && (
<Text size="xs">
{t("phase", { phase: t(`stage.${result.stage as "dns" | "connection" | "tls" | "response"}`) })}
</Text>
)}
{"hostname" in result && (
<Text size="sm" ff="monospace">
{result.hostname}
</Text>
)}
{result.addresses.length > 0 && (
<Group gap="xs">
{result.addresses.map(({ address }) => (
<Badge key={address} variant="outline" tt="none">
{address}
</Badge>
))}
</Group>
)}
{"httpStatus" in result && typeof result.httpStatus === "number" && typeof result.durationMs === "number" && (
<Text size="xs">{t("response", { status: result.httpStatus, milliseconds: result.durationMs })}</Text>
)}
{"sampleFields" in result && Array.isArray(result.sampleFields) && result.sampleFields.length > 0 && (
<Text size="xs">{t("fields", { fields: result.sampleFields.join(", ") })}</Text>
)}
</Stack>
</Alert>
<Accordion>
<Accordion.Item value="details">
<Accordion.Control>{t("details")}</Accordion.Control>
<Accordion.Panel>
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", overflowWrap: "anywhere" }}>
{JSON.stringify(result, null, 2)}
</Text>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
@@ -1,11 +1,13 @@
"use client";
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Alert, Button, Group, Stack, Text, TextInput, Title } from "@mantine/core";
import { Alert, Button, Group, Stack, Text, TextInput, Title, Skeleton } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import type { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { PackageWorkspace } from "./_package-workspace";
export function PackageConvert({ definitionId, name }: { definitionId: string; name: string }) {
const t = useI18n("customWidget.package.conversion");
@@ -46,3 +48,46 @@ export function PackageConvert({ definitionId, name }: { definitionId: string; n
</Stack>
);
}
export function NativePackageWorkspace({
userId,
sourceItemId,
starter,
}: {
userId: string;
sourceItemId: string;
starter: keyof typeof widgetReferencePackages;
}) {
const t = useI18n("customWidget.package");
const preparation = clientApi.customWidget.package.prepareNative.useMutation();
const prepare = preparation.mutate;
const started = useRef(false);
useEffect(() => {
if (started.current) return;
started.current = true;
prepare({ sourceItemId, starter });
}, [prepare, sourceItemId, starter]);
if (preparation.data)
return (
<PackageWorkspace
userId={userId}
initialSource={preparation.data.source}
initialName={preparation.data.name}
initialBindings={preparation.data.bindings}
initialBoardId={preparation.data.sourceBoardId}
/>
);
if (preparation.error)
return (
<Stack>
<Alert color="red">{preparation.error.message}</Alert>
<Button onClick={() => prepare({ sourceItemId, starter })}>{t("retryPreparation")}</Button>
</Stack>
);
return (
<Stack>
<Skeleton height={50} />
<Skeleton height={400} />
</Stack>
);
}
@@ -1,107 +0,0 @@
"use client";
import { useState } from "react";
import { Alert, Button, Paper, Select, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { isRecord } from "@homarr/common";
import { useI18n } from "@homarr/translation/client";
export function PackageConvertedPlacements({
id,
origin,
active,
onChange,
}: {
id: string;
origin: string | null;
active: boolean;
onChange(): void;
}) {
let definitionId: string | undefined;
try {
const value: unknown = JSON.parse(origin ?? "null");
if (isRecord(value) && value.kind === "converted-v2" && typeof value.definitionId === "string")
definitionId = value.definitionId;
} catch {
/* Other package origins have no legacy placement migration. */
}
if (!definitionId) return null;
return <ConvertedPlacementPicker id={id} definitionId={definitionId} active={active} onChange={onChange} />;
}
function ConvertedPlacementPicker({
id,
definitionId,
active,
onChange,
}: {
id: string;
definitionId: string;
active: boolean;
onChange(): void;
}) {
const t = useI18n("customWidget.package.conversion");
const placements = clientApi.customWidget.package.legacyPlacements.useQuery({ definitionId }, { enabled: active });
const migrate = clientApi.customWidget.package.migrateV2Placement.useMutation();
const [itemId, setItemId] = useState<string | null>(null);
const [replaced, setReplaced] = useState(false);
return (
<Paper withBorder p="md">
<Stack gap="sm">
<Text fw={600}>{t("replaceTitle")}</Text>
<Text size="sm">{t("replaceDescription")}</Text>
{!active && (
<Text size="sm" c="dimmed">
{t("activateFirst")}
</Text>
)}
{active && (
<>
<Select
label={t("choosePlacement")}
searchable
value={itemId}
onChange={(value) => {
setItemId(value);
setReplaced(false);
}}
data={(placements.data ?? []).map((placement) => ({
value: placement.id,
label: `${placement.boardName} · ${placement.id}`,
}))}
/>
{placements.data?.length === 0 && (
<Text size="sm" c="dimmed">
{t("noOriginalPlacements")}
</Text>
)}
<Button
disabled={!itemId}
loading={migrate.isPending}
onClick={() => {
if (!itemId) return;
migrate.mutate(
{ id, itemId, definitionId },
{
onSuccess: () => {
setItemId(null);
setReplaced(true);
void placements.refetch();
onChange();
},
},
);
}}
>
{t("replaceSelected")}
</Button>
</>
)}
{replaced && <Alert color="green">{t("replaced")}</Alert>}
{(migrate.error || placements.error) && (
<Alert color="red">{migrate.error?.message ?? placements.error?.message}</Alert>
)}
</Stack>
</Paper>
);
}
@@ -1,60 +0,0 @@
import { createId, isRecord } from "@homarr/common";
import { redactCustomWidgetCredentialLiterals } from "@homarr/custom-widgets/core";
export interface PackageDocument {
name: string;
metadata: string;
files: Record<string, string>;
}
export function documentFromSource(name: string, source: unknown): PackageDocument {
if (!isRecord(source)) return { name, metadata: "{}", files: {} };
const { files, _draftMetadata, ...metadata } = source;
const document = { name, metadata: JSON.stringify(metadata, null, 2), files: {} as Record<string, string> };
if (typeof _draftMetadata === "string") document.metadata = _draftMetadata;
if (isRecord(files)) {
for (const [path, content] of Object.entries(files))
if (typeof content === "string") document.files[path] = content;
}
return document;
}
export function documentFromTemplate(name: string, source: unknown): PackageDocument {
if (!isRecord(source) || !isRecord(source.manifest)) return documentFromSource(name, source);
return documentFromSource(name, {
...source,
manifest: { ...source.manifest, id: `local.${createId()}`, name, version: "1.0.0" },
});
}
export function documentSource(document: PackageDocument): Record<string, unknown> {
try {
const metadata: unknown = JSON.parse(document.metadata);
if (isRecord(metadata)) return { ...metadata, files: document.files };
} catch {
/* An incomplete manifest can still be saved as a draft. */
}
return { _draftMetadata: document.metadata, files: document.files };
}
const redact = (text: string) =>
redactCustomWidgetCredentialLiterals(text).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gu, "$1");
export function recoveryDocument(document: PackageDocument): PackageDocument {
return {
name: redact(document.name),
metadata: redact(document.metadata),
files: Object.fromEntries(Object.entries(document.files).map(([path, content]) => [path, redact(content)])),
};
}
export function downloadPackage(name: string, value: unknown) {
const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: "application/json" }));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `${name.replace(/[^a-z0-9._-]+/giu, "-") || "widget"}.json`;
anchor.click();
URL.revokeObjectURL(url);
}
export type PackageOperation = () => Promise<unknown>;
@@ -1,69 +0,0 @@
"use client";
import { useMemo } from "react";
import { Group, Text, Tree, useTree } from "@mantine/core";
import type { TreeNodeData } from "@mantine/core";
import { IconChevronRight, IconCode, IconFolder, IconFolderOpen } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
export function PackageFileTree({ files, selected, onSelect }: {
files: Record<string, string>;
selected: string;
onSelect(path: string): void;
}) {
const t = useI18n("customWidget.package");
const data = useMemo(() => {
const roots: TreeNodeData[] = [{ value: "/widget.json", label: t("manifestFile") }];
for (const path of Object.keys(files).toSorted()) {
const parts = path.split("/");
let siblings = roots;
let prefix = "";
for (const [index, label] of parts.entries()) {
prefix += label;
if (index === parts.length - 1) {
siblings.push({ value: path, label });
break;
}
prefix += "/";
let folder = siblings.find((node) => node.value === prefix);
if (!folder) {
folder = { value: prefix, label, children: [] };
siblings.push(folder);
}
siblings = folder.children ?? [];
}
}
return roots;
}, [files, t]);
const tree = useTree({
selectedState: [selected],
onSelectedStateChange: (values) => {
const value = values[0];
if (value && !value.endsWith("/")) onSelect(value);
},
});
return (
<Tree
aria-label={t("files")}
data={data}
tree={tree}
levelOffset={16}
selectOnClick
renderNode={({ node, expanded, hasChildren, elementProps }) => {
let Icon = IconCode;
if (hasChildren) Icon = IconFolder;
if (hasChildren && expanded) Icon = IconFolderOpen;
return (
<Group {...elementProps} gap={6} wrap="nowrap" py={5} title={node.value}>
{hasChildren && <IconChevronRight size={12} style={{ transform: `rotate(${expanded ? 90 : 0}deg)` }} />}
<Icon size={16} style={{ flexShrink: 0 }} />
<Text size="xs" truncate>
{node.label}
</Text>
</Group>
);
}}
/>
);
}
@@ -1,73 +0,0 @@
"use client";
import { Accordion, Alert, Group, Stack, Table, Text } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { useI18n } from "@homarr/translation/client";
type History = RouterOutputs["widget"]["customApi"]["packageHistory"];
export function PackageHistorySummary({ data }: { data: History }) {
const t = useI18n("customWidget.package.historySummary");
const latest = data.samples.at(-1);
return (
<Stack gap="xs">
{latest && (
<Group justify="space-between">
<Text fw={600}>
{formatCollectedValue(latest.value)} {data.unit}
</Text>
<Text size="xs" c="dimmed">
{t("latest", { time: new Date(latest.timestamp).toLocaleString() })}
</Text>
</Group>
)}
{!latest && (
<Text size="sm" c="dimmed">
{t("empty")}
</Text>
)}
{"lastError" in data && data.lastError && <Alert color="yellow">{data.lastError}</Alert>}
<Accordion multiple>
<Accordion.Item value="samples">
<Accordion.Control>{t("samples", { count: data.samples.length })}</Accordion.Control>
<Accordion.Panel>
<div style={{ maxHeight: 220, overflow: "auto" }}>
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th>{t("time")}</Table.Th>
<Table.Th>{t("value")}</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data.samples.toReversed().map((sample, index) => (
<Table.Tr key={`${sample.timestamp}-${index}`}>
<Table.Td>{new Date(sample.timestamp).toLocaleString()}</Table.Td>
<Table.Td>
{formatCollectedValue(sample.value)} {data.unit}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</div>
</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="technical">
<Accordion.Control>{t("details")}</Accordion.Control>
<Accordion.Panel>
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>
{JSON.stringify(data, null, 2)}
</Text>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
function formatCollectedValue(value: unknown): string {
if (typeof value === "number") return value.toLocaleString();
if (typeof value === "string") return value.slice(0, 240);
return (JSON.stringify(value) ?? "—").slice(0, 240);
}
@@ -1,5 +1,7 @@
"use client";
import { extractErrorMessage } from "@homarr/common";
import { useEffect, useMemo, useRef, useState } from "react";
import { Accordion, Alert, Button, Group, Stack, Text, TextInput, Tooltip } from "@mantine/core";
import {
@@ -33,7 +35,7 @@ export default function PackageLanguageEditor({ state }: { state: ReturnType<typ
setClient(service);
return () => service.dispose();
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
}, []);
useEffect(() => {
@@ -73,7 +75,7 @@ export default function PackageLanguageEditor({ state }: { state: ReturnType<typ
}, [client, state.language, state.selected]);
const reportError = (cause: unknown) => {
if (cause instanceof Error && cause.name === "AbortError") return;
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
};
const format = async () => {
if (!client) return;
@@ -1,19 +1,31 @@
"use client";
import { useRef, useState } from "react";
import { Alert, Avatar, Badge, Button, Group, Stack, Text } from "@mantine/core";
import { IconPackage, IconPencil, IconUpload } from "@tabler/icons-react";
import { extractErrorMessage, isRecord } from "@homarr/common";
import { useRef, useState } from "react";
import { Alert, Avatar, Badge, Button, Group, Stack, Text, ActionIcon, Menu } from "@mantine/core";
import {
IconPackage,
IconPencil,
IconUpload,
IconBuildingStore,
IconCopy,
IconDots,
IconDownload,
IconLayoutDashboard,
IconPlayerPause,
IconPlayerPlay,
IconPlugConnected,
} from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { customWidgetArchiveSchema, WIDGET_COLLECTION_MAX_BYTES } from "@homarr/custom-widgets/package";
import { isRecord } from "@homarr/common";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { ManageCollectionItem, ManageCollectionList } from "~/components/manage/manage-collection";
import { NoResults } from "~/components/no-results";
import { PackageRowActions } from "./_package-row-actions";
import { showErrorNotification } from "@homarr/notifications";
import { downloadPackage } from "@homarr/custom-widgets/workbench/package";
export function PackageList({ initialData }: { initialData: RouterOutputs["customWidget"]["package"]["list"] }) {
const t = useI18n("customWidget.package");
@@ -103,7 +115,7 @@ export function PackageImportButton() {
const result = await save.mutateAsync({ name, source });
window.location.assign(result.managementPath);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
} finally {
importing.current = false;
setReading(false);
@@ -138,3 +150,63 @@ export function PackageImportButton() {
</Stack>
);
}
function PackageRowActions({ entry }: { entry: RouterOutputs["customWidget"]["package"]["list"][number] }) {
const t = useI18n("customWidget.package");
const utils = clientApi.useUtils();
const fork = clientApi.customWidget.package.fork.useMutation();
const enable = clientApi.customWidget.package.setEnabled.useMutation();
const busy = fork.isPending || enable.isPending;
const path = `/manage/custom-widgets/packages/${entry.id}`;
const run = async (action: () => Promise<unknown>) => {
try {
await action();
await utils.customWidget.package.list.invalidate();
} catch (error) {
showErrorNotification({ title: t("title"), message: extractErrorMessage(error) });
}
};
return (
<Menu position="bottom-end" withinPortal>
<Menu.Target>
<ActionIcon variant="subtle" color="gray" aria-label={t("actionsMenu")} loading={busy}>
<IconDots size={20} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item component={Link} href={`${path}?tab=installation`} leftSection={<IconLayoutDashboard size={16} />}>
{t("addToBoard")}
</Menu.Item>
<Menu.Item component={Link} href={`${path}?tab=connections`} leftSection={<IconPlugConnected size={16} />}>
{t("connections")}
</Menu.Item>
<Menu.Item component={Link} href={`${path}?tab=workshop`} leftSection={<IconBuildingStore size={16} />}>
{t("workshopTab")}
</Menu.Item>
<Menu.Divider />
<Menu.Item disabled={busy} leftSection={<IconCopy size={16} />} onClick={() => void run(async () => {
await fork.mutateAsync({ id: entry.id, name: t("forkDefaultName", { name: entry.name }).slice(0, 128) });
})}>
{t("fork")}
</Menu.Item>
<Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
const draft = await utils.customWidget.package.get.fetch({ id: entry.id });
downloadPackage(entry.name, draft.source);
})}>
{t("exportDraft")}
</Menu.Item>
{entry.activeArtifactId && <Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
downloadPackage(entry.name, await utils.customWidget.package.export.fetch({ id: entry.id }));
})}>{t("exportActive")}</Menu.Item>}
<Menu.Divider />
<Menu.Item
disabled={busy || !entry.activeArtifactId}
leftSection={entry.enabled ? <IconPlayerPause size={16} /> : <IconPlayerPlay size={16} />}
onClick={() => void run(() => enable.mutateAsync({ id: entry.id, enabled: !entry.enabled }))}
>
{entry.enabled ? t("disable") : t("enable")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
}
@@ -1,53 +0,0 @@
"use client";
import { useEffect, useRef } from "react";
import { Alert, Button, Skeleton, Stack } from "@mantine/core";
import type { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { PackageWorkspace } from "./_package-workspace";
export function NativePackageWorkspace({
userId,
sourceItemId,
starter,
}: {
userId: string;
sourceItemId: string;
starter: keyof typeof widgetReferencePackages;
}) {
const t = useI18n("customWidget.package");
const preparation = clientApi.customWidget.package.prepareNative.useMutation();
const prepare = preparation.mutate;
const started = useRef(false);
useEffect(() => {
if (started.current) return;
started.current = true;
prepare({ sourceItemId, starter });
}, [prepare, sourceItemId, starter]);
if (preparation.data)
return (
<PackageWorkspace
userId={userId}
initialSource={preparation.data.source}
initialName={preparation.data.name}
initialBindings={preparation.data.bindings}
initialBoardId={preparation.data.sourceBoardId}
/>
);
if (preparation.error)
return (
<Stack>
<Alert color="red">{preparation.error.message}</Alert>
<Button onClick={() => prepare({ sourceItemId, starter })}>{t("retryPreparation")}</Button>
</Stack>
);
return (
<Stack>
<Skeleton height={50} />
<Skeleton height={400} />
</Stack>
);
}
@@ -1,5 +1,7 @@
"use client";
import { extractErrorMessage } from "@homarr/common";
import { useMemo, useState } from "react";
import { Accordion, Alert, Button, Checkbox, Group, Paper, Stack, Text } from "@mantine/core";
@@ -9,11 +11,9 @@ import { customWidgetPackageSchema, stringifyWidgetJson } from "@homarr/custom-w
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
import { AddPackagePlacement, PackagePlacements } from "./_package-placements";
import type { PackageOperation } from "./_package-document";
import { PackageArtifactReview } from "./_package-artifact-review";
import { PackageConvertedPlacements } from "./_package-converted-placements";
import { downloadPackage } from "./_package-document";
import { AddPackagePlacement, PackagePlacements, PackageConvertedPlacements } from "./_package-placements";
import { PackageArtifactReview } from "./_package-workshop";
import { downloadPackage } from "@homarr/custom-widgets/workbench/package";
type Installation = RouterOutputs["customWidget"]["package"]["get"];
@@ -80,13 +80,13 @@ export function PackageOperations({
utils.widget.customApi.getData.invalidate(),
]);
};
const run = async (action: PackageOperation, message: string) => {
const run = async (action: () => Promise<unknown>, message: string) => {
try {
await action();
await refresh();
onMessage(message);
} catch (error) {
onError(error instanceof Error ? error.message : String(error));
onError(extractErrorMessage(error));
}
};
return (
@@ -1,4 +1,7 @@
"use client";
import { extractErrorMessage, isRecord } from "@homarr/common";
import { useState } from "react";
import { Accordion, Alert, Button, Group, Paper, Select, Stack, Text, Textarea } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
@@ -214,7 +217,7 @@ function GuestActions({ itemId, actions }: { itemId: string; actions: Array<{ na
if (!Array.isArray(allowed)) throw new Error(t("inputsArray"));
mutation.mutate({ itemId, handler: name, enabled: true, allowedInputs: allowed }, callbacks);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
}}
>
@@ -227,3 +230,103 @@ function GuestActions({ itemId, actions }: { itemId: string; actions: Array<{ na
</Stack>
);
}
export function PackageConvertedPlacements({
id,
origin,
active,
onChange,
}: {
id: string;
origin: string | null;
active: boolean;
onChange(): void;
}) {
let definitionId: string | undefined;
try {
const value: unknown = JSON.parse(origin ?? "null");
if (isRecord(value) && value.kind === "converted-v2" && typeof value.definitionId === "string")
definitionId = value.definitionId;
} catch {
/* Other package origins have no legacy placement migration. */
}
if (!definitionId) return null;
return <ConvertedPlacementPicker id={id} definitionId={definitionId} active={active} onChange={onChange} />;
}
function ConvertedPlacementPicker({
id,
definitionId,
active,
onChange,
}: {
id: string;
definitionId: string;
active: boolean;
onChange(): void;
}) {
const t = useI18n("customWidget.package.conversion");
const placements = clientApi.customWidget.package.legacyPlacements.useQuery({ definitionId }, { enabled: active });
const migrate = clientApi.customWidget.package.migrateV2Placement.useMutation();
const [itemId, setItemId] = useState<string | null>(null);
const [replaced, setReplaced] = useState(false);
return (
<Paper withBorder p="md">
<Stack gap="sm">
<Text fw={600}>{t("replaceTitle")}</Text>
<Text size="sm">{t("replaceDescription")}</Text>
{!active && (
<Text size="sm" c="dimmed">
{t("activateFirst")}
</Text>
)}
{active && (
<>
<Select
label={t("choosePlacement")}
searchable
value={itemId}
onChange={(value) => {
setItemId(value);
setReplaced(false);
}}
data={(placements.data ?? []).map((placement) => ({
value: placement.id,
label: `${placement.boardName} · ${placement.id}`,
}))}
/>
{placements.data?.length === 0 && (
<Text size="sm" c="dimmed">
{t("noOriginalPlacements")}
</Text>
)}
<Button
disabled={!itemId}
loading={migrate.isPending}
onClick={() => {
if (!itemId) return;
migrate.mutate(
{ id, itemId, definitionId },
{
onSuccess: () => {
setItemId(null);
setReplaced(true);
void placements.refetch();
onChange();
},
},
);
}}
>
{t("replaceSelected")}
</Button>
</>
)}
{replaced && <Alert color="green">{t("replaced")}</Alert>}
{(migrate.error || placements.error) && (
<Alert color="red">{migrate.error?.message ?? placements.error?.message}</Alert>
)}
</Stack>
</Paper>
);
}
@@ -1,75 +0,0 @@
"use client";
import { Accordion, Group, NumberInput, Select, Stack, Text } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
import type { usePackageWorkspace } from "./_use-package-workspace";
export function PackagePreviewControls({ state }: { state: ReturnType<typeof usePackageWorkspace> }) {
const t = useI18n("customWidget.package");
const { width, height, scale, previewTheme, setWidth, setHeight, setScale, setPreviewTheme } = state;
return (
<Stack gap="xs">
<Group gap="xs" grow>
<Select
size="xs"
label={t("previewTheme")}
value={previewTheme}
data={[
{ value: "system", label: t("previewThemeCurrent") },
{ value: "light", label: t("previewThemeLight") },
{ value: "dark", label: t("previewThemeDark") },
]}
onChange={(value) => {
if (value === "system" || value === "light" || value === "dark") setPreviewTheme(value);
}}
/>
</Group>
<Accordion>
<Accordion.Item value="dimensions">
<Accordion.Control>{t("customViewport")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
<Text size="xs" c="dimmed">{t("customViewportDescription")}</Text>
<Group gap="xs" grow>
<NumberInput
size="xs"
label={t("width")}
min={100}
max={2400}
value={width}
onChange={(value) => {
if (typeof value === "number") setWidth(value);
}}
/>
<NumberInput
size="xs"
label={t("height")}
min={100}
max={1600}
value={height}
onChange={(value) => {
if (typeof value === "number") setHeight(value);
}}
/>
<NumberInput
size="xs"
label={t("previewScale")}
min={25}
max={90}
suffix="%"
step={10}
value={Math.round(scale * 100)}
onChange={(value) => {
if (typeof value === "number") setScale(Math.min(0.9, Math.max(0.25, value / 100)));
}}
/>
</Group>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
@@ -1,61 +0,0 @@
"use client";
import type { PropsWithChildren } from "react";
import { useId, useMemo, useRef } from "react";
import { MantineProvider, Portal, useComputedColorScheme, useMantineTheme } from "@mantine/core";
/** Scope preview colors and portal variables without changing the user's application theme. */
export function PackagePreviewViewport({
children,
colorScheme,
width,
height,
scale,
}: PropsWithChildren<{
colorScheme: "system" | "light" | "dark";
width: number;
height: number;
scale: number;
}>) {
const id = useId().replace(/[^a-zA-Z0-9_-]/gu, "");
const root = useRef<HTMLDivElement>(null);
const currentScheme = useComputedColorScheme("light");
const hostTheme = useMantineTheme();
let scheme = currentScheme;
if (colorScheme !== "system") scheme = colorScheme;
const theme = useMemo(
() => ({
...hostTheme,
components: {
...hostTheme.components,
Portal: Portal.extend({ defaultProps: { target: `#widget-preview-overlays-${id}` } }),
},
}),
[hostTheme, id],
);
return (
<MantineProvider
theme={theme}
forceColorScheme={scheme}
cssVariablesSelector={`[data-widget-preview-theme="${id}"]`}
getRootElement={() => root.current ?? undefined}
deduplicateCssVariables={false}
withGlobalClasses={false}
>
<div
ref={root}
data-widget-preview-theme={id}
data-mantine-color-scheme={scheme}
style={{
width: width * scale,
height: height * scale,
background: "var(--mantine-color-body)",
color: "var(--mantine-color-text)",
}}
>
<div style={{ width, height, transform: `scale(${scale})`, transformOrigin: "top left" }}>{children}</div>
</div>
<div id={`widget-preview-overlays-${id}`} data-widget-preview-theme={id} data-mantine-color-scheme={scheme} />
</MantineProvider>
);
}
@@ -2,18 +2,29 @@
import dynamic from "next/dynamic";
import { useState } from "react";
import { Accordion, Alert, Badge, Button, Checkbox, Group, Select, Stack, Text } from "@mantine/core";
import {
Accordion,
Alert,
Badge,
Button,
Checkbox,
Group,
Select,
Stack,
Text,
NumberInput,
Paper,
Skeleton,
Title,
} from "@mantine/core";
import { IconCode, IconPlayerPlay } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { WidgetPreviewFrame } from "@homarr/widgets/preview";
import { PackagePreviewViewport } from "./_package-preview-viewport";
import { PackagePreviewControls } from "./_package-preview-controls";
import { PackageRuntimeStatus } from "./_package-runtime-status";
import { downloadPackage } from "./_package-document";
import { WidgetPreviewFrame, WidgetPreviewViewport } from "@homarr/widgets/preview";
import { downloadPackage } from "@homarr/custom-widgets/workbench/package";
import type { usePackageWorkspace } from "./_use-package-workspace";
import classes from "./_package-workspace.module.css";
import { clientApi } from "@homarr/api/client";
import { Link } from "@homarr/ui";
const TrustedWidgetPreview = dynamic(() => import("@homarr/widgets/custom-api/trusted-widget-preview"), { ssr: false });
@@ -118,7 +129,7 @@ export function PackagePreview({ state }: { state: ReturnType<typeof usePackageW
{({ scale: fittedScale }) => (
<>
{preview && (
<PackagePreviewViewport width={width} height={height} scale={fittedScale} colorScheme={previewTheme}>
<WidgetPreviewViewport width={width} height={height} scale={fittedScale} colorScheme={previewTheme}>
<TrustedWidgetPreview
data={preview.displayData}
width={width}
@@ -131,7 +142,7 @@ export function PackagePreview({ state }: { state: ReturnType<typeof usePackageW
onReady={previewReady}
onLoadError={previewLoadError}
/>
</PackagePreviewViewport>
</WidgetPreviewViewport>
)}
{!preview && (
<Stack justify="center" align="center" mih={220} p="sm">
@@ -190,3 +201,179 @@ export function PackagePreview({ state }: { state: ReturnType<typeof usePackageW
</Stack>
);
}
function PackagePreviewControls({ state }: { state: ReturnType<typeof usePackageWorkspace> }) {
const t = useI18n("customWidget.package");
const { width, height, scale, previewTheme, setWidth, setHeight, setScale, setPreviewTheme } = state;
return (
<Stack gap="xs">
<Group gap="xs" grow>
<Select
size="xs"
label={t("previewTheme")}
value={previewTheme}
data={[
{ value: "system", label: t("previewThemeCurrent") },
{ value: "light", label: t("previewThemeLight") },
{ value: "dark", label: t("previewThemeDark") },
]}
onChange={(value) => {
if (value === "system" || value === "light" || value === "dark") setPreviewTheme(value);
}}
/>
</Group>
<Accordion>
<Accordion.Item value="dimensions">
<Accordion.Control>{t("customViewport")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
<Text size="xs" c="dimmed">{t("customViewportDescription")}</Text>
<Group gap="xs" grow>
<NumberInput
size="xs"
label={t("width")}
min={100}
max={2400}
value={width}
onChange={(value) => {
if (typeof value === "number") setWidth(value);
}}
/>
<NumberInput
size="xs"
label={t("height")}
min={100}
max={1600}
value={height}
onChange={(value) => {
if (typeof value === "number") setHeight(value);
}}
/>
<NumberInput
size="xs"
label={t("previewScale")}
min={25}
max={90}
suffix="%"
step={10}
value={Math.round(scale * 100)}
onChange={(value) => {
if (typeof value === "number") setScale(Math.min(0.9, Math.max(0.25, value / 100)));
}}
/>
</Group>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
</Stack>
);
}
function PackageRuntimeStatus({ id }: { id: string }) {
const t = useI18n("customWidget.package.runtime");
const status = clientApi.customWidget.package.runtimeStatus.useQuery({ id });
const data = status.data;
return (
<Stack gap="xs">
<Text size="sm" fw={600}>{t("title")}</Text>
<Text size="xs" c="dimmed">{t("description")}</Text>
<Group>
{data && <Badge variant="light">{t(data.state)}</Badge>}
<Button variant="subtle" size="xs" loading={status.isFetching} onClick={() => void status.refetch()}>{t("refresh")}</Button>
</Group>
{data && "pid" in data && (
<Text size="xs">{t("process", { pid: data.pid ?? "—", active: data.activeRequests, queued: data.queuedRequests })}</Text>
)}
{data && "error" in data && <Alert color="red">{data.error}</Alert>}
{status.error && <Alert color="red">{status.error.message}</Alert>}
<Button component={Link} href="/manage/tools/logs" target="_blank" rel="noopener noreferrer" variant="default" size="xs">{t("logs")}</Button>
</Stack>
);
}
export function PackageSessionPreview({ previewId }: { previewId: string }) {
const t = useI18n("customWidget.package");
const { data, error, isLoading } = clientApi.customWidget.package.previewGet.useQuery(
{ previewId },
{ retry: false },
);
const [surface, setSurface] = useState<"tile" | "advanced" | "configuration">("tile");
const [width, setWidth] = useState(480);
const [height, setHeight] = useState(360);
if (isLoading) return <Skeleton height={360} />;
if (error || !data)
return (
<Alert color="yellow" title={t("sessionUnavailable")}>
{t("sessionUnavailableDescription")}
</Alert>
);
const choices = [{ value: "tile", label: t("tile") }];
if (data.displayData.manifest.entrypoints.advanced) choices.push({ value: "advanced", label: t("advanced") });
if (data.displayData.manifest.entrypoints.configuration)
choices.push({ value: "configuration", label: t("configuration") });
return (
<Stack>
<Group justify="space-between">
<Title order={2}>{data.displayData.manifest.name}</Title>
<Button
component={Link}
href={`/manage/custom-widgets/packages/${data.displayData.installationId}`}
variant="subtle"
>
{t("openWorkspace")}
</Button>
</Group>
<Text size="sm" c="dimmed">
{t("sessionDescription")}
</Text>
{data.displayData.previewScenario && (
<Text size="sm" c="dimmed">
{t("previewSynthetic", { name: data.displayData.previewScenario.label })}
</Text>
)}
<Group align="end">
<Select
label={t("surface")}
data={choices}
value={surface}
onChange={(value) => {
if (value === "tile" || value === "advanced" || value === "configuration") setSurface(value);
}}
/>
<NumberInput
w={110}
label={t("width")}
min={100}
max={2400}
value={width}
onChange={(value) => {
if (typeof value === "number") setWidth(value);
}}
/>
<NumberInput
w={110}
label={t("height")}
min={100}
max={2400}
value={height}
onChange={(value) => {
if (typeof value === "number") setHeight(value);
}}
/>
</Group>
<Paper withBorder p="sm" style={{ overflow: "auto" }}>
<div style={{ width, height }}>
<TrustedWidgetPreview
data={data.displayData}
width={width}
height={height}
surface={surface}
onSurfaceChange={setSurface}
/>
</div>
</Paper>
</Stack>
);
}
@@ -1,72 +0,0 @@
"use client";
import { ActionIcon, Menu } from "@mantine/core";
import { IconBuildingStore, IconCopy, IconDots, IconDownload, IconLayoutDashboard, IconPlayerPause, IconPlayerPlay, IconPlugConnected } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { showErrorNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { downloadPackage } from "./_package-document";
export function PackageRowActions({ entry }: { entry: RouterOutputs["customWidget"]["package"]["list"][number] }) {
const t = useI18n("customWidget.package");
const utils = clientApi.useUtils();
const fork = clientApi.customWidget.package.fork.useMutation();
const enable = clientApi.customWidget.package.setEnabled.useMutation();
const busy = fork.isPending || enable.isPending;
const path = `/manage/custom-widgets/packages/${entry.id}`;
const run = async (action: () => Promise<unknown>) => {
try {
await action();
await utils.customWidget.package.list.invalidate();
} catch (error) {
showErrorNotification({ title: t("title"), message: error instanceof Error ? error.message : String(error) });
}
};
return (
<Menu position="bottom-end" withinPortal>
<Menu.Target>
<ActionIcon variant="subtle" color="gray" aria-label={t("actionsMenu")} loading={busy}>
<IconDots size={20} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item component={Link} href={`${path}?tab=installation`} leftSection={<IconLayoutDashboard size={16} />}>
{t("addToBoard")}
</Menu.Item>
<Menu.Item component={Link} href={`${path}?tab=connections`} leftSection={<IconPlugConnected size={16} />}>
{t("connections")}
</Menu.Item>
<Menu.Item component={Link} href={`${path}?tab=workshop`} leftSection={<IconBuildingStore size={16} />}>
{t("workshopTab")}
</Menu.Item>
<Menu.Divider />
<Menu.Item disabled={busy} leftSection={<IconCopy size={16} />} onClick={() => void run(async () => {
await fork.mutateAsync({ id: entry.id, name: t("forkDefaultName", { name: entry.name }).slice(0, 128) });
})}>
{t("fork")}
</Menu.Item>
<Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
const draft = await utils.customWidget.package.get.fetch({ id: entry.id });
downloadPackage(entry.name, draft.source);
})}>
{t("exportDraft")}
</Menu.Item>
{entry.activeArtifactId && <Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
downloadPackage(entry.name, await utils.customWidget.package.export.fetch({ id: entry.id }));
})}>{t("exportActive")}</Menu.Item>}
<Menu.Divider />
<Menu.Item
disabled={busy || !entry.activeArtifactId}
leftSection={entry.enabled ? <IconPlayerPause size={16} /> : <IconPlayerPlay size={16} />}
onClick={() => void run(() => enable.mutateAsync({ id: entry.id, enabled: !entry.enabled }))}
>
{entry.enabled ? t("disable") : t("enable")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
);
}
@@ -1,29 +0,0 @@
"use client";
import { Alert, Badge, Button, Group, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
export function PackageRuntimeStatus({ id }: { id: string }) {
const t = useI18n("customWidget.package.runtime");
const status = clientApi.customWidget.package.runtimeStatus.useQuery({ id });
const data = status.data;
return (
<Stack gap="xs">
<Text size="sm" fw={600}>{t("title")}</Text>
<Text size="xs" c="dimmed">{t("description")}</Text>
<Group>
{data && <Badge variant="light">{t(data.state)}</Badge>}
<Button variant="subtle" size="xs" loading={status.isFetching} onClick={() => void status.refetch()}>{t("refresh")}</Button>
</Group>
{data && "pid" in data && (
<Text size="xs">{t("process", { pid: data.pid ?? "—", active: data.activeRequests, queued: data.queuedRequests })}</Text>
)}
{data && "error" in data && <Alert color="red">{data.error}</Alert>}
{status.error && <Alert color="red">{status.error.message}</Alert>}
<Button component={Link} href="/manage/tools/logs" target="_blank" rel="noopener noreferrer" variant="default" size="xs">{t("logs")}</Button>
</Stack>
);
}
@@ -1,95 +0,0 @@
"use client";
import { useState } from "react";
import dynamic from "next/dynamic";
import { Alert, Button, Group, NumberInput, Paper, Select, Skeleton, Stack, Text, Title } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
const TrustedWidgetPreview = dynamic(() => import("@homarr/widgets/custom-api/trusted-widget-preview"), { ssr: false });
export function PackageSessionPreview({ previewId }: { previewId: string }) {
const t = useI18n("customWidget.package");
const { data, error, isLoading } = clientApi.customWidget.package.previewGet.useQuery(
{ previewId },
{ retry: false },
);
const [surface, setSurface] = useState<"tile" | "advanced" | "configuration">("tile");
const [width, setWidth] = useState(480);
const [height, setHeight] = useState(360);
if (isLoading) return <Skeleton height={360} />;
if (error || !data)
return (
<Alert color="yellow" title={t("sessionUnavailable")}>
{t("sessionUnavailableDescription")}
</Alert>
);
const choices = [{ value: "tile", label: t("tile") }];
if (data.displayData.manifest.entrypoints.advanced) choices.push({ value: "advanced", label: t("advanced") });
if (data.displayData.manifest.entrypoints.configuration)
choices.push({ value: "configuration", label: t("configuration") });
return (
<Stack>
<Group justify="space-between">
<Title order={2}>{data.displayData.manifest.name}</Title>
<Button
component={Link}
href={`/manage/custom-widgets/packages/${data.displayData.installationId}`}
variant="subtle"
>
{t("openWorkspace")}
</Button>
</Group>
<Text size="sm" c="dimmed">
{t("sessionDescription")}
</Text>
{data.displayData.previewScenario && (
<Text size="sm" c="dimmed">
{t("previewSynthetic", { name: data.displayData.previewScenario.label })}
</Text>
)}
<Group align="end">
<Select
label={t("surface")}
data={choices}
value={surface}
onChange={(value) => {
if (value === "tile" || value === "advanced" || value === "configuration") setSurface(value);
}}
/>
<NumberInput
w={110}
label={t("width")}
min={100}
max={2400}
value={width}
onChange={(value) => {
if (typeof value === "number") setWidth(value);
}}
/>
<NumberInput
w={110}
label={t("height")}
min={100}
max={2400}
value={height}
onChange={(value) => {
if (typeof value === "number") setHeight(value);
}}
/>
</Group>
<Paper withBorder p="sm" style={{ overflow: "auto" }}>
<div style={{ width, height }}>
<TrustedWidgetPreview
data={data.displayData}
width={width}
height={height}
surface={surface}
onSurfaceChange={setSurface}
/>
</div>
</Paper>
</Stack>
);
}
@@ -1,14 +1,16 @@
"use client";
import { useState } from "react";
import { useState, useMemo } from "react";
import dynamic from "next/dynamic";
import { Button, Group, Select, Stack, Tabs, Text, TextInput, Alert, Collapse } from "@mantine/core";
import { IconPlus, IconTrash } from "@tabler/icons-react";
import { Button, Group, Select, Stack, Tabs, Text, TextInput, Alert, Collapse, Tree, useTree } from "@mantine/core";
import { IconPlus, IconTrash, IconChevronRight, IconCode, IconFolder, IconFolderOpen } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { documentFromTemplate } from "./_package-document";
import { documentFromTemplate } from "@homarr/custom-widgets/workbench/package";
import type { usePackageWorkspace } from "./_use-package-workspace";
import classes from "./_package-workspace.module.css";
import { PackageFileTree } from "./_package-file-tree";
import type { TreeNodeData } from "@mantine/core";
const PackageLanguageEditor = dynamic(() => import("./_package-language-editor"), { ssr: false });
export function PackageSourceEditor({
state,
@@ -128,3 +130,64 @@ export function PackageSourceEditor({
</Tabs.Panel>
);
}
function PackageFileTree({ files, selected, onSelect }: {
files: Record<string, string>;
selected: string;
onSelect(path: string): void;
}) {
const t = useI18n("customWidget.package");
const data = useMemo(() => {
const roots: TreeNodeData[] = [{ value: "/widget.json", label: t("manifestFile") }];
for (const path of Object.keys(files).toSorted()) {
const parts = path.split("/");
let siblings = roots;
let prefix = "";
for (const [index, label] of parts.entries()) {
prefix += label;
if (index === parts.length - 1) {
siblings.push({ value: path, label });
break;
}
prefix += "/";
let folder = siblings.find((node) => node.value === prefix);
if (!folder) {
folder = { value: prefix, label, children: [] };
siblings.push(folder);
}
siblings = folder.children ?? [];
}
}
return roots;
}, [files, t]);
const tree = useTree({
selectedState: [selected],
onSelectedStateChange: (values) => {
const value = values[0];
if (value && !value.endsWith("/")) onSelect(value);
},
});
return (
<Tree
aria-label={t("files")}
data={data}
tree={tree}
levelOffset={16}
selectOnClick
renderNode={({ node, expanded, hasChildren, elementProps }) => {
let Icon = IconCode;
if (hasChildren) Icon = IconFolder;
if (hasChildren && expanded) Icon = IconFolderOpen;
return (
<Group {...elementProps} gap={6} wrap="nowrap" py={5} title={node.value}>
{hasChildren && <IconChevronRight size={12} style={{ transform: `rotate(${expanded ? 90 : 0}deg)` }} />}
<Icon size={16} style={{ flexShrink: 0 }} />
<Text size="xs" truncate>
{node.label}
</Text>
</Group>
);
}}
/>
);
}
@@ -1,109 +0,0 @@
"use client";
/* oxlint-disable jsx-a11y/prefer-tag-over-role -- A focusable window splitter is an interactive separator, not a thematic break. */
import type { CSSProperties, PropsWithChildren, ReactNode } from "react";
import { useEffect, useRef, useState } from "react";
import { useI18n } from "@homarr/translation/client";
import classes from "./_package-workspace.module.css";
const defaultWidth = 60;
const clampWidth = (value: number, maximum = 75) => Math.min(maximum, Math.max(30, value));
/** The split is an editor preference; it never changes the widget's authored dimensions. */
export function PackageSplit({
userId,
pane,
preview,
children,
}: PropsWithChildren<{ userId: string; pane: string; preview: ReactNode }>) {
const t = useI18n("customWidget.package");
const [width, setWidth] = useState(defaultWidth);
const [availableWidth, setAvailableWidth] = useState(0);
const container = useRef<HTMLDivElement>(null);
const key = `homarr:widget-workspace:split:${userId}`;
const latest = useRef(width);
let maximum = 75;
if (availableWidth >= 650) maximum = Math.min(75, ((availableWidth - 338) / availableWidth) * 100);
const visibleWidth = clampWidth(width, maximum);
useEffect(() => {
if (!container.current) return;
const observer = new ResizeObserver(([entry]) => setAvailableWidth(entry?.contentRect.width ?? 0));
observer.observe(container.current);
return () => observer.disconnect();
}, []);
useEffect(() => {
try {
const saved = localStorage.getItem(key);
if (saved && Number.isFinite(Number(saved))) {
const next = clampWidth(Number(saved));
latest.current = next;
setWidth(next);
}
} catch {
// Browser storage is optional for editor preferences.
}
}, [key]);
const remember = (value: number) => {
const next = clampWidth(value, maximum);
latest.current = next;
setWidth(next);
try {
localStorage.setItem(key, String(next));
} catch {
// Resizing remains available when browser storage is disabled.
}
};
return (
<div
ref={container}
className={classes.workspace}
data-pane={pane}
style={{ "--widget-editor-width": `${visibleWidth}%` } as CSSProperties}
>
{children}
<div
className={classes.divider}
role="separator"
tabIndex={0}
aria-label={t("resizeEditor")}
title={t("resizeEditorHint")}
aria-orientation="vertical"
aria-valuemin={30}
aria-valuemax={Math.round(maximum)}
aria-valuenow={Math.round(visibleWidth)}
onDoubleClick={() => remember(defaultWidth)}
onKeyDown={(event) => {
let next = visibleWidth;
if (event.key === "ArrowLeft") next -= 5;
else if (event.key === "ArrowRight") next += 5;
else if (event.key === "Home") next = 30;
else if (event.key === "End") next = maximum;
else return;
event.preventDefault();
remember(next);
}}
onPointerDown={(event) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
const bounds = container.current?.getBoundingClientRect();
if (!bounds?.width) return;
latest.current = clampWidth(((event.clientX - bounds.left) / bounds.width) * 100, maximum);
setWidth(latest.current);
}}
onPointerUp={(event) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
event.currentTarget.releasePointerCapture(event.pointerId);
remember(latest.current);
}}
/>
{preview}
</div>
);
}
@@ -1,150 +0,0 @@
"use client";
import { useRef, useState } from "react";
import { Accordion, Badge, Button, Checkbox, Group, Paper, SimpleGrid, Stack, Text, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { customWidgetArchiveSchema } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
import { CodeEditor } from "~/components/custom-widgets/code-editor";
export function PackageTransfer({
id,
name,
active,
dirty,
onError,
}: {
id: string;
name: string;
active: boolean;
dirty: boolean;
onError(error: string): void;
}) {
const t = useI18n("customWidget.package");
const input = useRef<HTMLInputElement>(null);
const [replace, setReplace] = useState(false);
const [forkName, setForkName] = useState(`${name} fork`);
const fork = clientApi.customWidget.package.fork.useMutation();
const update = clientApi.customWidget.package.stageUpdate.useMutation();
const changes = clientApi.customWidget.package.draftChanges.useQuery({ id });
const stage = async (file: File) => {
try {
if (file.size > 25_000_000) throw new Error(t("importTooLarge"));
const raw: unknown = JSON.parse(await file.text());
const archive = customWidgetArchiveSchema.parse(raw);
const result = await update.mutateAsync({ id, archive, replaceLocalDraft: true });
window.location.assign(result.managementPath);
} catch (error) {
onError(error instanceof Error ? error.message : String(error));
}
};
return (
<Stack>
<Accordion>
<Accordion.Item value="changes">
<Accordion.Control>{t("changes")}</Accordion.Control>
<Accordion.Panel>
<Stack>
<Text size="sm" c="dimmed">
{t("sourceOnly")}
</Text>
{changes.data?.valid && (
<>
<Text size="sm">
{changes.data.fromVersion ?? t("none")} → {changes.data.toVersion}
</Text>
<Group>
{changes.data.dependenciesChanged && <Badge color="yellow">{t("dependenciesChanged")}</Badge>}
{changes.data.connectionsChanged && <Badge color="yellow">{t("connectionsChanged")}</Badge>}
{changes.data.configurationChanged && <Badge color="yellow">{t("configurationChanged")}</Badge>}
</Group>
{changes.data.files.map((file) => (
<Stack key={file.name} gap="xs">
<Text fw={500}>{file.name}</Text>
<SimpleGrid cols={{ base: 1, lg: 2 }}>
<CodeEditor
id={`before-${file.name}`}
label={t("before")}
value={file.before ?? ""}
language="tsx"
readOnly
onChange={() => undefined}
/>
<CodeEditor
id={`after-${file.name}`}
label={t("after")}
value={file.after ?? ""}
language="tsx"
readOnly
onChange={() => undefined}
/>
</SimpleGrid>
</Stack>
))}
</>
)}
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
{active && (
<Paper withBorder p="md">
<Stack>
<Checkbox
checked={replace}
onChange={(event) => setReplace(event.currentTarget.checked)}
label={t("replaceDraft")}
/>
<input
hidden
type="file"
ref={input}
accept=".json,application/json"
onChange={(event) => {
const file = event.currentTarget.files?.[0];
event.currentTarget.value = "";
if (file) void stage(file);
}}
/>
<Button
variant="default"
disabled={!replace || dirty}
loading={update.isPending}
onClick={() => input.current?.click()}
>
{t("stageUpdate")}
</Button>
</Stack>
</Paper>
)}
<Paper withBorder p="md">
<Stack>
<Text size="sm">{t("forkDescription")}</Text>
<TextInput
label={t("forkName")}
value={forkName}
onChange={(event) => setForkName(event.currentTarget.value)}
/>
<Button
variant="default"
disabled={dirty || !forkName.trim()}
loading={fork.isPending}
onClick={() =>
fork.mutate(
{ id, name: forkName },
{
onSuccess: (result) => window.location.assign(result.managementPath),
onError: (error) => onError(error.message),
},
)
}
>
{t("fork")}
</Button>
</Stack>
</Paper>
</Stack>
);
}
@@ -1,13 +1,30 @@
"use client";
import { useState } from "react";
import { Alert, Button, Checkbox, Group, Paper, Select, Stack, Text, Textarea, TextInput } from "@mantine/core";
import { extractErrorMessage } from "@homarr/common";
import { useState, useRef } from "react";
import {
Alert,
Button,
Checkbox,
Group,
Paper,
Select,
Stack,
Text,
Textarea,
TextInput,
Accordion,
Badge,
SimpleGrid,
} from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { useWorkshopSubmissionQuery } from "@homarr/workshop/backend";
import { WorkshopAccountButton, useWorkshopSession } from "~/components/workshop/workshop-session";
import { customWidgetArchiveSchema } from "@homarr/custom-widgets/package";
import { CodeEditor } from "~/components/custom-widgets/code-editor";
import type { CustomWidgetArtifact } from "@homarr/custom-widgets/package";
export function PackageWorkshop({ id, dirty }: { id: string; dirty: boolean }) {
const t = useI18n("customWidget.package");
@@ -152,3 +169,188 @@ export function PackageWorkshop({ id, dirty }: { id: string; dirty: boolean }) {
</Paper>
);
}
export function PackageTransfer({
id,
name,
active,
dirty,
onError,
}: {
id: string;
name: string;
active: boolean;
dirty: boolean;
onError(error: string): void;
}) {
const t = useI18n("customWidget.package");
const input = useRef<HTMLInputElement>(null);
const [replace, setReplace] = useState(false);
const [forkName, setForkName] = useState(`${name} fork`);
const fork = clientApi.customWidget.package.fork.useMutation();
const update = clientApi.customWidget.package.stageUpdate.useMutation();
const changes = clientApi.customWidget.package.draftChanges.useQuery({ id });
const stage = async (file: File) => {
try {
if (file.size > 25_000_000) throw new Error(t("importTooLarge"));
const raw: unknown = JSON.parse(await file.text());
const archive = customWidgetArchiveSchema.parse(raw);
const result = await update.mutateAsync({ id, archive, replaceLocalDraft: true });
window.location.assign(result.managementPath);
} catch (error) {
onError(extractErrorMessage(error));
}
};
return (
<Stack>
<Accordion>
<Accordion.Item value="changes">
<Accordion.Control>{t("changes")}</Accordion.Control>
<Accordion.Panel>
<Stack>
<Text size="sm" c="dimmed">
{t("sourceOnly")}
</Text>
{changes.data?.valid && (
<>
<Text size="sm">
{changes.data.fromVersion ?? t("none")} → {changes.data.toVersion}
</Text>
<Group>
{changes.data.dependenciesChanged && <Badge color="yellow">{t("dependenciesChanged")}</Badge>}
{changes.data.connectionsChanged && <Badge color="yellow">{t("connectionsChanged")}</Badge>}
{changes.data.configurationChanged && <Badge color="yellow">{t("configurationChanged")}</Badge>}
</Group>
{changes.data.files.map((file) => (
<Stack key={file.name} gap="xs">
<Text fw={500}>{file.name}</Text>
<SimpleGrid cols={{ base: 1, lg: 2 }}>
<CodeEditor
id={`before-${file.name}`}
label={t("before")}
value={file.before ?? ""}
language="tsx"
readOnly
onChange={() => undefined}
/>
<CodeEditor
id={`after-${file.name}`}
label={t("after")}
value={file.after ?? ""}
language="tsx"
readOnly
onChange={() => undefined}
/>
</SimpleGrid>
</Stack>
))}
</>
)}
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
{active && (
<Paper withBorder p="md">
<Stack>
<Checkbox
checked={replace}
onChange={(event) => setReplace(event.currentTarget.checked)}
label={t("replaceDraft")}
/>
<input
hidden
type="file"
ref={input}
accept=".json,application/json"
onChange={(event) => {
const file = event.currentTarget.files?.[0];
event.currentTarget.value = "";
if (file) void stage(file);
}}
/>
<Button
variant="default"
disabled={!replace || dirty}
loading={update.isPending}
onClick={() => input.current?.click()}
>
{t("stageUpdate")}
</Button>
</Stack>
</Paper>
)}
<Paper withBorder p="md">
<Stack>
<Text size="sm">{t("forkDescription")}</Text>
<TextInput
label={t("forkName")}
value={forkName}
onChange={(event) => setForkName(event.currentTarget.value)}
/>
<Button
variant="default"
disabled={dirty || !forkName.trim()}
loading={fork.isPending}
onClick={() =>
fork.mutate(
{ id, name: forkName },
{
onSuccess: (result) => window.location.assign(result.managementPath),
onError: (error) => onError(error.message),
},
)
}
>
{t("fork")}
</Button>
</Stack>
</Paper>
</Stack>
);
}
export function PackageArtifactReview({ artifact }: { artifact: CustomWidgetArtifact }) {
const t = useI18n("customWidget.package.artifactReview");
const [selected, setSelected] = useState("dependency-lock.json");
const files: Record<string, string> = { "dependency-lock.json": JSON.stringify(artifact.dependencyLock, null, 2) };
for (const [surface, compiled] of Object.entries(artifact.client)) {
if (!compiled) continue;
files[`${surface}.js`] = compiled.javascript;
if (compiled.css) files[`${surface}.css`] = compiled.css;
}
if (artifact.server) files["server.js"] = artifact.server;
const path = Object.hasOwn(files, selected) ? selected : "dependency-lock.json";
return (
<Accordion>
<Accordion.Item value="artifact">
<Accordion.Control>{t("title")}</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
<Text size="sm">{t("description")}</Text>
<Text size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
{artifact.digest}
</Text>
<Select
label={t("file")}
value={path}
data={Object.keys(files)}
onChange={(value) => {
if (value) setSelected(value);
}}
/>
<CodeEditor
id={`artifact-${artifact.digest}-${path}`}
label={path}
value={files[path] ?? ""}
language={path.endsWith(".json") ? "json" : path.endsWith(".css") ? "css" : "tsx"}
readOnly
height="320px"
onChange={() => undefined}
/>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
);
}
@@ -1,5 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { useSearchParams } from "next/navigation";
import {
Alert,
@@ -20,17 +21,15 @@ import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { PackageOptionFields } from "@homarr/widgets/custom-api/package-option-fields";
import { PackagePreview } from "./_package-preview";
import { PackageSplit } from "./_package-split";
import { PackageAssistant } from "./_package-assistant";
import { usePackageAssistant } from "./_use-package-assistant";
import { PackageAssistant, usePackageAssistant } from "./_package-assistant";
import { PackageSourceEditor } from "./_package-source-editor";
import { PackageConnections } from "./_package-connections";
import { PackageOperations } from "./_package-operations";
import { PackageWorkshop } from "./_package-workshop";
import { PackageTransfer } from "./_package-transfer";
import { PackageWorkshop, PackageTransfer } from "./_package-workshop";
import { usePackageWorkspace } from "./_use-package-workspace";
import type { Installation } from "./_use-package-workspace";
import classes from "./_package-workspace.module.css";
import type { CSSProperties, PropsWithChildren, ReactNode } from "react";
const workspaceTabs = ["source", "connections", "options", "installation", "workshop"] as const;
type WorkspaceTab = (typeof workspaceTabs)[number];
@@ -309,3 +308,107 @@ export function PackageWorkspace({
</Stack>
);
}
/* oxlint-disable jsx-a11y/prefer-tag-over-role -- A focusable window splitter is an interactive separator, not a thematic break. */
const defaultWidth = 60;
const clampWidth = (value: number, maximum = 75) => Math.min(maximum, Math.max(30, value));
/** The split is an editor preference; it never changes the widget's authored dimensions. */
function PackageSplit({
userId,
pane,
preview,
children,
}: PropsWithChildren<{ userId: string; pane: string; preview: ReactNode }>) {
const t = useI18n("customWidget.package");
const [width, setWidth] = useState(defaultWidth);
const [availableWidth, setAvailableWidth] = useState(0);
const container = useRef<HTMLDivElement>(null);
const key = `homarr:widget-workspace:split:${userId}`;
const latest = useRef(width);
let maximum = 75;
if (availableWidth >= 650) maximum = Math.min(75, ((availableWidth - 338) / availableWidth) * 100);
const visibleWidth = clampWidth(width, maximum);
useEffect(() => {
if (!container.current) return;
const observer = new ResizeObserver(([entry]) => setAvailableWidth(entry?.contentRect.width ?? 0));
observer.observe(container.current);
return () => observer.disconnect();
}, []);
useEffect(() => {
try {
const saved = localStorage.getItem(key);
if (saved && Number.isFinite(Number(saved))) {
const next = clampWidth(Number(saved));
latest.current = next;
setWidth(next);
}
} catch {
// Browser storage is optional for editor preferences.
}
}, [key]);
const remember = (value: number) => {
const next = clampWidth(value, maximum);
latest.current = next;
setWidth(next);
try {
localStorage.setItem(key, String(next));
} catch {
// Resizing remains available when browser storage is disabled.
}
};
return (
<div
ref={container}
className={classes.workspace}
data-pane={pane}
style={{ "--widget-editor-width": `${visibleWidth}%` } as CSSProperties}
>
{children}
<div
className={classes.divider}
role="separator"
tabIndex={0}
aria-label={t("resizeEditor")}
title={t("resizeEditorHint")}
aria-orientation="vertical"
aria-valuemin={30}
aria-valuemax={Math.round(maximum)}
aria-valuenow={Math.round(visibleWidth)}
onDoubleClick={() => remember(defaultWidth)}
onKeyDown={(event) => {
let next = visibleWidth;
if (event.key === "ArrowLeft") next -= 5;
else if (event.key === "ArrowRight") next += 5;
else if (event.key === "Home") next = 30;
else if (event.key === "End") next = maximum;
else return;
event.preventDefault();
remember(next);
}}
onPointerDown={(event) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
const bounds = container.current?.getBoundingClientRect();
if (!bounds?.width) return;
latest.current = clampWidth(((event.clientX - bounds.left) / bounds.width) * 100, maximum);
setWidth(latest.current);
}}
onPointerUp={(event) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
event.currentTarget.releasePointerCapture(event.pointerId);
remember(latest.current);
}}
/>
{preview}
</div>
);
}
@@ -1,173 +0,0 @@
"use client";
import { useEffect, useRef } from "react";
import { createId } from "@homarr/common";
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { packageDraftToolContracts } from "~/components/assistant/assistant-package-draft-contracts";
import type {
PackageDraftReview,
ProposePackageChangesArgs,
} from "~/components/assistant/assistant-package-draft-contracts";
import {
notifyPackageDraftChanged,
registerAssistantPackageDraft,
} from "~/components/assistant/assistant-package-draft-registry";
import { packageAssistantSdkContext } from "./_package-assistant-context";
import { recoveryDocument } from "./_package-document";
import type { PackageDocument } from "./_package-document";
import type { usePackageWorkspace } from "./_use-package-workspace";
type Workspace = ReturnType<typeof usePackageWorkspace>;
const maximumContextCharacters = 180_000;
export function usePackageAssistant(workspace: Workspace) {
const identity = useRef({ document: workspace.document, revision: createId() });
if (identity.current.document !== workspace.document)
identity.current = { document: workspace.document, revision: createId() };
const revision = identity.current.revision;
const latest = useRef({ workspace, revision });
latest.current = { workspace, revision };
const readState = useRef({ revision: "", paths: new Set<string>(), metadata: false });
useEffect(
() =>
registerAssistantPackageDraft({
read(input) {
const { workspace: state, revision: currentRevision } = latest.current;
const sanitized = recoveryDocument(state.document);
if (readState.current.revision !== currentRevision)
readState.current = { revision: currentRevision, paths: new Set(), metadata: false };
const metadataOmitted = sanitized.metadata.length > 60_000;
if (!metadataOmitted) readState.current.metadata = true;
const files: Record<string, string> = {};
const omittedFiles: string[] = [];
let remaining = maximumContextCharacters;
for (const path of input.paths ?? Object.keys(sanitized.files)) {
const value = sanitized.files[path];
if (value === undefined || value.length > remaining) {
omittedFiles.push(path);
continue;
}
files[path] = value;
remaining -= value.length;
readState.current.paths.add(path);
}
const redactedFiles = Object.keys(sanitized.files).filter(
(path) => sanitized.files[path] !== state.document.files[path],
);
let previewEvidence: unknown = { status: "not-previewed-current-candidate" };
if (state.preview && !state.stale)
previewEvidence = {
status: "compiled-and-preview-session-created",
revision: currentRevision,
artifactDigest: state.preview.displayData.artifactDigest,
browserRenderingVerified: false,
liveActions: state.preview.liveActions,
};
return {
installationId: state.installationId,
saved: !state.editor.dirty,
revision: currentRevision,
name: sanitized.name,
metadata: metadataOmitted ? undefined : sanitized.metadata,
metadataOmitted,
selectedFile: state.selected,
filePaths: Object.keys(sanitized.files),
files,
omittedFiles,
oversizedFiles: Object.entries(sanitized.files)
.filter(([, value]) => value.length > maximumContextCharacters)
.map(([path]) => path),
contextLimits: {
fileCharacters: maximumContextCharacters,
metadataCharacters: 60_000,
oversizedFilesRequireManualEdit: true,
},
redactedFiles,
metadataRedacted: sanitized.metadata !== state.document.metadata,
diagnostics: recoveryDocument({ name: "", metadata: state.error, files: {} }).metadata.slice(0, 4000),
schemaValid: state.parsed.success,
validationIssues: state.parsed.success
? []
: state.parsed.error.issues.map(({ path, message }) => ({ path, message })),
sdk: packageAssistantSdkContext,
reference: input.reference ? widgetReferencePackages[input.reference] : undefined,
previewEvidence,
excluded: [
"local connection bindings",
"connection settings and credentials",
"preview option values",
"runtime response data",
],
};
},
review(input) {
return prepare(input, latest.current, readState.current).review;
},
apply(input) {
const prepared = prepare(input, latest.current, readState.current);
if (!prepared.review.available || !prepared.next) return { applied: false, error: prepared.review.error };
latest.current.workspace.resetExecution();
readState.current = { revision: "", paths: new Set(), metadata: false };
latest.current.workspace.edit(prepared.next);
return { applied: true };
},
}),
[],
);
useEffect(() => {
notifyPackageDraftChanged();
}, [revision, workspace.busy, workspace.preview, workspace.error]);
}
function prepare(
input: ProposePackageChangesArgs,
{ workspace, revision }: { workspace: Workspace; revision: string },
read: { revision: string; paths: Set<string>; metadata: boolean },
): { review: PackageDraftReview; next?: PackageDocument } {
const parsed = packageDraftToolContracts.propose_widget_package_changes.parameters.safeParse(input);
if (!parsed.success) return unavailable("The proposed patch is invalid.");
if (revision !== input.revision || read.revision !== revision)
return unavailable("The draft changed. Ask the Assistant to read the current draft and propose again.");
if (workspace.busy) return unavailable("Wait for the current save or preview to finish.");
const current = workspace.document;
if (input.metadata !== undefined && !read.metadata)
return unavailable(
"The manifest is too large for Assistant context. Edit it directly before proposing a replacement.",
);
const sanitized = recoveryDocument(current);
if (input.metadata !== undefined && sanitized.metadata !== current.metadata)
return unavailable(
"The manifest contains redacted credentials. Move them to a local connection before replacing this file.",
);
if (input.name !== undefined && sanitized.name !== current.name)
return unavailable("The name contains redacted credentials. Edit it directly before proposing a replacement.");
const next = {
name: input.name ?? current.name,
metadata: input.metadata ?? current.metadata,
files: { ...current.files },
};
const changes: PackageDraftReview["changes"] = [];
if (next.name !== current.name) changes.push({ path: "Installation name", before: current.name, after: next.name });
if (next.metadata !== current.metadata)
changes.push({ path: "widget.json", before: current.metadata, after: next.metadata });
for (const [path, value] of Object.entries(input.files)) {
if (Object.hasOwn(current.files, path) && !read.paths.has(path))
return unavailable(`Read '${path}' before proposing changes to it.`);
if (sanitized.files[path] !== current.files[path])
return unavailable(
`'${path}' contains redacted credentials. Move them to local connections before replacing this file.`,
);
if (value === null) delete next.files[path];
else next.files[path] = value;
if (value !== current.files[path]) changes.push({ path, before: current.files[path] ?? "", after: value ?? "" });
}
if (
Object.keys(next.files).length > 256 ||
Object.values(next.files).reduce((size, file) => size + file.length, 0) > 20_000_000
)
return unavailable("The proposed draft exceeds package size limits.");
return { next, review: { available: true, changes } };
}
const unavailable = (error: string) => ({ review: { available: false, error, changes: [] } });
@@ -1,14 +1,22 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { extractErrorMessage, usePendingOperations } from "@homarr/common";
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
import { customWidgetPackageSchema, widgetPackagePathSchema } from "@homarr/custom-widgets/package";
import { useI18n } from "@homarr/translation/client";
import clock from "@homarr/widget-sdk/examples/clock.json";
import { getLogicalTrackSize } from "~/components/board/layout/geometry";
import { documentFromSource, documentFromTemplate, documentSource } from "./_package-document";
import { usePackageDocument } from "./_use-package-document";
import {
documentFromSource,
documentFromTemplate,
documentSource,
usePackageDocument,
} from "@homarr/custom-widgets/workbench/package";
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
export type Installation = RouterOutputs["customWidget"]["package"]["get"];
type Preview = RouterOutputs["customWidget"]["package"]["preview"] & { liveActions: boolean };
export function usePackageWorkspace(
@@ -28,16 +36,11 @@ export function usePackageWorkspace(
const [installationId, setInstallationId] = useState(installation?.id);
const [bindings, setBindings] = useState(installation?.bindings ?? initialBindings ?? {});
const [savedBindings, setSavedBindings] = useState(installation?.bindings ?? {});
const [pendingConnections, setPendingConnections] = useState(0);
const connectionPreparationChanged = useCallback((pending: boolean) => {
setPendingConnections((current) => {
if (pending) return current + 1;
return current - 1;
});
}, []);
const [connectionsPending, connectionPreparationChanged] = usePendingOperations();
const bindingsDirty =
JSON.stringify(Object.entries(bindings).toSorted()) !== JSON.stringify(Object.entries(savedBindings).toSorted());
const editor = usePackageDocument(initial, userId, installationId, bindingsDirty);
const editor = usePackageDocument(initial, userId, installationId);
useUnsavedChangesGuard(editor.dirty || bindingsDirty, { navigationKey: installationId });
const { document, edit } = editor;
const [selected, setSelected] = useState(Object.keys(initial.files)[0] ?? "/widget.json");
const [path, setPath] = useState("");
@@ -76,7 +79,7 @@ export function usePackageWorkspace(
const discard = clientApi.customWidget.package.discardPreview.useMutation();
const saveBindings = clientApi.customWidget.package.setBindings.useMutation();
const discardPreview = discard.mutate;
const busy = save.isPending || saveBindings.isPending || previewMutation.isPending || pendingConnections > 0;
const busy = save.isPending || saveBindings.isPending || previewMutation.isPending || connectionsPending;
const resetExecution = useCallback(() => {
generation.current += 1;
if (previewId.current) setStale(true);
@@ -134,7 +137,7 @@ export function usePackageWorkspace(
setMessage(t("draftSaved"));
return result.id;
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
};
const runPreview = async () => {
@@ -165,7 +168,7 @@ export function usePackageWorkspace(
setStale(false);
setPane("preview");
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
}
};
const addFile = () => {
@@ -1,86 +0,0 @@
"use client";
import { useState } from "react";
import { Accordion, Alert, Button, Group, MultiSelect, Stack, Text, TextInput } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { fetchApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { downloadPackage } from "../_package-document";
export function PackageCollectionExport({
installations,
}: {
installations: RouterOutputs["customWidget"]["package"]["list"];
}) {
const t = useI18n("customWidget.package.collections");
const [selected, setSelected] = useState<string[]>([]);
const [name, setName] = useState("");
const [id, setId] = useState("");
const [version, setVersion] = useState("1.0.0");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const exportCollection = async () => {
setBusy(true);
setError("");
try {
const archive = await fetchApi.customWidget.package.exportCollection.query({
manifest: { id, name, version },
installationIds: selected,
});
downloadPackage(name, archive);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
} finally {
setBusy(false);
}
};
return (
<Accordion variant="contained">
<Accordion.Item value="export">
<Accordion.Control>{t("export")}</Accordion.Control>
<Accordion.Panel>
<Stack>
<Text size="sm" c="dimmed">
{t("exportDescription")}
</Text>
<MultiSelect
label={t("widgets")}
searchable
value={selected}
onChange={setSelected}
maxValues={32}
data={installations
.filter((entry) => entry.activeArtifactId)
.map((entry) => ({ value: entry.id, label: entry.name }))}
/>
<Group grow>
<TextInput label={t("name")} value={name} onChange={(event) => setName(event.currentTarget.value)} />
<TextInput
label={t("identity")}
description={t("identityDescription")}
placeholder={t("identityPlaceholder")}
value={id}
onChange={(event) => setId(event.currentTarget.value)}
/>
<TextInput
label={t("version")}
value={version}
onChange={(event) => setVersion(event.currentTarget.value)}
/>
</Group>
{error && <Alert color="red">{error}</Alert>}
<Button
loading={busy}
disabled={!selected.length || !name.trim() || !id.trim()}
onClick={() => void exportCollection()}
>
{t("export")}
</Button>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
);
}
@@ -1,15 +1,16 @@
"use client";
import { Alert, Badge, Button, Stack, Text } from "@mantine/core";
import { IconLayoutGrid } from "@tabler/icons-react";
import { extractErrorMessage } from "@homarr/common";
import { Alert, Badge, Button, Stack, Text, Accordion, Group, MultiSelect, TextInput } from "@mantine/core";
import { IconLayoutGrid } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { clientApi, fetchApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { ManageCollectionItem, ManageCollectionList } from "~/components/manage/manage-collection";
import { PackageCollectionExport } from "./_collection-export";
import { useState } from "react";
import { downloadPackage } from "@homarr/custom-widgets/workbench/package";
export function PackageCollectionList({
initialData,
@@ -57,3 +58,79 @@ export function PackageCollectionList({
</Stack>
);
}
export function PackageCollectionExport({
installations,
}: {
installations: RouterOutputs["customWidget"]["package"]["list"];
}) {
const t = useI18n("customWidget.package.collections");
const [selected, setSelected] = useState<string[]>([]);
const [name, setName] = useState("");
const [id, setId] = useState("");
const [version, setVersion] = useState("1.0.0");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const exportCollection = async () => {
setBusy(true);
setError("");
try {
const archive = await fetchApi.customWidget.package.exportCollection.query({
manifest: { id, name, version },
installationIds: selected,
});
downloadPackage(name, archive);
} catch (cause) {
setError(extractErrorMessage(cause));
} finally {
setBusy(false);
}
};
return (
<Accordion variant="contained">
<Accordion.Item value="export">
<Accordion.Control>{t("export")}</Accordion.Control>
<Accordion.Panel>
<Stack>
<Text size="sm" c="dimmed">
{t("exportDescription")}
</Text>
<MultiSelect
label={t("widgets")}
searchable
value={selected}
onChange={setSelected}
maxValues={32}
data={installations
.filter((entry) => entry.activeArtifactId)
.map((entry) => ({ value: entry.id, label: entry.name }))}
/>
<Group grow>
<TextInput label={t("name")} value={name} onChange={(event) => setName(event.currentTarget.value)} />
<TextInput
label={t("identity")}
description={t("identityDescription")}
placeholder={t("identityPlaceholder")}
value={id}
onChange={(event) => setId(event.currentTarget.value)}
/>
<TextInput
label={t("version")}
value={version}
onChange={(event) => setVersion(event.currentTarget.value)}
/>
</Group>
{error && <Alert color="red">{error}</Alert>}
<Button
loading={busy}
disabled={!selected.length || !name.trim() || !id.trim()}
onClick={() => void exportCollection()}
>
{t("export")}
</Button>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
);
}
@@ -1,6 +1,8 @@
"use client";
import { useCallback, useState } from "react";
import { usePendingOperations } from "@homarr/common";
import { useState } from "react";
import { Accordion, Alert, Badge, Button, Checkbox, Group, Paper, Select, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
@@ -19,13 +21,7 @@ export function PackageCollectionSetup({ initialData }: { initialData: WidgetCol
const boards = clientApi.board.getAllBoards.useQuery();
const saveBindings = clientApi.customWidget.package.setCollectionBindings.useMutation();
const [bindings, setBindings] = useState(initialData.bindings);
const [pendingConnections, setPendingConnections] = useState(0);
const connectionPreparationChanged = useCallback((pending: boolean) => {
setPendingConnections((current) => {
if (pending) return current + 1;
return current - 1;
});
}, []);
const [connectionsPending, connectionPreparationChanged] = usePendingOperations();
const [configuration, setConfiguration] = useState<CollectionConfiguration>({});
const [selected, setSelected] = useState(initialData.entries.map((entry) => entry.id));
const [boardId, setBoardId] = useState<string | null>(null);
@@ -40,7 +36,7 @@ export function PackageCollectionSetup({ initialData }: { initialData: WidgetCol
};
const [error, setError] = useState("");
const progress = useCollectionPlacement(collection);
const busy = progress.busy || saveBindings.isPending || pendingConnections > 0;
const busy = progress.busy || saveBindings.isPending || connectionsPending;
const board = boards.data?.find((candidate) => candidate.id === boardId);
const requiredSlots = new Set(
collection.entries
@@ -1,5 +1,7 @@
"use client";
import { extractErrorMessage } from "@homarr/common";
import { useEffect, useRef, useState } from "react";
import type { RouterOutputs } from "@homarr/api";
@@ -94,12 +96,12 @@ export function useCollectionPlacement(collection: WidgetCollection) {
report(t("added"));
added = true;
} catch (cause) {
report(cause instanceof Error ? cause.message : String(cause), true);
report(extractErrorMessage(cause), true);
}
}
if (added) setCompletedBoard(board.name);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
setError(extractErrorMessage(cause));
} finally {
running.current = false;
setBusy(false);
@@ -5,7 +5,7 @@ import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
import { auth } from "@homarr/auth/next";
import { getI18n } from "@homarr/translation/server";
import { NativePackageWorkspace } from "../_package-native-workspace";
import { NativePackageWorkspace } from "../_package-convert";
import { PackageWorkspace } from "../_package-workspace";
export default async function NewWidgetPackagePage({
@@ -1,7 +1,7 @@
import { redirect } from "next/navigation";
import { Container } from "@mantine/core";
import { auth } from "@homarr/auth/next";
import { PackageSessionPreview } from "../../_package-session-preview";
import { PackageSessionPreview } from "../../_package-preview";
export default async function PackagePreviewPage({ params }: { params: Promise<{ previewId: string }> }) {
const session = await auth();
@@ -1,6 +1,8 @@
"use client";
import { useCallback, useState } from "react";
import { usePendingOperations } from "@homarr/common";
import { useState } from "react";
import { Accordion, Alert, Button, Paper, Select, Stack, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
@@ -8,7 +10,7 @@ import { useI18n } from "@homarr/translation/client";
import { CodeEditor } from "~/components/custom-widgets/code-editor";
import { PackageConnections } from "../../packages/_package-connections";
import { PackageArtifactReview } from "../../packages/_package-artifact-review";
import { PackageArtifactReview } from "../../packages/_package-workshop";
export function WorkshopPackageReview({ submissionId }: { submissionId: string }) {
const t = useI18n("customWidget.package");
@@ -20,15 +22,9 @@ export function WorkshopPackageReview({ submissionId }: { submissionId: string }
{ enabled: Boolean(releaseId) },
);
const [bindings, setBindings] = useState<Record<string, string>>({});
const [pendingConnections, setPendingConnections] = useState(0);
const connectionPreparationChanged = useCallback((pending: boolean) => {
setPendingConnections((current) => {
if (pending) return current + 1;
return current - 1;
});
}, []);
const [connectionsPending, connectionPreparationChanged] = usePendingOperations();
const install = clientApi.customWidget.package.installWorkshop.useMutation();
const busy = install.isPending || pendingConnections > 0;
const busy = install.isPending || connectionsPending;
return (
<Paper withBorder p="md">
<Stack>
+13 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
@@ -42,3 +42,15 @@ export const useIntegrationConnected = (updatedAt: Date, { timeout = 30000 }) =>
return connected;
};
/** Track overlapping preparations without allowing one completion to clear another's pending state. */
export function usePendingOperations() {
const [count, setCount] = useState(0);
const trackPending = useCallback((pending: boolean) => {
setCount((current) => {
if (pending) return current + 1;
return current - 1;
});
}, []);
return [count > 0, trackPending] as const;
}
+1
View File
@@ -12,3 +12,4 @@ export * from "./error";
export * from "./theme";
export * from "./function";
export * from "./grid-algorithm";
export * from "./browser";
+10
View File
@@ -99,3 +99,13 @@ const parseHttpUrl = (value: unknown, baseUrl?: string): URL | undefined => {
}
return url;
};
/** Offer an explicit prefix; preserve the owner's hostname, port and path text. */
export function getConnectionUrlSuggestion(value: string): string | undefined {
const input = value.trim();
if (!input || input.includes("://") || (input.startsWith("/") && !input.startsWith("//"))) return undefined;
let candidate = `http://${input}`;
if (input.startsWith("//")) candidate = `http:${input}`;
if (!getSafeApplicationUrl(candidate)) return undefined;
return candidate;
}
+2
View File
@@ -23,6 +23,7 @@
"./package/server": "./src/package/server.ts",
"./runtime": "./src/runtime/index.ts",
"./server": "./src/server/index.ts",
"./workbench/package": "./src/workbench/package-document.ts",
"./workbench": "./src/workbench/index.ts",
"./workbench/package-language": "./src/workbench/package-language/index.ts"
},
@@ -52,6 +53,7 @@
"@codemirror/state": "catalog:",
"@codemirror/theme-one-dark": "catalog:",
"@codemirror/view": "catalog:",
"@homarr/common": "workspace:^0.1.0",
"@homarr/widget-sdk": "workspace:^0.1.0",
"@mantine/charts": "catalog:",
"@mantine/core": "catalog:",
@@ -25,17 +25,10 @@ async function collect(directory) {
for (const sourceRoot of sourceRoots) await collect(sourceRoot);
const failures = [];
const graph = new Map();
const algorithmicExceptions = new Map([
["packages/custom-widgets/src/jsx/analyzer.ts", 400],
["packages/custom-widgets/src/jsx/interpreter.tsx", 400],
]);
for (const file of productionFiles) {
const source = await readFile(file, "utf8");
const name = relative(repositoryRoot, file);
const lineCount = source.trimEnd().split("\n").length;
const limit = algorithmicExceptions.get(name) ?? 300;
if (lineCount > limit) failures.push(`${name} has ${lineCount} lines (limit ${limit})`);
if (file.startsWith(join(packageRoot, "src")) && /from\s+["']@homarr\/(?:api|widgets)(?:\/|["'])/u.test(source)) {
failures.push(`${name} imports a forbidden adapter package`);
}
@@ -1,3 +1,4 @@
import { HOST_WIDGET_MODULES } from "../package/schema";
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
import { customJsxAuthoringCatalog } from "./component-catalog";
import {
@@ -284,3 +285,22 @@ function truncatePromptText(value: string, limit: number) {
const marker = "\n... [content omitted to fit the prompt budget]";
return `${value.slice(0, Math.max(0, limit - marker.length))}${marker}`;
}
/** Public authoring context only. Local bindings and runtime response data never belong here. */
export const packageAssistantSdkContext = {
schema: "homarr-widget-package-v3",
sdkVersion: "1",
hostModules: HOST_WIDGET_MODULES,
package:
"widget.json contains $schema, manifest, dependencies, connections, options; files are edited separately. manifest requires id, name, version (exact semver), sdkVersion:'1', entrypoints:{tile,advanced?,configuration?,server?}. Each client surface default-exports a React component. Local relative modules and CSS imports work. dependencies maps npm names to exact versions. No request, connection or server file is required for static widgets. Declare connections as named {label,kind:'http'|'integration'|'service',optional?}; service requirements also declare serviceType. Owners bind local settings and encrypted secrets. Never embed credentials, local addresses or connection IDs in portable source.",
styling:
"Use normal TSX, React hooks, imported Mantine components, CSS and reusable modules. manifest.styles defaults to scoped CSS; 'global' is an explicit package choice. Build dashboard tiles and advanced views; there is no standalone application route. Respect host.visibleWidth/visibleHeight, colorScheme, locale, reducedMotion and isEditMode. Entry points may reuse the same component and branch on displayMode.",
client:
"Import @homarr/widget-sdk. useWidgetHost() returns displayMode:'compact'|'advanced',width,height,visibleWidth,visibleHeight,displayScale,visible,isPreview,isEditMode,locale,timeZone,colorScheme,reducedMotion. useWidgetOptions<T>() returns option values. useWidgetState<T>(key,initial) shares instance state between tile and advanced. useWidgetClock(intervalMs=1000) returns epoch milliseconds or null, pauses when hidden. useWidgetQuery<T>(name,input?,{enabled?,refetchInterval?,staleTime?}) returns query state. useWidgetAction<Output,Input>(name) returns mutation (mutate/mutateAsync). useWidgetSubscription<T>(name,input?,{enabled?,maximumEvents?}) returns data,events,error,connected,reconnect. useWidgetStorage<T>('user'|'instance'|'installation',key,initial) returns data,set,saving,saveError. useWidgetCommands([{id,label,run,disabled?,destructive?}]) registers native menu commands. WidgetScope name/handlerPrefix/options isolates composed components.",
services:
"useWidgetServices() exposes notify({title,message?,color?}), navigate(href), openAdvanced(), closeAdvanced(), openDetail({title,content:ReactNode}), closeDetail(), confirm({title,message,destructive?}):Promise<boolean>, updateOptions(record):Promise<void>. Use updateOptions from an authored configuration surface. Managed storage is isolated memory in preview. Query results and local options are not part of Assistant context.",
server:
"Optional server.ts imports @homarr/widget-sdk/server and default-exports defineWidgetServer({handler:async(input,context)=>value}). Declare every handler in manifest.handlers with kind:'query'|'action'|'subscription'|'migration', permission:'view'|'modify'|'full', inputSchema? (JSON Schema), guestAccess?; actions default to modify. fetchWidgetConnection<T>(context,{connection:'slot',path,method?,query?,body?,responseType?}) returns {data,ok,status,contentType,durationMs,updatedAt}. getWidgetConnection<TSettings>(context,{connection,serviceType?}) returns {configuration:{kind,serviceType?,settings?:TSettings,...},secrets:Record<string,string>} only to trusted server code for Node SQL, MQTT, SSH, files or other service clients; never return secrets to browser queries. getWidgetServerContext(context) returns options,installationId,bindingNames,bindingLabels,isPreview. Declare connections with multiple:true for a repeatable group, and integrationKind (for example sonarr) to filter compatible native integrations. getWidgetConnectionGroup(context,slot) returns all {connection,label} members for queries and actions; do not hard-code first/second server slots. callWidgetIntegration(context,{connection,capability,input?}) invokes native adapters; subscribeWidgetIntegration yields native stream events. callWidgetRunner and subscribeWidgetRunner address owner-managed remote runners. Server modules have trusted Node capabilities. Secrets stay in owner-bound connections. Do not invent integration capabilities: use reference packages or declared capability docs.",
lifecycle:
"Proposals only change the visible draft after explicit review; they never save, trust, run or activate code. The owner saves the draft, reviews dependencies and trust, runs exact-candidate Preview, then explicitly activates the saved release for all placements. SDK actions are simulated in default previews, but arbitrary trusted browser/Node code still executes. A preview session proves compilation/session creation only, not successful UI rendering, live action success or all application behavior. Any source/options/binding edit invalidates preview evidence.",
};
@@ -1,12 +1,58 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
import { isRecord } from "@homarr/common";
import { createId, downloadJson, isRecord } from "@homarr/common";
import { redactCustomWidgetCredentialLiterals } from "../core/definition-security";
import { documentFromSource, recoveryDocument } from "./_package-document";
import type { PackageDocument } from "./_package-document";
export interface PackageDocument {
name: string;
metadata: string;
files: Record<string, string>;
}
export function documentFromSource(name: string, source: unknown): PackageDocument {
if (!isRecord(source)) return { name, metadata: "{}", files: {} };
const { files, _draftMetadata, ...metadata } = source;
const document = { name, metadata: JSON.stringify(metadata, null, 2), files: {} as Record<string, string> };
if (typeof _draftMetadata === "string") document.metadata = _draftMetadata;
if (isRecord(files)) {
for (const [path, content] of Object.entries(files))
if (typeof content === "string") document.files[path] = content;
}
return document;
}
export function documentFromTemplate(name: string, source: unknown): PackageDocument {
if (!isRecord(source) || !isRecord(source.manifest)) return documentFromSource(name, source);
return documentFromSource(name, {
...source,
manifest: { ...source.manifest, id: `local.${createId()}`, name, version: "1.0.0" },
});
}
export function documentSource(document: PackageDocument): Record<string, unknown> {
try {
const metadata: unknown = JSON.parse(document.metadata);
if (isRecord(metadata)) return { ...metadata, files: document.files };
} catch {
/* An incomplete manifest can still be saved as a draft. */
}
return { _draftMetadata: document.metadata, files: document.files };
}
const redact = (text: string) =>
redactCustomWidgetCredentialLiterals(text).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gu, "$1");
export function recoveryDocument(document: PackageDocument): PackageDocument {
return {
name: redact(document.name),
metadata: redact(document.metadata),
files: Object.fromEntries(Object.entries(document.files).map(([path, content]) => [path, redact(content)])),
};
}
export function downloadPackage(name: string, value: unknown) {
downloadJson(value, `${name.replace(/[^a-z0-9._-]+/giu, "-") || "widget"}.json`);
}
const maximumHistoryBytes = 2_000_000;
const maximumRecoveryBytes = 1_000_000;
@@ -15,7 +61,6 @@ export function usePackageDocument(
initial: PackageDocument,
userId: string,
installationId?: string,
connectionsDirty = false,
) {
const [document, setDocument] = useState(initial);
const [saved, setSaved] = useState(initial);
@@ -106,8 +151,6 @@ export function usePackageDocument(
return () => clearTimeout(timer);
}, [definitionId, dirty, document, key, recovery]);
useUnsavedChangesGuard(dirty || connectionsDirty, { navigationKey: installationId });
const discardRecovery = () => {
setRecovery(null);
try {
+71 -2
View File
@@ -1,7 +1,20 @@
"use client";
import type { ReactNode } from "react";
import { Badge, Center, Group, NumberInput, Stack, Text, Tooltip } from "@mantine/core";
import { useId, useMemo, useRef } from "react";
import type { PropsWithChildren, ReactNode } from "react";
import {
Badge,
Center,
Group,
NumberInput,
Stack,
Text,
Tooltip,
MantineProvider,
Portal,
useComputedColorScheme,
useMantineTheme,
} from "@mantine/core";
import { useElementSize } from "@mantine/hooks";
import { useI18n } from "@homarr/translation/client";
@@ -66,3 +79,59 @@ export function WidgetPreviewFrame({ dimensions, resize, children }: {
</Stack>
);
}
/** Scope preview colors and portal variables without changing the user's application theme. */
export function WidgetPreviewViewport({
children,
colorScheme,
width,
height,
scale,
}: PropsWithChildren<{
colorScheme: "system" | "light" | "dark";
width: number;
height: number;
scale: number;
}>) {
const id = useId().replace(/[^a-zA-Z0-9_-]/gu, "");
const root = useRef<HTMLDivElement>(null);
const currentScheme = useComputedColorScheme("light");
const hostTheme = useMantineTheme();
let scheme = currentScheme;
if (colorScheme !== "system") scheme = colorScheme;
const theme = useMemo(
() => ({
...hostTheme,
components: {
...hostTheme.components,
Portal: Portal.extend({ defaultProps: { target: `#widget-preview-overlays-${id}` } }),
},
}),
[hostTheme, id],
);
return (
<MantineProvider
theme={theme}
forceColorScheme={scheme}
cssVariablesSelector={`[data-widget-preview-theme="${id}"]`}
getRootElement={() => root.current ?? undefined}
deduplicateCssVariables={false}
withGlobalClasses={false}
>
<div
ref={root}
data-widget-preview-theme={id}
data-mantine-color-scheme={scheme}
style={{
width: width * scale,
height: height * scale,
background: "var(--mantine-color-body)",
color: "var(--mantine-color-text)",
}}
>
<div style={{ width, height, transform: `scale(${scale})`, transformOrigin: "top left" }}>{children}</div>
</div>
<div id={`widget-preview-overlays-${id}`} data-widget-preview-theme={id} data-mantine-color-scheme={scheme} />
</MantineProvider>
);
}
+3
View File
@@ -1934,6 +1934,9 @@ importers:
'@codemirror/view':
specifier: 'catalog:'
version: 6.43.0
'@homarr/common':
specifier: workspace:^0.1.0
version: link:../common
'@homarr/widget-sdk':
specifier: workspace:^0.1.0
version: link:../widget-sdk