feat: configure custom widget sources

This commit is contained in:
Thomas Camlong committed 2026-07-22 18:12:09 +02:00
1 parent 47cd7dda1f
commit e94b4d4bc9
43 files changed
+2361 -394

No files matched your search

@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { Alert, Button, Card, Center, PasswordInput, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
import { Alert, Button, Card, Center, PasswordInput, Select, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
import { IconCheck, IconKey, IconLock } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
@@ -12,22 +12,30 @@ interface RequestDetails {
kinds: Array<"apiKey" | "username" | "password">;
expiresAt: number;
status: "pending" | "completed";
source: {
baseUrl: string;
networkScope: "public" | "private" | "loopback";
};
}
export function CustomWidgetSecretEntry({ token }: { token: string }) {
export function CustomWidgetConfigurationEntry({ token }: { token: string }) {
const t = useScopedI18n("customWidget.secretEntry");
const [details, setDetails] = useState<RequestDetails | null>(null);
const [values, setValues] = useState<Record<string, string>>({});
const [baseUrl, setBaseUrl] = useState("");
const [networkScope, setNetworkScope] = useState<"public" | "private" | "loopback">("public");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
void fetch(`/api/custom-widgets/secret-request/${encodeURIComponent(token)}`)
void fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`)
.then(async (response) => {
const body = (await response.json()) as RequestDetails | { error: string };
if (!response.ok || "error" in body) throw new Error("error" in body ? body.error : t("unavailable"));
setDetails(body);
setBaseUrl(body.source.baseUrl);
setNetworkScope(body.source.networkScope);
})
.catch((cause: unknown) => setError(cause instanceof Error ? cause.message : t("unavailable")))
.finally(() => setLoading(false));
@@ -37,10 +45,10 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
setSaving(true);
setError(null);
try {
const response = await fetch(`/api/custom-widgets/secret-request/${encodeURIComponent(token)}`, {
const response = await fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ secrets: values }),
body: JSON.stringify({ baseUrl, networkScope, secrets: values }),
});
const body = (await response.json()) as { status?: string; error?: string };
if (!response.ok) throw new Error(body.error ?? t("saveError"));
@@ -81,6 +89,14 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
{t("source", { name: details.sourceName })}
</Text>
</Card>
<TextInput label={t("baseUrl")} type="url" value={baseUrl} onChange={(event) => setBaseUrl(event.currentTarget.value)} required />
<Select
label={t("networkScope")}
data={["public", "private", "loopback"]}
value={networkScope}
allowDeselect={false}
onChange={(value) => value && setNetworkScope(value as typeof networkScope)}
/>
{details.kinds.map((kind) => {
const Input = kind === "username" ? TextInput : PasswordInput;
return (
@@ -97,7 +113,7 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
})}
<Button
loading={saving}
disabled={details.kinds.some((kind) => !values[kind])}
disabled={!URL.canParse(baseUrl) || details.kinds.some((kind) => !values[kind])}
onClick={() => void submit()}
>
{t("save")}
@@ -0,0 +1,13 @@
import type { Metadata } from "next";
import { CustomWidgetConfigurationEntry } from "./configuration-entry";
export const metadata: Metadata = {
title: "Configure custom widget API source",
robots: { index: false, follow: false },
};
export default async function CustomWidgetConfigurationPage({ params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
return <CustomWidgetConfigurationEntry token={token} />;
}
@@ -1,13 +0,0 @@
import type { Metadata } from "next";
import { CustomWidgetSecretEntry } from "./secret-entry";
export const metadata: Metadata = {
title: "Configure custom widget credential",
robots: { index: false, follow: false },
};
export default async function CustomWidgetSecretPage({ params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
return <CustomWidgetSecretEntry token={token} />;
}
@@ -0,0 +1,182 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import {
claimCustomWidgetConfigurationRequest,
completeCustomWidgetConfigurationRequest,
configurePreviewSessionSource,
getCustomWidgetConfigurationRequest,
parseStoredCustomWidgetDefinition,
releaseCustomWidgetConfigurationRequest,
serializeCustomWidgetDefinition,
} from "@homarr/api/custom-widget-configuration";
import { encryptSecret } from "@homarr/common/server";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
import { and, db, eq, handleTransactionsAsync } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
interface RouteContext {
params: Promise<{ token: string }>;
}
export async function GET(_request: NextRequest, context: RouteContext) {
const { token } = await context.params;
const request = await getCustomWidgetConfigurationRequest(token);
if (!request)
return NextResponse.json({ error: "This source configuration request is invalid or expired." }, { status: 404 });
return NextResponse.json(
{
widgetName: request.widgetName,
sourceName: request.sourceName,
kinds: request.kinds,
source: request.source,
expiresAt: request.expiresAt,
status: request.status,
},
{ headers: { "Cache-Control": "no-store" } },
);
}
export async function POST(request: NextRequest, context: RouteContext) {
const { token } = await context.params;
const pending = await getCustomWidgetConfigurationRequest(token);
if (!pending || pending.status !== "pending") {
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
}
const body = (await request.json().catch(() => null)) as {
baseUrl?: unknown;
networkScope?: unknown;
secrets?: Record<string, unknown>;
} | null;
const sourceResult = customWidgetSourceSchema.safeParse({
...pending.source,
baseUrl: body?.baseUrl,
networkScope: body?.networkScope,
});
if (!sourceResult.success) {
return NextResponse.json(
{ error: sourceResult.error.issues[0]?.message ?? "Enter a valid server URL." },
{ status: 400 },
);
}
const secrets = pending.kinds.flatMap((kind) => {
const value = body?.secrets?.[kind];
return typeof value === "string" && value.length > 0 && value.length <= 8192
? [{ sourceId: pending.sourceId, kind, value }]
: [];
});
if (secrets.length !== pending.kinds.length) {
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
}
const claimed = await claimCustomWidgetConfigurationRequest(token);
if (!claimed) {
return NextResponse.json(
{ error: "This source configuration request is already being completed." },
{ status: 409 },
);
}
try {
if (claimed.target.type === "preview") {
await configurePreviewSessionSource(
claimed.target.id,
claimed.userId,
claimed.sourceId,
sourceResult.data,
secrets,
);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
} else {
const definition = await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, claimed.target.id),
});
if (!definition) return NextResponse.json({ error: "The custom widget no longer exists." }, { status: 404 });
const parsed = parseStoredCustomWidgetDefinition(definition);
const currentSource = parsed.sources[claimed.sourceId];
if (!currentSource) {
return NextResponse.json(
{ error: "This API source changed after the setup link was created. Request a new setup link." },
{ status: 409 },
);
}
if (!hasSameCustomWidgetSourceAuthentication(currentSource, claimed.source)) {
return NextResponse.json(
{
error: "This API source authentication changed after the setup link was created. Request a new setup link.",
},
{ status: 409 },
);
}
const configuredSource = customWidgetSourceSchema.parse({
...currentSource,
baseUrl: sourceResult.data.baseUrl,
networkScope: sourceResult.data.networkScope,
});
const definitionChanges = {
...serializeCustomWidgetDefinition({
...parsed,
sources: { ...parsed.sources, [claimed.sourceId]: configuredSource },
}),
updatedAt: new Date(),
};
const secretRows = secrets.map((secret) => ({
definitionId: claimed.target.id,
sourceId: secret.sourceId,
kind: secret.kind,
encryptedValue: encryptSecret(secret.value),
updatedAt: new Date(),
}));
await handleTransactionsAsync(db, {
async handleAsync(database, schema) {
await database.transaction(async (transaction) => {
await transaction
.update(schema.customWidgetDefinitions)
.set(definitionChanges)
.where(eq(schema.customWidgetDefinitions.id, claimed.target.id));
for (const secret of secretRows) {
await transaction
.delete(schema.customWidgetSecrets)
.where(
and(
eq(schema.customWidgetSecrets.definitionId, claimed.target.id),
eq(schema.customWidgetSecrets.sourceId, secret.sourceId),
eq(schema.customWidgetSecrets.kind, secret.kind),
),
);
await transaction.insert(schema.customWidgetSecrets).values(secret);
}
});
},
handleSync(database) {
database.transaction((transaction) => {
transaction
.update(customWidgetDefinitions)
.set(definitionChanges)
.where(eq(customWidgetDefinitions.id, claimed.target.id))
.run();
for (const secret of secretRows) {
transaction
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, claimed.target.id),
eq(customWidgetSecrets.sourceId, secret.sourceId),
eq(customWidgetSecrets.kind, secret.kind),
),
)
.run();
transaction.insert(customWidgetSecrets).values(secret).run();
}
});
},
});
}
await completeCustomWidgetConfigurationRequest(token);
return NextResponse.json({ status: "completed" }, { headers: { "Cache-Control": "no-store" } });
} finally {
await releaseCustomWidgetConfigurationRequest(token);
}
}
@@ -1,96 +0,0 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import {
claimCustomWidgetSecretRequest,
completeCustomWidgetSecretRequest,
getCustomWidgetSecretRequest,
releaseCustomWidgetSecretRequest,
setPreviewSessionSecrets,
} from "@homarr/api/custom-widget-secrets";
import { encryptSecret } from "@homarr/common/server";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { and, db, eq } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
interface RouteContext {
params: Promise<{ token: string }>;
}
export async function GET(_request: NextRequest, context: RouteContext) {
const { token } = await context.params;
const request = await getCustomWidgetSecretRequest(token);
if (!request) return NextResponse.json({ error: "This credential request is invalid or expired." }, { status: 404 });
return NextResponse.json(
{
widgetName: request.widgetName,
sourceName: request.sourceName,
kinds: request.kinds,
expiresAt: request.expiresAt,
status: request.status,
},
{ headers: { "Cache-Control": "no-store" } },
);
}
export async function POST(request: NextRequest, context: RouteContext) {
const { token } = await context.params;
const pending = await getCustomWidgetSecretRequest(token);
if (!pending || pending.status !== "pending") {
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
}
const body = (await request.json().catch(() => null)) as { secrets?: Record<string, unknown> } | null;
const secrets = pending.kinds.flatMap((kind) => {
const value = body?.secrets?.[kind];
return typeof value === "string" && value.length > 0 && value.length <= 8192
? [{ sourceId: pending.sourceId, kind, value }]
: [];
});
if (secrets.length !== pending.kinds.length) {
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
}
const claimed = await claimCustomWidgetSecretRequest(token);
if (!claimed) {
return NextResponse.json({ error: "This credential request is already being completed." }, { status: 409 });
}
try {
if (claimed.target.type === "preview") {
await setPreviewSessionSecrets(claimed.target.id, claimed.userId, secrets);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
} else {
const definition = await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, claimed.target.id),
});
if (!definition) return NextResponse.json({ error: "The custom widget no longer exists." }, { status: 404 });
for (const secret of secrets) {
await db
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, claimed.target.id),
eq(customWidgetSecrets.sourceId, secret.sourceId),
eq(customWidgetSecrets.kind, secret.kind),
),
);
await db.insert(customWidgetSecrets).values({
definitionId: claimed.target.id,
sourceId: secret.sourceId,
kind: secret.kind,
encryptedValue: encryptSecret(secret.value),
updatedAt: new Date(),
});
}
await db
.update(customWidgetDefinitions)
.set({ updatedAt: new Date() })
.where(eq(customWidgetDefinitions.id, claimed.target.id));
}
await completeCustomWidgetSecretRequest(token);
return NextResponse.json({ status: "completed" }, { headers: { "Cache-Control": "no-store" } });
} finally {
await releaseCustomWidgetSecretRequest(token);
}
}
@@ -2,35 +2,64 @@
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { Alert, PasswordInput, Stack, Text, TextInput } from "@mantine/core";
import { IconKey } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { getCustomWidgetSecretRequirements, getImportReview } from "@homarr/custom-widgets/core";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { ImportReviewDialog } from "@homarr/custom-widgets/workbench";
import { applyCustomWidgetSourceSetup, getCustomWidgetSourceSetups, getImportReview } from "@homarr/custom-widgets/core";
import type { CustomWidgetSecretKind, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import {
createCustomWidgetSourceSetupValues,
CustomWidgetSourceSetupPanel,
ImportReviewDialog,
isCustomWidgetSourceSetupReady,
} from "@homarr/custom-widgets/workbench";
import type { CustomWidgetSourceSetupValue } from "@homarr/custom-widgets/workbench";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
interface CustomWidgetImportDialogProps {
opened: boolean;
widget: HomarrCustomWidgetV2 | null;
stackId?: string;
zIndex?: number;
onClose(): void;
onImported?(result: { id: string }): void;
}
export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }: CustomWidgetImportDialogProps) {
export function CustomWidgetImportDialog({
opened,
widget,
stackId,
zIndex,
onClose,
onImported,
}: CustomWidgetImportDialogProps) {
const t = useScopedI18n("customWidget");
const router = useRouter();
const utils = clientApi.useUtils();
const [values, setValues] = useState<Record<string, string>>({});
const review = useMemo(() => getImportReview(widget), [widget]);
const requirements = useMemo(() => getCustomWidgetSecretRequirements(widget?.sources ?? {}), [widget]);
const setups = useMemo(() => getCustomWidgetSourceSetups(widget?.sources ?? {}), [widget]);
const [values, setValues] = useState<Record<string, CustomWidgetSourceSetupValue>>({});
const configuredWidget = useMemo(() => {
if (!widget) return null;
return {
...widget,
sources: applyCustomWidgetSourceSetup(
widget.sources,
Object.fromEntries(
Object.entries(values).map(([sourceId, value]) => [
sourceId,
{ baseUrl: value.baseUrl, networkScope: value.networkScope },
]),
),
),
};
}, [values, widget]);
const review = useMemo(() => getImportReview(configuredWidget), [configuredWidget]);
const mutation = clientApi.customWidget.import.useMutation({
onSuccess: (result) => {
showSuccessNotification({ title: t("action.import"), message: t("notification.imported") });
void utils.customWidget.list.invalidate();
void utils.customWidget.available.invalidate();
void revalidatePathActionAsync("/manage/custom-widgets").then(() => router.refresh());
onImported?.(result);
onClose();
@@ -41,27 +70,27 @@ export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }
});
useEffect(() => {
if (opened) setValues({});
}, [opened, widget]);
const setValue = (sourceId: string, kind: string, value: string) => {
setValues((current) => ({ ...current, [`${sourceId}:${kind}`]: value }));
};
if (opened) setValues(createCustomWidgetSourceSetupValues(setups));
}, [opened, setups]);
const importWidget = () => {
if (!widget) return;
const secrets = requirements.flatMap((requirement) => {
const value = values[`${requirement.sourceId}:${requirement.kind}`] ?? "";
return value.trim() ? [{ sourceId: requirement.sourceId, kind: requirement.kind, value }] : [];
});
mutation.mutate({ widget, secrets });
if (!configuredWidget) return;
const secrets = Object.entries(values).flatMap(([sourceId, value]) =>
Object.entries(value.secrets).flatMap(([kind, secret]) =>
secret?.trim() ? [{ sourceId, kind: kind as CustomWidgetSecretKind, value: secret }] : [],
),
);
mutation.mutate({ widget: configuredWidget, secrets });
};
return (
<ImportReviewDialog
opened={opened}
stackId={stackId}
zIndex={zIndex}
review={review}
pending={mutation.isPending}
confirmDisabled={!isCustomWidgetSourceSetupReady(setups, values)}
onClose={onClose}
onConfirm={importWidget}
messages={{
@@ -80,39 +109,27 @@ export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }
permission: (permission) => t(`preview.request.permission.${permission}` as never),
}}
>
{requirements.length > 0 && (
<Stack gap="sm">
<Alert color="yellow" icon={<IconKey size={16} />}>
<Text fw={600} size="sm">
{t("importReview.credentials.title")}
</Text>
<Text size="sm">{t("importReview.credentials.description")}</Text>
</Alert>
{requirements.map((requirement) => {
const key = `${requirement.sourceId}:${requirement.kind}`;
const label = `${requirement.sourceName} · ${t(`importReview.credentials.field.${requirement.kind}`)}`;
const description = requirement.destination
? t(
requirement.authType === "apiKeyHeader"
? "importReview.credentials.header"
: "importReview.credentials.query",
{ name: requirement.destination },
)
: undefined;
const Input = requirement.kind === "username" ? TextInput : PasswordInput;
return (
<Input
key={key}
label={label}
description={description}
value={values[key] ?? ""}
onChange={(event) => setValue(requirement.sourceId, requirement.kind, event.currentTarget.value)}
autoComplete="off"
/>
);
})}
</Stack>
)}
<CustomWidgetSourceSetupPanel
setups={setups}
values={values}
onChange={(sourceId, value) => setValues((current) => ({ ...current, [sourceId]: value }))}
messages={{
title: t("importReview.sourceSetup.title"),
description: t("importReview.sourceSetup.description"),
suggestedUrl: t("importReview.sourceSetup.suggestedUrl"),
baseUrl: t("workbench.sources.baseUrl"),
networkScope: t("workbench.sources.networkScope"),
authentication: t("workbench.sources.authentication"),
confirmUrl: t("importReview.sourceSetup.confirmUrl"),
ready: t("importReview.sourceSetup.ready"),
needsUrl: t("importReview.sourceSetup.needsUrl"),
credentialsMissing: t("importReview.sourceSetup.credentialsMissing"),
credentialsOptional: t("importReview.sourceSetup.credentialsOptional"),
configured: t("workbench.sources.configured"),
secret: (kind) => t(`importReview.credentials.field.${kind}`),
urlError: (issue) => t(`workbench.sources.baseUrlError.${issue}`),
}}
/>
</ImportReviewDialog>
);
}
@@ -1,13 +1,14 @@
import { WorkshopClient, WORKSHOP_API_URL } from "@homarr/workshop";
import { WorkshopBackend } from "@homarr/workshop/backend";
import { WORKSHOP_API_URL } from "@homarr/workshop/schema";
let browserClient: WorkshopClient | undefined;
let browserClient: WorkshopBackend | undefined;
export function createWorkshopClient() {
if (typeof document === "undefined") return new WorkshopClient(WORKSHOP_API_URL);
if (typeof document === "undefined") return new WorkshopBackend(WORKSHOP_API_URL);
if (browserClient) return browserClient;
const runtimeUrl = document.querySelector<HTMLMetaElement>('meta[name="homarr-workshop-api-url"]')?.content;
browserClient = new WorkshopClient(runtimeUrl || WORKSHOP_API_URL);
browserClient = new WorkshopBackend(runtimeUrl || WORKSHOP_API_URL);
return browserClient;
}
@@ -1,8 +1,8 @@
"use client";
import type { ReactNode } from "react";
import { useState } from "react";
import { Button, Modal } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { Button, getDefaultZIndex, Modal, useModalsStack } from "@mantine/core";
import { IconBuildingStore } from "@tabler/icons-react";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
@@ -11,33 +11,52 @@ import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { WorkshopBrowser } from "./workshop-browser";
export function WorkshopInstallButton() {
interface WorkshopInstallButtonProps {
children?: ReactNode;
fullWidth?: boolean;
}
export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallButtonProps = {}) {
const t = useScopedI18n("workshop");
const [opened, controls] = useDisclosure(false);
const [reviewOpened, reviewControls] = useDisclosure(false);
const stack = useModalsStack(["workshop", "review"]);
const [pendingWidget, setPendingWidget] = useState<HomarrCustomWidgetV2 | null>(null);
const zIndex = getDefaultZIndex("modal") + 10;
const closeReview = () => {
stack.close("review");
setPendingWidget(null);
};
return (
<>
<Button variant="default" leftSection={<IconBuildingStore size={16} />} onClick={controls.open}>
{t("title")}
<Button
variant="default"
leftSection={<IconBuildingStore size={16} />}
onClick={() => stack.open("workshop")}
fullWidth={fullWidth}
>
{children ?? t("title")}
</Button>
<Modal opened={opened} onClose={controls.close} title={t("installDialog")} size="90%">
<WorkshopBrowser
onInstall={async (widget) => {
setPendingWidget(widget);
reviewControls.open();
<Modal.Stack>
<Modal {...stack.register("workshop")} title={t("installDialog")} size="90%" zIndex={zIndex}>
<WorkshopBrowser
onInstall={async (widget) => {
setPendingWidget(widget);
stack.open("review");
}}
/>
</Modal>
<CustomWidgetImportDialog
{...stack.register("review")}
widget={pendingWidget}
zIndex={zIndex + 1}
onClose={closeReview}
onImported={() => {
stack.closeAll();
setPendingWidget(null);
}}
/>
</Modal>
<CustomWidgetImportDialog
opened={reviewOpened}
widget={pendingWidget}
onClose={() => {
reviewControls.close();
setPendingWidget(null);
}}
onImported={controls.close}
/>
</Modal.Stack>
</>
);
}
@@ -1,11 +1,12 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Alert, Button, FileInput, Group, Modal, Stack, Textarea, TextInput } from "@mantine/core";
import { Alert, Button, Checkbox, FileInput, Group, Modal, Stack, Textarea, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { showErrorNotification } from "@homarr/notifications";
import type { WorkshopUser } from "@homarr/workshop";
import { useWorkshopCreateMutation } from "@homarr/workshop/backend";
import type { WorkshopUser } from "@homarr/workshop/schema";
import { useScopedI18n } from "@homarr/translation/client";
import { createWorkshopClient } from "./workshop-client";
@@ -26,9 +27,14 @@ export function WorkshopPublishModal({
const [title, setTitle] = useState(widget.name);
const [description, setDescription] = useState("");
const [screenshots, setScreenshots] = useState<File[]>([]);
const [pending, setPending] = useState(false);
const createSubmission = useWorkshopCreateMutation(client);
const [error, setError] = useState<string | null>(null);
const [published, setPublished] = useState(false);
const [sourceUrlsReviewed, setSourceUrlsReviewed] = useState(false);
const definition = clientApi.customWidget.get.useQuery({ id: widget.id }, { enabled: opened });
const privateSources = Object.entries(definition.data?.sources ?? {}).filter(
([, source]) => source.networkScope !== "public",
);
useEffect(() => {
const unsubscribe = client.subscribeToAuth(setUser);
@@ -42,22 +48,20 @@ export function WorkshopPublishModal({
setScreenshots([]);
setError(null);
setPublished(false);
setSourceUrlsReviewed(false);
}, [opened, widget.name]);
const publish = async () => {
setPending(true);
setError(null);
try {
const definition = await utils.customWidget.export.fetch({ id: widget.id });
await client.create(
{ type: "customWidget", title, description, content: JSON.stringify(definition) },
await createSubmission.mutateAsync({
input: { type: "customWidget", title, description, content: JSON.stringify(definition) },
screenshots,
);
});
setPublished(true);
} catch (cause) {
setError(cause instanceof Error ? cause.message : t("publish.error"));
} finally {
setPending(false);
}
};
@@ -109,8 +113,25 @@ export function WorkshopPublishModal({
value={screenshots}
onChange={setScreenshots}
/>
{privateSources.length > 0 && (
<Alert color="yellow">
{t("publish.privateSourceWarning", {
sources: privateSources.map(([sourceId, source]) => source.name ?? sourceId).join(", "),
})}
<Checkbox
mt="sm"
checked={sourceUrlsReviewed}
onChange={(event) => setSourceUrlsReviewed(event.currentTarget.checked)}
label={t("publish.privateSourceConfirmation")}
/>
</Alert>
)}
{error && <Alert color="red">{error}</Alert>}
<Button loading={pending} disabled={!user || title.trim().length < 3} onClick={() => void publish()}>
<Button
loading={createSubmission.isPending}
disabled={!user || title.trim().length < 3 || (privateSources.length > 0 && !sourceUrlsReviewed)}
onClick={() => void publish()}
>
{t("publish.action")}
</Button>
</>