diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx index 828eeb10a..42bf260a1 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-actions.tsx @@ -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 }; diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-artifact-review.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-artifact-review.tsx deleted file mode 100644 index f1084d932..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-artifact-review.tsx +++ /dev/null @@ -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 = { "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 ( - - - {t("title")} - - - {t("description")} - - {artifact.digest} - - void change(value ? [value] : [])} /> - )} - {error && {error}} - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-collectors.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-collectors.tsx index 1a5382706..6fedabc88 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-collectors.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-collectors.tsx @@ -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({ ); } + +type History = RouterOutputs["widget"]["customApi"]["packageHistory"]; + +function PackageHistorySummary({ data }: { data: History }) { + const t = useI18n("customWidget.package.historySummary"); + const latest = data.samples.at(-1); + return ( + + {latest && ( + + + {formatCollectedValue(latest.value)} {data.unit} + + + {t("latest", { time: new Date(latest.timestamp).toLocaleString() })} + + + )} + {!latest && ( + + {t("empty")} + + )} + {"lastError" in data && data.lastError && {data.lastError}} + + + {t("samples", { count: data.samples.length })} + +
+ + + + {t("time")} + {t("value")} + + + + {data.samples.toReversed().map((sample, index) => ( + + {new Date(sample.timestamp).toLocaleString()} + + {formatCollectedValue(sample.value)} {data.unit} + + + ))} + +
+
+
+
+ + {t("details")} + + + {JSON.stringify(data, null, 2)} + + + +
+
+ ); +} + +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); +} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-diagnostic.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-diagnostic.tsx deleted file mode 100644 index e0f988168..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-diagnostic.tsx +++ /dev/null @@ -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 ( - - - - {t(`help.${result.status}`)} - {"stage" in result && ( - - {t("phase", { phase: t(`stage.${result.stage as "dns" | "connection" | "tls" | "response"}`) })} - - )} - {"hostname" in result && ( - - {result.hostname} - - )} - {result.addresses.length > 0 && ( - - {result.addresses.map(({ address }) => ( - - {address} - - ))} - - )} - {"httpStatus" in result && typeof result.httpStatus === "number" && typeof result.durationMs === "number" && ( - {t("response", { status: result.httpStatus, milliseconds: result.durationMs })} - )} - {"sampleFields" in result && Array.isArray(result.sampleFields) && result.sampleFields.length > 0 && ( - {t("fields", { fields: result.sampleFields.join(", ") })} - )} - - - - - {t("details")} - - - {JSON.stringify(result, null, 2)} - - - - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-editor.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-editor.tsx index 0177a8dcf..a63739e96 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-editor.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-editor.tsx @@ -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 ( diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-url.ts b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-url.ts deleted file mode 100644 index fa0e87c57..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connection-url.ts +++ /dev/null @@ -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; -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connections.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connections.tsx index a795bbb9b..4462b266c 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connections.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-connections.tsx @@ -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({ ); } + +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; + onChange: Dispatch>>; + 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 ( + + {requirement.multiple ? ( + void change(values)} /> + ) : ( + { - setItemId(value); - setReplaced(false); - }} - data={(placements.data ?? []).map((placement) => ({ - value: placement.id, - label: `${placement.boardName} · ${placement.id}`, - }))} - /> - {placements.data?.length === 0 && ( - - {t("noOriginalPlacements")} - - )} - - - )} - {replaced && {t("replaced")}} - {(migrate.error || placements.error) && ( - {migrate.error?.message ?? placements.error?.message} - )} - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-document.ts b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-document.ts deleted file mode 100644 index fee0b5bb4..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-document.ts +++ /dev/null @@ -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; -} - -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 }; - 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 { - 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; diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-file-tree.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-file-tree.tsx deleted file mode 100644 index 296f80778..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-file-tree.tsx +++ /dev/null @@ -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; - 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 ( - { - let Icon = IconCode; - if (hasChildren) Icon = IconFolder; - if (hasChildren && expanded) Icon = IconFolderOpen; - return ( - - {hasChildren && } - - - {node.label} - - - ); - }} - /> - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-history-summary.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-history-summary.tsx deleted file mode 100644 index 9e4b1022c..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-history-summary.tsx +++ /dev/null @@ -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 ( - - {latest && ( - - - {formatCollectedValue(latest.value)} {data.unit} - - - {t("latest", { time: new Date(latest.timestamp).toLocaleString() })} - - - )} - {!latest && ( - - {t("empty")} - - )} - {"lastError" in data && data.lastError && {data.lastError}} - - - {t("samples", { count: data.samples.length })} - -
- - - - {t("time")} - {t("value")} - - - - {data.samples.toReversed().map((sample, index) => ( - - {new Date(sample.timestamp).toLocaleString()} - - {formatCollectedValue(sample.value)} {data.unit} - - - ))} - -
-
-
-
- - {t("details")} - - - {JSON.stringify(data, null, 2)} - - - -
-
- ); -} - -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); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-language-editor.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-language-editor.tsx index b60fa2738..bbba642c4 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-language-editor.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-language-editor.tsx @@ -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 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 { 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; diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-list.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-list.tsx index fc5e78989..2b9320241 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-list.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-list.tsx @@ -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() { ); } + +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) => { + try { + await action(); + await utils.customWidget.package.list.invalidate(); + } catch (error) { + showErrorNotification({ title: t("title"), message: extractErrorMessage(error) }); + } + }; + return ( + + + + + + + + }> + {t("addToBoard")} + + }> + {t("connections")} + + }> + {t("workshopTab")} + + + } onClick={() => void run(async () => { + await fork.mutateAsync({ id: entry.id, name: t("forkDefaultName", { name: entry.name }).slice(0, 128) }); + })}> + {t("fork")} + + } onClick={() => void run(async () => { + const draft = await utils.customWidget.package.get.fetch({ id: entry.id }); + downloadPackage(entry.name, draft.source); + })}> + {t("exportDraft")} + + {entry.activeArtifactId && } onClick={() => void run(async () => { + downloadPackage(entry.name, await utils.customWidget.package.export.fetch({ id: entry.id })); + })}>{t("exportActive")}} + + : } + onClick={() => void run(() => enable.mutateAsync({ id: entry.id, enabled: !entry.enabled }))} + > + {entry.enabled ? t("disable") : t("enable")} + + + + ); +} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-native-workspace.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-native-workspace.tsx deleted file mode 100644 index 82ae9e457..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-native-workspace.tsx +++ /dev/null @@ -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 ( - - ); - if (preparation.error) - return ( - - {preparation.error.message} - - - ); - return ( - - - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-operations.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-operations.tsx index c8088d56e..9d7ffc938 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-operations.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-operations.tsx @@ -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, message: string) => { try { await action(); await refresh(); onMessage(message); } catch (error) { - onError(error instanceof Error ? error.message : String(error)); + onError(extractErrorMessage(error)); } }; return ( diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-placements.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-placements.tsx index bb5a15784..5c20808e8 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-placements.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-placements.tsx @@ -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 ); } + +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 ; +} + +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(null); + const [replaced, setReplaced] = useState(false); + return ( + + + {t("replaceTitle")} + {t("replaceDescription")} + {!active && ( + + {t("activateFirst")} + + )} + {active && ( + <> + { - if (value === "system" || value === "light" || value === "dark") setPreviewTheme(value); - }} - /> - - - - {t("customViewport")} - - - {t("customViewportDescription")} - - { - if (typeof value === "number") setWidth(value); - }} - /> - { - if (typeof value === "number") setHeight(value); - }} - /> - { - if (typeof value === "number") setScale(Math.min(0.9, Math.max(0.25, value / 100))); - }} - /> - - - - - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview-viewport.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview-viewport.tsx deleted file mode 100644 index 3e36d2921..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview-viewport.tsx +++ /dev/null @@ -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(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 ( - root.current ?? undefined} - deduplicateCssVariables={false} - withGlobalClasses={false} - > -
-
{children}
-
-
- - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview.tsx index 5f81b94e6..1dab014e2 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-preview.tsx @@ -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 ( <> {preview && ( - + - + )} {!preview && ( @@ -190,3 +201,179 @@ export function PackagePreview({ state }: { state: ReturnType ); } + +function PackagePreviewControls({ state }: { state: ReturnType }) { + const t = useI18n("customWidget.package"); + const { width, height, scale, previewTheme, setWidth, setHeight, setScale, setPreviewTheme } = state; + return ( + + + { + if (value === "tile" || value === "advanced" || value === "configuration") setSurface(value); + }} + /> + { + if (typeof value === "number") setWidth(value); + }} + /> + { + if (typeof value === "number") setHeight(value); + }} + /> + + +
+ +
+
+
+ ); +} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-row-actions.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-row-actions.tsx deleted file mode 100644 index 19b821842..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-row-actions.tsx +++ /dev/null @@ -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) => { - try { - await action(); - await utils.customWidget.package.list.invalidate(); - } catch (error) { - showErrorNotification({ title: t("title"), message: error instanceof Error ? error.message : String(error) }); - } - }; - return ( - - - - - - - - }> - {t("addToBoard")} - - }> - {t("connections")} - - }> - {t("workshopTab")} - - - } onClick={() => void run(async () => { - await fork.mutateAsync({ id: entry.id, name: t("forkDefaultName", { name: entry.name }).slice(0, 128) }); - })}> - {t("fork")} - - } onClick={() => void run(async () => { - const draft = await utils.customWidget.package.get.fetch({ id: entry.id }); - downloadPackage(entry.name, draft.source); - })}> - {t("exportDraft")} - - {entry.activeArtifactId && } onClick={() => void run(async () => { - downloadPackage(entry.name, await utils.customWidget.package.export.fetch({ id: entry.id })); - })}>{t("exportActive")}} - - : } - onClick={() => void run(() => enable.mutateAsync({ id: entry.id, enabled: !entry.enabled }))} - > - {entry.enabled ? t("disable") : t("enable")} - - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-runtime-status.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-runtime-status.tsx deleted file mode 100644 index 5bdd057ce..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-runtime-status.tsx +++ /dev/null @@ -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 ( - - {t("title")} - {t("description")} - - {data && {t(data.state)}} - - - {data && "pid" in data && ( - {t("process", { pid: data.pid ?? "—", active: data.activeRequests, queued: data.queuedRequests })} - )} - {data && "error" in data && {data.error}} - {status.error && {status.error.message}} - - - ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-session-preview.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-session-preview.tsx deleted file mode 100644 index e706eb437..000000000 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-session-preview.tsx +++ /dev/null @@ -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 ; - if (error || !data) - return ( - - {t("sessionUnavailableDescription")} - - ); - 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 ( - - - {data.displayData.manifest.name} - - - - {t("sessionDescription")} - - {data.displayData.previewScenario && ( - - {t("previewSynthetic", { name: data.displayData.previewScenario.label })} - - )} - - { - const file = event.currentTarget.files?.[0]; - event.currentTarget.value = ""; - if (file) void stage(file); - }} - /> - - - - )} - - - {t("forkDescription")} - setForkName(event.currentTarget.value)} - /> - - - -
- ); -} diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-workshop.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-workshop.tsx index 92b8f794d..4549ddc37 100644 --- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-workshop.tsx +++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/packages/_package-workshop.tsx @@ -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 }) { ); } + +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(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 ( + + + + {t("changes")} + + + + {t("sourceOnly")} + + {changes.data?.valid && ( + <> + + {changes.data.fromVersion ?? t("none")} → {changes.data.toVersion} + + + {changes.data.dependenciesChanged && {t("dependenciesChanged")}} + {changes.data.connectionsChanged && {t("connectionsChanged")}} + {changes.data.configurationChanged && {t("configurationChanged")}} + + {changes.data.files.map((file) => ( + + {file.name} + + undefined} + /> + undefined} + /> + + + ))} + + )} + + + + + {active && ( + + + setReplace(event.currentTarget.checked)} + label={t("replaceDraft")} + /> + { + const file = event.currentTarget.files?.[0]; + event.currentTarget.value = ""; + if (file) void stage(file); + }} + /> + + + + )} + + + {t("forkDescription")} + setForkName(event.currentTarget.value)} + /> + + + + + ); +} + +export function PackageArtifactReview({ artifact }: { artifact: CustomWidgetArtifact }) { + const t = useI18n("customWidget.package.artifactReview"); + const [selected, setSelected] = useState("dependency-lock.json"); + const files: Record = { "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 ( + + + {t("title")} + + + {t("description")} + + {artifact.digest} + +