fix: simplify custom widget package workbench

This commit is contained in:
ajnart committed 2026-09-12 15:33:51 +02:00
1 parent 9a52a035aa
commit 48042a08ff
37 files changed
+1155 -608

No files matched your search

@@ -7,8 +7,18 @@ import { assertWidgetArtifactIntegrity } from "@homarr/custom-widgets/package/se
import { getArtifact, getInstallation, readPackageDraft } from "./records";
import { widgetPackageAdminProcedure } from "./procedure";
import { getWidgetPackageSupervisor } from "./invocations";
export const packageArtifactReviewProcedures = {
runtimeStatus: widgetPackageAdminProcedure
.input(z.object({ id: z.string().min(1) }))
.query(async ({ ctx, input }) => {
const installation = await getInstallation(ctx, input.id);
if (!installation.activeArtifactId) return { state: "unactivated" as const };
const { artifact } = await getArtifact(ctx, installation.activeArtifactId);
if (!artifact.server) return { state: "browserOnly" as const };
return getWidgetPackageSupervisor().inspect(artifact.digest);
}),
inspectArtifact: widgetPackageAdminProcedure
.input(z.object({ id: z.string().min(1) }))
.query(async ({ ctx, input }) => {
@@ -42,10 +42,13 @@ export async function getBoundConnection(ctx: PackageContext, bindings: Record<s
const row = await ctx.db.query.customWidgetConnections.findFirst({ where: eq(customWidgetConnections.id, id) });
if (!row) throw new TRPCError({ code: "PRECONDITION_FAILED", message: "Bound connection is unavailable" });
const configuration = connectionConfigurationSchema.parse(JSON.parse(row.configuration));
const integration = row.integrationId
? await ctx.db.query.integrations.findFirst({ where: eq(integrations.id, row.integrationId) })
: undefined;
const secrets = z
.record(z.string(), z.string())
.parse(JSON.parse(decryptSecret(row.encryptedSecrets as `${string}.${string}`)));
return { row, configuration, secrets };
return { row, configuration: { ...configuration, integrationKind: integration?.kind }, secrets };
}
export async function getBindingsDigest(ctx: PackageContext, bindings: Record<string, string>) {
@@ -81,9 +84,14 @@ const admin = widgetPackageAdminProcedure;
export const packageConnectionProcedures = {
connections: admin.query(async ({ ctx }) => {
const rows = await ctx.db.query.customWidgetConnections.findMany();
const nativeIntegrations = await ctx.db.query.integrations.findMany({ columns: { id: true, kind: true } });
const kinds = new Map(nativeIntegrations.map(({ id, kind }) => [id, kind]));
return rows.map(({ encryptedSecrets: _secrets, ...row }) => ({
...row,
configuration: JSON.parse(row.configuration) as unknown,
configuration: {
...connectionConfigurationSchema.parse(JSON.parse(row.configuration)),
integrationKind: row.integrationId ? kinds.get(row.integrationId) : undefined,
},
}));
}),
saveConnection: admin
@@ -1,4 +1,4 @@
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { getWidgetConnectionRequirement, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { widgetPackageAdminProcedure } from "./procedure";
import { TRPCError } from "@trpc/server";
import { nativeScaffoldProcedures } from "./native-scaffold";
@@ -187,7 +187,7 @@ export const customWidgetPackageRouter = createTRPCRouter({
const draft = customWidgetPackageSchema.safeParse(JSON.parse(installation.draft));
for (const [name] of Object.entries(input.bindings)) {
const connection = await getBoundConnection(ctx, input.bindings, name);
const requirement = draft.success ? draft.data.connections[name] : undefined;
const requirement = draft.success ? getWidgetConnectionRequirement(draft.data.connections, name) : undefined;
if (requirement && !isWidgetConnectionCompatible(requirement, connection.configuration))
throw new TRPCError({
code: "BAD_REQUEST",
@@ -1,4 +1,4 @@
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { getWidgetConnectionBindingNames, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { TRPCError } from "@trpc/server";
import { parse, stringify } from "superjson";
import { z } from "zod/v4";
@@ -60,13 +60,17 @@ export async function prepareWidgetMigration(
throw new TRPCError({ code: "PRECONDITION_FAILED", message: `Placement ${placement.id}: ${issues[0]?.message}` });
const mergedBindings = { ...bindings, ...placement.packageOptions.connectionBindings };
for (const [name, requirement] of Object.entries(source.connections)) {
if (requirement.optional && !mergedBindings[name]) continue;
const connection = await getBoundConnection(ctx, mergedBindings, name);
if (!isWidgetConnectionCompatible(requirement, connection.configuration))
throw new TRPCError({
code: "PRECONDITION_FAILED",
message: `Connection '${name}' requires ${requirement.serviceType ?? requirement.kind}`,
});
const names = getWidgetConnectionBindingNames(name, requirement, mergedBindings);
if (!names.length && !requirement.optional)
throw new TRPCError({ code: "PRECONDITION_FAILED", message: `Connection '${name}' needs setup` });
for (const bindingName of names) {
const connection = await getBoundConnection(ctx, mergedBindings, bindingName);
if (!isWidgetConnectionCompatible(requirement, connection.configuration))
throw new TRPCError({
code: "PRECONDITION_FAILED",
message: `Connection '${name}' requires ${requirement.serviceType ?? requirement.kind}`,
});
}
}
const raw: unknown = parse(placement.options);
if (!isRecord(raw)) throw new TRPCError({ code: "PRECONDITION_FAILED", message: "Placement options are invalid" });
@@ -59,29 +59,34 @@ export const nativeScaffoldProcedures = {
for (const [name, requirement] of Object.entries(source.connections)) {
if (requirement.kind !== "integration") continue;
const accepted = acceptedIntegrationKinds(input.starter, name);
const integration = bound.find(
const matches = bound.filter(
(candidate) => accepted.includes(candidate.kind) && !usedIntegrationIds.has(candidate.id),
);
if (!integration) continue;
usedIntegrationIds.add(integration.id);
let connection = await ctx.db.query.customWidgetConnections.findFirst({
where: eq(customWidgetConnections.integrationId, integration.id),
});
if (!connection) {
const id = createId();
const row = {
id,
name: integration.name,
integrationId: integration.id,
configuration: JSON.stringify(connectionConfigurationSchema.parse({ kind: "integration" })),
encryptedSecrets: encryptSecret("{}"),
createdAt: new Date(),
updatedAt: new Date(),
};
await ctx.db.insert(customWidgetConnections).values(row);
connection = row;
let candidates = matches;
if (!requirement.multiple) candidates = matches.slice(0, 1);
for (const [index, integration] of candidates.entries()) {
usedIntegrationIds.add(integration.id);
let connection = await ctx.db.query.customWidgetConnections.findFirst({
where: eq(customWidgetConnections.integrationId, integration.id),
});
if (!connection) {
const id = createId();
const row = {
id,
name: integration.name,
integrationId: integration.id,
configuration: JSON.stringify(connectionConfigurationSchema.parse({ kind: "integration" })),
encryptedSecrets: encryptSecret("{}"),
createdAt: new Date(),
updatedAt: new Date(),
};
await ctx.db.insert(customWidgetConnections).values(row);
connection = row;
}
let bindingName = name;
if (index > 0) bindingName = `${name}:${connection.id}`;
bindings[bindingName] = connection.id;
}
bindings[name] = connection.id;
}
return { name: `${source.manifest.name} (custom)`, source, bindings, sourceBoardId: item.boardId };
}),
@@ -2,7 +2,7 @@ import { TRPCError } from "@trpc/server";
import { eq, handleTransactionsAsync } from "@homarr/db";
import { customWidgetInstallations } from "@homarr/db/schema";
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { getWidgetConnectionBindingNames, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { publishWidgetPackageChange } from "./events";
import { getWidgetCollection } from "./portable-collection-records";
@@ -34,7 +34,11 @@ export async function setWidgetCollectionBindings(
message: `Widget '${entry.key}' has an invalid source draft. Repair it first.`,
});
const nextBindings = { ...entry.bindings };
for (const name of Object.keys(entry.mapping)) delete nextBindings[name];
for (const name of Object.keys(entry.mapping)) {
for (const key of Object.keys(nextBindings)) {
if (key === name || key.startsWith(`${name}:`)) delete nextBindings[key];
}
}
Object.assign(nextBindings, mapCollectionBindings(entry.mapping, bindings));
for (const name of Object.keys(entry.mapping)) {
const requirement = entry.requirements[name];
@@ -43,13 +47,14 @@ export async function setWidgetCollectionBindings(
code: "PRECONDITION_FAILED",
message: `Widget '${entry.key}' no longer declares connection '${name}'. Review its package mapping.`,
});
if (!nextBindings[name]) continue;
const connection = await getBoundConnection(ctx, nextBindings, name);
if (!isWidgetConnectionCompatible(requirement, connection.configuration))
throw new TRPCError({
code: "BAD_REQUEST",
message: `Widget '${entry.key}' connection '${name}' is incompatible with the selected shared connection`,
});
for (const bindingName of getWidgetConnectionBindingNames(name, requirement, nextBindings)) {
const connection = await getBoundConnection(ctx, nextBindings, bindingName);
if (!isWidgetConnectionCompatible(requirement, connection.configuration))
throw new TRPCError({
code: "BAD_REQUEST",
message: `Widget '${entry.key}' connection '${name}' is incompatible with the selected shared connection`,
});
}
}
changes.push({
id: entry.id,
@@ -78,7 +78,11 @@ export async function getWidgetCollection(ctx: PackageContext, importId: string)
for (const entry of entries) {
for (const [name, slot] of Object.entries(entry.mapping)) {
const bindings = values.get(slot) ?? new Set<string>();
bindings.add(entry.bindings[name] ?? "");
const members = Object.entries(entry.bindings)
.filter(([binding]) => binding === name || binding.startsWith(`${name}:`))
.map(([binding, id]) => [binding.slice(name.length), id])
.toSorted(([left], [right]) => (left ?? "").localeCompare(right ?? ""));
bindings.add(JSON.stringify(members));
values.set(slot, bindings);
}
}
@@ -87,8 +91,8 @@ export async function getWidgetCollection(ctx: PackageContext, importId: string)
for (const [slot, ids] of values) {
if (ids.size > 1) bindingConflicts.push(slot);
else {
const id = [...ids][0];
if (id) bindings[slot] = id;
const members = JSON.parse([...ids][0] ?? "[]") as [string, string][];
for (const [suffix, id] of members) bindings[`${slot}${suffix}`] = id;
}
}
return {
@@ -8,7 +8,7 @@ import type {
WidgetCollectionContents,
WidgetCollectionManifest,
} from "@homarr/custom-widgets/package";
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { getWidgetConnectionBindingNames, getWidgetConnectionRequirement, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
import { createWidgetCollectionArchive, validateWidgetCollectionArchive } from "@homarr/custom-widgets/package/server";
import { withWidgetArtifactReferenceLock } from "./artifact-references";
@@ -37,7 +37,7 @@ export async function validateCollectionBindings(
bindings: Record<string, string>,
) {
for (const [name] of Object.entries(bindings)) {
const requirement = collection.connections[name];
const requirement = getWidgetConnectionRequirement(collection.connections, name);
if (!requirement) throw new TRPCError({ code: "BAD_REQUEST", message: `Unknown collection connection '${name}'` });
try {
const connection = await getBoundConnection(ctx, bindings, name);
@@ -55,9 +55,9 @@ export async function validateCollectionBindings(
export function mapCollectionBindings(mapping: Record<string, string>, bindings: Record<string, string>) {
return Object.fromEntries(
Object.entries(mapping).flatMap(([name, slot]) => {
const id = bindings[slot];
if (!id) return [];
return [[name, id]];
return Object.entries(bindings)
.filter(([binding]) => binding === slot || binding.startsWith(`${slot}:`))
.map(([binding, id]) => [`${name}${binding.slice(slot.length)}`, id]);
}),
);
}
@@ -145,7 +145,8 @@ export async function exportWidgetCollection(ctx: PackageContext, manifest: Widg
const bindings = parseBindings(row.bindings);
const mapping: Record<string, string> = {};
for (const [name, requirement] of Object.entries(source.connections)) {
const identity = `${requirement.kind}:${requirement.serviceType ?? ""}:${bindings[name] ?? `${id}:${name}`}`;
const members = getWidgetConnectionBindingNames(name, requirement, bindings).map((key) => bindings[key]).toSorted();
const identity = JSON.stringify([requirement.kind, requirement.serviceType, requirement.integrationKind, requirement.multiple, members.length ? members : [id, name]]);
let slot = shared.get(identity);
if (!slot) {
slot = `connection${shared.size + 1}`;
@@ -6,7 +6,7 @@ import { constructIntegrationPermissions } from "@homarr/auth/shared";
import { decryptSecret } from "@homarr/common/server";
import { createId } from "@homarr/common";
import { eq, inArray } from "@homarr/db";
import { groupMembers, integrationGroupPermissions, integrations, integrationUserPermissions } from "@homarr/db/schema";
import { customWidgetConnections, groupMembers, integrationGroupPermissions, integrations, integrationUserPermissions } from "@homarr/db/schema";
import type { WidgetSdkInvocation } from "@homarr/custom-widgets/package/server";
import { readPackageHistory, widgetHistoryInputSchema } from "./history";
@@ -56,13 +56,24 @@ export function createWidgetSdkBridge(
}
signal?.throwIfAborted();
if (operation === "legacy.request") return invokeLegacyWidgetRequest(ctx, resolved, kind, input, signal);
if (operation === "widget.context")
if (operation === "widget.context") {
const ids = Object.values(resolved.bindings);
let labels = new Map<string, string>();
if (ids.length) {
const rows = await ctx.db.query.customWidgetConnections.findMany({
where: inArray(customWidgetConnections.id, ids),
columns: { id: true, name: true },
});
labels = new Map(rows.map((row) => [row.id, row.name]));
}
return {
options: resolved.configuration,
bindingNames: Object.keys(resolved.bindings),
bindingLabels: Object.fromEntries(Object.entries(resolved.bindings).map(([name, id]) => [name, labels.get(id) ?? name])),
installationId: resolved.installation.id,
isPreview: Boolean(resolved.preview),
};
}
if (operation === "integration.next" || operation === "integration.unsubscribe") {
const { id } = z.object({ id: z.string() }).parse(input);
const iterator = subscriptions.get(id);
@@ -90,6 +90,8 @@ export const widgetCollectionContentsSchema = z
else if (!shared) issue(["connections", name], `collection slot '${slot}' is undeclared`);
else if (!isWidgetConnectionCompatible(requirement, shared))
issue(["connections", name], `slot '${slot}' requires compatible ${requirement.kind} settings`);
else if (Boolean(requirement.multiple) !== Boolean(shared.multiple))
issue(["connections", name], `slot '${slot}' must use the same repeatable connection setting`);
else if (!requirement.optional && shared.optional)
issue(["connections", name], `slot '${slot}' must be required because this widget requires it`);
}
@@ -76,6 +76,17 @@ export class WidgetPackageProcess {
public get stopped() {
return this.dead;
}
public inspect() {
let state: "running" | "stopped" = "running";
if (this.dead) state = "stopped";
return {
state,
pid: this.child.pid ?? null,
activeRequests: this.pending.size,
queuedRequests: this.queued,
lastUsed: this.lastUsed,
};
}
public waitUntilReady() {
return this.ready;
}
+32 -2
View File
@@ -79,6 +79,9 @@ export const widgetPackageConnectionSchema = z
label: z.string().trim().min(1).max(128),
kind: z.enum(["http", "integration", "service"]),
serviceType: identifier.optional(),
integrationKind: identifier.optional(),
// Optional fields preserve the digest of existing package archives.
multiple: z.boolean().optional(),
optional: z.boolean().default(false),
description: z.string().max(2048).optional(),
})
@@ -89,14 +92,41 @@ export const widgetPackageConnectionSchema = z
/** Shared by binding pickers, activation and portable collection imports. */
export function isWidgetConnectionCompatible(
requirement: { kind: string; serviceType?: string },
configuration: { kind?: unknown; serviceType?: unknown },
requirement: { kind: string; serviceType?: string; integrationKind?: string },
configuration: { kind?: unknown; serviceType?: unknown; integrationKind?: unknown },
) {
if (requirement.kind !== configuration.kind) return false;
if (requirement.kind === "service") return requirement.serviceType === configuration.serviceType;
if (requirement.kind === "integration" && requirement.integrationKind)
return requirement.integrationKind === configuration.integrationKind;
return true;
}
/** Repeatable connections retain the original named binding and add stable, namespaced members.
* A colon cannot appear in a manifest connection name, so groups cannot overlap.
*/
export function getWidgetConnectionBindingNames(
name: string,
requirement: { multiple?: boolean },
bindings: Record<string, string>,
) {
return Object.keys(bindings).filter(
(key) => Boolean(bindings[key]) && (key === name || (requirement.multiple && key.startsWith(`${name}:`))),
);
}
export function getWidgetConnectionRequirement<T extends { multiple?: boolean }>(
requirements: Record<string, T>,
name: string,
) {
const exact = requirements[name];
if (exact) return exact;
const prefix = name.split(":")[0];
const group = prefix && requirements[prefix];
if (group && group.multiple) return group;
return undefined;
}
export const customWidgetPackageSchema = z
.strictObject({
$schema: z.literal(CUSTOM_WIDGET_PACKAGE_SCHEMA),
@@ -100,6 +100,17 @@ export class CustomWidgetPackageSupervisor {
if (pending) (await pending.catch(() => undefined))?.stop();
}
/** Read only: inspecting an inactive artifact must never start its server. */
public async inspect(digest: string) {
const pending = this.processes.get(digest);
if (!pending) return { state: "idle" as const };
try {
return (await pending).inspect();
} catch (error) {
return { state: "failed" as const, error: error instanceof Error ? error.message : String(error) };
}
}
public async cancelInstances(instanceIds: string[], options: { actions?: boolean } = {}): Promise<void> {
for (const id of instanceIds) this.instanceGenerations.set(id, (this.instanceGenerations.get(id) ?? 0) + 1);
const ids = new Set(instanceIds);
+68 -17
View File
@@ -1196,7 +1196,7 @@
"library": "Packages",
"libraryDescription": "Build dashboard widgets with full TSX, CSS, modules, and optional server code. Import a package to inspect its source and connect your local services before activating it.",
"search": "Search packages",
"empty": "No matching packages. Create a source-free widget or import a package to get started.",
"empty": "No widget packages yet.",
"openWorkspace": "Open workspace",
"draftOnly": "Draft only",
"active": "Active",
@@ -1204,11 +1204,12 @@
"import": "Import package",
"importTooLarge": "Package exceeds the 25 MB import limit.",
"invalidPackage": "Choose a widget package or archive JSON file.",
"name": "Installation name",
"name": "Widget name",
"unsaved": "Unsaved changes",
"saved": "Saved draft",
"notSaved": "Not saved yet",
"saveDraft": "Save draft",
"draftSaved": "Draft saved. Dashboard placements still use the active release.",
"draftSaved": "Draft saved. Use on dashboard lets you activate this version and add it to a board. Existing tiles keep using their active version until then.",
"recovery": "A recovery draft is available for this package. Local connection credentials are stored separately; recognized credential literals are removed from recovery source.",
"restore": "Restore draft",
"discard": "Discard recovery",
@@ -1218,9 +1219,9 @@
"historyDescription": "Undo/Redo covers the whole document, up to 100 changes and 2 MB. One browser recovery draft, up to 1 MB.",
"code": "Source files",
"connections": "Connections",
"installation": "Activation & boards",
"starter": "Reference starter",
"chooseStarter": "Choose a reference package",
"installation": "Use on dashboard",
"starter": "Start from an example",
"chooseStarter": "Choose a widget to customize",
"clock": "World clock · no API required",
"filePath": "Relative file path",
"addFile": "Add",
@@ -1231,13 +1232,13 @@
"renameImports": "File renamed. Update imports and manifest entrypoints that refer to its previous path.",
"draftInvalid": "This draft can be saved. Resolve these package errors before preview or activation.",
"reviewTrust": "Review code & dependencies",
"trustedCode": "This package runs trusted JavaScript in Homarr and may run Node code with Homarr's server privileges. Review every source file and dependency before running it. Preview also executes package code.",
"trustedCode": "Trusted browser code has access to your Homarr session and browser APIs. Server code runs with Homarr's operating-system authority, including available credentials, networks and mounted files. The separate process is not a security sandbox. Only run code and dependencies you trust; preview executes them too.",
"dependencies": "Additional dependencies",
"hostOnly": "Shared Homarr modules only",
"trustAcknowledgement": "I trust this source and its dependencies to run on my Homarr instance.",
"preview": "Run preview",
"exportDraft": "Export source draft",
"saveFirst": "Save this draft first to enable preview, save local bindings, and activate it.",
"saveFirst": "Save your draft, then activate it to make it available on dashboards.",
"surface": "Preview surface",
"tile": "Dashboard tile",
"advanced": "Advanced view",
@@ -1295,12 +1296,12 @@
},
"previewLiveSession": "Session: live SDK actions",
"previewSimulatedSession": "Session: simulated SDK actions",
"connectionsDescription": "Bind the package's named connections to services on this Homarr instance. Saving bindings updates every placement that inherits them; placements can override a connection in board settings.",
"connectionsDescription": "Choose existing Homarr integrations or create local API connections. No trust acknowledgement is needed to configure them. Save connections to apply them to tiles that inherit this setup.",
"noConnections": "This package needs no API or service connection.",
"diagnose": "Diagnose",
"newConnection": "Create local connection",
"saveBindings": "Save installation bindings",
"bindingsSaved": "Installation bindings saved.",
"saveBindings": "Save connections",
"bindingsSaved": "Connections saved for tiles that inherit this setup.",
"connectionKind": "Connection type",
"integration": "Homarr integration",
"serverUrl": "Server URL",
@@ -1316,13 +1317,13 @@
"stringMap": "Enter a JSON object whose values are strings.",
"previewOptions": "Preview options",
"resetOptions": "Reset preview options to package defaults",
"activation": "Activation",
"activation": "Make this version available on dashboards",
"activationDescription": "Activate the saved draft for all {count} dashboard placements of this installation. Existing placements keep their option values. A failed activation keeps the current release running.",
"activeArtifact": "Active artifact",
"none": "None",
"saveBeforeActivate": "Save your changes before activating. Activation always uses the saved draft.",
"activate": "Activate saved draft",
"activated": "Saved package activated.",
"activate": "Activate for dashboards",
"activated": "This version is ready for dashboards. Add it to a board below, or open an existing placement.",
"disable": "Disable installation",
"enable": "Enable installation",
"stateSaved": "Installation state saved.",
@@ -1410,7 +1411,7 @@
"connectionName": "Connection name",
"assistant": {
"open": "Ask Assistant",
"context": "Uses this draft and public SDK context",
"context": "Assistant can read this open draft and propose edits for you to review. You can undo an applied proposal in one step.",
"request": "What would you like to build?",
"requestPlaceholder": "Describe a widget, a design change, or a capability…",
"send": "Propose changes",
@@ -1431,7 +1432,14 @@
"preparing": "Preparing proposed changes…",
"invalidProposal": "This proposal is incomplete or invalid.",
"reading": "Reading the open package draft…",
"read": "Read the open package draft"
"read": "Read the open package draft",
"unavailable": "Assistant is not configured or is unavailable for your account.",
"setup": "Open Assistant setup",
"manual": "You can still choose an example, edit its files and preview it without Assistant.",
"busy": "Assistant is already responding. Wait for it to finish before sending another request.",
"sendFailed": "The request could not be sent. Check the Assistant panel and try again.",
"create": "Build a widget with me",
"createPrompt": "Help me create a widget package. Ask what app or idea I want to build, then propose an approachable first version using the available SDK. Explain any connection setup. Do not assume I want to keep the current example."
},
"sessionUnavailable": "Preview session unavailable",
"sessionUnavailableDescription": "The session expired, was discarded, or belongs to another account. Sign in as the API key owner and create a fresh CLI preview.",
@@ -1545,7 +1553,50 @@
"previewThemeDark": "Dark",
"previewScale": "Display scale",
"savedSourceChanged": "The saved source changed. Reload and review it before activating.",
"previewPane": "Preview"
"previewPane": "Preview",
"starterDescription": "Pick a working example, then edit its files or ask Assistant for changes. Switching examples replaces this draft; Undo restores it.",
"gettingStarted": "Your widget, your way",
"gettingStartedDescription": "Packages support full React, TypeScript, CSS and optional Node code. Custom JSX is the simpler template editor. Neither needs an API for a static widget.",
"manualSteps": "Choose an example → connect services if needed → edit files and options → preview → use on dashboard. Assistant is optional.",
"manageFiles": "Add, rename or remove files",
"optionsDescription": "Adjust the preview without editing code. These values also start the setup for your next dashboard tile. Existing tiles keep their own settings.",
"noOptions": "This example has no configurable options. Edit its files to customize it.",
"useDescription": "Save a draft to keep your work. Activate it when you want boards to use that code, then add it to a board below. One package can appear on several boards.",
"previewSavesFirst": "Your first preview also saves a draft. It does not add or change dashboard tiles.",
"workshopTab": "Workshop",
"workshopDescription": "Share your finished widget, publish a new release, or review upstream updates. Local connections and credentials stay on your Homarr instance.",
"releaseTools": "Release details, disable and rollback",
"chooseConnection": "Choose a connection or Homarr integration",
"noCompatibleConnections": "No compatible connections yet. Create one below, then refresh this list.",
"unavailableConnection": "Connection unavailable — choose a replacement",
"createIntegration": "Create Homarr integration ↗",
"connectionsUnsaved": "Connection changes are not saved yet. Save connections before using them on dashboards.",
"customViewport": "Custom viewport and scale",
"customViewportDescription": "Use the grid controls in the preview for normal board sizes. Pixel dimensions below override the grid for this preview only.",
"browserExecution": "React and CSS run in your browser, inside Homarr, with its theme and UI context.",
"serverExecution": "This package has a server entrypoint. Homarr starts a supervised Node process on demand when a handler is called and shares it between users of that artifact. Idle processes are released.",
"browserOnlyExecution": "This package has no server entrypoint, so it needs no separate Node process. Static widgets do not need a connection.",
"runtimeLogs": "Build and preview errors appear here. Server output is included in Homarr logs under custom-widget-package. The active release process can be inspected below.",
"buildState": "Preview build: {state}",
"actionsMenu": "Widget package actions",
"forkDefaultName": "{name} fork",
"previewBuilding": "Building preview…",
"previewBuildReady": "Preview build ready",
"previewBuildFailed": "Preview build failed",
"previewNotBuilt": "Preview not built yet",
"runtime": {
"title": "Active release process",
"description": "This is a snapshot from the Homarr replica serving this request. It does not start code or inspect a separate preview process. Refresh after opening a tile to see its current state.",
"unactivated": "No active release",
"browserOnly": "Browser only · no Node process",
"idle": "No process on this replica",
"running": "Running",
"stopped": "Stopped",
"failed": "Startup failed",
"refresh": "Refresh status",
"process": "PID {pid} · {active} active requests · {queued} queued",
"logs": "Open Homarr logs ↗"
}
}
},
"workshop": {
+17 -24
View File
@@ -2,10 +2,10 @@
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.sonarr",
"version": "1.1.0",
"version": "1.2.0",
"sdkVersion": "1",
"name": "Sonarr operations",
"description": "Two-server Sonarr operations: upcoming episodes, missing releases, queue progress, filtered advanced views and confirmed episode search through the native adapter.",
"description": "Calendar, missing episodes and queue across any number of Sonarr integrations, with per-server search controls.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
@@ -21,11 +21,16 @@
"permission": "modify",
"inputSchema": {
"type": "object",
"required": ["connection", "episodeIds"],
"required": [
"connection",
"episodeIds"
],
"additionalProperties": false,
"properties": {
"connection": {
"enum": ["sonarr", "secondary"]
"type": "string",
"minLength": 1,
"maxLength": 256
},
"episodeIds": {
"type": "array",
@@ -42,21 +47,19 @@
}
},
"files": {
"widget.tsx": "import { Alert, Badge, Button, Group, Loader, Progress, SegmentedControl, Select, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport type { Connection, Overview, SonarrOptions } from \"./types\";\nexport default function Sonarr() {\n const host = useWidgetHost(); const services = useWidgetServices(); const options = useWidgetOptions<SonarrOptions>();\n const [tab,setTab] = useWidgetState(\"tab\",\"calendar\");\n const [source,setSource] = useWidgetState(\"source\",\"all\");\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const query = useWidgetQuery<Overview>(\"overview\",{}, {refetchInterval:60000});\n const search = useWidgetAction<{id:number;status:string},{connection:Connection;episodeIds:number[]}>(\"searchEpisodes\");\n const label = (connection:Connection) => connection === \"sonarr\" ? options.primaryName : options.secondaryName;\n const sources = query.data?.sources ?? [];\n const rows = sources.filter((entry) => source === \"all\" || source === entry.connection).flatMap((entry) => {\n let items = entry.calendar;\n if (tab === \"missing\") items = entry.missing.items;\n if (tab === \"queue\") items = entry.queue.items;\n return items.map((item,index) => ({...item,connection:entry.connection,rowKey:`${entry.connection}:${tab}:${item.id ?? index}`}));\n }).filter((item) => `${item.title} ${item.subTitle ?? item.seriesTitle ?? \"\"}`.toLowerCase().includes(filter.toLowerCase()));\n const visible = host.displayMode === \"advanced\" ? rows : rows.slice(0,4);\n const requestSearch = async (connection:Connection,id:number,title:string) => {\n if (await services.confirm({title:\"Search for this episode?\",message:`Ask ${label(connection)} to find and download an eligible release for ${title}?`})) search.mutate({connection,episodeIds:[id]});\n };\n return <Stack h=\"100%\" p=\"md\" gap=\"sm\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge>{sources.reduce((sum,entry) => sum+entry.queue.totalCount,0)} queued</Badge></Group>\n <SegmentedControl value={tab} onChange={setTab} data={[{label:\"Upcoming\",value:\"calendar\"},{label:\"Missing\",value:\"missing\"},{label:\"Queue\",value:\"queue\"}]} />\n {sources.length > 1 && <Select aria-label=\"Sonarr server\" value={source} onChange={(value) => setSource(value ?? \"all\")} data={[{value:\"all\",label:\"All servers\"},...sources.map((entry) => ({value:entry.connection,label:label(entry.connection)}))]} />}\n {host.displayMode === \"advanced\" && <TextInput aria-label=\"Filter episodes\" placeholder=\"Filter series or episode…\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} />}\n {query.isPending && <Loader size=\"sm\" />}\n {query.error && <Alert color=\"red\">{query.error.message}</Alert>}\n {sources.filter((entry) => entry.error).map((entry) => <Alert key={entry.connection} color=\"red\" title={label(entry.connection)}>{entry.error}</Alert>)}\n {search.error && <Alert color=\"red\">{search.error.message}</Alert>}\n {search.data?.id && <Text size=\"xs\" c=\"teal\">Search command {search.data.id}: {search.data.status}. Sonarr will select an eligible release.</Text>}\n {visible.map((item) => <Stack key={item.rowKey} gap={4}><Group justify=\"space-between\"><Text fw={500} size=\"sm\">{item.subTitle ?? item.seriesTitle ?? item.title}</Text><Badge size=\"xs\" variant=\"light\">{label(item.connection)}</Badge></Group><Text size=\"xs\" c=\"dimmed\">{item.title}{item.seasonNumber !== undefined && ` · S${item.seasonNumber} E${item.episodeNumber ?? \"?\"}`}</Text>{item.startDate && <Text size=\"xs\">{new Date(item.startDate).toLocaleString(host.locale)}</Text>}{item.percentComplete !== undefined && <Progress value={item.percentComplete} aria-label={`${item.title} download progress`} />}<Group gap=\"xs\">{(item.link || item.links?.[0]?.href) && <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => services.navigate(item.link ?? item.links?.[0]?.href ?? \"\")}>Open in Sonarr</Button>}{tab === \"missing\" && typeof item.id === \"number\" && <Button size=\"compact-xs\" disabled={host.isEditMode || search.isPending} onClick={() => void requestSearch(item.connection,item.id!,item.title)}>Search episode</Button>}</Group></Stack>)}\n {query.data && !rows.length && <Text c=\"dimmed\">No episodes match this view.</Text>}\n <Group><Button size=\"xs\" variant=\"light\" onClick={() => void query.refetch()}>Refresh</Button>{host.displayMode === \"compact\" && <Button size=\"xs\" variant=\"subtle\" onClick={services.openAdvanced}>All episodes and filters</Button>}</Group>\n </Stack>;\n}\n",
"server.ts": "import type { Connection, EpisodeRow, SearchInput, SonarrOptions } from \"./types\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nconst connections:Connection[] = [\"sonarr\", \"secondary\"];\nexport default defineWidgetServer({\n overview: async (_input, context) => {\n const {bindingNames,options} = await getWidgetServerContext<SonarrOptions>(context);\n const start = new Date();\n const end = new Date(start.getTime()+Math.max(1,Math.min(90,Number(options.days)||7))*86400000);\n const names = connections.filter((name) => bindingNames.includes(name));\n if (!names.length) throw new Error(\"Bind at least one Sonarr integration\");\n const sources = await Promise.all(names.map(async (connection) => {\n const call = <T,>(capability:string,input:unknown) => callWidgetIntegration<T>(context,{connection,capability,input});\n try {\n const [calendar,missing,queue] = await Promise.all([\n call<EpisodeRow[]>(\"sonarr.calendar\",{start:start.toISOString(),end:end.toISOString()}),\n call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.missing\",{limit:100}), call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.queue\",{limit:100}),\n ]);\n return {connection,calendar,missing,queue};\n } catch (error) { return {connection,calendar:[],missing:{items:[],totalCount:0},queue:{items:[],totalCount:0},error:error instanceof Error ? error.message : String(error)}; }\n }));\n return {sources};\n },\n searchEpisodes: (input:SearchInput,context) => {\n if (!connections.includes(input?.connection) || !Array.isArray(input?.episodeIds) || !input.episodeIds.length || input.episodeIds.length > 100 || input.episodeIds.some((id) => !Number.isInteger(id) || id < 1)) throw new Error(\"Choose valid episode IDs from a declared Sonarr server\");\n return callWidgetIntegration(context,{connection:input.connection,capability:\"sonarr.searchEpisodes\",input:{episodeIds:input.episodeIds}});\n },\n});\n",
"types.ts": "export type Connection = \"sonarr\" | \"secondary\";\nexport interface EpisodeRow { id?:number; title:string; subTitle?:string; seriesTitle?:string; startDate?:string; seasonNumber?:number; episodeNumber?:number; percentComplete?:number; status?:string; timeLeft?:string|null; link?:string; links?:{href:string}[]; }\nexport interface Source { connection:Connection; calendar:EpisodeRow[]; missing:{items:EpisodeRow[];totalCount:number}; queue:{items:EpisodeRow[];totalCount:number}; error?:string; }\nexport interface Overview { sources:Source[]; }\nexport type SonarrOptions = {title:string;primaryName:string;secondaryName:string;days:number};\nexport type SearchInput = {connection:Connection;episodeIds:number[]};\n",
"README.md": "# Sonarr operations\nBind the primary Sonarr integration and optionally a second one. Existing Homarr native query and interaction permissions apply. Each result retains its connection identity, including when different servers use the same numeric episode ID.\n\nCompact view shows four episodes; advanced view includes all loaded rows, source selection and text filtering. The reference reads up to 100 missing and queued episodes per server. A failure on one server does not hide the other server's result.\n\nSearch episode is a named modify action. It confirms the target server and episode before submitting the native Sonarr EpisodeSearch command. A queued command does not prove a release was found or downloaded. Default previews simulate actions. The integration sends the API key server-side; no key is embedded in portable source.\n\nAPI reference: https://github.com/Sonarr/Sonarr/blob/develop/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs and https://github.com/Sonarr/Sonarr/blob/develop/src/Sonarr.Api.V3/Commands/CommandController.cs\n"
"widget.tsx": "import { Alert, Badge, Button, Group, Loader, Progress, SegmentedControl, Select, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport type { Connection, Overview, SonarrOptions } from \"./types\";\nexport default function Sonarr() {\n const host = useWidgetHost(); const services = useWidgetServices(); const options = useWidgetOptions<SonarrOptions>();\n const [tab,setTab] = useWidgetState(\"tab\",\"calendar\");\n const [source,setSource] = useWidgetState(\"source\",\"all\");\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const query = useWidgetQuery<Overview>(\"overview\",{}, {refetchInterval:60000});\n const search = useWidgetAction<{id:number;status:string},{connection:Connection;episodeIds:number[]}>(\"searchEpisodes\");\n const label = (connection:Connection) => sources.find((source) => source.connection === connection)?.label ?? connection;\n const sources = query.data?.sources ?? [];\n const rows = sources.filter((entry) => source === \"all\" || source === entry.connection).flatMap((entry) => {\n let items = entry.calendar;\n if (tab === \"missing\") items = entry.missing.items;\n if (tab === \"queue\") items = entry.queue.items;\n return items.map((item,index) => ({...item,connection:entry.connection,rowKey:`${entry.connection}:${tab}:${item.id ?? index}`}));\n }).filter((item) => `${item.title} ${item.subTitle ?? item.seriesTitle ?? \"\"}`.toLowerCase().includes(filter.toLowerCase()));\n const visible = host.displayMode === \"advanced\" ? rows : rows.slice(0,4);\n const requestSearch = async (connection:Connection,id:number,title:string) => {\n if (await services.confirm({title:\"Search for this episode?\",message:`Ask ${label(connection)} to find and download an eligible release for ${title}?`})) search.mutate({connection,episodeIds:[id]});\n };\n return <Stack h=\"100%\" p=\"md\" gap=\"sm\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge>{sources.reduce((sum,entry) => sum+entry.queue.totalCount,0)} queued</Badge></Group>\n <SegmentedControl value={tab} onChange={setTab} data={[{label:\"Upcoming\",value:\"calendar\"},{label:\"Missing\",value:\"missing\"},{label:\"Queue\",value:\"queue\"}]} />\n {sources.length > 1 && <Select aria-label=\"Sonarr server\" value={source} onChange={(value) => setSource(value ?? \"all\")} data={[{value:\"all\",label:\"All servers\"},...sources.map((entry) => ({value:entry.connection,label:label(entry.connection)}))]} />}\n {host.displayMode === \"advanced\" && <TextInput aria-label=\"Filter episodes\" placeholder=\"Filter series or episode…\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} />}\n {query.isPending && <Loader size=\"sm\" />}\n {query.error && <Alert color=\"red\">{query.error.message}</Alert>}\n {sources.filter((entry) => entry.error).map((entry) => <Alert key={entry.connection} color=\"red\" title={label(entry.connection)}>{entry.error}</Alert>)}\n {search.error && <Alert color=\"red\">{search.error.message}</Alert>}\n {search.data?.id && <Text size=\"xs\" c=\"teal\">Search command {search.data.id}: {search.data.status}. Sonarr will select an eligible release.</Text>}\n {visible.map((item) => <Stack key={item.rowKey} gap={4}><Group justify=\"space-between\"><Text fw={500} size=\"sm\">{item.subTitle ?? item.seriesTitle ?? item.title}</Text><Badge size=\"xs\" variant=\"light\">{label(item.connection)}</Badge></Group><Text size=\"xs\" c=\"dimmed\">{item.title}{item.seasonNumber !== undefined && ` · S${item.seasonNumber} E${item.episodeNumber ?? \"?\"}`}</Text>{item.startDate && <Text size=\"xs\">{new Date(item.startDate).toLocaleString(host.locale)}</Text>}{item.percentComplete !== undefined && <Progress value={item.percentComplete} aria-label={`${item.title} download progress`} />}<Group gap=\"xs\">{(item.link || item.links?.[0]?.href) && <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => services.navigate(item.link ?? item.links?.[0]?.href ?? \"\")}>Open in Sonarr</Button>}{tab === \"missing\" && typeof item.id === \"number\" && <Button size=\"compact-xs\" disabled={host.isEditMode || search.isPending} onClick={() => void requestSearch(item.connection,item.id!,item.title)}>Search episode</Button>}</Group></Stack>)}\n {query.data && !rows.length && <Text c=\"dimmed\">No episodes match this view.</Text>}\n <Group><Button size=\"xs\" variant=\"light\" onClick={() => void query.refetch()}>Refresh</Button>{host.displayMode === \"compact\" && <Button size=\"xs\" variant=\"subtle\" onClick={services.openAdvanced}>All episodes and filters</Button>}</Group>\n </Stack>;\n}\n",
"server.ts": "import type { EpisodeRow, SearchInput, SonarrOptions } from \"./types\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetConnectionGroup, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nexport default defineWidgetServer({\n overview: async (_input, context) => {\n const {options} = await getWidgetServerContext<SonarrOptions>(context);\n const start = new Date();\n const end = new Date(start.getTime()+Math.max(1,Math.min(90,Number(options.days)||7))*86400000);\n const names = await getWidgetConnectionGroup(context, \"sonarr\");\n if (!names.length) throw new Error(\"Bind at least one Sonarr integration\");\n const sources = await Promise.all(names.map(async ({connection,label}) => {\n const call = <T,>(capability:string,input:unknown) => callWidgetIntegration<T>(context,{connection,capability,input});\n try {\n const [calendar,missing,queue] = await Promise.all([\n call<EpisodeRow[]>(\"sonarr.calendar\",{start:start.toISOString(),end:end.toISOString()}),\n call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.missing\",{limit:100}), call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.queue\",{limit:100}),\n ]);\n return {connection,label,calendar,missing,queue};\n } catch (error) { return {connection,label,calendar:[],missing:{items:[],totalCount:0},queue:{items:[],totalCount:0},error:error instanceof Error ? error.message : String(error)}; }\n }));\n return {sources};\n },\n searchEpisodes: async (input:SearchInput,context) => {\n const connections = await getWidgetConnectionGroup(context, \"sonarr\");\n if (!connections.some(({connection}) => connection === input?.connection) || !Array.isArray(input?.episodeIds) || !input.episodeIds.length || input.episodeIds.length > 100 || input.episodeIds.some((id) => !Number.isInteger(id) || id < 1)) throw new Error(\"Choose valid episode IDs from a declared Sonarr server\");\n return callWidgetIntegration(context,{connection:input.connection,capability:\"sonarr.searchEpisodes\",input:{episodeIds:input.episodeIds}});\n },\n});\n",
"types.ts": "export type Connection = string;\nexport interface EpisodeRow { id?:number; title:string; subTitle?:string; seriesTitle?:string; startDate?:string; seasonNumber?:number; episodeNumber?:number; percentComplete?:number; status?:string; timeLeft?:string|null; link?:string; links?:{href:string}[]; }\nexport interface Source { connection:Connection; label:string; calendar:EpisodeRow[]; missing:{items:EpisodeRow[];totalCount:number}; queue:{items:EpisodeRow[];totalCount:number}; error?:string; }\nexport interface Overview { sources:Source[]; }\nexport type SonarrOptions = {title:string;days:number};\nexport type SearchInput = {connection:Connection;episodeIds:number[]};\n",
"README.md": "# Sonarr operations\n\nChoose one or more Sonarr integrations in Connections. Each server contributes an independent calendar, missing list and queue. A failed server leaves other results visible. Search controls always name the selected server. Expand for the detailed view.\n\nThe server uses getWidgetConnectionGroup(context, \"sonarr\") to enumerate the repeatable connection requirement; adding a server requires no source edit.\n"
},
"dependencies": {},
"connections": {
"sonarr": {
"kind": "integration",
"label": "Sonarr integration"
},
"secondary": {
"kind": "integration",
"label": "Second Sonarr integration",
"optional": true
"integrationKind": "sonarr",
"multiple": true,
"label": "Sonarr servers",
"description": "Select one or more existing Homarr Sonarr integrations. Add another server at any time."
}
},
"options": {
@@ -65,16 +68,6 @@
"label": "Title",
"default": "Sonarr"
},
"primaryName": {
"control": "text",
"label": "Primary server label",
"default": "Primary"
},
"secondaryName": {
"control": "text",
"label": "Second server label",
"default": "Secondary"
},
"days": {
"control": "number",
"label": "Calendar days",
+9
View File
@@ -87,10 +87,19 @@ export function getWidgetServerContext<TOptions extends Record<string, unknown>
options: TOptions;
installationId: string;
bindingNames: string[];
bindingLabels: Record<string, string>;
isPreview: boolean;
}>;
}
/** Enumerate every member of a repeatable connection requirement, including its original named binding. */
export async function getWidgetConnectionGroup(context: WidgetServerContext, name: string) {
const { bindingNames, bindingLabels } = await getWidgetServerContext(context);
return bindingNames
.filter((binding) => binding === name || binding.startsWith(`${name}:`))
.map((connection) => ({ connection, label: bindingLabels[connection] ?? connection }));
}
export function callWidgetIntegration<T = unknown>(context: WidgetServerContext, input: WidgetIntegrationInput) {
return context.sdk.invoke("integration.call", input) as Promise<T>;
}
+1
View File
@@ -33,6 +33,7 @@
"./widget-integration-select": "./src/widget-integration-select.tsx",
"./modals": "./src/modals/index.ts",
"./prefetch": "./src/prefetch.ts",
"./preview": "./src/widget-preview.tsx",
"./refetch-intervals": "./src/refetch-intervals.ts",
"./widget-card-shell": "./src/widget-card-shell.tsx"
},
+62 -138
View File
@@ -7,26 +7,21 @@ import type { ComponentType, FormEvent, PropsWithChildren } from "react";
import {
Accordion,
Alert,
Badge,
Box,
Button,
Center,
CloseButton,
ColorInput,
Divider,
Group,
Input as MantineInput,
NumberInput,
SimpleGrid,
Stack,
Tabs,
Text,
TextInput,
Tooltip,
useMantineTheme,
} from "@mantine/core";
import { schemaResolver } from "@mantine/form";
import { useElementSize } from "@mantine/hooks";
import { IconArrowLeft, IconEye, IconPencil, IconSettings } from "@tabler/icons-react";
import { QueryErrorResetBoundary } from "@tanstack/react-query";
import { ErrorBoundary } from "react-error-boundary";
@@ -56,6 +51,7 @@ import { WidgetCardShell, WidgetTitleBadge } from "../widget-card-shell";
import type { EmbeddedAppEditFormHandle } from "./embedded-app-edit-form";
import { EmbeddedAppEditForm } from "./embedded-app-edit-form";
import classes from "./widget-edit-modal.module.css";
import { WidgetPreviewFrame } from "../widget-preview";
export interface WidgetEditModalState {
options: Record<string, unknown>;
@@ -152,23 +148,9 @@ const WidgetEditPreview = ({
resize,
PreviewWrapper,
}: WidgetEditPreviewProps) => {
const t = useI18n();
const tItem = useI18n("item.edit");
const board = useOptionalBoard();
const generatedPreviewId = useId().replaceAll(":", "");
const { ref, width: availableWidth, height: availableHeight } = useElementSize<HTMLDivElement>();
const sourceWidth = Math.max(dimensions.width, 1);
const sourceHeight = Math.max(dimensions.height, 1);
let maximumScale = dimensions.scale ?? 0.9;
if (!Number.isFinite(maximumScale) || maximumScale <= 0) maximumScale = 0.9;
maximumScale = Math.min(maximumScale, 0.9);
let previewScale = maximumScale;
if (availableWidth > 0 && availableHeight > 0) {
previewScale = Math.min(availableWidth / sourceWidth, availableHeight / sourceHeight, maximumScale);
}
const previewWidth = sourceWidth * previewScale;
const previewHeight = sourceHeight * previewScale;
const hasIntegrationSupport = "supportedIntegrations" in definition;
const integrationRequired = hasIntegrationSupport && definition.integrationsRequired !== false;
const isMissingIntegration = integrationRequired && state.integrationIds.length === 0;
@@ -188,129 +170,71 @@ const WidgetEditPreview = ({
}
const isPendingCustomWidget = kind === "customApi" && !itemId;
const previewOpacity = (board?.opacity ?? 100) / 100;
const handleResizeValue = (dimension: keyof WidgetEditModalSize, value: string | number) => {
if (typeof value !== "number" || !Number.isFinite(value) || !resize) return;
resize.onChange(
normalizePreviewSize(
{
...resize.size,
[dimension]: value,
},
resize.maximumSize,
),
);
};
return (
<Stack className={classes.previewPanel} gap={0}>
<Center ref={ref} className={classes.previewCanvas}>
{resize && (
<Group className={classes.previewSizeControls} gap={6} wrap="nowrap">
<Text size="xs" fw={600} c="dimmed">
{tItem("preview.size")}
</Text>
<Tooltip label={t("item.moveResize.field.width.label")}>
<NumberInput
className={classes.previewSizeInput}
aria-label={t("item.moveResize.field.width.label")}
value={resize.size.width}
onChange={(value) => handleResizeValue("width", value)}
min={1}
max={resize.maximumSize.width}
step={1}
allowDecimal={false}
allowNegative={false}
clampBehavior="strict"
size="xs"
leftSection={t("item.moveResize.field.width.shortLabel")}
leftSectionPointerEvents="none"
/>
</Tooltip>
<Text size="xs" c="dimmed" aria-hidden>
×
</Text>
<Tooltip label={t("item.moveResize.field.height.label")}>
<NumberInput
className={classes.previewSizeInput}
aria-label={t("item.moveResize.field.height.label")}
value={resize.size.height}
onChange={(value) => handleResizeValue("height", value)}
min={1}
max={resize.maximumSize.height}
step={1}
allowDecimal={false}
allowNegative={false}
clampBehavior="strict"
size="xs"
leftSection={t("item.moveResize.field.height.shortLabel")}
leftSectionPointerEvents="none"
/>
</Tooltip>
</Group>
)}
<Badge className={classes.previewDimensions} size="xs" variant="light" color="gray">
{Math.round(sourceWidth)} × {Math.round(sourceHeight)}
</Badge>
{isMissingIntegration ? (
<Alert color="gray" variant="light" icon={<IconEye size={18} />} maw={320}>
{tItem("preview.integrationRequired")}
</Alert>
) : (
<Box className={classes.previewViewport} w={previewWidth} h={previewHeight}>
<WidgetCardShell
className={classes.previewWidget}
kind={kind}
advancedOptions={state.advancedOptions}
opacity={previewOpacity}
radius={board?.itemRadius}
w={sourceWidth}
h={sourceHeight}
p={0}
data-grid-item-content
style={{ transform: `scale(${previewScale})` }}
>
<WidgetTitleBadge
<WidgetPreviewFrame dimensions={dimensions} resize={resize}>
{({ width: sourceWidth, height: sourceHeight, scale: previewScale }) => (
<>
{isMissingIntegration ? (
<Alert color="gray" variant="light" icon={<IconEye size={18} />} maw={320}>
{tItem("preview.integrationRequired")}
</Alert>
) : (
<Box className={classes.previewViewport} w={sourceWidth * previewScale} h={sourceHeight * previewScale}>
<WidgetCardShell
className={classes.previewWidget}
kind={kind}
advancedOptions={state.advancedOptions}
opacity={previewOpacity}
radius={board?.itemRadius}
/>
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
resetKeys={[state.options, state.integrationIds]}
fallbackRender={({ resetErrorBoundary, error }) => (
<WidgetError definition={definition} error={error} resetErrorBoundary={resetErrorBoundary} />
)}
>
<PreviewRuntimeBoundary Wrapper={PreviewWrapper}>
<SpotlightProvider>
<IntegrationProvider integrations={previewIntegrations}>
<div className={classes.previewContent} inert>
<Component
options={state.options as never}
integrationIds={state.integrationIds}
width={sourceWidth}
height={sourceHeight}
displayScale={previewScale}
isEditMode={isPendingCustomWidget}
displayMode="compact"
boardId={boardId}
itemId={componentItemId}
setOptions={({ newOptions }) => onChangeOptions(newOptions as Record<string, unknown>)}
/>
</div>
</IntegrationProvider>
</SpotlightProvider>
</PreviewRuntimeBoundary>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
</WidgetCardShell>
</Box>
)}
</Center>
</Stack>
w={sourceWidth}
h={sourceHeight}
p={0}
data-grid-item-content
style={{ transform: `scale(${previewScale})` }}
>
<WidgetTitleBadge
advancedOptions={state.advancedOptions}
opacity={previewOpacity}
radius={board?.itemRadius}
/>
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
resetKeys={[state.options, state.integrationIds]}
fallbackRender={({ resetErrorBoundary, error }) => (
<WidgetError definition={definition} error={error} resetErrorBoundary={resetErrorBoundary} />
)}
>
<PreviewRuntimeBoundary Wrapper={PreviewWrapper}>
<SpotlightProvider>
<IntegrationProvider integrations={previewIntegrations}>
<div className={classes.previewContent} inert>
<Component
options={state.options as never}
integrationIds={state.integrationIds}
width={sourceWidth}
height={sourceHeight}
displayScale={previewScale}
isEditMode={isPendingCustomWidget}
displayMode="compact"
boardId={boardId}
itemId={componentItemId}
setOptions={({ newOptions }) => onChangeOptions(newOptions as Record<string, unknown>)}
/>
</div>
</IntegrationProvider>
</SpotlightProvider>
</PreviewRuntimeBoundary>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
</WidgetCardShell>
</Box>
)}
</>
)}
</WidgetPreviewFrame>
);
};
+68
View File
@@ -0,0 +1,68 @@
"use client";
import type { ReactNode } from "react";
import { Badge, Center, Group, NumberInput, Stack, Text, Tooltip } from "@mantine/core";
import { useElementSize } from "@mantine/hooks";
import { useI18n } from "@homarr/translation/client";
import classes from "./modals/widget-edit-modal.module.css";
type Size = { width: number; height: number };
/** The same board grid controls and fitted canvas used by Edit Widget and package authoring. */
export function WidgetPreviewFrame({ dimensions, resize, children }: {
dimensions: Size & { scale?: number };
resize?: { size: Size; maximumSize: Size; onChange(size: Size): void };
children(dimensions: Size & { scale: number }): ReactNode;
}) {
const t = useI18n();
const { ref, width, height } = useElementSize<HTMLDivElement>();
const sourceWidth = Math.max(dimensions.width, 1);
const sourceHeight = Math.max(dimensions.height, 1);
let scale = dimensions.scale ?? 0.9;
if (!Number.isFinite(scale) || scale <= 0) scale = 0.9;
scale = Math.min(scale, 0.9);
if (width > 0 && height > 0) scale = Math.min(width / sourceWidth, height / sourceHeight, scale);
const change = (dimension: keyof Size, value: string | number) => {
if (!resize || typeof value !== "number" || !Number.isFinite(value)) return;
resize.onChange({ ...resize.size, [dimension]: Math.max(1, Math.min(Math.round(value), resize.maximumSize[dimension])) });
};
return (
<Stack className={classes.previewPanel} gap={0}>
<Center ref={ref} className={classes.previewCanvas}>
{resize && (
<Group className={classes.previewSizeControls} gap={6} wrap="nowrap">
<Text size="xs" fw={600} c="dimmed">{t("item.edit.preview.size")}</Text>
{(["width", "height"] as const).map((dimension) => (
<Group key={dimension} gap={6} wrap="nowrap">
{dimension === "height" && <Text size="xs" c="dimmed" aria-hidden>×</Text>}
<Tooltip label={t(`item.moveResize.field.${dimension}.label`)}>
<NumberInput
className={classes.previewSizeInput}
aria-label={t(`item.moveResize.field.${dimension}.label`)}
value={resize.size[dimension]}
onChange={(value) => change(dimension, value)}
min={1}
max={resize.maximumSize[dimension]}
step={1}
allowDecimal={false}
allowNegative={false}
clampBehavior="strict"
size="xs"
leftSection={t(`item.moveResize.field.${dimension}.shortLabel`)}
leftSectionPointerEvents="none"
/>
</Tooltip>
</Group>
))}
</Group>
)}
<Badge className={classes.previewDimensions} size="xs" variant="light" color="gray">
{Math.round(sourceWidth)} × {Math.round(sourceHeight)}
</Badge>
{children({ width: sourceWidth, height: sourceHeight, scale })}
</Center>
</Stack>
);
}