feat(custom-widgets): add extensible widget platform
This commit is contained in:
1 parent
6cca757493
commit
8f152f1929
317 files changed
+32326
-1788
No files matched your search
@@ -43,7 +43,17 @@ const nextConfig: NextConfig = {
|
||||
* dockerode is required in the external server packages because of https://github.com/homarr-labs/homarr/issues/612
|
||||
* isomorphic-dompurify and jsdom are required, see https://github.com/kkomelin/isomorphic-dompurify/issues/356
|
||||
*/
|
||||
serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3"],
|
||||
serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3", "esbuild"],
|
||||
outputFileTracingRoot: path.resolve(import.meta.dirname, "../.."),
|
||||
outputFileTracingIncludes: {
|
||||
"/*": [
|
||||
"../../node_modules/esbuild/**/*",
|
||||
"../../node_modules/@esbuild/**/*",
|
||||
"../../node_modules/@tabler/icons-react/**/*",
|
||||
"../../packages/widget-sdk/package.json",
|
||||
"../../packages/widget-sdk/src/**/*",
|
||||
],
|
||||
},
|
||||
experimental: {
|
||||
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
|
||||
preloadEntriesOnStart: true,
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "HOMARR_VERSION=$(node -p \"require('../../package.json').version\") pnpm with-env next build",
|
||||
"build": "pnpm --filter @homarr/custom-widgets generate:editor && HOMARR_VERSION=$(node -p \"require('../../package.json').version\") pnpm with-env next build",
|
||||
"clean": "git clean -xdf .next .turbo node_modules",
|
||||
"dev": "pnpm with-env next dev",
|
||||
"dev": "pnpm --filter @homarr/custom-widgets generate:editor && pnpm with-env next dev",
|
||||
"format": "oxfmt .",
|
||||
"lint": "oxlint",
|
||||
"start": "pnpm with-env next start",
|
||||
@@ -58,6 +58,7 @@
|
||||
"@homarr/ui": "workspace:^0.1.0",
|
||||
"@homarr/validation": "workspace:^0.1.0",
|
||||
"@homarr/websocket": "workspace:^0.1.0",
|
||||
"@homarr/widget-sdk": "workspace:^0.1.0",
|
||||
"@homarr/widgets": "workspace:^0.1.0",
|
||||
"@homarr/workshop": "workspace:^0.1.0",
|
||||
"@mantine/colors-generator": "catalog:",
|
||||
|
||||
@@ -1 +1,15 @@
|
||||
export { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
"use client";
|
||||
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
import { CodeEditor as SharedCodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
|
||||
export function CodeEditor(props: ComponentProps<typeof SharedCodeEditor>) {
|
||||
const localHistory =
|
||||
props.id === "raw-widget-manifest" || props.id.endsWith("-request-body-editor") || props.id.startsWith("option-");
|
||||
return (
|
||||
<div data-custom-widget-local-history={localHistory || undefined}>
|
||||
<SharedCodeEditor {...props} hideHistoryActions={!localHistory} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { redactCustomWidgetCredentialLiterals } from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
||||
|
||||
export type CustomWidgetDocumentContent = Omit<CustomWidgetFormValues, "secrets">;
|
||||
export interface CustomWidgetDocumentHistoryState {
|
||||
canUndo: boolean;
|
||||
canRedo: boolean;
|
||||
}
|
||||
|
||||
const MAX_HISTORY_ENTRIES = 100;
|
||||
const MAX_HISTORY_CHARACTERS = 2_000_000;
|
||||
const COALESCE_DELAY = 600;
|
||||
const typingFields = new Set(["name", "description", "iconUrl", "template"]);
|
||||
|
||||
export function getCustomWidgetDocumentContent(values: CustomWidgetFormValues): CustomWidgetDocumentContent {
|
||||
const { secrets: _secrets, ...content } = values;
|
||||
return content;
|
||||
}
|
||||
|
||||
export function getCustomWidgetRecoveryContent(values: CustomWidgetFormValues): CustomWidgetDocumentContent {
|
||||
const content = getCustomWidgetDocumentContent(values);
|
||||
for (const key of Object.keys(content) as Array<keyof CustomWidgetDocumentContent>) {
|
||||
let value = content[key];
|
||||
for (const secret of values.secrets) {
|
||||
if (secret.value) value = value.replaceAll(secret.value, "[REDACTED]");
|
||||
}
|
||||
content[key] = redactCustomWidgetCredentialLiterals(value.replaceAll(/\b(https?:\/\/)[^\s/"'<>]+@/giu, "$1"));
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
export function createCustomWidgetDocumentHistory(initialValues: CustomWidgetFormValues) {
|
||||
const initial = getCustomWidgetDocumentContent(initialValues);
|
||||
let entries = [{ content: initial, size: JSON.stringify(initial).length }];
|
||||
let position = 0;
|
||||
let lastChangeAt = 0;
|
||||
let lastTypingField: string | undefined;
|
||||
let sameTurn = false;
|
||||
let state: CustomWidgetDocumentHistoryState = { canUndo: false, canRedo: false };
|
||||
|
||||
const refreshState = () => {
|
||||
state = { canUndo: position > 0, canRedo: position < entries.length - 1 };
|
||||
};
|
||||
const stopCoalescing = () => {
|
||||
sameTurn = false;
|
||||
lastChangeAt = 0;
|
||||
lastTypingField = undefined;
|
||||
};
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
record(values: CustomWidgetFormValues) {
|
||||
const next = getCustomWidgetDocumentContent(values);
|
||||
const current = entries[position]?.content;
|
||||
const changed = (Object.keys(next) as Array<keyof CustomWidgetDocumentContent>).filter(
|
||||
(key) => next[key] !== current?.[key],
|
||||
);
|
||||
if (changed.length === 0) return;
|
||||
const now = Date.now();
|
||||
const field = changed[0];
|
||||
const isTyping = changed.length === 1 && field !== undefined && typingFields.has(field);
|
||||
const coalesce =
|
||||
position > 0 &&
|
||||
position === entries.length - 1 &&
|
||||
(sameTurn || (isTyping && field === lastTypingField && now - lastChangeAt < COALESCE_DELAY));
|
||||
entries = entries.slice(0, position + 1);
|
||||
const entry = { content: next, size: JSON.stringify(next).length };
|
||||
if (coalesce) entries[position] = entry;
|
||||
else {
|
||||
entries.push(entry);
|
||||
position += 1;
|
||||
}
|
||||
let size = entries.reduce((total, item) => total + item.size, 0);
|
||||
while (entries.length > 1 && (entries.length > MAX_HISTORY_ENTRIES || size > MAX_HISTORY_CHARACTERS)) {
|
||||
const removed = entries.shift();
|
||||
if (removed) size -= removed.size;
|
||||
position -= 1;
|
||||
}
|
||||
lastChangeAt = now;
|
||||
lastTypingField = undefined;
|
||||
if (isTyping) lastTypingField = field;
|
||||
sameTurn = true;
|
||||
queueMicrotask(() => {
|
||||
sameTurn = false;
|
||||
});
|
||||
refreshState();
|
||||
},
|
||||
undo() {
|
||||
if (position === 0) return null;
|
||||
position -= 1;
|
||||
stopCoalescing();
|
||||
refreshState();
|
||||
return entries[position]?.content ?? null;
|
||||
},
|
||||
redo() {
|
||||
if (position === entries.length - 1) return null;
|
||||
position += 1;
|
||||
stopCoalescing();
|
||||
refreshState();
|
||||
return entries[position]?.content ?? null;
|
||||
},
|
||||
stopCoalescing,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconArrowBackUp, IconArrowForwardUp, IconRestore } from "@tabler/icons-react";
|
||||
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { customWidgetFormSchema } from "@homarr/custom-widgets/workbench";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { getCustomWidgetRecoveryContent } from "./_custom-widget-document-history";
|
||||
import type { CustomWidgetDocumentContent } from "./_custom-widget-document-history";
|
||||
import { useCustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
|
||||
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
||||
|
||||
interface RecoveryDraft {
|
||||
definitionId: string | null;
|
||||
content: CustomWidgetDocumentContent;
|
||||
}
|
||||
|
||||
const MAX_RECOVERY_CHARACTERS = 1_000_000;
|
||||
|
||||
export function CustomWidgetDraftControls({
|
||||
form,
|
||||
definitionId,
|
||||
disabled,
|
||||
}: {
|
||||
form: CustomWidgetWorkbenchForm;
|
||||
definitionId?: string;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const t = useI18n("customWidget.workbench.history");
|
||||
const store = useCustomWidgetFormDocumentStore();
|
||||
const history = useSyncExternalStore(store.subscribe, store.getHistory, store.getHistory);
|
||||
const dirty = useSyncExternalStore(store.subscribe, store.getDirty, store.getDirty);
|
||||
const { data: session } = useSession();
|
||||
const userId = session?.user.id;
|
||||
const [recovery, setRecovery] = useState<RecoveryDraft | null>(null);
|
||||
const storageKey = userId ? `homarr:custom-widget-recovery:${userId}` : null;
|
||||
|
||||
const restoreHistory = useCallback(
|
||||
(direction: "undo" | "redo") => {
|
||||
if (disabled) return;
|
||||
const restored = store[direction]();
|
||||
if (restored) form.setValues(restored);
|
||||
},
|
||||
[disabled, form, store],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.key.toLowerCase() !== "z") return;
|
||||
const target = event.target;
|
||||
if (!(target instanceof Element) || !target.closest("[data-custom-widget-workbench]")) return;
|
||||
if (target.closest("[data-custom-widget-secret], [data-custom-widget-local-history], #preview")) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.shiftKey) restoreHistory("redo");
|
||||
else restoreHistory("undo");
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown, true);
|
||||
return () => window.removeEventListener("keydown", onKeyDown, true);
|
||||
}, [restoreHistory]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (!saved || saved.length > MAX_RECOVERY_CHARACTERS) return;
|
||||
const parsed = JSON.parse(saved) as RecoveryDraft;
|
||||
if (!parsed || parsed.definitionId !== (definitionId ?? null)) return;
|
||||
if (!isRecord(parsed.content)) return;
|
||||
const keys = customWidgetFormSchema.keyof().options.filter((key) => key !== "secrets");
|
||||
if (!keys.every((key) => typeof parsed.content[key] === "string")) return;
|
||||
setRecovery({
|
||||
definitionId: parsed.definitionId,
|
||||
content: getCustomWidgetRecoveryContent({ ...parsed.content, secrets: [] }),
|
||||
});
|
||||
} catch {
|
||||
// Browser storage is optional; editing and saving continue without it.
|
||||
}
|
||||
}, [definitionId, storageKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!storageKey || recovery) return;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
const persist = () => {
|
||||
clearTimeout(timeout);
|
||||
if (!store.getDirty()) {
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved && (JSON.parse(saved) as RecoveryDraft).definitionId === (definitionId ?? null)) {
|
||||
localStorage.removeItem(storageKey);
|
||||
}
|
||||
} catch {
|
||||
/* Storage is optional. */
|
||||
}
|
||||
return;
|
||||
}
|
||||
timeout = setTimeout(() => {
|
||||
try {
|
||||
const draft = JSON.stringify({
|
||||
definitionId: definitionId ?? null,
|
||||
content: getCustomWidgetRecoveryContent(store.getValues()),
|
||||
} satisfies RecoveryDraft);
|
||||
if (draft.length <= MAX_RECOVERY_CHARACTERS) localStorage.setItem(storageKey, draft);
|
||||
} catch {
|
||||
// Quota limits and blocked storage must not interrupt the workbench.
|
||||
}
|
||||
}, 500);
|
||||
};
|
||||
const unsubscribe = store.subscribe(persist);
|
||||
if (store.getDirty()) persist();
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [definitionId, recovery, storageKey, store]);
|
||||
|
||||
const dismissRecovery = () => {
|
||||
if (storageKey) {
|
||||
try {
|
||||
localStorage.removeItem(storageKey);
|
||||
} catch {
|
||||
/* Storage is optional. */
|
||||
}
|
||||
}
|
||||
setRecovery(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap="sm" mb="md">
|
||||
{recovery && (
|
||||
<Alert title={t("recoveryTitle")}>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{t("recoveryDescription")}</Text>
|
||||
<Group gap="xs">
|
||||
<Button
|
||||
size="xs"
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
form.setValues({ ...store.getValues(), ...recovery.content, secrets: [] });
|
||||
dismissRecovery();
|
||||
}}
|
||||
>
|
||||
{t("restore")}
|
||||
</Button>
|
||||
<Button size="xs" type="button" variant="subtle" onClick={dismissRecovery}>
|
||||
{t("discard")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
<Group gap="xs">
|
||||
<Button
|
||||
type="button"
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
leftSection={<IconArrowBackUp size={16} />}
|
||||
disabled={disabled || !history.canUndo}
|
||||
onClick={() => restoreHistory("undo")}
|
||||
aria-keyshortcuts="Control+Z Meta+Z"
|
||||
>
|
||||
{t("undo")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
leftSection={<IconArrowForwardUp size={16} />}
|
||||
disabled={disabled || !history.canRedo}
|
||||
onClick={() => restoreHistory("redo")}
|
||||
aria-keyshortcuts="Control+Shift+Z Meta+Shift+Z"
|
||||
>
|
||||
{t("redo")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
leftSection={<IconRestore size={16} />}
|
||||
disabled={disabled || !dirty}
|
||||
onClick={() => form.setValues(store.resetToSaved())}
|
||||
>
|
||||
{t("reset")}
|
||||
</Button>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("credentialsExcluded")}
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -201,7 +201,7 @@ interface CustomWidgetPreviewSectionProps {
|
||||
onSizeChange(size: string): void;
|
||||
optionsSnapshot: Record<string, unknown>;
|
||||
onOptionsChange: Dispatch<SetStateAction<Record<string, unknown>>>;
|
||||
onLiveActionsChange(enabled: boolean): void;
|
||||
onLiveActionsChange(enabled: boolean, sessionId: string): void;
|
||||
}
|
||||
|
||||
export function CustomWidgetPreviewSection(props: CustomWidgetPreviewSectionProps) {
|
||||
|
||||
@@ -13,10 +13,17 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import type { UseFormReturnType } from "@mantine/form";
|
||||
|
||||
import {
|
||||
customWidgetSourcesSchema,
|
||||
getCustomWidgetRequiredSecretKinds,
|
||||
hasSameCustomWidgetSourceBinding,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import { customWidgetFormSchema } from "@homarr/custom-widgets/workbench";
|
||||
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
||||
|
||||
import { areCustomWidgetValuesEqual } from "./_custom-widget-value-equality";
|
||||
import { createCustomWidgetDocumentHistory, getCustomWidgetDocumentContent } from "./_custom-widget-document-history";
|
||||
import type { CustomWidgetDocumentContent, CustomWidgetDocumentHistoryState } from "./_custom-widget-document-history";
|
||||
|
||||
export interface CustomWidgetFormDocumentStore {
|
||||
getValues(): CustomWidgetFormValues;
|
||||
@@ -24,6 +31,10 @@ export interface CustomWidgetFormDocumentStore {
|
||||
getDirty(): boolean;
|
||||
subscribe(listener: () => void): () => void;
|
||||
markSaved(values: CustomWidgetFormValues): void;
|
||||
getHistory(): CustomWidgetDocumentHistoryState;
|
||||
undo(): CustomWidgetFormValues | null;
|
||||
redo(): CustomWidgetFormValues | null;
|
||||
resetToSaved(): CustomWidgetFormValues;
|
||||
}
|
||||
|
||||
const documentValueKeys = customWidgetFormSchema.keyof().options;
|
||||
@@ -42,19 +53,58 @@ export function createCustomWidgetFormDocumentStore(
|
||||
let values = initialValues;
|
||||
let persistedValues = initialValues;
|
||||
let dirty = false;
|
||||
const history = createCustomWidgetDocumentHistory(initialValues);
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const notify = () => listeners.forEach((listener) => listener());
|
||||
const restore = (content: CustomWidgetDocumentContent | null): CustomWidgetFormValues | null => {
|
||||
if (!content) return null;
|
||||
let secrets: CustomWidgetFormValues["secrets"] = [];
|
||||
try {
|
||||
const sources = customWidgetSourcesSchema.parse(JSON.parse(content.sources));
|
||||
const currentSources = customWidgetSourcesSchema.parse(JSON.parse(values.sources));
|
||||
secrets = values.secrets.filter((secret) => {
|
||||
const source = sources[secret.sourceId];
|
||||
const currentSource = currentSources[secret.sourceId];
|
||||
if (!source || !currentSource || !hasSameCustomWidgetSourceBinding(source, currentSource)) return false;
|
||||
const auth = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
return getCustomWidgetRequiredSecretKinds(auth).some((kind) => kind === secret.kind);
|
||||
});
|
||||
} catch {
|
||||
// An unfinished source document cannot safely retain credential bindings.
|
||||
}
|
||||
const restored = { ...content, secrets };
|
||||
values = restored;
|
||||
dirty = !areDocumentValuesEqual(restored, persistedValues);
|
||||
notify();
|
||||
return restored;
|
||||
};
|
||||
|
||||
return {
|
||||
getValues: () => values,
|
||||
setValues: (nextValues) => {
|
||||
if (Object.is(values, nextValues)) return;
|
||||
history.record(nextValues);
|
||||
values = nextValues;
|
||||
dirty = !areDocumentValuesEqual(nextValues, persistedValues);
|
||||
notify();
|
||||
},
|
||||
getDirty: () => dirty,
|
||||
getHistory: history.getState,
|
||||
undo: () => restore(history.undo()),
|
||||
redo: () => restore(history.redo()),
|
||||
resetToSaved: () => {
|
||||
history.stopCoalescing();
|
||||
const restored = {
|
||||
...getCustomWidgetDocumentContent(persistedValues),
|
||||
secrets: persistedValues.secrets.map((secret) => ({ ...secret, value: "" })),
|
||||
};
|
||||
history.record(restored);
|
||||
values = restored;
|
||||
dirty = !areDocumentValuesEqual(restored, persistedValues);
|
||||
notify();
|
||||
return restored;
|
||||
},
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
@@ -62,6 +112,7 @@ export function createCustomWidgetFormDocumentStore(
|
||||
markSaved: (savedValues) => {
|
||||
const wasDirty = dirty;
|
||||
persistedValues = savedValues;
|
||||
history.stopCoalescing();
|
||||
dirty = !areDocumentValuesEqual(values, persistedValues);
|
||||
if (wasDirty !== dirty) notify();
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useZodForm } from "@homarr/form";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CustomWidgetAdvancedManifest } from "./_custom-widget-advanced-manifest";
|
||||
import { CustomWidgetDraftControls } from "./_custom-widget-draft-controls";
|
||||
import {
|
||||
CustomWidgetOptionsSnapshotSync,
|
||||
CustomWidgetSaveActions,
|
||||
@@ -111,19 +112,24 @@ const CustomWidgetFormView = memo(function CustomWidgetFormView(props: CustomWid
|
||||
[setMobilePane],
|
||||
);
|
||||
const handleLiveActionsChange = useCallback(
|
||||
(enabled: boolean) =>
|
||||
setPreview((current) => ({
|
||||
...current,
|
||||
session: current.session ? { ...current.session, liveActions: enabled } : null,
|
||||
})),
|
||||
(enabled: boolean, sessionId: string) =>
|
||||
setPreview((current) => {
|
||||
if (current.session?.id !== sessionId) return current;
|
||||
return { ...current, session: { ...current.session, liveActions: enabled } };
|
||||
}),
|
||||
[setPreview],
|
||||
);
|
||||
|
||||
return (
|
||||
<CustomWidgetFormDocumentProvider store={documentStore}>
|
||||
<CustomWidgetFormAnalysisProvider>
|
||||
<form onSubmit={props.onSubmit} className={classes.form}>
|
||||
<form onSubmit={props.onSubmit} className={classes.form} data-custom-widget-workbench>
|
||||
<CustomWidgetUnsavedChangesGuard />
|
||||
<CustomWidgetDraftControls
|
||||
form={form}
|
||||
definitionId={props.definitionId}
|
||||
disabled={props.savePending || props.previewPending}
|
||||
/>
|
||||
<CustomWidgetOptionsSnapshotSync setOptionsSnapshot={props.setOptionsSnapshot} />
|
||||
<SegmentedControl
|
||||
className={classes.paneSwitcher}
|
||||
|
||||
@@ -89,7 +89,7 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
|
||||
}
|
||||
actions={
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{widget.valid && (
|
||||
{!widget.migrationRequired && (
|
||||
<Button
|
||||
component={Link}
|
||||
href={`/manage/custom-widgets/edit/${widget.id}`}
|
||||
@@ -97,7 +97,17 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
|
||||
size="sm"
|
||||
leftSection={<IconPencil size={16} stroke={1.5} />}
|
||||
>
|
||||
{tCommon("action.edit")}
|
||||
{widget.valid ? tCommon("action.edit") : t("workbench.repair.title")}
|
||||
</Button>
|
||||
)}
|
||||
{widget.valid && (
|
||||
<Button
|
||||
component={Link}
|
||||
href={`/manage/custom-widgets/packages/convert/${widget.id}`}
|
||||
variant="light"
|
||||
size="sm"
|
||||
>
|
||||
{t("package.conversion.shortTitle")}
|
||||
</Button>
|
||||
)}
|
||||
<CustomWidgetRowActions
|
||||
|
||||
@@ -47,7 +47,7 @@ export function createPreviewDisplayData({
|
||||
})),
|
||||
previewSessionId: preview.session?.id,
|
||||
previewLiveActions: preview.session?.liveActions ?? false,
|
||||
queriesDisabled: fixture !== "live",
|
||||
queriesDisabled: fixture !== "live" || !preview.session,
|
||||
isEditMode: fixture !== "live",
|
||||
};
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export interface PreviewState {
|
||||
status: Record<string, unknown>;
|
||||
session: { id: string; expiresAt: number; liveActions: boolean } | null;
|
||||
outcome: PreviewOutcome;
|
||||
stale?: boolean;
|
||||
}
|
||||
|
||||
interface PreviewPanelProps {
|
||||
@@ -36,7 +37,7 @@ interface PreviewPanelProps {
|
||||
onSizeChange(value: string): void;
|
||||
optionsSnapshot: Record<string, unknown>;
|
||||
onOptionsChange(value: Record<string, unknown>): void;
|
||||
onLiveActionsChange(enabled: boolean): void;
|
||||
onLiveActionsChange(enabled: boolean, sessionId: string): void;
|
||||
}
|
||||
|
||||
function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
|
||||
@@ -131,6 +132,7 @@ function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
|
||||
]}
|
||||
/>
|
||||
</Group>
|
||||
{props.preview.stale && <Alert color="yellow">{t("staleSnapshot")}</Alert>}
|
||||
{candidate && (
|
||||
<PreviewResult
|
||||
outcome={props.preview.outcome}
|
||||
@@ -203,11 +205,12 @@ function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
|
||||
disabled={!props.preview.session || liveActionsMutation.isPending}
|
||||
onChange={(event) => {
|
||||
if (!props.preview.session) return;
|
||||
const sessionId = props.preview.session.id;
|
||||
const enabled = event.currentTarget.checked;
|
||||
liveActionsMutation.mutate(
|
||||
{ sessionId: props.preview.session.id, enabled },
|
||||
{
|
||||
onSuccess: () => props.onLiveActionsChange(enabled),
|
||||
onSuccess: () => props.onLiveActionsChange(enabled, sessionId),
|
||||
onError: (error) => showErrorNotification({ title: t("liveActions"), message: error.message }),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, Group, Stack, Text, Title } from "@mantine/core";
|
||||
import { parse } from "superjson";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
|
||||
function readStored(value: string): unknown {
|
||||
try {
|
||||
return parse(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function CustomWidgetRepair({ definition }: { definition: RouterOutputs["customWidget"]["getRaw"] }) {
|
||||
const t = useI18n("customWidget.workbench.repair");
|
||||
const [source, setSource] = useState(() =>
|
||||
JSON.stringify(
|
||||
{
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: definition.name,
|
||||
description: definition.description ?? undefined,
|
||||
iconUrl: definition.iconUrl ?? undefined,
|
||||
sources: readStored(definition.sources),
|
||||
requests: readStored(definition.requests),
|
||||
options: readStored(definition.options),
|
||||
template: definition.template,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
const [error, setError] = useState("");
|
||||
const repair = clientApi.customWidget.repair.useMutation();
|
||||
const save = async () => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(source);
|
||||
const widget = customWidgetDefinitionSchema.parse(parsed);
|
||||
const result = await repair.mutateAsync({ id: definition.id, widget });
|
||||
window.location.assign(result.managementPath);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
const download = () => {
|
||||
const url = URL.createObjectURL(new Blob([source], { type: "application/json" }));
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `${definition.id}-repair.json`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
return (
|
||||
<Stack>
|
||||
<Title>
|
||||
{t("title")}: {definition.name}
|
||||
</Title>
|
||||
<Alert color="yellow">
|
||||
<Text>{t("description")}</Text>
|
||||
{definition.issues.map((issue, index) => (
|
||||
<Text size="sm" key={index}>
|
||||
{issue.path}: {issue.message}
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
<CodeEditor
|
||||
id="repair-source"
|
||||
label={t("source")}
|
||||
language="json"
|
||||
value={source}
|
||||
onChange={setSource}
|
||||
height="60vh"
|
||||
/>
|
||||
<Group>
|
||||
<Button loading={repair.isPending} onClick={() => void save()}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
<Button variant="default" onClick={download}>
|
||||
{t("export")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+16
-3
@@ -24,7 +24,7 @@ export function CustomWidgetRequestsEditor({
|
||||
const parsed = parseJson(form.values.requests);
|
||||
const entries = isRecord(parsed) ? Object.entries(parsed) : [];
|
||||
const sources = parseJson(form.values.sources);
|
||||
const sourceIds = isRecord(sources) ? Object.keys(sources) : ["default"];
|
||||
const sourceIds = isRecord(sources) ? Object.keys(sources) : [];
|
||||
const options = parseJson(form.values.options);
|
||||
const optionNames = isRecord(options) ? Object.keys(options) : [];
|
||||
|
||||
@@ -41,13 +41,20 @@ export function CustomWidgetRequestsEditor({
|
||||
commit(next);
|
||||
};
|
||||
const add = () => {
|
||||
const source = sourceIds[0];
|
||||
if (!source) return;
|
||||
let suffix = entries.length + 1;
|
||||
while (entries.some(([id]) => id === `request-${suffix}`)) suffix += 1;
|
||||
commit([...entries, [`request-${suffix}`, { path: "/api/data" }]]);
|
||||
commit([...entries, [`request-${suffix}`, { source, path: "/api/data" }]]);
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
{sourceIds.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("sourceRequired")}
|
||||
</Text>
|
||||
)}
|
||||
{entries.map(([id, rawRequest], index) => {
|
||||
const request = isRecord(rawRequest) ? rawRequest : {};
|
||||
const kind = request.kind === "action" ? "action" : "query";
|
||||
@@ -212,7 +219,13 @@ export function CustomWidgetRequestsEditor({
|
||||
</Fieldset>
|
||||
);
|
||||
})}
|
||||
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={add}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={add}
|
||||
disabled={sourceIds.length === 0 || entries.length >= 64}
|
||||
>
|
||||
{t("addRequest")}
|
||||
</Button>
|
||||
{form.errors.requests && (
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
|
||||
|
||||
import type { CustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
|
||||
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
|
||||
|
||||
export function applyCustomWidgetSavedState(
|
||||
form: CustomWidgetWorkbenchForm,
|
||||
store: CustomWidgetFormDocumentStore,
|
||||
submitted: CustomWidgetFormValues,
|
||||
) {
|
||||
const savedValues = {
|
||||
...submitted,
|
||||
secrets: submitted.secrets.map((secret) => {
|
||||
if (!secret.value.trim()) return secret;
|
||||
return { ...secret, value: "", hasValue: true };
|
||||
}),
|
||||
};
|
||||
const currentValues = store.getValues();
|
||||
form.setInitialValues(savedValues);
|
||||
form.setValues({
|
||||
...currentValues,
|
||||
secrets: currentValues.secrets.map((secret) => {
|
||||
const saved = submitted.secrets.find((entry) => entry.sourceId === secret.sourceId && entry.kind === secret.kind);
|
||||
if (!saved?.value.trim() || saved.value !== secret.value) return secret;
|
||||
return { ...secret, value: "", hasValue: true };
|
||||
}),
|
||||
});
|
||||
form.resetDirty();
|
||||
store.markSaved(savedValues);
|
||||
}
|
||||
+2
-2
@@ -3,14 +3,14 @@ import { isRecord } from "@homarr/common";
|
||||
export function getDependentRequestIds(requestsJson: string, sourceId: string) {
|
||||
const requests = parseRequestRecord(requestsJson);
|
||||
return Object.entries(requests).flatMap(([requestId, request]) =>
|
||||
isRecord(request) && request.source === sourceId ? [requestId] : [],
|
||||
isRecord(request) && (request.source ?? "default") === sourceId ? [requestId] : [],
|
||||
);
|
||||
}
|
||||
|
||||
export function removeDependentRequests(requestsJson: string, sourceId: string) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(parseRequestRecord(requestsJson)).filter(
|
||||
([, request]) => !isRecord(request) || request.source !== sourceId,
|
||||
([, request]) => !isRecord(request) || (request.source ?? "default") !== sourceId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
+12
-13
@@ -57,13 +57,13 @@ export function CustomWidgetSourceField({
|
||||
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
|
||||
return (
|
||||
<Fieldset legend={index === 0 ? t("primary") : source.name}>
|
||||
<Fieldset legend={source.name ?? source.id}>
|
||||
<Stack gap="sm">
|
||||
<Group grow align="start">
|
||||
<CustomWidgetIdentifierInput
|
||||
label={t("id")}
|
||||
value={source.id}
|
||||
disabled={source.id === "default" || Boolean(definitionId)}
|
||||
disabled={Boolean(definitionId)}
|
||||
error={form.errors.sources}
|
||||
onCommit={(value) => onUpdate(index, { id: value })}
|
||||
/>
|
||||
@@ -118,6 +118,7 @@ export function CustomWidgetSourceField({
|
||||
return (
|
||||
<Group key={kind} align="end" wrap="nowrap">
|
||||
<Input
|
||||
data-custom-widget-secret
|
||||
style={{ flex: 1 }}
|
||||
label={tSecret(kind)}
|
||||
value={secret?.value ?? ""}
|
||||
@@ -139,17 +140,15 @@ export function CustomWidgetSourceField({
|
||||
</Group>
|
||||
);
|
||||
})}
|
||||
{index > 0 && (
|
||||
<Button
|
||||
type="button"
|
||||
color="red"
|
||||
variant="subtle"
|
||||
leftSection={<IconTrash size={16} />}
|
||||
onClick={() => onRemove(index)}
|
||||
>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
color="red"
|
||||
variant="subtle"
|
||||
leftSection={<IconTrash size={16} />}
|
||||
onClick={() => onRemove(index)}
|
||||
>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Fieldset>
|
||||
);
|
||||
|
||||
+19
-13
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Button, List, Stack, Text } from "@mantine/core";
|
||||
import { Button, List, Stack, Text } from "@mantine/core";
|
||||
import { IconPlus } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
@@ -55,7 +55,9 @@ export function CustomWidgetSourcesEditor({
|
||||
? Object.fromEntries(
|
||||
Object.entries(parsedRequests).map(([id, request]) => [
|
||||
id,
|
||||
isRecord(request) && request.source === previousId ? { ...request, source: nextId } : request,
|
||||
isRecord(request) && (request.source ?? "default") === previousId
|
||||
? { ...request, source: nextId }
|
||||
: request,
|
||||
]),
|
||||
)
|
||||
: {};
|
||||
@@ -100,7 +102,7 @@ export function CustomWidgetSourcesEditor({
|
||||
{
|
||||
name: t("newName", { count: sources.length + 1 }),
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: sources.length === 0 ? "public" : "private",
|
||||
networkScope: "private",
|
||||
auth: "none",
|
||||
},
|
||||
],
|
||||
@@ -164,6 +166,11 @@ export function CustomWidgetSourcesEditor({
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
{sources.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("empty")}
|
||||
</Text>
|
||||
)}
|
||||
{sources.map((source, index) => {
|
||||
return (
|
||||
<CustomWidgetSourceField
|
||||
@@ -181,16 +188,15 @@ export function CustomWidgetSourcesEditor({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<Accordion variant="contained">
|
||||
<Accordion.Item value="advanced">
|
||||
<Accordion.Control>{t("advanced")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={addSource}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={addSource}
|
||||
disabled={sources.length >= 8}
|
||||
>
|
||||
{t("add")}
|
||||
</Button>
|
||||
{form.errors.sources && (
|
||||
<Text c="red" size="xs">
|
||||
{form.errors.sources}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { Tabs } from "@mantine/core";
|
||||
import { IconApi, IconBuildingStore } from "@tabler/icons-react";
|
||||
import { IconApi, IconBuildingStore, IconPackage } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
const tabs = {
|
||||
packages: "/manage/custom-widgets/packages",
|
||||
installed: "/manage/custom-widgets",
|
||||
workshop: "/manage/custom-widgets/workshop",
|
||||
} as const;
|
||||
@@ -18,6 +19,13 @@ export const CustomWidgetTabs = ({ active }: { active: keyof typeof tabs }) => {
|
||||
return (
|
||||
<Tabs value={tabs[active]}>
|
||||
<Tabs.List aria-label={t("ariaLabel")}>
|
||||
<Tabs.Tab
|
||||
value={tabs.packages}
|
||||
leftSection={<IconPackage size={16} stroke={1.5} />}
|
||||
renderRoot={(props) => <Link href={tabs.packages} {...props} />}
|
||||
>
|
||||
{t("packages")}
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value={tabs.installed}
|
||||
leftSection={<IconApi size={16} stroke={1.5} />}
|
||||
|
||||
+26
-13
@@ -24,6 +24,7 @@ import { extractCustomWidgetSaveIssues } from "./_custom-widget-save-errors";
|
||||
import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
|
||||
import { clearSaveIssues, reportSaveIssues } from "./_custom-widget-save-issue-utils";
|
||||
import type { CustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
|
||||
import { applyCustomWidgetSavedState } from "./_custom-widget-save-state";
|
||||
|
||||
interface FormActionsInput {
|
||||
mode: "create" | "edit";
|
||||
@@ -44,14 +45,22 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
const createMutation = clientApi.customWidget.create.useMutation();
|
||||
const updateMutation = clientApi.customWidget.update.useMutation();
|
||||
const previewMutation = clientApi.customWidget.previewCreate.useMutation();
|
||||
const discardPreviewMutation = clientApi.customWidget.previewDiscard.useMutation();
|
||||
const discardPreview = discardPreviewMutation.mutate;
|
||||
const [saveIssues, setSaveIssues] = useState<CustomWidgetSaveIssue[]>([]);
|
||||
const [previewPending, setPreviewPending] = useState(false);
|
||||
const setPreview = input.setPreview;
|
||||
const previewGeneration = useRef(0);
|
||||
const activePreviewGeneration = useRef<number | null>(null);
|
||||
const activeSessionId = useRef<string | null>(null);
|
||||
const discardCurrentSession = useCallback(() => {
|
||||
const sessionId = activeSessionId.current;
|
||||
activeSessionId.current = null;
|
||||
if (sessionId) discardPreview({ sessionId });
|
||||
}, [discardPreview]);
|
||||
const invalidatePreview = useCallback(() => {
|
||||
previewGeneration.current += 1;
|
||||
if (activePreviewGeneration.current !== null) return;
|
||||
discardCurrentSession();
|
||||
setPreview((preview) => {
|
||||
if (
|
||||
preview.outcome === "idle" &&
|
||||
@@ -60,9 +69,9 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
Object.keys(preview.status).length === 0
|
||||
)
|
||||
return preview;
|
||||
return { data: {}, status: {}, session: null, outcome: "idle" };
|
||||
return { ...preview, session: null, outcome: "idle", stale: true };
|
||||
});
|
||||
}, [setPreview]);
|
||||
}, [discardCurrentSession, setPreview]);
|
||||
useLayoutEffect(() => {
|
||||
invalidatePreview();
|
||||
}, [input.optionsSnapshot, invalidatePreview]);
|
||||
@@ -71,8 +80,9 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
() => () => {
|
||||
previewGeneration.current += 1;
|
||||
activePreviewGeneration.current = null;
|
||||
discardCurrentSession();
|
||||
},
|
||||
[],
|
||||
[discardCurrentSession],
|
||||
);
|
||||
let actionLabel = tCommon("action.save");
|
||||
if (input.mode === "create") actionLabel = tCommon("action.create");
|
||||
@@ -100,9 +110,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
title: tCommon("action.create"),
|
||||
message: t("notification.created", { name: values.name }),
|
||||
});
|
||||
input.form.setInitialValues(values);
|
||||
input.form.resetDirty();
|
||||
input.documentStore.markSaved(values);
|
||||
applyCustomWidgetSavedState(input.form, input.documentStore, values);
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||
window.location.assign(result.managementPath);
|
||||
} else if (input.definitionId) {
|
||||
@@ -116,9 +124,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
utils.customWidget.get.invalidate({ id: input.definitionId }),
|
||||
utils.widget.customApi.getData.invalidate(),
|
||||
]);
|
||||
input.form.setInitialValues(values);
|
||||
input.form.resetDirty();
|
||||
input.documentStore.markSaved(values);
|
||||
applyCustomWidgetSavedState(input.form, input.documentStore, values);
|
||||
showSuccessNotification({
|
||||
title: tCommon("action.save"),
|
||||
message: t("notification.updated", { name: values.name }),
|
||||
@@ -157,11 +163,12 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
}
|
||||
const secretsAtStart = getChangedSecrets(valuesAtStart);
|
||||
const generation = previewGeneration.current + 1;
|
||||
discardCurrentSession();
|
||||
previewGeneration.current = generation;
|
||||
activePreviewGeneration.current = generation;
|
||||
const isCurrent = () => previewGeneration.current === generation;
|
||||
input.setMobilePane("preview");
|
||||
input.setPreview({ data: {}, status: {}, session: null, outcome: "loading" });
|
||||
input.setPreview((current) => ({ ...current, session: null, outcome: "loading" }));
|
||||
setPreviewPending(true);
|
||||
try {
|
||||
const created = await previewMutation.mutateAsync({
|
||||
@@ -170,7 +177,11 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
options: optionsAtStart,
|
||||
secrets: secretsAtStart,
|
||||
});
|
||||
if (!isCurrent()) return;
|
||||
if (!isCurrent()) {
|
||||
discardPreview({ sessionId: created.previewSession.id });
|
||||
return;
|
||||
}
|
||||
activeSessionId.current = created.previewSession.id;
|
||||
const snapshot = await loadPreviewQueries(candidateAtStart.data, created.previewSession.id);
|
||||
if (!isCurrent()) return;
|
||||
const failed = Object.values(snapshot.status).filter((status) => isRecord(status) && status.ok === false).length;
|
||||
@@ -178,6 +189,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
...snapshot,
|
||||
session: created.previewSession,
|
||||
outcome: failed > 0 ? "error" : "success",
|
||||
stale: false,
|
||||
});
|
||||
if (failed > 0) {
|
||||
showWarningNotification({
|
||||
@@ -198,13 +210,14 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
}
|
||||
} catch {
|
||||
if (!isCurrent()) return;
|
||||
discardCurrentSession();
|
||||
input.setPreview((current) => ({ ...current, outcome: "error" }));
|
||||
showErrorNotification({ title: w("section.preview"), message: t("notification.previewError") });
|
||||
} finally {
|
||||
if (activePreviewGeneration.current === generation) {
|
||||
activePreviewGeneration.current = null;
|
||||
setPreviewPending(false);
|
||||
if (!isCurrent()) setPreview({ data: {}, status: {}, session: null, outcome: "idle" });
|
||||
if (!isCurrent()) setPreview((current) => ({ ...current, session: null, outcome: "idle", stale: true }));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Container, Stack, Title } from "@mantine/core";
|
||||
import { Button, Container, Group, Stack, Title } from "@mantine/core";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
@@ -8,6 +10,7 @@ import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
||||
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
|
||||
import { CustomWidgetBetaBanner } from "../../_beta-banner";
|
||||
import { CustomWidgetForm } from "../../_custom-widget-form";
|
||||
import { CustomWidgetRepair } from "../../_custom-widget-repair";
|
||||
import { FormErrorBoundary } from "../../_form-error-boundary";
|
||||
|
||||
interface EditCustomWidgetPageProps {
|
||||
@@ -20,14 +23,27 @@ export default async function EditCustomWidgetPage(props: EditCustomWidgetPagePr
|
||||
redirect("/manage/custom-widgets");
|
||||
}
|
||||
const params = await props.params;
|
||||
const raw = await api.customWidget.getRaw({ id: params.id }).catch(catchTrpcNotFound);
|
||||
if (raw.issues.length > 0)
|
||||
return (
|
||||
<Container fluid>
|
||||
<CustomWidgetRepair definition={raw} />
|
||||
</Container>
|
||||
);
|
||||
const definition = await api.customWidget.get({ id: params.id }).catch(catchTrpcNotFound);
|
||||
const t = await getI18n("customWidget.package.conversion");
|
||||
|
||||
return (
|
||||
<>
|
||||
<DynamicBreadcrumb dynamicMappings={new Map([[params.id, definition.name]])} nonInteractable={["edit"]} />
|
||||
<Container fluid>
|
||||
<Stack>
|
||||
<Title>{definition.name}</Title>
|
||||
<Group justify="space-between">
|
||||
<Title>{definition.name}</Title>
|
||||
<Button component={Link} href={`/manage/custom-widgets/packages/convert/${params.id}`} variant="light">
|
||||
{t("title")}
|
||||
</Button>
|
||||
</Group>
|
||||
<CustomWidgetBetaBanner />
|
||||
<FormErrorBoundary>
|
||||
<CustomWidgetForm
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Container, Stack } from "@mantine/core";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
|
||||
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
||||
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
|
||||
import { PackageWorkspace } from "../_package-workspace";
|
||||
|
||||
export default async function WidgetPackagePage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
searchParams: Promise<{ boardId?: string }>;
|
||||
}) {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const { id } = await params;
|
||||
const { boardId } = await searchParams;
|
||||
const installation = await api.customWidget.package.get({ id }).catch(catchTrpcNotFound);
|
||||
return (
|
||||
<Container fluid>
|
||||
<DynamicBreadcrumb dynamicMappings={new Map([[id, installation.name]])} />
|
||||
<Stack>
|
||||
<PackageWorkspace installation={installation} userId={session.user.id} initialBoardId={boardId} />
|
||||
</Stack>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Accordion, Select, Stack, Text } from "@mantine/core";
|
||||
import type { CustomWidgetArtifact } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
|
||||
export function PackageArtifactReview({ artifact }: { artifact: CustomWidgetArtifact }) {
|
||||
const t = useI18n("customWidget.package.artifactReview");
|
||||
const [selected, setSelected] = useState("dependency-lock.json");
|
||||
const files: Record<string, string> = { "dependency-lock.json": JSON.stringify(artifact.dependencyLock, null, 2) };
|
||||
for (const [surface, compiled] of Object.entries(artifact.client)) {
|
||||
if (!compiled) continue;
|
||||
files[`${surface}.js`] = compiled.javascript;
|
||||
if (compiled.css) files[`${surface}.css`] = compiled.css;
|
||||
}
|
||||
if (artifact.server) files["server.js"] = artifact.server;
|
||||
const path = Object.hasOwn(files, selected) ? selected : "dependency-lock.json";
|
||||
return (
|
||||
<Accordion>
|
||||
<Accordion.Item value="artifact">
|
||||
<Accordion.Control>{t("title")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{t("description")}</Text>
|
||||
<Text size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
|
||||
{artifact.digest}
|
||||
</Text>
|
||||
<Select
|
||||
label={t("file")}
|
||||
value={path}
|
||||
data={Object.keys(files)}
|
||||
onChange={(value) => {
|
||||
if (value) setSelected(value);
|
||||
}}
|
||||
/>
|
||||
<CodeEditor
|
||||
id={`artifact-${artifact.digest}-${path}`}
|
||||
label={path}
|
||||
value={files[path] ?? ""}
|
||||
language={path.endsWith(".json") ? "json" : path.endsWith(".css") ? "css" : "tsx"}
|
||||
readOnly
|
||||
height="320px"
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { HOST_WIDGET_MODULES } from "@homarr/custom-widgets/package";
|
||||
|
||||
/** Public authoring context only. Local bindings and runtime response data never belong here. */
|
||||
export const packageAssistantSdkContext = {
|
||||
schema: "homarr-widget-package-v3",
|
||||
sdkVersion: "1",
|
||||
hostModules: HOST_WIDGET_MODULES,
|
||||
package:
|
||||
"widget.json contains $schema, manifest, dependencies, connections, options; files are edited separately. manifest requires id, name, version (exact semver), sdkVersion:'1', entrypoints:{tile,advanced?,configuration?,server?}. Each client surface default-exports a React component. Local relative modules and CSS imports work. dependencies maps npm names to exact versions. No request, connection or server file is required for static widgets. Declare connections as named {label,kind:'http'|'integration'|'service',optional?}; service requirements also declare serviceType. Owners bind local settings and encrypted secrets. Never embed credentials, local addresses or connection IDs in portable source.",
|
||||
styling:
|
||||
"Use normal TSX, React hooks, imported Mantine components, CSS and reusable modules. manifest.styles defaults to scoped CSS; 'global' is an explicit package choice. Build dashboard tiles and advanced views; there is no standalone application route. Respect host.visibleWidth/visibleHeight, colorScheme, locale, reducedMotion and isEditMode. Entry points may reuse the same component and branch on displayMode.",
|
||||
client:
|
||||
"Import @homarr/widget-sdk. useWidgetHost() returns displayMode:'compact'|'advanced',width,height,visibleWidth,visibleHeight,displayScale,visible,isPreview,isEditMode,locale,timeZone,colorScheme,reducedMotion. useWidgetOptions<T>() returns option values. useWidgetState<T>(key,initial) shares instance state between tile and advanced. useWidgetClock(intervalMs=1000) returns epoch milliseconds or null, pauses when hidden. useWidgetQuery<T>(name,input?,{enabled?,refetchInterval?,staleTime?}) returns query state. useWidgetAction<Output,Input>(name) returns mutation (mutate/mutateAsync). useWidgetSubscription<T>(name,input?,{enabled?,maximumEvents?}) returns data,events,error,connected,reconnect. useWidgetStorage<T>('user'|'instance'|'installation',key,initial) returns data,set,saving,saveError. useWidgetCommands([{id,label,run,disabled?,destructive?}]) registers native menu commands. WidgetScope name/handlerPrefix/options isolates composed components.",
|
||||
services:
|
||||
"useWidgetServices() exposes notify({title,message?,color?}), navigate(href), openAdvanced(), closeAdvanced(), openDetail({title,content:ReactNode}), closeDetail(), confirm({title,message,destructive?}):Promise<boolean>, updateOptions(record):Promise<void>. Use updateOptions from an authored configuration surface. Managed storage is isolated memory in preview. Query results and local options are not part of Assistant context.",
|
||||
server:
|
||||
"Optional server.ts imports @homarr/widget-sdk/server and default-exports defineWidgetServer({handler:async(input,context)=>value}). Declare every handler in manifest.handlers with kind:'query'|'action'|'subscription'|'migration', permission:'view'|'modify'|'full', inputSchema? (JSON Schema), guestAccess?; actions default to modify. fetchWidgetConnection<T>(context,{connection:'slot',path,method?,query?,body?,responseType?}) returns {data,ok,status,contentType,durationMs,updatedAt}. getWidgetConnection<TSettings>(context,{connection,serviceType?}) returns {configuration:{kind,serviceType?,settings?:TSettings,...},secrets:Record<string,string>} only to trusted server code for Node SQL, MQTT, SSH, files or other service clients; never return secrets to browser queries. getWidgetServerContext(context) returns options,installationId,bindingNames,isPreview. callWidgetIntegration(context,{connection,capability,input?}) invokes native adapters; subscribeWidgetIntegration yields native stream events. callWidgetRunner and subscribeWidgetRunner address owner-managed remote runners. Server modules have trusted Node capabilities. Secrets stay in owner-bound connections. Do not invent integration capabilities: use reference packages or declared capability docs.",
|
||||
lifecycle:
|
||||
"Proposals only change the visible draft after explicit review; they never save, trust, run or activate code. The owner saves the draft, reviews dependencies and trust, runs exact-candidate Preview, then explicitly activates the saved release for all placements. SDK actions are simulated in default previews, but arbitrary trusted browser/Node code still executes. A preview session proves compilation/session creation only, not successful UI rendering, live action success or all application behavior. Any source/options/binding edit invalidates preview evidence.",
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { Button, Divider, Group, Popover, Stack, Text, Textarea } from "@mantine/core";
|
||||
import { IconSparkles } from "@tabler/icons-react";
|
||||
import { useState } from "react";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
|
||||
|
||||
export function PackageAssistant() {
|
||||
const t = useI18n("customWidget.package.assistant");
|
||||
const assistant = useOptionalHomarrAssistant();
|
||||
const [request, setRequest] = useState("");
|
||||
const [opened, setOpened] = useState(false);
|
||||
if (!assistant?.enabled) return null;
|
||||
const send = (intent: string) => {
|
||||
assistant.open();
|
||||
if (
|
||||
assistant.sendPrompt(
|
||||
`${intent}\nWork on the currently visible trusted widget package v3 draft. First call read_widget_package_draft, then propose_widget_package_changes against its exact revision. Read relevant source examples through that tool when helpful. Keep credentials in local connections. Propose reviewable changes; do not save, activate, install or claim preview success.`,
|
||||
)
|
||||
) {
|
||||
setOpened(false);
|
||||
setRequest("");
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Popover opened={opened} onChange={setOpened} width={320} withinPortal position="bottom-start">
|
||||
<Popover.Target>
|
||||
<Button size="xs" variant="light" leftSection={<IconSparkles size={14} />} disabled={assistant.isRunning}>
|
||||
{t("open")}
|
||||
</Button>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown>
|
||||
<Text size="xs" c="dimmed" mb="xs">
|
||||
{t("context")}
|
||||
</Text>
|
||||
<Textarea
|
||||
mx="xs"
|
||||
mb="xs"
|
||||
label={t("request")}
|
||||
placeholder={t("requestPlaceholder")}
|
||||
value={request}
|
||||
onChange={(event) => setRequest(event.currentTarget.value)}
|
||||
minRows={3}
|
||||
/>
|
||||
<Group px="xs" pb="xs">
|
||||
<Button size="xs" disabled={!request.trim()} onClick={() => send(request)}>
|
||||
{t("send")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Divider my="xs" />
|
||||
<Stack gap={4}>
|
||||
<Button variant="subtle" size="xs" justify="start" onClick={() => send(t("improvePrompt"))}>
|
||||
{t("improve")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" justify="start" onClick={() => send(t("advancedPrompt"))}>
|
||||
{t("advanced")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" justify="start" onClick={() => send(t("fixPrompt"))}>
|
||||
{t("fix")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Group,
|
||||
NumberInput,
|
||||
Paper,
|
||||
Select,
|
||||
Stack,
|
||||
Text,
|
||||
Textarea,
|
||||
TextInput,
|
||||
} 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");
|
||||
const collectors = clientApi.customWidget.package.collectors.useQuery({ itemId });
|
||||
const save = clientApi.customWidget.package.saveCollector.useMutation();
|
||||
const [name, setName] = useState("");
|
||||
const [handler, setHandler] = useState<string | null>(queries[0] ?? null);
|
||||
const [input, setInput] = useState("{}");
|
||||
const [valuePath, setValuePath] = useState("");
|
||||
const [unit, setUnit] = useState("");
|
||||
const [intervalSeconds, setIntervalSeconds] = useState(60);
|
||||
const [retentionDays, setRetentionDays] = useState(7);
|
||||
const [maximumPoints, setMaximumPoints] = useState(2000);
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const submit = () => {
|
||||
if (!handler) return;
|
||||
try {
|
||||
const params: unknown = JSON.parse(input);
|
||||
save.mutate(
|
||||
{
|
||||
itemId,
|
||||
name,
|
||||
handler,
|
||||
input: params,
|
||||
valuePath,
|
||||
unit,
|
||||
intervalSeconds,
|
||||
retentionDays,
|
||||
maximumPoints,
|
||||
enabled,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setName("");
|
||||
setEnabled(false);
|
||||
void collectors.refetch();
|
||||
},
|
||||
onError: (cause) => setError(cause.message),
|
||||
},
|
||||
);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Stack>
|
||||
<Text size="sm">{t("collectionDescription")}</Text>
|
||||
{(collectors.data ?? []).map((collector) => (
|
||||
<CollectorRow key={collector.id} collector={collector} onChange={() => void collectors.refetch()} />
|
||||
))}
|
||||
{queries.length > 0 && (
|
||||
<Paper withBorder p="sm">
|
||||
<Stack gap="xs">
|
||||
<TextInput
|
||||
label={t("collectorName")}
|
||||
value={name}
|
||||
onChange={(event) => setName(event.currentTarget.value)}
|
||||
/>
|
||||
<Select label={t("queryHandler")} data={queries} value={handler} onChange={setHandler} />
|
||||
<Textarea label={t("queryInput")} value={input} onChange={(event) => setInput(event.currentTarget.value)} />
|
||||
<TextInput
|
||||
label={t("valuePath")}
|
||||
value={valuePath}
|
||||
onChange={(event) => setValuePath(event.currentTarget.value)}
|
||||
/>
|
||||
<TextInput label={t("unit")} value={unit} onChange={(event) => setUnit(event.currentTarget.value)} />
|
||||
<Group grow>
|
||||
<NumberInput
|
||||
label={t("collectionInterval")}
|
||||
value={intervalSeconds}
|
||||
min={15}
|
||||
max={86400}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setIntervalSeconds(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
label={t("retentionDays")}
|
||||
value={retentionDays}
|
||||
min={1}
|
||||
max={365}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setRetentionDays(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
label={t("maximumPoints")}
|
||||
value={maximumPoints}
|
||||
min={10}
|
||||
max={10000}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setMaximumPoints(value);
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
<Checkbox
|
||||
label={t("enableCollection")}
|
||||
checked={enabled}
|
||||
onChange={(event) => setEnabled(event.currentTarget.checked)}
|
||||
/>
|
||||
<Button loading={save.isPending} disabled={!name.trim() || !handler} onClick={submit}>
|
||||
{t("saveCollector")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
{collectors.error && <Alert color="red">{collectors.error.message}</Alert>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function CollectorRow({
|
||||
collector,
|
||||
onChange,
|
||||
}: {
|
||||
collector: RouterOutputs["customWidget"]["package"]["collectors"][number];
|
||||
onChange(): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const save = clientApi.customWidget.package.saveCollector.useMutation();
|
||||
const remove = clientApi.customWidget.package.removeCollector.useMutation();
|
||||
const history = clientApi.widget.customApi.packageHistory.useQuery({
|
||||
itemId: collector.itemId,
|
||||
collectorId: collector.id,
|
||||
maximumPoints: 20,
|
||||
});
|
||||
const [discard, setDiscard] = useState(false);
|
||||
return (
|
||||
<Paper withBorder p="sm">
|
||||
<Stack gap="xs">
|
||||
<Text fw={500}>{collector.name}</Text>
|
||||
<Text size="xs">
|
||||
{collector.handler} · {collector.intervalSeconds}s · {collector.unit}
|
||||
</Text>
|
||||
<Text size="xs" ff="monospace">
|
||||
{collector.id}
|
||||
</Text>
|
||||
<Group>
|
||||
<Button
|
||||
variant="light"
|
||||
size="xs"
|
||||
loading={save.isPending}
|
||||
onClick={() => save.mutate({ ...collector, enabled: !collector.enabled }, { onSuccess: onChange })}
|
||||
>
|
||||
{collector.enabled ? t("pauseCollection") : t("enableCollection")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" onClick={() => void history.refetch()}>
|
||||
{t("refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
{history.data && <PackageHistorySummary data={history.data} />}
|
||||
<Checkbox
|
||||
checked={discard}
|
||||
onChange={(event) => setDiscard(event.currentTarget.checked)}
|
||||
label={t("discardCollectedHistory")}
|
||||
/>
|
||||
<Button
|
||||
variant="subtle"
|
||||
color="red"
|
||||
disabled={!discard}
|
||||
loading={remove.isPending}
|
||||
onClick={() =>
|
||||
remove.mutate({ itemId: collector.itemId, id: collector.id, discardHistory: true }, { onSuccess: onChange })
|
||||
}
|
||||
>
|
||||
{t("removeCollector")}
|
||||
</Button>
|
||||
{save.error && <Alert color="red">{save.error.message}</Alert>}
|
||||
{remove.error && <Alert color="red">{remove.error.message}</Alert>}
|
||||
{history.error && <Alert color="red">{history.error.message}</Alert>}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Alert, Badge, Group, Stack, Text } from "@mantine/core";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
type Diagnostic = RouterOutputs["customWidget"]["package"]["diagnoseConnection"];
|
||||
|
||||
export function PackageConnectionDiagnostic({ result }: { result: Diagnostic }) {
|
||||
const t = useI18n("customWidget.package.diagnostic");
|
||||
let color = "yellow";
|
||||
if (["connected", "integration", "fileReadable", "transportReachable"].includes(result.status)) color = "green";
|
||||
if (["dnsError", "unavailable", "httpError", "serviceUnavailable"].includes(result.status)) color = "red";
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Alert color={color} title={t(`status.${result.status}`)}>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{t(`help.${result.status}`)}</Text>
|
||||
{"stage" in result && (
|
||||
<Text size="xs">
|
||||
{t("phase", { phase: t(`stage.${result.stage as "dns" | "connection" | "tls" | "response"}`) })}
|
||||
</Text>
|
||||
)}
|
||||
{"hostname" in result && (
|
||||
<Text size="sm" ff="monospace">
|
||||
{result.hostname}
|
||||
</Text>
|
||||
)}
|
||||
{result.addresses.length > 0 && (
|
||||
<Group gap="xs">
|
||||
{result.addresses.map(({ address }) => (
|
||||
<Badge key={address} variant="outline" tt="none">
|
||||
{address}
|
||||
</Badge>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
{"httpStatus" in result && typeof result.httpStatus === "number" && typeof result.durationMs === "number" && (
|
||||
<Text size="xs">{t("response", { status: result.httpStatus, milliseconds: result.durationMs })}</Text>
|
||||
)}
|
||||
{"sampleFields" in result && Array.isArray(result.sampleFields) && result.sampleFields.length > 0 && (
|
||||
<Text size="xs">{t("fields", { fields: result.sampleFields.join(", ") })}</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Alert>
|
||||
<Accordion>
|
||||
<Accordion.Item value="details">
|
||||
<Accordion.Control>{t("details")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", overflowWrap: "anywhere" }}>
|
||||
{JSON.stringify(result, null, 2)}
|
||||
</Text>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
NumberInput,
|
||||
Paper,
|
||||
PasswordInput,
|
||||
Select,
|
||||
Stack,
|
||||
Text,
|
||||
Textarea,
|
||||
TextInput,
|
||||
} 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"];
|
||||
export function ConnectionEditor({ onSaved, connection }: { onSaved(): void; connection?: Connection }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const integrations = clientApi.integration.all.useQuery();
|
||||
const save = clientApi.customWidget.package.saveConnection.useMutation();
|
||||
const configuration = isRecord(connection?.configuration) ? connection.configuration : {};
|
||||
const tls = isRecord(configuration.tls) ? configuration.tls : {};
|
||||
let initialAuth: Authentication = "none";
|
||||
if (typeof configuration.auth === "string" && authKinds.includes(configuration.auth))
|
||||
initialAuth = configuration.auth as Authentication;
|
||||
let initialKind: "http" | "integration" | "service" = "http";
|
||||
if (configuration.kind === "integration") initialKind = "integration";
|
||||
if (configuration.kind === "service") initialKind = "service";
|
||||
const [name, setName] = useState(connection?.name ?? "");
|
||||
const [kind, setKind] = useState<"http" | "integration" | "service">(initialKind);
|
||||
const [integrationId, setIntegrationId] = useState<string | null>(connection?.integrationId ?? null);
|
||||
const [baseUrl, setBaseUrl] = useState(typeof configuration.baseUrl === "string" ? configuration.baseUrl : "");
|
||||
const [browserUrl, setBrowserUrl] = useState(
|
||||
typeof configuration.browserUrl === "string" ? configuration.browserUrl : "",
|
||||
);
|
||||
const [auth, setAuth] = useState<Authentication>(initialAuth);
|
||||
const [secret, setSecret] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [headers, setHeaders] = useState("{}");
|
||||
const [verifyTls, setVerifyTls] = useState(tls.rejectUnauthorized !== false);
|
||||
const [timeoutMs, setTimeoutMs] = useState(
|
||||
typeof configuration.timeoutMs === "number" ? configuration.timeoutMs : 30_000,
|
||||
);
|
||||
const [serviceType, setServiceType] = useState(
|
||||
typeof configuration.serviceType === "string" ? configuration.serviceType : "custom",
|
||||
);
|
||||
const [serviceSettings, setServiceSettings] = useState(JSON.stringify(configuration.settings ?? {}, null, 2));
|
||||
const [serviceSecrets, setServiceSecrets] = useState("");
|
||||
const [replaceServiceSecrets, setReplaceServiceSecrets] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const serverUrlSuggestion = getConnectionUrlSuggestion(baseUrl);
|
||||
const browserUrlSuggestion = getConnectionUrlSuggestion(browserUrl);
|
||||
const submit = async () => {
|
||||
try {
|
||||
let secrets: Record<string, string> = {};
|
||||
if (auth === "basic") secrets = { username, password: secret };
|
||||
if (auth === "bearer") secrets = { token: secret };
|
||||
if (auth === "cookie") secrets = { cookie: secret };
|
||||
if (auth === "headers" || auth === "query") {
|
||||
const parsed: unknown = JSON.parse(headers);
|
||||
if (!isRecord(parsed) || Object.values(parsed).some((value) => typeof value !== "string"))
|
||||
throw new Error(t("stringMap"));
|
||||
secrets = parsed as Record<string, string>;
|
||||
}
|
||||
let settings: Record<string, WidgetJson> | undefined;
|
||||
if (kind === "service") {
|
||||
const parsed: unknown = JSON.parse(serviceSettings);
|
||||
if (!isRecord(parsed)) throw new Error(t("serviceSettingsObject"));
|
||||
settings = parsed as Record<string, WidgetJson>;
|
||||
const credentials: unknown = JSON.parse(serviceSecrets || "{}");
|
||||
if (!isRecord(credentials) || Object.values(credentials).some((value) => typeof value !== "string"))
|
||||
throw new Error(t("stringMap"));
|
||||
secrets = credentials as Record<string, string>;
|
||||
}
|
||||
let replaceSecrets = !connection || initialAuth !== auth || secret !== "" || username !== "" || headers !== "{}";
|
||||
if (kind === "service")
|
||||
replaceSecrets = !connection || initialKind !== kind || serviceSecrets !== "" || replaceServiceSecrets;
|
||||
let secretUpdates: Record<string, string> | undefined;
|
||||
if (
|
||||
connection &&
|
||||
kind === "http" &&
|
||||
initialKind === kind &&
|
||||
initialAuth === auth &&
|
||||
["basic", "bearer", "cookie"].includes(auth) &&
|
||||
replaceSecrets
|
||||
) {
|
||||
secretUpdates = Object.fromEntries(Object.entries(secrets).filter(([, value]) => value !== ""));
|
||||
replaceSecrets = false;
|
||||
}
|
||||
await save.mutateAsync({
|
||||
id: connection?.id,
|
||||
name,
|
||||
integrationId,
|
||||
configuration: {
|
||||
kind,
|
||||
serviceType: kind === "service" ? serviceType : undefined,
|
||||
settings,
|
||||
baseUrl: kind === "http" ? baseUrl || undefined : undefined,
|
||||
browserUrl: browserUrl || undefined,
|
||||
auth,
|
||||
headers: isRecord(configuration.headers)
|
||||
? Object.fromEntries(
|
||||
Object.entries(configuration.headers).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === "string",
|
||||
),
|
||||
)
|
||||
: {},
|
||||
tls: {
|
||||
rejectUnauthorized: verifyTls,
|
||||
ca: typeof tls.ca === "string" ? tls.ca : undefined,
|
||||
cert: typeof tls.cert === "string" ? tls.cert : undefined,
|
||||
},
|
||||
maxResponseBytes:
|
||||
typeof configuration.maxResponseBytes === "number" ? configuration.maxResponseBytes : undefined,
|
||||
timeoutMs,
|
||||
},
|
||||
secrets: replaceSecrets ? secrets : undefined,
|
||||
secretUpdates,
|
||||
});
|
||||
setSecret("");
|
||||
setHeaders("{}");
|
||||
onSaved();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{connection ? t("editConnection") : t("newConnection")}</Text>
|
||||
{connection && <Alert color="yellow">{t("editConnectionImpact")}</Alert>}
|
||||
<TextInput
|
||||
label={t("connectionName")}
|
||||
required
|
||||
value={name}
|
||||
onChange={(event) => setName(event.currentTarget.value)}
|
||||
/>
|
||||
<Select
|
||||
label={t("connectionKind")}
|
||||
value={kind}
|
||||
data={[
|
||||
{ value: "http", label: "HTTP" },
|
||||
{ value: "integration", label: t("integration") },
|
||||
{ value: "service", label: t("service") },
|
||||
]}
|
||||
onChange={(value) => {
|
||||
if (value === "http" || value === "integration" || value === "service") setKind(value);
|
||||
}}
|
||||
/>
|
||||
{kind === "integration" && (
|
||||
<Select
|
||||
searchable
|
||||
label={t("integration")}
|
||||
data={(integrations.data ?? []).map((integration) => ({ value: integration.id, label: integration.name }))}
|
||||
value={integrationId}
|
||||
onChange={setIntegrationId}
|
||||
/>
|
||||
)}
|
||||
{kind === "service" && (
|
||||
<>
|
||||
<TextInput
|
||||
label={t("serviceType")}
|
||||
description={t("serviceTypeHelp")}
|
||||
value={serviceType}
|
||||
onChange={(event) => setServiceType(event.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
<Textarea
|
||||
label={t("serviceSettings")}
|
||||
description={t("serviceSettingsHelp")}
|
||||
value={serviceSettings}
|
||||
onChange={(event) => setServiceSettings(event.currentTarget.value)}
|
||||
autosize
|
||||
minRows={4}
|
||||
maxRows={12}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<Textarea
|
||||
label={t("serviceSecrets")}
|
||||
description={t("serviceSecretsHelp")}
|
||||
value={serviceSecrets}
|
||||
onChange={(event) => setServiceSecrets(event.currentTarget.value)}
|
||||
autosize
|
||||
minRows={3}
|
||||
maxRows={8}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{connection && (
|
||||
<Checkbox
|
||||
label={t("replaceServiceSecrets")}
|
||||
checked={replaceServiceSecrets}
|
||||
onChange={(event) => setReplaceServiceSecrets(event.currentTarget.checked)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{kind === "http" && (
|
||||
<>
|
||||
<TextInput
|
||||
label={t("serverUrl")}
|
||||
description={t("localNetwork")}
|
||||
placeholder={t("serverUrlExample")}
|
||||
required
|
||||
value={baseUrl}
|
||||
onChange={(event) => setBaseUrl(event.currentTarget.value)}
|
||||
/>
|
||||
{serverUrlSuggestion && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
w="fit-content"
|
||||
onClick={() => setBaseUrl(serverUrlSuggestion)}
|
||||
>
|
||||
{t("useUrlSuggestion", { url: serverUrlSuggestion })}
|
||||
</Button>
|
||||
)}
|
||||
<TextInput
|
||||
label={t("browserUrl")}
|
||||
value={browserUrl}
|
||||
onChange={(event) => setBrowserUrl(event.currentTarget.value)}
|
||||
/>
|
||||
{browserUrlSuggestion && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
w="fit-content"
|
||||
onClick={() => setBrowserUrl(browserUrlSuggestion)}
|
||||
>
|
||||
{t("useUrlSuggestion", { url: browserUrlSuggestion })}
|
||||
</Button>
|
||||
)}
|
||||
<Select
|
||||
label={t("authentication")}
|
||||
value={auth}
|
||||
data={["none", "basic", "bearer", "headers", "cookie", "query"]}
|
||||
onChange={(value) => {
|
||||
if (value && ["none", "basic", "bearer", "headers", "cookie", "query"].includes(value))
|
||||
setAuth(value as typeof auth);
|
||||
}}
|
||||
/>
|
||||
{auth === "basic" && (
|
||||
<TextInput
|
||||
autoComplete="off"
|
||||
label={t("username")}
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
{["basic", "bearer", "cookie"].includes(auth) && (
|
||||
<PasswordInput
|
||||
autoComplete="new-password"
|
||||
label={t("credential")}
|
||||
value={secret}
|
||||
onChange={(event) => setSecret(event.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
{(auth === "headers" || auth === "query") && (
|
||||
<Textarea
|
||||
autoComplete="off"
|
||||
label={auth === "query" ? t("secretQuery") : t("secretHeaders")}
|
||||
placeholder={t("headersExample")}
|
||||
value={headers}
|
||||
onChange={(event) => setHeaders(event.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
label={t("verifyTls")}
|
||||
checked={verifyTls}
|
||||
onChange={(event) => setVerifyTls(event.currentTarget.checked)}
|
||||
/>
|
||||
<NumberInput
|
||||
label={t("timeout")}
|
||||
value={timeoutMs}
|
||||
min={100}
|
||||
max={300000}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setTimeoutMs(value);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
<Button loading={save.isPending} disabled={!name.trim()} onClick={() => void submit()}>
|
||||
{t("saveConnection")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { ConnectionEditor } from "./_package-connection-editor";
|
||||
import { PackageConnectionDiagnostic } from "./_package-connection-diagnostic";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, Group, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export function PackageConnections({
|
||||
requirements,
|
||||
bindings,
|
||||
onChange,
|
||||
onSave,
|
||||
saving,
|
||||
onConnectionSaved,
|
||||
}: {
|
||||
requirements: CustomWidgetPackage["connections"];
|
||||
bindings: Record<string, string>;
|
||||
onChange(bindings: Record<string, string>): void;
|
||||
onSave?(): void;
|
||||
saving: boolean;
|
||||
onConnectionSaved?(): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const connections = clientApi.customWidget.package.connections.useQuery();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [diagnostic, setDiagnostic] = useState<RouterOutputs["customWidget"]["package"]["diagnoseConnection"] | null>(
|
||||
null,
|
||||
);
|
||||
const [diagnosticError, setDiagnosticError] = useState("");
|
||||
const diagnose = clientApi.customWidget.package.diagnoseConnection.useMutation();
|
||||
return (
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("connectionsDescription")}
|
||||
</Text>
|
||||
{Object.keys(requirements).length === 0 && <Alert>{t("noConnections")}</Alert>}
|
||||
{Object.entries(requirements).map(([name, requirement]) => (
|
||||
<Paper key={name} withBorder p="sm">
|
||||
<Group align="end">
|
||||
<Select
|
||||
flex={1}
|
||||
label={requirement.label}
|
||||
description={requirement.description}
|
||||
required={!requirement.optional}
|
||||
clearable
|
||||
searchable
|
||||
value={bindings[name] ?? null}
|
||||
data={(connections.data ?? [])
|
||||
.filter(
|
||||
(connection) =>
|
||||
isRecord(connection.configuration) &&
|
||||
isWidgetConnectionCompatible(requirement, connection.configuration),
|
||||
)
|
||||
.map((connection) => ({ value: connection.id, label: connection.name }))}
|
||||
onChange={(value) => {
|
||||
const next = { ...bindings };
|
||||
delete next[name];
|
||||
if (value) next[name] = value;
|
||||
onChange(next);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={!bindings[name]}
|
||||
loading={diagnose.isPending}
|
||||
onClick={() => {
|
||||
const id = bindings[name];
|
||||
if (!id) return;
|
||||
setDiagnostic(null);
|
||||
setDiagnosticError("");
|
||||
diagnose.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: setDiagnostic,
|
||||
onError: (error) => setDiagnosticError(error.message),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("diagnose")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="subtle"
|
||||
disabled={!bindings[name]}
|
||||
onClick={() => {
|
||||
setCreating(false);
|
||||
setEditingId(bindings[name] ?? null);
|
||||
}}
|
||||
>
|
||||
{t("editConnection")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Paper>
|
||||
))}
|
||||
{diagnostic && <PackageConnectionDiagnostic result={diagnostic} />}
|
||||
{diagnosticError && <Alert color="red">{diagnosticError}</Alert>}
|
||||
<Group>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
setEditingId(null);
|
||||
setCreating(!creating);
|
||||
}}
|
||||
>
|
||||
{t("newConnection")}
|
||||
</Button>
|
||||
{onSave && (
|
||||
<Button loading={saving} onClick={onSave}>
|
||||
{t("saveBindings")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
{(creating || editingId) && (
|
||||
<ConnectionEditor
|
||||
key={editingId ?? "new"}
|
||||
connection={connections.data?.find((entry) => entry.id === editingId)}
|
||||
onSaved={() => {
|
||||
setCreating(false);
|
||||
setEditingId(null);
|
||||
void connections.refetch();
|
||||
void utils.customWidget.package.guestGrants.invalidate();
|
||||
void utils.customWidget.package.webhooks.invalidate();
|
||||
onConnectionSaved?.();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Group, Stack, Text, TextInput, Title } from "@mantine/core";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
export function PackageConvert({ definitionId, name }: { definitionId: string; name: string }) {
|
||||
const t = useI18n("customWidget.package.conversion");
|
||||
const router = useRouter();
|
||||
const convert = clientApi.customWidget.package.convertV2.useMutation();
|
||||
const [nextName, setNextName] = useState(name);
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={2}>{t("title")}</Title>
|
||||
<Text>{t("description")}</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("savedSource")}
|
||||
</Text>
|
||||
<TextInput
|
||||
label={t("name")}
|
||||
value={nextName}
|
||||
maxLength={128}
|
||||
onChange={(event) => setNextName(event.currentTarget.value)}
|
||||
/>
|
||||
{convert.error && <Alert color="red">{convert.error.message}</Alert>}
|
||||
<Group>
|
||||
<Button
|
||||
disabled={!nextName.trim()}
|
||||
loading={convert.isPending}
|
||||
onClick={() =>
|
||||
convert.mutate(
|
||||
{ definitionId, name: nextName },
|
||||
{ onSuccess: (result) => router.push(result.managementPath) },
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("create")}
|
||||
</Button>
|
||||
<Button component={Link} href={`/manage/custom-widgets/edit/${definitionId}`} variant="subtle">
|
||||
{t("back")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export function PackageConvertedPlacements({
|
||||
id,
|
||||
origin,
|
||||
active,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
origin: string | null;
|
||||
active: boolean;
|
||||
onChange(): void;
|
||||
}) {
|
||||
let definitionId: string | undefined;
|
||||
try {
|
||||
const value: unknown = JSON.parse(origin ?? "null");
|
||||
if (isRecord(value) && value.kind === "converted-v2" && typeof value.definitionId === "string")
|
||||
definitionId = value.definitionId;
|
||||
} catch {
|
||||
/* Other package origins have no legacy placement migration. */
|
||||
}
|
||||
if (!definitionId) return null;
|
||||
return <ConvertedPlacementPicker id={id} definitionId={definitionId} active={active} onChange={onChange} />;
|
||||
}
|
||||
|
||||
function ConvertedPlacementPicker({
|
||||
id,
|
||||
definitionId,
|
||||
active,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
definitionId: string;
|
||||
active: boolean;
|
||||
onChange(): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package.conversion");
|
||||
const placements = clientApi.customWidget.package.legacyPlacements.useQuery({ definitionId }, { enabled: active });
|
||||
const migrate = clientApi.customWidget.package.migrateV2Placement.useMutation();
|
||||
const [itemId, setItemId] = useState<string | null>(null);
|
||||
const [replaced, setReplaced] = useState(false);
|
||||
return (
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="sm">
|
||||
<Text fw={600}>{t("replaceTitle")}</Text>
|
||||
<Text size="sm">{t("replaceDescription")}</Text>
|
||||
{!active && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("activateFirst")}
|
||||
</Text>
|
||||
)}
|
||||
{active && (
|
||||
<>
|
||||
<Select
|
||||
label={t("choosePlacement")}
|
||||
searchable
|
||||
value={itemId}
|
||||
onChange={(value) => {
|
||||
setItemId(value);
|
||||
setReplaced(false);
|
||||
}}
|
||||
data={(placements.data ?? []).map((placement) => ({
|
||||
value: placement.id,
|
||||
label: `${placement.boardName} · ${placement.id}`,
|
||||
}))}
|
||||
/>
|
||||
{placements.data?.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("noOriginalPlacements")}
|
||||
</Text>
|
||||
)}
|
||||
<Button
|
||||
disabled={!itemId}
|
||||
loading={migrate.isPending}
|
||||
onClick={() => {
|
||||
if (!itemId) return;
|
||||
migrate.mutate(
|
||||
{ id, itemId, definitionId },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setItemId(null);
|
||||
setReplaced(true);
|
||||
void placements.refetch();
|
||||
onChange();
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("replaceSelected")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{replaced && <Alert color="green">{t("replaced")}</Alert>}
|
||||
{(migrate.error || placements.error) && (
|
||||
<Alert color="red">{migrate.error?.message ?? placements.error?.message}</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createId, isRecord } from "@homarr/common";
|
||||
import { redactCustomWidgetCredentialLiterals } from "@homarr/custom-widgets/core";
|
||||
|
||||
export interface PackageDocument {
|
||||
name: string;
|
||||
metadata: string;
|
||||
files: Record<string, string>;
|
||||
}
|
||||
|
||||
export function documentFromSource(name: string, source: unknown): PackageDocument {
|
||||
if (!isRecord(source)) return { name, metadata: "{}", files: {} };
|
||||
const { files, _draftMetadata, ...metadata } = source;
|
||||
const document = { name, metadata: JSON.stringify(metadata, null, 2), files: {} as Record<string, string> };
|
||||
if (typeof _draftMetadata === "string") document.metadata = _draftMetadata;
|
||||
if (isRecord(files)) {
|
||||
for (const [path, content] of Object.entries(files))
|
||||
if (typeof content === "string") document.files[path] = content;
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
export function documentFromTemplate(name: string, source: unknown): PackageDocument {
|
||||
if (!isRecord(source) || !isRecord(source.manifest)) return documentFromSource(name, source);
|
||||
return documentFromSource(name, {
|
||||
...source,
|
||||
manifest: { ...source.manifest, id: `local.${createId()}`, name, version: "1.0.0" },
|
||||
});
|
||||
}
|
||||
|
||||
export function documentSource(document: PackageDocument): Record<string, unknown> {
|
||||
try {
|
||||
const metadata: unknown = JSON.parse(document.metadata);
|
||||
if (isRecord(metadata)) return { ...metadata, files: document.files };
|
||||
} catch {
|
||||
/* An incomplete manifest can still be saved as a draft. */
|
||||
}
|
||||
return { _draftMetadata: document.metadata, files: document.files };
|
||||
}
|
||||
|
||||
const redact = (text: string) =>
|
||||
redactCustomWidgetCredentialLiterals(text).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gu, "$1");
|
||||
|
||||
export function recoveryDocument(document: PackageDocument): PackageDocument {
|
||||
return {
|
||||
name: redact(document.name),
|
||||
metadata: redact(document.metadata),
|
||||
files: Object.fromEntries(Object.entries(document.files).map(([path, content]) => [path, redact(content)])),
|
||||
};
|
||||
}
|
||||
|
||||
export function downloadPackage(name: string, value: unknown) {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: "application/json" }));
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `${name.replace(/[^a-z0-9._-]+/giu, "-") || "widget"}.json`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export type PackageOperation = () => Promise<unknown>;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Alert, Group, Stack, Table, Text } from "@mantine/core";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
type History = RouterOutputs["widget"]["customApi"]["packageHistory"];
|
||||
|
||||
export function PackageHistorySummary({ data }: { data: History }) {
|
||||
const t = useI18n("customWidget.package.historySummary");
|
||||
const latest = data.samples.at(-1);
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
{latest && (
|
||||
<Group justify="space-between">
|
||||
<Text fw={600}>
|
||||
{formatCollectedValue(latest.value)} {data.unit}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("latest", { time: new Date(latest.timestamp).toLocaleString() })}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
{!latest && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("empty")}
|
||||
</Text>
|
||||
)}
|
||||
{"lastError" in data && data.lastError && <Alert color="yellow">{data.lastError}</Alert>}
|
||||
<Accordion multiple>
|
||||
<Accordion.Item value="samples">
|
||||
<Accordion.Control>{t("samples", { count: data.samples.length })}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<div style={{ maxHeight: 220, overflow: "auto" }}>
|
||||
<Table>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("time")}</Table.Th>
|
||||
<Table.Th>{t("value")}</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data.samples.toReversed().map((sample, index) => (
|
||||
<Table.Tr key={`${sample.timestamp}-${index}`}>
|
||||
<Table.Td>{new Date(sample.timestamp).toLocaleString()}</Table.Td>
|
||||
<Table.Td>
|
||||
{formatCollectedValue(sample.value)} {data.unit}
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</div>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
<Accordion.Item value="technical">
|
||||
<Accordion.Control>{t("details")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Text component="pre" size="xs" style={{ whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>
|
||||
{JSON.stringify(data, null, 2)}
|
||||
</Text>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function formatCollectedValue(value: unknown): string {
|
||||
if (typeof value === "number") return value.toLocaleString();
|
||||
if (typeof value === "string") return value.slice(0, 240);
|
||||
return (JSON.stringify(value) ?? "—").slice(0, 240);
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Accordion, Alert, Button, Group, Stack, Text, TextInput, Tooltip } from "@mantine/core";
|
||||
import {
|
||||
PackageLanguageClient,
|
||||
createPackageLanguageExtensions,
|
||||
} from "@homarr/custom-widgets/workbench/package-language";
|
||||
import type {
|
||||
PackageLanguageDiagnostic,
|
||||
PackageLanguageLocation,
|
||||
} from "@homarr/custom-widgets/workbench/package-language";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
import type { usePackageWorkspace } from "./_use-package-workspace";
|
||||
|
||||
export default function PackageLanguageEditor({ state }: { state: ReturnType<typeof usePackageWorkspace> }) {
|
||||
const t = useI18n("customWidget.package.languageService");
|
||||
const current = useRef(state);
|
||||
current.current = state;
|
||||
const [client, setClient] = useState<PackageLanguageClient>();
|
||||
const [diagnostics, setDiagnostics] = useState<PackageLanguageDiagnostic[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [checked, setChecked] = useState(false);
|
||||
const [definition, setDefinition] = useState<PackageLanguageLocation>();
|
||||
const [reveal, setReveal] = useState<PackageLanguageLocation>();
|
||||
const [rename, setRename] = useState<{ path: string; position: number; name: string; revision: number }>();
|
||||
const [operationPending, setOperationPending] = useState(false);
|
||||
useEffect(() => {
|
||||
try {
|
||||
const service = new PackageLanguageClient();
|
||||
setClient(service);
|
||||
return () => service.dispose();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
client?.update(state.document.files);
|
||||
}, [client, state.document.files]);
|
||||
useEffect(() => {
|
||||
setDefinition(undefined);
|
||||
setRename(undefined);
|
||||
setDiagnostics([]);
|
||||
setChecked(false);
|
||||
setError("");
|
||||
}, [state.selected]);
|
||||
const navigate = (location: PackageLanguageLocation) => {
|
||||
setReveal(location);
|
||||
if (location.declaration) setDefinition(location);
|
||||
else {
|
||||
setDefinition(undefined);
|
||||
current.current.setSelected(location.path);
|
||||
}
|
||||
};
|
||||
const extensions = useMemo(() => {
|
||||
if (!client || state.language !== "tsx") return undefined;
|
||||
const path = state.selected;
|
||||
return createPackageLanguageExtensions(client, path, {
|
||||
navigate,
|
||||
diagnostics: (next) => {
|
||||
if (current.current.selected !== path) return;
|
||||
setDiagnostics(next);
|
||||
setChecked(true);
|
||||
setError("");
|
||||
},
|
||||
error: (message) => {
|
||||
if (current.current.selected === path) setError(message);
|
||||
},
|
||||
rename: (position, name) => setRename({ path, position, name, revision: client.getRevision() }),
|
||||
});
|
||||
}, [client, state.language, state.selected]);
|
||||
const reportError = (cause: unknown) => {
|
||||
if (cause instanceof Error && cause.name === "AbortError") return;
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
};
|
||||
const format = async () => {
|
||||
if (!client) return;
|
||||
const path = state.selected;
|
||||
const submittedFiles = state.document.files;
|
||||
client.update(state.document.files);
|
||||
setOperationPending(true);
|
||||
try {
|
||||
const source = await client.request("format", { path });
|
||||
const latest = current.current;
|
||||
if (latest.selected !== path || latest.document.files !== submittedFiles) return;
|
||||
latest.edit({ ...latest.document, files: { ...latest.document.files, [path]: source } });
|
||||
} catch (cause) {
|
||||
reportError(cause);
|
||||
} finally {
|
||||
setOperationPending(false);
|
||||
}
|
||||
};
|
||||
const renameSymbol = async () => {
|
||||
if (!client || !rename) return;
|
||||
if (client.getRevision() !== rename.revision) {
|
||||
setError(t("changed"));
|
||||
return;
|
||||
}
|
||||
const submittedFiles = current.current.document.files;
|
||||
setOperationPending(true);
|
||||
try {
|
||||
const files = await client.request("rename", rename);
|
||||
const latest = current.current;
|
||||
if (latest.document.files !== submittedFiles) {
|
||||
setError(t("changed"));
|
||||
return;
|
||||
}
|
||||
latest.edit({ ...latest.document, files: { ...latest.document.files, ...files } });
|
||||
setRename(undefined);
|
||||
} catch (cause) {
|
||||
reportError(cause);
|
||||
} finally {
|
||||
setOperationPending(false);
|
||||
}
|
||||
};
|
||||
let status = t("loading");
|
||||
if (checked) status = t("ready");
|
||||
if (diagnostics.length) status = t("problems", { count: diagnostics.length });
|
||||
if (error) status = t("unavailable");
|
||||
let visiblePath = state.selected;
|
||||
let value = state.editorValue;
|
||||
let language = state.language;
|
||||
if (definition?.declaration) {
|
||||
visiblePath = definition.path;
|
||||
value = definition.declaration.source;
|
||||
language = "tsx";
|
||||
}
|
||||
let range: { from: number; to: number } | undefined;
|
||||
if (reveal?.path === visiblePath) range = reveal;
|
||||
return (
|
||||
<Stack gap="xs" miw={0}>
|
||||
{rename && (
|
||||
<Group align="end" gap="xs">
|
||||
<TextInput
|
||||
label={t("rename")}
|
||||
value={rename.name}
|
||||
onChange={(event) => setRename({ ...rename, name: event.currentTarget.value })}
|
||||
/>
|
||||
<Button size="sm" loading={operationPending} disabled={state.busy} onClick={() => void renameSymbol()}>
|
||||
{t("applyRename")}
|
||||
</Button>
|
||||
<Button size="sm" variant="subtle" onClick={() => setRename(undefined)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
{definition?.declaration && (
|
||||
<Group justify="space-between" gap="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("declaration", { line: definition.declaration.line })}
|
||||
</Text>
|
||||
<Button size="compact-xs" variant="subtle" onClick={() => setDefinition(undefined)}>
|
||||
{t("backToSource")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
<CodeEditor
|
||||
key={visiblePath}
|
||||
id="package-source"
|
||||
label={visiblePath}
|
||||
language={language}
|
||||
value={value}
|
||||
hideHistoryActions
|
||||
readOnly={state.busy || operationPending || Boolean(definition?.declaration)}
|
||||
height="max(280px, calc(100dvh - 310px))"
|
||||
extensions={definition?.declaration ? undefined : extensions}
|
||||
revealRange={range}
|
||||
onFormat={state.language === "tsx" && client ? () => void format() : undefined}
|
||||
status={
|
||||
state.language === "tsx" &&
|
||||
!definition?.declaration && (
|
||||
<Tooltip label={t("help")} multiline maw={380}>
|
||||
<Text size="xs" c="dimmed">
|
||||
{status}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
onChange={(next) => {
|
||||
if (state.selected === "/widget.json") state.edit({ ...state.document, metadata: next }, state.selected);
|
||||
else
|
||||
state.edit(
|
||||
{ ...state.document, files: { ...state.document.files, [state.selected]: next } },
|
||||
state.selected,
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
<Alert color="yellow" title={t("unavailable")}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
{!definition && diagnostics.length > 0 && (
|
||||
<Accordion variant="default">
|
||||
<Accordion.Item value="types">
|
||||
<Accordion.Control>{t("problems", { count: diagnostics.length })}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap={4}>
|
||||
{diagnostics.slice(0, 20).map((diagnostic, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant="subtle"
|
||||
size="compact-xs"
|
||||
justify="start"
|
||||
styles={{ label: { whiteSpace: "normal", textAlign: "start" } }}
|
||||
onClick={() => navigate(diagnostic)}
|
||||
>
|
||||
{`TS${diagnostic.code}: ${diagnostic.message}`}
|
||||
</Button>
|
||||
))}
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Alert, Badge, Button, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { IconPackage, IconUpload } 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";
|
||||
|
||||
export function PackageList({ initialData }: { initialData: RouterOutputs["customWidget"]["package"]["list"] }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const installations = clientApi.customWidget.package.list.useQuery(undefined, { initialData });
|
||||
const [filter, setFilter] = useState("");
|
||||
const filtered = (installations.data ?? []).filter((entry) =>
|
||||
entry.name.toLowerCase().includes(filter.toLowerCase()),
|
||||
);
|
||||
return (
|
||||
<Stack>
|
||||
<Text c="dimmed">{t("libraryDescription")}</Text>
|
||||
<TextInput label={t("search")} value={filter} onChange={(event) => setFilter(event.currentTarget.value)} />
|
||||
{filtered.length === 0 && <Alert>{t("empty")}</Alert>}
|
||||
<ManageCollectionList ariaLabel={t("title")}>
|
||||
{filtered.map((entry) => {
|
||||
let status = t("draftOnly");
|
||||
let color = "gray";
|
||||
if (entry.activeArtifactId) {
|
||||
status = t("disabled");
|
||||
if (entry.enabled) {
|
||||
status = t("active");
|
||||
color = "green";
|
||||
}
|
||||
}
|
||||
return (
|
||||
<ManageCollectionItem
|
||||
key={entry.id}
|
||||
leading={<IconPackage size={26} stroke={1.4} />}
|
||||
title={<Text fw={600}>{entry.name}</Text>}
|
||||
badges={
|
||||
<Badge color={color} variant="light">
|
||||
{status}
|
||||
</Badge>
|
||||
}
|
||||
description={
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("placements", { count: entry.placementCount })}
|
||||
</Text>
|
||||
}
|
||||
actions={
|
||||
<Button component={Link} href={`/manage/custom-widgets/packages/${entry.id}`} variant="default">
|
||||
{t("openWorkspace")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</ManageCollectionList>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export function PackageImportButton() {
|
||||
const t = useI18n("customWidget.package");
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const save = clientApi.customWidget.package.saveDraft.useMutation();
|
||||
const importArchive = clientApi.customWidget.package.import.useMutation();
|
||||
const importCollection = clientApi.customWidget.package.importCollection.useMutation();
|
||||
const importing = useRef(false);
|
||||
const [reading, setReading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const importFile = async (file: File) => {
|
||||
if (importing.current) return;
|
||||
importing.current = true;
|
||||
setReading(true);
|
||||
setError("");
|
||||
try {
|
||||
if (file.size > WIDGET_COLLECTION_MAX_BYTES) throw new Error(t("collections.importTooLarge"));
|
||||
const raw: unknown = JSON.parse(await file.text());
|
||||
if (!isRecord(raw)) throw new Error(t("invalidPackage"));
|
||||
if (raw.format === "homarr-widget-collection-v1") {
|
||||
const result = await importCollection.mutateAsync({ archive: raw });
|
||||
window.location.assign(`/manage/custom-widgets/packages/collections/${result.importId}`);
|
||||
return;
|
||||
}
|
||||
if (file.size > 25_000_000) throw new Error(t("importTooLarge"));
|
||||
if (raw.format === "homarr-widget-archive-v3") {
|
||||
const result = await importArchive.mutateAsync({ archive: customWidgetArchiveSchema.parse(raw) });
|
||||
window.location.assign(result.managementPath);
|
||||
return;
|
||||
}
|
||||
let source = raw;
|
||||
if (isRecord(raw.source)) source = raw.source;
|
||||
let name = file.name.replace(/\.json$/iu, "");
|
||||
if (isRecord(source.manifest) && typeof source.manifest.name === "string") name = source.manifest.name;
|
||||
const result = await save.mutateAsync({ name, source });
|
||||
window.location.assign(result.managementPath);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
} finally {
|
||||
importing.current = false;
|
||||
setReading(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<input
|
||||
ref={input}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0];
|
||||
event.currentTarget.value = "";
|
||||
if (file) void importFile(file);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="default"
|
||||
leftSection={<IconUpload size={16} />}
|
||||
loading={reading || save.isPending || importArchive.isPending || importCollection.isPending}
|
||||
onClick={() => input.current?.click()}
|
||||
>
|
||||
{t("import")}
|
||||
</Button>
|
||||
{error && (
|
||||
<Alert color="red" withCloseButton onClose={() => setError("")}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Alert, Button, Skeleton, Stack } from "@mantine/core";
|
||||
|
||||
import type { widgetReferencePackages } from "@homarr/widget-sdk/examples";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { PackageWorkspace } from "./_package-workspace";
|
||||
|
||||
export function NativePackageWorkspace({
|
||||
userId,
|
||||
sourceItemId,
|
||||
starter,
|
||||
}: {
|
||||
userId: string;
|
||||
sourceItemId: string;
|
||||
starter: keyof typeof widgetReferencePackages;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const preparation = clientApi.customWidget.package.prepareNative.useMutation();
|
||||
const prepare = preparation.mutate;
|
||||
const started = useRef(false);
|
||||
useEffect(() => {
|
||||
if (started.current) return;
|
||||
started.current = true;
|
||||
prepare({ sourceItemId, starter });
|
||||
}, [prepare, sourceItemId, starter]);
|
||||
if (preparation.data)
|
||||
return (
|
||||
<PackageWorkspace
|
||||
userId={userId}
|
||||
initialSource={preparation.data.source}
|
||||
initialName={preparation.data.name}
|
||||
initialBindings={preparation.data.bindings}
|
||||
initialBoardId={preparation.data.sourceBoardId}
|
||||
/>
|
||||
);
|
||||
if (preparation.error)
|
||||
return (
|
||||
<Stack>
|
||||
<Alert color="red">{preparation.error.message}</Alert>
|
||||
<Button onClick={() => prepare({ sourceItemId, starter })}>{t("retryPreparation")}</Button>
|
||||
</Stack>
|
||||
);
|
||||
return (
|
||||
<Stack>
|
||||
<Skeleton height={50} />
|
||||
<Skeleton height={400} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { Accordion, Alert, Button, Checkbox, Group, Paper, Stack, Text } from "@mantine/core";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { customWidgetPackageSchema, stringifyWidgetJson } from "@homarr/custom-widgets/package";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { PackageOptionFields } from "@homarr/widgets/custom-api/package-option-fields";
|
||||
|
||||
import { AddPackagePlacement, PackagePlacements } from "./_package-placements";
|
||||
import type { PackageOperation } from "./_package-document";
|
||||
import { PackageWorkshop } from "./_package-workshop";
|
||||
import { PackageTransfer } from "./_package-transfer";
|
||||
import { PackageArtifactReview } from "./_package-artifact-review";
|
||||
import { PackageConvertedPlacements } from "./_package-converted-placements";
|
||||
import { downloadPackage } from "./_package-document";
|
||||
|
||||
type Installation = RouterOutputs["customWidget"]["package"]["get"];
|
||||
|
||||
export function PackageOperations({
|
||||
installation,
|
||||
initialBoardId,
|
||||
source,
|
||||
options,
|
||||
setOptions,
|
||||
dirty,
|
||||
trusted,
|
||||
onError,
|
||||
onMessage,
|
||||
}: {
|
||||
installation?: Installation;
|
||||
initialBoardId?: string;
|
||||
source?: CustomWidgetPackage;
|
||||
options: Record<string, unknown>;
|
||||
setOptions(options: Record<string, unknown>): void;
|
||||
dirty: boolean;
|
||||
trusted: boolean;
|
||||
onError(error: string): void;
|
||||
onMessage(message: string): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const details = clientApi.customWidget.package.get.useQuery(
|
||||
{ id: installation?.id ?? "" },
|
||||
{ enabled: Boolean(installation), initialData: installation },
|
||||
);
|
||||
const current = details.data;
|
||||
const matchesReviewedSource = useMemo(() => {
|
||||
if (!source) return false;
|
||||
const saved = customWidgetPackageSchema.safeParse(current?.source);
|
||||
return saved.success && stringifyWidgetJson(saved.data) === stringifyWidgetJson(source);
|
||||
}, [current?.source, source]);
|
||||
const inspected = clientApi.customWidget.package.inspectArtifact.useQuery(
|
||||
{ id: installation?.id ?? "" },
|
||||
{ enabled: Boolean(installation) },
|
||||
);
|
||||
const activate = clientApi.customWidget.package.activate.useMutation();
|
||||
const rollback = clientApi.customWidget.package.rollback.useMutation();
|
||||
const enable = clientApi.customWidget.package.setEnabled.useMutation();
|
||||
const exported = clientApi.customWidget.package.export.useQuery(
|
||||
{ id: installation?.id ?? "" },
|
||||
{ enabled: Boolean(current?.activeArtifactId) },
|
||||
);
|
||||
const activeSource = useMemo(() => customWidgetPackageSchema.safeParse(exported.data?.source), [exported.data]);
|
||||
const [rollbackConfirmed, setRollbackConfirmed] = useState(false);
|
||||
const refresh = async () => {
|
||||
await Promise.all([
|
||||
utils.customWidget.package.get.invalidate(),
|
||||
utils.customWidget.package.list.invalidate(),
|
||||
utils.customWidget.package.export.invalidate(),
|
||||
utils.customWidget.package.guestGrants.invalidate(),
|
||||
utils.customWidget.package.webhooks.invalidate(),
|
||||
utils.customWidget.package.inspectArtifact.invalidate(),
|
||||
utils.widget.customApi.getData.invalidate(),
|
||||
]);
|
||||
};
|
||||
const run = async (action: PackageOperation, message: string) => {
|
||||
try {
|
||||
await action();
|
||||
await refresh();
|
||||
onMessage(message);
|
||||
} catch (error) {
|
||||
onError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Stack>
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("previewOptions")}</Text>
|
||||
{source && <PackageOptionFields schema={source.options} value={options} onChange={setOptions} />}
|
||||
<Button variant="subtle" onClick={() => setOptions({})}>
|
||||
{t("resetOptions")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
{!current && <Alert>{t("saveFirst")}</Alert>}
|
||||
{current && (
|
||||
<>
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("activation")}</Text>
|
||||
<Text size="sm">{t("activationDescription", { count: current.placements.length })}</Text>
|
||||
<Text size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
|
||||
{t("activeArtifact")}: {current.activeArtifactId ?? t("none")}
|
||||
</Text>
|
||||
{dirty && <Alert color="yellow">{t("saveBeforeActivate")}</Alert>}
|
||||
{!dirty && !matchesReviewedSource && <Alert color="yellow">{t("savedSourceChanged")}</Alert>}
|
||||
{inspected.data?.artifact && <PackageArtifactReview artifact={inspected.data.artifact} />}
|
||||
{inspected.error && <Alert color="red">{inspected.error.message}</Alert>}
|
||||
<Group>
|
||||
<Button
|
||||
disabled={dirty || !trusted || !source || !matchesReviewedSource}
|
||||
loading={activate.isPending}
|
||||
onClick={() =>
|
||||
void run(
|
||||
() =>
|
||||
activate.mutateAsync({
|
||||
id: current.id,
|
||||
trusted: true,
|
||||
expectedDraftDigest: current.draftDigest,
|
||||
}),
|
||||
t("activated"),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("activate")}
|
||||
</Button>
|
||||
{current.activeArtifactId && (
|
||||
<Button
|
||||
variant="default"
|
||||
loading={enable.isPending}
|
||||
onClick={() =>
|
||||
void run(() => enable.mutateAsync({ id: current.id, enabled: !current.enabled }), t("stateSaved"))
|
||||
}
|
||||
>
|
||||
{current.enabled ? t("disable") : t("enable")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={!exported.data}
|
||||
onClick={() => {
|
||||
if (exported.data) downloadPackage(current.name, exported.data);
|
||||
}}
|
||||
>
|
||||
{t("exportActive")}
|
||||
</Button>
|
||||
</Group>
|
||||
{current.previousArtifactId && (
|
||||
<>
|
||||
<Checkbox
|
||||
checked={rollbackConfirmed}
|
||||
onChange={(event) => setRollbackConfirmed(event.currentTarget.checked)}
|
||||
label={t("rollbackAcknowledgement")}
|
||||
/>
|
||||
<Button
|
||||
variant="light"
|
||||
color="orange"
|
||||
disabled={!rollbackConfirmed}
|
||||
loading={rollback.isPending}
|
||||
onClick={() =>
|
||||
void run(
|
||||
() => rollback.mutateAsync({ id: current.id, discardNewerWidgetData: true }),
|
||||
t("rolledBack"),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("rollback")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
<PackageConvertedPlacements
|
||||
id={current.id}
|
||||
origin={current.origin}
|
||||
active={Boolean(current.activeArtifactId && current.enabled)}
|
||||
onChange={() => void refresh()}
|
||||
/>
|
||||
{activeSource.success && current.enabled && (
|
||||
<AddPackagePlacement
|
||||
installation={current}
|
||||
initialBoardId={initialBoardId}
|
||||
source={activeSource.data}
|
||||
onAdded={() => void refresh()}
|
||||
onError={onError}
|
||||
onMessage={onMessage}
|
||||
/>
|
||||
)}
|
||||
{activeSource.success && <PackagePlacements installation={current} source={activeSource.data} />}
|
||||
<PackageTransfer
|
||||
id={current.id}
|
||||
name={current.name}
|
||||
active={Boolean(current.activeArtifactId)}
|
||||
dirty={dirty}
|
||||
onError={onError}
|
||||
/>
|
||||
<PackageWorkshop id={current.id} dirty={dirty} />
|
||||
<PackageActivity id={current.id} />
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function PackageActivity({ id }: { id: string }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const activity = clientApi.customWidget.package.activity.useQuery({ id, limit: 20 });
|
||||
return (
|
||||
<Accordion>
|
||||
<Accordion.Item value="activity">
|
||||
<Accordion.Control>{t("activity")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<Button variant="subtle" size="xs" onClick={() => void activity.refetch()}>
|
||||
{t("refresh")}
|
||||
</Button>
|
||||
{(activity.data ?? []).map((entry) => (
|
||||
<Text key={entry.id} size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
|
||||
{JSON.stringify(entry)}
|
||||
</Text>
|
||||
))}
|
||||
{activity.data?.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("noActivity")}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { Accordion, Alert, Button, Group, Paper, Select, Stack, Text, Textarea } from "@mantine/core";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getCustomWidgetDefaultOptions, validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { PackageOptionFields } from "@homarr/widgets/custom-api/package-option-fields";
|
||||
import { PackageCollectors } from "./_package-collectors";
|
||||
import { PackageWebhooks } from "./_package-webhooks";
|
||||
|
||||
type Installation = RouterOutputs["customWidget"]["package"]["get"];
|
||||
export function AddPackagePlacement({
|
||||
installation,
|
||||
initialBoardId,
|
||||
source,
|
||||
onAdded,
|
||||
onError,
|
||||
onMessage,
|
||||
}: {
|
||||
installation: Installation;
|
||||
initialBoardId?: string;
|
||||
source: CustomWidgetPackage;
|
||||
onAdded(): void;
|
||||
onError(error: string): void;
|
||||
onMessage(message: string): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const boards = clientApi.board.getAllBoards.useQuery();
|
||||
const add = clientApi.board.addItem.useMutation();
|
||||
const [boardId, setBoardId] = useState<string | null>(initialBoardId ?? null);
|
||||
const [configuration, setConfiguration] = useState<Record<string, unknown>>({});
|
||||
const values = { ...getCustomWidgetDefaultOptions(source.options), ...configuration };
|
||||
const missingConnections = Object.entries(source.connections).filter(
|
||||
([name, requirement]) => !requirement.optional && !installation.bindings[name],
|
||||
);
|
||||
const issues = validateCustomWidgetOptions(source.options, values);
|
||||
return (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("addToBoard")}</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("placementDescription")}
|
||||
</Text>
|
||||
<Select
|
||||
searchable
|
||||
label={t("board")}
|
||||
value={boardId}
|
||||
onChange={setBoardId}
|
||||
data={(boards.data ?? []).map((board) => ({ value: board.id, label: board.name }))}
|
||||
/>
|
||||
<PackageOptionFields schema={source.options} value={values} onChange={setConfiguration} />
|
||||
{missingConnections.length > 0 && (
|
||||
<Alert color="yellow">
|
||||
{t("bindFirst", { names: missingConnections.map(([, requirement]) => requirement.label).join(", ") })}
|
||||
</Alert>
|
||||
)}
|
||||
{issues.length > 0 && <Alert color="yellow">{issues[0]?.message}</Alert>}
|
||||
<Button
|
||||
disabled={!boardId || missingConnections.length > 0 || issues.length > 0}
|
||||
loading={add.isPending}
|
||||
onClick={() => {
|
||||
if (!boardId) return;
|
||||
add.mutate(
|
||||
{
|
||||
boardId,
|
||||
kind: "customApi",
|
||||
options: {
|
||||
definitionId: installation.id,
|
||||
configuration: values,
|
||||
configurationVersion: source.manifest.configurationVersion,
|
||||
connectionBindings: {},
|
||||
refreshInterval: 30,
|
||||
},
|
||||
integrationIds: [],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
onAdded();
|
||||
onMessage(t("addedToBoard"));
|
||||
},
|
||||
onError: (error) => onError(error.message),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("addToBoard")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export function PackagePlacements({
|
||||
installation,
|
||||
source,
|
||||
}: {
|
||||
installation: Installation;
|
||||
source: CustomWidgetPackage;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const boards = clientApi.board.getAllBoards.useQuery();
|
||||
const actions = Object.entries(source.manifest.handlers).filter(
|
||||
([, handler]) => handler.kind === "action" && handler.guestAccess,
|
||||
);
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Text fw={600}>{t("placements", { count: installation.placements.length })}</Text>
|
||||
{installation.placements.map((placement) => {
|
||||
const board = boards.data?.find((entry) => entry.id === placement.boardId);
|
||||
return (
|
||||
<Paper key={placement.id} withBorder p="sm">
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm">{board?.name ?? placement.boardId}</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{placement.id}
|
||||
</Text>
|
||||
{board && (
|
||||
<Button
|
||||
component={Link}
|
||||
href={`/boards/${encodeURIComponent(board.name)}`}
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
>
|
||||
{t("openBoard")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
<Accordion>
|
||||
<Accordion.Item value="webhooks">
|
||||
<Accordion.Control>{t("webhook.title")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<PackageWebhooks
|
||||
itemId={placement.id}
|
||||
handlers={Object.entries(source.manifest.handlers)
|
||||
.filter(([, handler]) => handler.kind === "action" && handler.inputSchema)
|
||||
.map(([name]) => name)}
|
||||
/>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
<Accordion.Item value="collection">
|
||||
<Accordion.Control>{t("collection")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<PackageCollectors
|
||||
itemId={placement.id}
|
||||
queries={Object.entries(source.manifest.handlers)
|
||||
.filter(([, handler]) => handler.kind === "query")
|
||||
.map(([name]) => name)}
|
||||
/>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
{actions.length > 0 && (
|
||||
<Accordion>
|
||||
<Accordion.Item value="guests">
|
||||
<Accordion.Control>{t("guestActions")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<GuestActions
|
||||
itemId={placement.id}
|
||||
actions={actions.map(([name, handler]) => ({ name, description: handler.description }))}
|
||||
/>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function GuestActions({ itemId, actions }: { itemId: string; actions: Array<{ name: string; description?: string }> }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const grants = clientApi.customWidget.package.guestGrants.useQuery({ itemId });
|
||||
const mutation = clientApi.customWidget.package.setGuestGrant.useMutation();
|
||||
const [inputs, setInputs] = useState<Record<string, string>>({});
|
||||
const [error, setError] = useState("");
|
||||
return (
|
||||
<Stack>
|
||||
<Text size="sm">{t("guestDescription")}</Text>
|
||||
{actions.map(({ name, description }) => {
|
||||
const grant = grants.data?.find((entry) => entry.handler === name);
|
||||
const enabled = Boolean(grant?.current);
|
||||
return (
|
||||
<Stack key={name} gap="xs">
|
||||
<Text fw={500}>{name}</Text>
|
||||
{description && <Text size="xs">{description}</Text>}
|
||||
<Textarea
|
||||
label={t("allowedInputs")}
|
||||
value={inputs[name] ?? JSON.stringify(grant?.allowedInputs ?? [{}], null, 2)}
|
||||
onChange={(event) => setInputs({ ...inputs, [name]: event.currentTarget.value })}
|
||||
/>
|
||||
<Button
|
||||
variant="light"
|
||||
loading={mutation.isPending}
|
||||
onClick={() => {
|
||||
const callbacks = {
|
||||
onSuccess: () => void grants.refetch(),
|
||||
onError: (cause: { message: string }) => setError(cause.message),
|
||||
};
|
||||
if (enabled) {
|
||||
mutation.mutate({ itemId, handler: name, enabled: false }, callbacks);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const allowed: unknown = JSON.parse(inputs[name] ?? JSON.stringify(grant?.allowedInputs ?? [{}]));
|
||||
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));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{enabled ? t("disableGuest") : t("enableGuest")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import { Group, NumberInput, Select, Stack } from "@mantine/core";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { usePackageWorkspace } from "./_use-package-workspace";
|
||||
|
||||
const presets = {
|
||||
compact: { width: 320, height: 260 },
|
||||
wide: { width: 640, height: 320 },
|
||||
phone: { width: 390, height: 640 },
|
||||
tablet: { width: 768, height: 540 },
|
||||
};
|
||||
|
||||
export function PackagePreviewControls({ state }: { state: ReturnType<typeof usePackageWorkspace> }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const { width, height, scale, previewTheme, setWidth, setHeight, setScale, setPreviewTheme } = state;
|
||||
const labels = {
|
||||
compact: t("viewportcompact"),
|
||||
wide: t("viewportwide"),
|
||||
phone: t("viewportphone"),
|
||||
tablet: t("viewporttablet"),
|
||||
};
|
||||
let preset = "custom";
|
||||
for (const [name, size] of Object.entries(presets)) {
|
||||
if (size.width === width && size.height === height) preset = name;
|
||||
}
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs" grow>
|
||||
<Select
|
||||
size="xs"
|
||||
label={t("previewViewport")}
|
||||
value={preset}
|
||||
data={[
|
||||
{ value: "custom", label: t("viewportCustom") },
|
||||
...Object.entries(labels).map(([value, label]) => ({ value, label })),
|
||||
]}
|
||||
onChange={(value) => {
|
||||
if (!value || !Object.hasOwn(presets, value)) return;
|
||||
const size = presets[value as keyof typeof presets];
|
||||
setWidth(size.width);
|
||||
setHeight(size.height);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
size="xs"
|
||||
label={t("previewTheme")}
|
||||
value={previewTheme}
|
||||
data={[
|
||||
{ value: "system", label: t("previewThemeCurrent") },
|
||||
{ value: "light", label: t("previewThemeLight") },
|
||||
{ value: "dark", label: t("previewThemeDark") },
|
||||
]}
|
||||
onChange={(value) => {
|
||||
if (value === "system" || value === "light" || value === "dark") setPreviewTheme(value);
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
<Group gap="xs" grow>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("width")}
|
||||
min={100}
|
||||
max={2400}
|
||||
value={width}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setWidth(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("height")}
|
||||
min={100}
|
||||
max={1600}
|
||||
value={height}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setHeight(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("previewScale")}
|
||||
min={25}
|
||||
max={200}
|
||||
suffix="%"
|
||||
step={10}
|
||||
value={Math.round(scale * 100)}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setScale(Math.min(2, Math.max(0.25, value / 100)));
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useId, useMemo, useRef } from "react";
|
||||
import { MantineProvider, Portal, useComputedColorScheme, useMantineTheme } from "@mantine/core";
|
||||
|
||||
/** Scope preview colors and portal variables without changing the user's application theme. */
|
||||
export function PackagePreviewViewport({
|
||||
children,
|
||||
colorScheme,
|
||||
width,
|
||||
height,
|
||||
scale,
|
||||
}: PropsWithChildren<{
|
||||
colorScheme: "system" | "light" | "dark";
|
||||
width: number;
|
||||
height: number;
|
||||
scale: number;
|
||||
}>) {
|
||||
const id = useId().replace(/[^a-zA-Z0-9_-]/gu, "");
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const currentScheme = useComputedColorScheme("light");
|
||||
const hostTheme = useMantineTheme();
|
||||
let scheme = currentScheme;
|
||||
if (colorScheme !== "system") scheme = colorScheme;
|
||||
const theme = useMemo(
|
||||
() => ({
|
||||
...hostTheme,
|
||||
components: {
|
||||
...hostTheme.components,
|
||||
Portal: Portal.extend({ defaultProps: { target: `#widget-preview-overlays-${id}` } }),
|
||||
},
|
||||
}),
|
||||
[hostTheme, id],
|
||||
);
|
||||
return (
|
||||
<MantineProvider
|
||||
theme={theme}
|
||||
forceColorScheme={scheme}
|
||||
cssVariablesSelector={`[data-widget-preview-theme="${id}"]`}
|
||||
getRootElement={() => root.current ?? undefined}
|
||||
deduplicateCssVariables={false}
|
||||
withGlobalClasses={false}
|
||||
>
|
||||
<div
|
||||
ref={root}
|
||||
data-widget-preview-theme={id}
|
||||
data-mantine-color-scheme={scheme}
|
||||
style={{
|
||||
width: width * scale,
|
||||
height: height * scale,
|
||||
background: "var(--mantine-color-body)",
|
||||
color: "var(--mantine-color-text)",
|
||||
}}
|
||||
>
|
||||
<div style={{ width, height, transform: `scale(${scale})`, transformOrigin: "top left" }}>{children}</div>
|
||||
</div>
|
||||
<div id={`widget-preview-overlays-${id}`} data-widget-preview-theme={id} data-mantine-color-scheme={scheme} />
|
||||
</MantineProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { Accordion, Alert, Button, Checkbox, Group, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
import { IconCode, IconPlayerPlay } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { PackagePreviewViewport } from "./_package-preview-viewport";
|
||||
import { PackagePreviewControls } from "./_package-preview-controls";
|
||||
import { downloadPackage } from "./_package-document";
|
||||
import type { usePackageWorkspace } from "./_use-package-workspace";
|
||||
import classes from "./_package-workspace.module.css";
|
||||
|
||||
const TrustedWidgetPreview = dynamic(() => import("@homarr/widgets/custom-api/trusted-widget-preview"), { ssr: false });
|
||||
|
||||
export function PackagePreview({
|
||||
state,
|
||||
existing,
|
||||
}: {
|
||||
state: ReturnType<typeof usePackageWorkspace>;
|
||||
existing: boolean;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const {
|
||||
parsed,
|
||||
trusted,
|
||||
setTrusted,
|
||||
liveActions,
|
||||
setLiveActions,
|
||||
busy,
|
||||
previewMutation,
|
||||
save,
|
||||
runPreview,
|
||||
document,
|
||||
source,
|
||||
surfaceChoices,
|
||||
surface,
|
||||
setSurface,
|
||||
width,
|
||||
height,
|
||||
scale,
|
||||
previewTheme,
|
||||
scenario,
|
||||
setScenario,
|
||||
stale,
|
||||
preview,
|
||||
previewReady,
|
||||
previewLoadError,
|
||||
setOptions,
|
||||
} = state;
|
||||
return (
|
||||
<Stack className={classes.preview} gap="sm">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Select
|
||||
flex={1}
|
||||
aria-label={t("surface")}
|
||||
data={surfaceChoices}
|
||||
value={surface}
|
||||
onChange={(value) => {
|
||||
if (value === "tile" || value === "advanced" || value === "configuration") setSurface(value);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
leftSection={<IconPlayerPlay size={16} />}
|
||||
loading={previewMutation.isPending}
|
||||
disabled={!existing || !parsed.success || !trusted || save.isPending}
|
||||
onClick={() => void runPreview()}
|
||||
>
|
||||
{t("preview")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Checkbox
|
||||
size="xs"
|
||||
checked={trusted}
|
||||
disabled={!parsed.success || busy}
|
||||
onChange={(event) => setTrusted(event.currentTarget.checked)}
|
||||
label={t("trustShort")}
|
||||
/>
|
||||
{parsed.success && Object.keys(parsed.data.previewScenarios ?? {}).length > 0 && (
|
||||
<Select
|
||||
label={t("previewScenario")}
|
||||
value={scenario ?? ""}
|
||||
disabled={busy}
|
||||
onChange={(value) => setScenario(value || null)}
|
||||
data={[
|
||||
{ value: "", label: t("previewConnected") },
|
||||
...Object.entries(parsed.data.previewScenarios ?? {}).map(([id, fixture]) => ({
|
||||
value: id,
|
||||
label: fixture.label,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
size="xs"
|
||||
checked={liveActions}
|
||||
disabled={!parsed.success || busy || Boolean(scenario)}
|
||||
onChange={(event) => setLiveActions(event.currentTarget.checked)}
|
||||
label={t("previewLiveActions")}
|
||||
/>
|
||||
{!existing && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("saveFirst")}
|
||||
</Text>
|
||||
)}
|
||||
{stale && (
|
||||
<Alert color="yellow" p="xs">
|
||||
{t("previewStale")}
|
||||
</Alert>
|
||||
)}
|
||||
<Paper withBorder className={classes.canvas} p="xs">
|
||||
{preview && (
|
||||
<PackagePreviewViewport width={width} height={height} scale={scale} colorScheme={previewTheme}>
|
||||
<TrustedWidgetPreview
|
||||
data={preview.displayData}
|
||||
width={width}
|
||||
height={height}
|
||||
displayScale={scale}
|
||||
surface={surface}
|
||||
onOptionsChange={setOptions}
|
||||
onSurfaceChange={setSurface}
|
||||
frozen={stale || previewMutation.isPending}
|
||||
onReady={previewReady}
|
||||
onLoadError={previewLoadError}
|
||||
/>
|
||||
</PackagePreviewViewport>
|
||||
)}
|
||||
{!preview && (
|
||||
<Stack justify="center" align="center" mih={220} p="sm">
|
||||
<IconCode size={32} stroke={1} />
|
||||
<Text c="dimmed" size="sm" ta="center">
|
||||
{t("previewEmpty")}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
</Paper>
|
||||
<Group gap="xs" align="center">
|
||||
{preview && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t(preview.liveActions ? "previewLiveSession" : "previewSimulatedSession")}
|
||||
</Text>
|
||||
)}
|
||||
{preview?.displayData.previewScenario && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("previewSynthetic", { name: preview.displayData.previewScenario.label })}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<PackagePreviewControls state={state} />
|
||||
<Accordion variant="default">
|
||||
<Accordion.Item value="trust">
|
||||
<Accordion.Control>{t("executionDetails")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{t("trustedCode")}</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("previewDescription")}
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
{t("dependencies")}:{" "}
|
||||
{(parsed.success &&
|
||||
Object.entries(parsed.data.dependencies)
|
||||
.map(([name, version]) => `${name}@${version}`)
|
||||
.join(", ")) ||
|
||||
t("hostOnly")}
|
||||
</Text>
|
||||
<Button variant="default" size="xs" onClick={() => downloadPackage(document.name, source)}>
|
||||
{t("exportDraft")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { Alert, Button, Group, NumberInput, Paper, Select, Skeleton, Stack, Text, Title } from "@mantine/core";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
const TrustedWidgetPreview = dynamic(() => import("@homarr/widgets/custom-api/trusted-widget-preview"), { ssr: false });
|
||||
|
||||
export function PackageSessionPreview({ previewId }: { previewId: string }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const { data, error, isLoading } = clientApi.customWidget.package.previewGet.useQuery(
|
||||
{ previewId },
|
||||
{ retry: false },
|
||||
);
|
||||
const [surface, setSurface] = useState<"tile" | "advanced" | "configuration">("tile");
|
||||
const [width, setWidth] = useState(480);
|
||||
const [height, setHeight] = useState(360);
|
||||
if (isLoading) return <Skeleton height={360} />;
|
||||
if (error || !data)
|
||||
return (
|
||||
<Alert color="yellow" title={t("sessionUnavailable")}>
|
||||
{t("sessionUnavailableDescription")}
|
||||
</Alert>
|
||||
);
|
||||
const choices = [{ value: "tile", label: t("tile") }];
|
||||
if (data.displayData.manifest.entrypoints.advanced) choices.push({ value: "advanced", label: t("advanced") });
|
||||
if (data.displayData.manifest.entrypoints.configuration)
|
||||
choices.push({ value: "configuration", label: t("configuration") });
|
||||
return (
|
||||
<Stack>
|
||||
<Group justify="space-between">
|
||||
<Title order={2}>{data.displayData.manifest.name}</Title>
|
||||
<Button
|
||||
component={Link}
|
||||
href={`/manage/custom-widgets/packages/${data.displayData.installationId}`}
|
||||
variant="subtle"
|
||||
>
|
||||
{t("openWorkspace")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("sessionDescription")}
|
||||
</Text>
|
||||
{data.displayData.previewScenario && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("previewSynthetic", { name: data.displayData.previewScenario.label })}
|
||||
</Text>
|
||||
)}
|
||||
<Group align="end">
|
||||
<Select
|
||||
label={t("surface")}
|
||||
data={choices}
|
||||
value={surface}
|
||||
onChange={(value) => {
|
||||
if (value === "tile" || value === "advanced" || value === "configuration") setSurface(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
w={110}
|
||||
label={t("width")}
|
||||
min={100}
|
||||
max={2400}
|
||||
value={width}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setWidth(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
w={110}
|
||||
label={t("height")}
|
||||
min={100}
|
||||
max={2400}
|
||||
value={height}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setHeight(value);
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
<Paper withBorder p="sm" style={{ overflow: "auto" }}>
|
||||
<div style={{ width, height }}>
|
||||
<TrustedWidgetPreview
|
||||
data={data.displayData}
|
||||
width={width}
|
||||
height={height}
|
||||
surface={surface}
|
||||
onSurfaceChange={setSurface}
|
||||
/>
|
||||
</div>
|
||||
</Paper>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { Button, Group, NavLink, Select, Stack, Tabs, Text, TextInput, Alert } from "@mantine/core";
|
||||
import { IconCode, IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
|
||||
import { documentFromTemplate } from "./_package-document";
|
||||
import type { usePackageWorkspace } from "./_use-package-workspace";
|
||||
import classes from "./_package-workspace.module.css";
|
||||
const PackageLanguageEditor = dynamic(() => import("./_package-language-editor"), { ssr: false });
|
||||
export function PackageSourceEditor({
|
||||
state,
|
||||
existing,
|
||||
}: {
|
||||
state: ReturnType<typeof usePackageWorkspace>;
|
||||
existing: boolean;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const [filesOpen, setFilesOpen] = useState(false);
|
||||
const { document, edit, selected, setSelected, path, setPath, busy, addFile, renameFile, removeFile, parsed } = state;
|
||||
return (
|
||||
<Tabs.Panel value="source" pt="md">
|
||||
<Stack>
|
||||
{!existing && (
|
||||
<Select
|
||||
label={t("starter")}
|
||||
placeholder={t("chooseStarter")}
|
||||
data={Object.entries(widgetReferencePackages).map(([key, template]) => ({
|
||||
value: key,
|
||||
label: template.manifest.name,
|
||||
}))}
|
||||
disabled={busy}
|
||||
onChange={(starter) => {
|
||||
if (!starter) return;
|
||||
const template = Object.entries(widgetReferencePackages).find(([key]) => key === starter)?.[1];
|
||||
if (!template) return;
|
||||
edit(documentFromTemplate(document.name, template));
|
||||
setSelected("/widget.json");
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Group gap="xs">
|
||||
<Select
|
||||
flex={1}
|
||||
searchable
|
||||
aria-label={t("filePath")}
|
||||
value={selected}
|
||||
data={[
|
||||
{ value: "/widget.json", label: t("manifestFile") },
|
||||
...Object.keys(document.files)
|
||||
.toSorted()
|
||||
.map((file) => ({ value: file, label: file })),
|
||||
]}
|
||||
onChange={(value) => {
|
||||
if (value) setSelected(value);
|
||||
}}
|
||||
/>
|
||||
<Button variant="subtle" size="sm" onClick={() => setFilesOpen(!filesOpen)} aria-expanded={filesOpen}>
|
||||
{t("files")}
|
||||
</Button>
|
||||
</Group>
|
||||
<div className={classes.editor} data-package-document data-files-open={filesOpen}>
|
||||
{filesOpen && (
|
||||
<Stack gap="xs" className={classes.files}>
|
||||
<NavLink
|
||||
label={t("manifestFile")}
|
||||
active={selected === "/widget.json"}
|
||||
onClick={() => setSelected("/widget.json")}
|
||||
leftSection={<IconCode size={15} />}
|
||||
/>
|
||||
{Object.keys(document.files)
|
||||
.toSorted()
|
||||
.map((file) => (
|
||||
<NavLink
|
||||
key={file}
|
||||
label={file}
|
||||
active={selected === file}
|
||||
onClick={() => setSelected(file)}
|
||||
styles={{ label: { overflowWrap: "anywhere" } }}
|
||||
/>
|
||||
))}
|
||||
<TextInput
|
||||
aria-label={t("filePath")}
|
||||
placeholder={t("filePathExample")}
|
||||
value={path}
|
||||
onChange={(event) => setPath(event.currentTarget.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
<Group gap={4}>
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
leftSection={<IconPlus size={12} />}
|
||||
onClick={addFile}
|
||||
disabled={busy || !path.trim()}
|
||||
>
|
||||
{t("addFile")}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
onClick={renameFile}
|
||||
disabled={busy || !path.trim() || selected === "/widget.json"}
|
||||
>
|
||||
{t("renameFile")}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact-xs"
|
||||
color="red"
|
||||
variant="subtle"
|
||||
leftSection={<IconTrash size={12} />}
|
||||
onClick={removeFile}
|
||||
disabled={busy || selected === "/widget.json"}
|
||||
>
|
||||
{t("removeFile")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
<PackageLanguageEditor state={state} />
|
||||
</div>
|
||||
{!parsed.success && (
|
||||
<Alert color="yellow">
|
||||
<Text fw={500}>{t("draftInvalid")}</Text>
|
||||
{parsed.error.issues.slice(0, 8).map((issue, index) => (
|
||||
<Text key={index} size="sm">
|
||||
{issue.path.join(".")}: {issue.message}
|
||||
</Text>
|
||||
))}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
/* oxlint-disable jsx-a11y/prefer-tag-over-role -- A focusable window splitter is an interactive separator, not a thematic break. */
|
||||
|
||||
import type { CSSProperties, PropsWithChildren, ReactNode } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import classes from "./_package-workspace.module.css";
|
||||
|
||||
const defaultWidth = 60;
|
||||
const clampWidth = (value: number, maximum = 75) => Math.min(maximum, Math.max(30, value));
|
||||
|
||||
/** The split is an editor preference; it never changes the widget's authored dimensions. */
|
||||
export function PackageSplit({
|
||||
userId,
|
||||
pane,
|
||||
preview,
|
||||
children,
|
||||
}: PropsWithChildren<{ userId: string; pane: string; preview: ReactNode }>) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const [width, setWidth] = useState(defaultWidth);
|
||||
const [availableWidth, setAvailableWidth] = useState(0);
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const key = `homarr:widget-workspace:split:${userId}`;
|
||||
const latest = useRef(width);
|
||||
let maximum = 75;
|
||||
if (availableWidth >= 650) maximum = Math.min(75, ((availableWidth - 338) / availableWidth) * 100);
|
||||
const visibleWidth = clampWidth(width, maximum);
|
||||
useEffect(() => {
|
||||
if (!container.current) return;
|
||||
const observer = new ResizeObserver(([entry]) => setAvailableWidth(entry?.contentRect.width ?? 0));
|
||||
observer.observe(container.current);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved && Number.isFinite(Number(saved))) {
|
||||
const next = clampWidth(Number(saved));
|
||||
latest.current = next;
|
||||
setWidth(next);
|
||||
}
|
||||
} catch {
|
||||
// Browser storage is optional for editor preferences.
|
||||
}
|
||||
}, [key]);
|
||||
const remember = (value: number) => {
|
||||
const next = clampWidth(value, maximum);
|
||||
latest.current = next;
|
||||
setWidth(next);
|
||||
try {
|
||||
localStorage.setItem(key, String(next));
|
||||
} catch {
|
||||
// Resizing remains available when browser storage is disabled.
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div
|
||||
ref={container}
|
||||
className={classes.workspace}
|
||||
data-pane={pane}
|
||||
style={{ "--widget-editor-width": `${visibleWidth}%` } as CSSProperties}
|
||||
>
|
||||
{children}
|
||||
<div
|
||||
className={classes.divider}
|
||||
role="separator"
|
||||
tabIndex={0}
|
||||
aria-label={t("resizeEditor")}
|
||||
title={t("resizeEditorHint")}
|
||||
aria-orientation="vertical"
|
||||
aria-valuemin={30}
|
||||
aria-valuemax={Math.round(maximum)}
|
||||
aria-valuenow={Math.round(visibleWidth)}
|
||||
onDoubleClick={() => remember(defaultWidth)}
|
||||
onKeyDown={(event) => {
|
||||
let next = visibleWidth;
|
||||
if (event.key === "ArrowLeft") next -= 5;
|
||||
else if (event.key === "ArrowRight") next += 5;
|
||||
else if (event.key === "Home") next = 30;
|
||||
else if (event.key === "End") next = maximum;
|
||||
else return;
|
||||
event.preventDefault();
|
||||
remember(next);
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
|
||||
const bounds = container.current?.getBoundingClientRect();
|
||||
if (!bounds?.width) return;
|
||||
latest.current = clampWidth(((event.clientX - bounds.left) / bounds.width) * 100, maximum);
|
||||
setWidth(latest.current);
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
remember(latest.current);
|
||||
}}
|
||||
/>
|
||||
{preview}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Accordion, Badge, Button, Checkbox, Group, Paper, SimpleGrid, Stack, Text, TextInput } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { customWidgetArchiveSchema } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
|
||||
export function PackageTransfer({
|
||||
id,
|
||||
name,
|
||||
active,
|
||||
dirty,
|
||||
onError,
|
||||
}: {
|
||||
id: string;
|
||||
name: string;
|
||||
active: boolean;
|
||||
dirty: boolean;
|
||||
onError(error: string): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const [replace, setReplace] = useState(false);
|
||||
const [forkName, setForkName] = useState(`${name} fork`);
|
||||
const fork = clientApi.customWidget.package.fork.useMutation();
|
||||
const update = clientApi.customWidget.package.stageUpdate.useMutation();
|
||||
const changes = clientApi.customWidget.package.draftChanges.useQuery({ id });
|
||||
const stage = async (file: File) => {
|
||||
try {
|
||||
if (file.size > 25_000_000) throw new Error(t("importTooLarge"));
|
||||
const raw: unknown = JSON.parse(await file.text());
|
||||
const archive = customWidgetArchiveSchema.parse(raw);
|
||||
const result = await update.mutateAsync({ id, archive, replaceLocalDraft: true });
|
||||
window.location.assign(result.managementPath);
|
||||
} catch (error) {
|
||||
onError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Stack>
|
||||
<Accordion>
|
||||
<Accordion.Item value="changes">
|
||||
<Accordion.Control>{t("changes")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("sourceOnly")}
|
||||
</Text>
|
||||
{changes.data?.valid && (
|
||||
<>
|
||||
<Text size="sm">
|
||||
{changes.data.fromVersion ?? t("none")} → {changes.data.toVersion}
|
||||
</Text>
|
||||
<Group>
|
||||
{changes.data.dependenciesChanged && <Badge color="yellow">{t("dependenciesChanged")}</Badge>}
|
||||
{changes.data.connectionsChanged && <Badge color="yellow">{t("connectionsChanged")}</Badge>}
|
||||
{changes.data.configurationChanged && <Badge color="yellow">{t("configurationChanged")}</Badge>}
|
||||
</Group>
|
||||
{changes.data.files.map((file) => (
|
||||
<Stack key={file.name} gap="xs">
|
||||
<Text fw={500}>{file.name}</Text>
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
<CodeEditor
|
||||
id={`before-${file.name}`}
|
||||
label={t("before")}
|
||||
value={file.before ?? ""}
|
||||
language="tsx"
|
||||
readOnly
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
<CodeEditor
|
||||
id={`after-${file.name}`}
|
||||
label={t("after")}
|
||||
value={file.after ?? ""}
|
||||
language="tsx"
|
||||
readOnly
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
{active && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Checkbox
|
||||
checked={replace}
|
||||
onChange={(event) => setReplace(event.currentTarget.checked)}
|
||||
label={t("replaceDraft")}
|
||||
/>
|
||||
<input
|
||||
hidden
|
||||
type="file"
|
||||
ref={input}
|
||||
accept=".json,application/json"
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0];
|
||||
event.currentTarget.value = "";
|
||||
if (file) void stage(file);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={!replace || dirty}
|
||||
loading={update.isPending}
|
||||
onClick={() => input.current?.click()}
|
||||
>
|
||||
{t("stageUpdate")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text size="sm">{t("forkDescription")}</Text>
|
||||
<TextInput
|
||||
label={t("forkName")}
|
||||
value={forkName}
|
||||
onChange={(event) => setForkName(event.currentTarget.value)}
|
||||
/>
|
||||
<Button
|
||||
variant="default"
|
||||
disabled={dirty || !forkName.trim()}
|
||||
loading={fork.isPending}
|
||||
onClick={() =>
|
||||
fork.mutate(
|
||||
{ id, name: forkName },
|
||||
{
|
||||
onSuccess: (result) => window.location.assign(result.managementPath),
|
||||
onError: (error) => onError(error.message),
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("fork")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Alert, Badge, Button, CopyButton, Group, PasswordInput, Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
type IssuedWebhook = RouterOutputs["customWidget"]["package"]["createWebhook"];
|
||||
|
||||
export function PackageWebhooks({ itemId, handlers }: { itemId: string; handlers: string[] }) {
|
||||
const t = useI18n("customWidget.package.webhook");
|
||||
const commonT = useI18n("common.action");
|
||||
const hooks = clientApi.customWidget.package.webhooks.useQuery({ itemId });
|
||||
const create = clientApi.customWidget.package.createWebhook.useMutation();
|
||||
const revoke = clientApi.customWidget.package.revokeWebhook.useMutation();
|
||||
const [handler, setHandler] = useState<string | null>(null);
|
||||
const [issued, setIssued] = useState<IssuedWebhook | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
<Text size="sm">{t("description")}</Text>
|
||||
<Group align="end">
|
||||
<Select
|
||||
flex={1}
|
||||
label={t("handler")}
|
||||
data={handlers}
|
||||
value={handler}
|
||||
onChange={setHandler}
|
||||
disabled={handlers.length === 0}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!handler}
|
||||
loading={create.isPending}
|
||||
onClick={() => {
|
||||
if (!handler) return;
|
||||
setError("");
|
||||
create.mutate(
|
||||
{ itemId, handler },
|
||||
{
|
||||
onSuccess: (result) => {
|
||||
setIssued(result);
|
||||
create.reset();
|
||||
void hooks.refetch();
|
||||
},
|
||||
onError: (cause) => setError(cause.message),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("create")}
|
||||
</Button>
|
||||
</Group>
|
||||
{handlers.length === 0 && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("noHandlers")}
|
||||
</Text>
|
||||
)}
|
||||
{issued && (
|
||||
<Alert color="yellow" title={t("issued")} withCloseButton onClose={() => setIssued(null)}>
|
||||
<Stack gap="xs">
|
||||
<Text size="xs">{t("issuedDescription")}</Text>
|
||||
<TextInput label={t("url")} readOnly value={new URL(issued.path, window.location.origin).href} />
|
||||
<CopyButton value={new URL(issued.path, window.location.origin).href}>
|
||||
{({ copied, copy }) => (
|
||||
<Button size="xs" variant="subtle" onClick={copy}>
|
||||
{copied ? commonT("copied") : t("copyUrl")}
|
||||
</Button>
|
||||
)}
|
||||
</CopyButton>
|
||||
<PasswordInput label={t("token")} readOnly value={issued.token} />
|
||||
<CopyButton value={issued.token}>
|
||||
{({ copied, copy }) => (
|
||||
<Button size="xs" variant="subtle" onClick={copy}>
|
||||
{copied ? commonT("copied") : t("copyToken")}
|
||||
</Button>
|
||||
)}
|
||||
</CopyButton>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
{(hooks.data ?? []).map((hook) => (
|
||||
<Group key={hook.id} justify="space-between">
|
||||
<Text size="sm">{hook.handler}</Text>
|
||||
<Badge color={hook.current ? "green" : "yellow"}>{hook.current ? t("current") : t("reissue")}</Badge>
|
||||
<Button
|
||||
size="compact-xs"
|
||||
color="red"
|
||||
variant="subtle"
|
||||
loading={revoke.isPending}
|
||||
onClick={() =>
|
||||
revoke.mutate(
|
||||
{ itemId, id: hook.id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
if (issued?.id === hook.id) setIssued(null);
|
||||
void hooks.refetch();
|
||||
},
|
||||
onError: (cause) => setError(cause.message),
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("revoke")}
|
||||
</Button>
|
||||
</Group>
|
||||
))}
|
||||
{(error || hooks.error) && <Alert color="red">{error || hooks.error?.message}</Alert>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, Checkbox, Group, Paper, Select, Stack, Text, Textarea, TextInput } 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";
|
||||
|
||||
export function PackageWorkshop({ id, dirty }: { id: string; dirty: boolean }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const session = useWorkshopSession();
|
||||
const update = clientApi.customWidget.package.checkUpdate.useQuery({ id });
|
||||
const stage = clientApi.customWidget.package.stageWorkshopUpdate.useMutation();
|
||||
const publish = clientApi.customWidget.package.publishWorkshop.useMutation();
|
||||
const [replace, setReplace] = useState(false);
|
||||
const [mode, setMode] = useState<"new" | "update" | "fork">("new");
|
||||
const [changelog, setChangelog] = useState("");
|
||||
const [forkedFrom, setForkedFrom] = useState("");
|
||||
const [reviewed, setReviewed] = useState(false);
|
||||
const updateData = update.data;
|
||||
const linked = updateData?.origin !== undefined;
|
||||
let submissionId = "";
|
||||
if (linked) submissionId = updateData.origin.submissionId;
|
||||
const submission = useWorkshopSubmissionQuery(session.client, submissionId);
|
||||
return (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("workshopLifecycle")}</Text>
|
||||
{update.error && <Alert color="yellow">{update.error.message}</Alert>}
|
||||
<Button variant="subtle" onClick={() => void update.refetch()}>
|
||||
{t("checkUpdates")}
|
||||
</Button>
|
||||
{linked && (
|
||||
<>
|
||||
<Text size="sm">{t("upstreamRelease", { version: updateData.origin.version })}</Text>
|
||||
{updateData.hasLocalChanges && <Alert color="yellow">{t("localChanges")}</Alert>}
|
||||
{updateData.available && updateData.latest && (
|
||||
<Stack gap="xs">
|
||||
<Text fw={500}>{t("updateAvailable", { version: updateData.latest.version })}</Text>
|
||||
<Text size="sm" style={{ whiteSpace: "pre-wrap" }}>
|
||||
{updateData.latest.changelog}
|
||||
</Text>
|
||||
<Checkbox
|
||||
checked={replace}
|
||||
onChange={(event) => setReplace(event.currentTarget.checked)}
|
||||
label={t("replaceDraft")}
|
||||
/>
|
||||
<Button
|
||||
disabled={!replace || dirty}
|
||||
loading={stage.isPending}
|
||||
onClick={() => {
|
||||
if (!updateData.latest) return;
|
||||
stage.mutate(
|
||||
{
|
||||
id,
|
||||
releaseId: updateData.latest.id,
|
||||
replaceLocalDraft: true,
|
||||
expectedDraftDigest: updateData.draftDigest,
|
||||
},
|
||||
{ onSuccess: (result) => window.location.assign(result.managementPath) },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("stageWorkshopUpdate")}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Group justify="space-between">
|
||||
<Text fw={600}>{t("publishWorkshop")}</Text>
|
||||
<WorkshopAccountButton session={session} />
|
||||
</Group>
|
||||
<Select
|
||||
label={t("publishMode")}
|
||||
value={mode}
|
||||
onChange={(value) => {
|
||||
if (value === "new" || value === "update" || value === "fork") setMode(value);
|
||||
}}
|
||||
data={[
|
||||
{ value: "new", label: t("publishNew") },
|
||||
{ value: "update", label: t("publishUpdate") },
|
||||
{ value: "fork", label: t("publishFork") },
|
||||
]}
|
||||
/>
|
||||
{mode === "fork" && (
|
||||
<TextInput
|
||||
label={t("forkedFrom")}
|
||||
value={forkedFrom}
|
||||
onChange={(event) => setForkedFrom(event.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
<Textarea
|
||||
label={t("changelog")}
|
||||
value={changelog}
|
||||
onChange={(event) => setChangelog(event.currentTarget.value)}
|
||||
autosize
|
||||
minRows={3}
|
||||
/>
|
||||
<Checkbox
|
||||
checked={reviewed}
|
||||
onChange={(event) => setReviewed(event.currentTarget.checked)}
|
||||
label={t("publishAcknowledgement")}
|
||||
/>
|
||||
<Button
|
||||
disabled={!session.user || dirty || !reviewed || (mode === "update" && !submission.data)}
|
||||
loading={publish.isPending}
|
||||
onClick={() => {
|
||||
const token = session.client.authToken;
|
||||
if (!token) return;
|
||||
publish.mutate(
|
||||
{
|
||||
id,
|
||||
token,
|
||||
mode,
|
||||
submissionId: submissionId || undefined,
|
||||
expectedRevision: submission.data?.revision,
|
||||
forkedFrom: forkedFrom || undefined,
|
||||
changelog,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setReviewed(false);
|
||||
void update.refetch();
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("publishWorkshop")}
|
||||
</Button>
|
||||
{publish.data && (
|
||||
<Alert color="green">
|
||||
<Text>{t("published", { version: publish.data.version })}</Text>
|
||||
<Button
|
||||
component="a"
|
||||
href={publish.data.workshopUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
variant="subtle"
|
||||
>
|
||||
{t("openWorkshop")}
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
{stage.error && <Alert color="red">{stage.error.message}</Alert>}
|
||||
{publish.error && <Alert color="red">{publish.error.message}</Alert>}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
.workspace {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, var(--widget-editor-width, 60%)) 10px minmax(0, 1fr);
|
||||
gap: var(--mantine-spacing-xs);
|
||||
align-items: start;
|
||||
}
|
||||
.divider {
|
||||
width: 10px;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
align-self: stretch;
|
||||
min-height: 280px;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
background: linear-gradient(var(--mantine-color-default-border), var(--mantine-color-default-border)) center / 2px
|
||||
100% no-repeat;
|
||||
}
|
||||
.divider:hover,
|
||||
.divider:focus-visible {
|
||||
background-color: var(--mantine-primary-color-light);
|
||||
outline: 2px solid var(--mantine-primary-color-filled);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.editor {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--mantine-spacing-sm);
|
||||
min-width: 0;
|
||||
}
|
||||
.editor[data-files-open="true"] {
|
||||
grid-template-columns: 140px minmax(0, 1fr);
|
||||
}
|
||||
.files {
|
||||
overflow: auto;
|
||||
max-height: 65vh;
|
||||
}
|
||||
.preview {
|
||||
position: sticky;
|
||||
top: calc(var(--mantine-spacing-md) + 60px);
|
||||
min-width: 0;
|
||||
}
|
||||
.canvas {
|
||||
overflow: auto;
|
||||
max-width: 100%;
|
||||
max-height: max(260px, calc(100dvh - 270px));
|
||||
background: var(--mantine-color-body);
|
||||
}
|
||||
.switcher {
|
||||
display: none;
|
||||
}
|
||||
@media (max-width: 70em) {
|
||||
.workspace {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.divider {
|
||||
width: 10px;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
display: none;
|
||||
}
|
||||
.preview {
|
||||
position: static;
|
||||
}
|
||||
.switcher {
|
||||
display: block;
|
||||
}
|
||||
.workspace[data-pane="edit"] .preview {
|
||||
display: none;
|
||||
}
|
||||
.workspace[data-pane="preview"] .authoring {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media (max-width: 40em) {
|
||||
.editor,
|
||||
.editor[data-files-open="true"] {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.files {
|
||||
max-height: 180px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
"use client";
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
SegmentedControl,
|
||||
Stack,
|
||||
Tabs,
|
||||
Text,
|
||||
TextInput,
|
||||
Tooltip,
|
||||
ActionIcon,
|
||||
} from "@mantine/core";
|
||||
import { IconArrowBackUp, IconArrowForwardUp, IconInfoCircle } from "@tabler/icons-react";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { PackagePreview } from "./_package-preview";
|
||||
import { PackageSplit } from "./_package-split";
|
||||
import { PackageAssistant } from "./_package-assistant";
|
||||
import { usePackageAssistant } from "./_use-package-assistant";
|
||||
import { PackageSourceEditor } from "./_package-source-editor";
|
||||
import { PackageConnections } from "./_package-connections";
|
||||
import { PackageOperations } from "./_package-operations";
|
||||
import { usePackageWorkspace } from "./_use-package-workspace";
|
||||
import type { Installation } from "./_use-package-workspace";
|
||||
import classes from "./_package-workspace.module.css";
|
||||
export function PackageWorkspace({
|
||||
installation,
|
||||
userId,
|
||||
initialSource,
|
||||
initialName,
|
||||
initialBindings,
|
||||
initialBoardId,
|
||||
}: {
|
||||
installation?: Installation;
|
||||
userId: string;
|
||||
initialSource?: unknown;
|
||||
initialName?: string;
|
||||
initialBindings?: Record<string, string>;
|
||||
initialBoardId?: string;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const workspace = usePackageWorkspace(
|
||||
installation,
|
||||
userId,
|
||||
initialSource,
|
||||
initialName,
|
||||
initialBindings,
|
||||
initialBoardId,
|
||||
);
|
||||
const {
|
||||
editor,
|
||||
document,
|
||||
edit,
|
||||
pane,
|
||||
setPane,
|
||||
trusted,
|
||||
error,
|
||||
setError,
|
||||
message,
|
||||
setMessage,
|
||||
bindings,
|
||||
setBindings,
|
||||
setOptions,
|
||||
parsed,
|
||||
effectiveOptions,
|
||||
save,
|
||||
previewMutation,
|
||||
saveBindings,
|
||||
busy,
|
||||
saveDraft,
|
||||
saveLocalBindings,
|
||||
} = workspace;
|
||||
usePackageAssistant(workspace);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
gap="sm"
|
||||
onKeyDownCapture={(event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement) || !target.closest("[data-package-document]") || busy) return;
|
||||
if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "z" || event.altKey) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.shiftKey) editor.redo();
|
||||
else editor.undo();
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" align="end" data-package-document>
|
||||
<TextInput
|
||||
flex={1}
|
||||
maw={440}
|
||||
label={t("name")}
|
||||
value={document.name}
|
||||
disabled={busy}
|
||||
onChange={(event) => edit({ ...document, name: event.currentTarget.value }, "name")}
|
||||
/>
|
||||
<Group gap="xs">
|
||||
<Button variant="subtle" component={Link} href="/manage/custom-widgets/packages">
|
||||
{t("library")}
|
||||
</Button>
|
||||
<Badge variant="light">{editor.dirty ? t("unsaved") : t("saved")}</Badge>
|
||||
<Button
|
||||
loading={save.isPending}
|
||||
disabled={!document.name.trim() || previewMutation.isPending}
|
||||
onClick={() => void saveDraft()}
|
||||
>
|
||||
{t("saveDraft")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
{error && (
|
||||
<Alert color="red" withCloseButton onClose={() => setError("")}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
{message && (
|
||||
<Alert color="blue" withCloseButton onClose={() => setMessage("")}>
|
||||
{message}
|
||||
</Alert>
|
||||
)}
|
||||
{editor.recovery && (
|
||||
<Alert color="yellow">
|
||||
<Stack gap="xs">
|
||||
<Text>{t("recovery")}</Text>
|
||||
<Group>
|
||||
<Button size="xs" onClick={editor.restoreRecovery}>
|
||||
{t("restore")}
|
||||
</Button>
|
||||
<Button size="xs" variant="subtle" onClick={editor.discardRecovery}>
|
||||
{t("discard")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
<Group gap="xs">
|
||||
<PackageAssistant />
|
||||
<Button
|
||||
size="xs"
|
||||
variant="default"
|
||||
leftSection={<IconArrowBackUp size={14} />}
|
||||
disabled={busy || !editor.historyState.undo}
|
||||
onClick={editor.undo}
|
||||
>
|
||||
{t("undo")}
|
||||
</Button>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="default"
|
||||
leftSection={<IconArrowForwardUp size={14} />}
|
||||
disabled={busy || !editor.historyState.redo}
|
||||
onClick={editor.redo}
|
||||
>
|
||||
{t("redo")}
|
||||
</Button>
|
||||
<Button size="xs" variant="subtle" disabled={busy || !editor.dirty} onClick={editor.reset}>
|
||||
{t("reset")}
|
||||
</Button>
|
||||
<Tooltip label={t("historyDescription")} multiline maw={360}>
|
||||
<ActionIcon variant="subtle" color="gray" aria-label={t("historyInfo")}>
|
||||
<IconInfoCircle size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
<SegmentedControl
|
||||
className={classes.switcher}
|
||||
value={pane}
|
||||
onChange={setPane}
|
||||
data={[
|
||||
{ value: "edit", label: t("code") },
|
||||
{ value: "preview", label: t("previewPane") },
|
||||
]}
|
||||
/>
|
||||
<PackageSplit
|
||||
userId={userId}
|
||||
pane={pane}
|
||||
preview={<PackagePreview state={workspace} existing={Boolean(installation)} />}
|
||||
>
|
||||
<Stack className={classes.authoring}>
|
||||
<Tabs defaultValue="source">
|
||||
<Tabs.List>
|
||||
<Tabs.Tab value="source">{t("code")}</Tabs.Tab>
|
||||
<Tabs.Tab value="connections">{t("connections")}</Tabs.Tab>
|
||||
<Tabs.Tab value="installation">{t("installation")}</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
<PackageSourceEditor state={workspace} existing={Boolean(installation)} />
|
||||
<Tabs.Panel value="connections" pt="md">
|
||||
<PackageConnections
|
||||
requirements={parsed.success ? parsed.data.connections : {}}
|
||||
bindings={bindings}
|
||||
onChange={setBindings}
|
||||
onSave={saveLocalBindings}
|
||||
saving={saveBindings.isPending}
|
||||
onConnectionSaved={workspace.connectionChanged}
|
||||
/>
|
||||
{!installation && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("saveFirst")}
|
||||
</Text>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="installation" pt="md">
|
||||
<PackageOperations
|
||||
installation={installation}
|
||||
initialBoardId={initialBoardId}
|
||||
source={parsed.success ? parsed.data : undefined}
|
||||
options={effectiveOptions}
|
||||
setOptions={setOptions}
|
||||
dirty={editor.dirty}
|
||||
trusted={trusted}
|
||||
onError={setError}
|
||||
onMessage={setMessage}
|
||||
/>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
</Stack>
|
||||
</PackageSplit>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createId } from "@homarr/common";
|
||||
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
|
||||
import { packageDraftToolContracts } from "~/components/assistant/assistant-package-draft-contracts";
|
||||
import type {
|
||||
PackageDraftReview,
|
||||
ProposePackageChangesArgs,
|
||||
} from "~/components/assistant/assistant-package-draft-contracts";
|
||||
import {
|
||||
notifyPackageDraftChanged,
|
||||
registerAssistantPackageDraft,
|
||||
} from "~/components/assistant/assistant-package-draft-registry";
|
||||
import { packageAssistantSdkContext } from "./_package-assistant-context";
|
||||
import { recoveryDocument } from "./_package-document";
|
||||
import type { PackageDocument } from "./_package-document";
|
||||
import type { usePackageWorkspace } from "./_use-package-workspace";
|
||||
|
||||
type Workspace = ReturnType<typeof usePackageWorkspace>;
|
||||
const maximumContextCharacters = 180_000;
|
||||
|
||||
export function usePackageAssistant(workspace: Workspace) {
|
||||
const identity = useRef({ document: workspace.document, revision: createId() });
|
||||
if (identity.current.document !== workspace.document)
|
||||
identity.current = { document: workspace.document, revision: createId() };
|
||||
const revision = identity.current.revision;
|
||||
const latest = useRef({ workspace, revision });
|
||||
latest.current = { workspace, revision };
|
||||
const readState = useRef({ revision: "", paths: new Set<string>(), metadata: false });
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
registerAssistantPackageDraft({
|
||||
read(input) {
|
||||
const { workspace: state, revision: currentRevision } = latest.current;
|
||||
const sanitized = recoveryDocument(state.document);
|
||||
if (readState.current.revision !== currentRevision)
|
||||
readState.current = { revision: currentRevision, paths: new Set(), metadata: false };
|
||||
const metadataOmitted = sanitized.metadata.length > 60_000;
|
||||
if (!metadataOmitted) readState.current.metadata = true;
|
||||
const files: Record<string, string> = {};
|
||||
const omittedFiles: string[] = [];
|
||||
let remaining = maximumContextCharacters;
|
||||
for (const path of input.paths ?? Object.keys(sanitized.files)) {
|
||||
const value = sanitized.files[path];
|
||||
if (value === undefined || value.length > remaining) {
|
||||
omittedFiles.push(path);
|
||||
continue;
|
||||
}
|
||||
files[path] = value;
|
||||
remaining -= value.length;
|
||||
readState.current.paths.add(path);
|
||||
}
|
||||
const redactedFiles = Object.keys(sanitized.files).filter(
|
||||
(path) => sanitized.files[path] !== state.document.files[path],
|
||||
);
|
||||
let previewEvidence: unknown = { status: "not-previewed-current-candidate" };
|
||||
if (state.preview && !state.stale)
|
||||
previewEvidence = {
|
||||
status: "compiled-and-preview-session-created",
|
||||
revision: currentRevision,
|
||||
artifactDigest: state.preview.displayData.artifactDigest,
|
||||
browserRenderingVerified: false,
|
||||
liveActions: state.preview.liveActions,
|
||||
};
|
||||
return {
|
||||
installationId: state.installationId,
|
||||
saved: !state.editor.dirty,
|
||||
revision: currentRevision,
|
||||
name: sanitized.name,
|
||||
metadata: metadataOmitted ? undefined : sanitized.metadata,
|
||||
metadataOmitted,
|
||||
selectedFile: state.selected,
|
||||
filePaths: Object.keys(sanitized.files),
|
||||
files,
|
||||
omittedFiles,
|
||||
oversizedFiles: Object.entries(sanitized.files)
|
||||
.filter(([, value]) => value.length > maximumContextCharacters)
|
||||
.map(([path]) => path),
|
||||
contextLimits: {
|
||||
fileCharacters: maximumContextCharacters,
|
||||
metadataCharacters: 60_000,
|
||||
oversizedFilesRequireManualEdit: true,
|
||||
},
|
||||
redactedFiles,
|
||||
metadataRedacted: sanitized.metadata !== state.document.metadata,
|
||||
diagnostics: recoveryDocument({ name: "", metadata: state.error, files: {} }).metadata.slice(0, 4000),
|
||||
schemaValid: state.parsed.success,
|
||||
validationIssues: state.parsed.success
|
||||
? []
|
||||
: state.parsed.error.issues.map(({ path, message }) => ({ path, message })),
|
||||
sdk: packageAssistantSdkContext,
|
||||
reference: input.reference ? widgetReferencePackages[input.reference] : undefined,
|
||||
previewEvidence,
|
||||
excluded: [
|
||||
"local connection bindings",
|
||||
"connection settings and credentials",
|
||||
"preview option values",
|
||||
"runtime response data",
|
||||
],
|
||||
};
|
||||
},
|
||||
review(input) {
|
||||
return prepare(input, latest.current, readState.current).review;
|
||||
},
|
||||
apply(input) {
|
||||
const prepared = prepare(input, latest.current, readState.current);
|
||||
if (!prepared.review.available || !prepared.next) return { applied: false, error: prepared.review.error };
|
||||
latest.current.workspace.resetExecution();
|
||||
readState.current = { revision: "", paths: new Set(), metadata: false };
|
||||
latest.current.workspace.edit(prepared.next);
|
||||
return { applied: true };
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
notifyPackageDraftChanged();
|
||||
}, [revision, workspace.busy, workspace.preview, workspace.error]);
|
||||
}
|
||||
|
||||
function prepare(
|
||||
input: ProposePackageChangesArgs,
|
||||
{ workspace, revision }: { workspace: Workspace; revision: string },
|
||||
read: { revision: string; paths: Set<string>; metadata: boolean },
|
||||
): { review: PackageDraftReview; next?: PackageDocument } {
|
||||
const parsed = packageDraftToolContracts.propose_widget_package_changes.parameters.safeParse(input);
|
||||
if (!parsed.success) return unavailable("The proposed patch is invalid.");
|
||||
if (revision !== input.revision || read.revision !== revision)
|
||||
return unavailable("The draft changed. Ask the Assistant to read the current draft and propose again.");
|
||||
if (workspace.busy) return unavailable("Wait for the current save or preview to finish.");
|
||||
const current = workspace.document;
|
||||
if (input.metadata !== undefined && !read.metadata)
|
||||
return unavailable(
|
||||
"The manifest is too large for Assistant context. Edit it directly before proposing a replacement.",
|
||||
);
|
||||
const sanitized = recoveryDocument(current);
|
||||
if (input.metadata !== undefined && sanitized.metadata !== current.metadata)
|
||||
return unavailable(
|
||||
"The manifest contains redacted credentials. Move them to a local connection before replacing this file.",
|
||||
);
|
||||
if (input.name !== undefined && sanitized.name !== current.name)
|
||||
return unavailable("The name contains redacted credentials. Edit it directly before proposing a replacement.");
|
||||
const next = {
|
||||
name: input.name ?? current.name,
|
||||
metadata: input.metadata ?? current.metadata,
|
||||
files: { ...current.files },
|
||||
};
|
||||
const changes: PackageDraftReview["changes"] = [];
|
||||
if (next.name !== current.name) changes.push({ path: "Installation name", before: current.name, after: next.name });
|
||||
if (next.metadata !== current.metadata)
|
||||
changes.push({ path: "widget.json", before: current.metadata, after: next.metadata });
|
||||
for (const [path, value] of Object.entries(input.files)) {
|
||||
if (Object.hasOwn(current.files, path) && !read.paths.has(path))
|
||||
return unavailable(`Read '${path}' before proposing changes to it.`);
|
||||
if (sanitized.files[path] !== current.files[path])
|
||||
return unavailable(
|
||||
`'${path}' contains redacted credentials. Move them to local connections before replacing this file.`,
|
||||
);
|
||||
if (value === null) delete next.files[path];
|
||||
else next.files[path] = value;
|
||||
if (value !== current.files[path]) changes.push({ path, before: current.files[path] ?? "", after: value ?? "" });
|
||||
}
|
||||
if (
|
||||
Object.keys(next.files).length > 256 ||
|
||||
Object.values(next.files).reduce((size, file) => size + file.length, 0) > 20_000_000
|
||||
)
|
||||
return unavailable("The proposed draft exceeds package size limits.");
|
||||
return { next, review: { available: true, changes } };
|
||||
}
|
||||
|
||||
const unavailable = (error: string) => ({ review: { available: false, error, changes: [] } });
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
import { documentFromSource, recoveryDocument } from "./_package-document";
|
||||
import type { PackageDocument } from "./_package-document";
|
||||
|
||||
const maximumHistoryBytes = 2_000_000;
|
||||
const maximumRecoveryBytes = 1_000_000;
|
||||
|
||||
export function usePackageDocument(initial: PackageDocument, userId: string, installationId?: string) {
|
||||
const [document, setDocument] = useState(initial);
|
||||
const [saved, setSaved] = useState(initial);
|
||||
const [recovery, setRecovery] = useState<PackageDocument | null>(null);
|
||||
const [historyState, setHistoryState] = useState({ undo: false, redo: false });
|
||||
const history = useRef({ entries: [JSON.stringify(initial)], index: 0, lastChange: 0, field: "" });
|
||||
const current = useRef(document);
|
||||
const key = `homarr:custom-widget-recovery:${userId}`;
|
||||
const definitionId = `package:${installationId ?? "new"}`;
|
||||
const dirty = JSON.stringify(document) !== JSON.stringify(saved);
|
||||
current.current = document;
|
||||
|
||||
const syncHistory = () =>
|
||||
setHistoryState({
|
||||
undo: history.current.index > 0,
|
||||
redo: history.current.index < history.current.entries.length - 1,
|
||||
});
|
||||
const edit = (next: PackageDocument, field = "") => {
|
||||
const state = history.current;
|
||||
const serialized = JSON.stringify(next);
|
||||
if (serialized === state.entries[state.index]) return;
|
||||
const now = Date.now();
|
||||
const coalesce =
|
||||
field &&
|
||||
state.field === field &&
|
||||
now - state.lastChange < 600 &&
|
||||
state.index > 0 &&
|
||||
state.index === state.entries.length - 1;
|
||||
state.entries = state.entries.slice(0, state.index + 1);
|
||||
if (coalesce) state.entries[state.index] = serialized;
|
||||
else {
|
||||
state.entries.push(serialized);
|
||||
state.index += 1;
|
||||
}
|
||||
let size = state.entries.reduce((sum, entry) => sum + entry.length, 0);
|
||||
while (state.entries.length > 1 && (state.entries.length > 100 || size > maximumHistoryBytes)) {
|
||||
size -= state.entries.shift()?.length ?? 0;
|
||||
state.index -= 1;
|
||||
}
|
||||
state.lastChange = now;
|
||||
state.field = field;
|
||||
current.current = next;
|
||||
setDocument(next);
|
||||
syncHistory();
|
||||
};
|
||||
const move = (offset: number) => {
|
||||
const state = history.current;
|
||||
const index = state.index + offset;
|
||||
if (index < 0 || index >= state.entries.length) return;
|
||||
state.index = index;
|
||||
state.field = "";
|
||||
const entry = state.entries[index];
|
||||
if (!entry) return;
|
||||
const next = JSON.parse(entry) as PackageDocument;
|
||||
current.current = next;
|
||||
setDocument(next);
|
||||
syncHistory();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
|
||||
if (!isRecord(stored) || stored.definitionId !== definitionId || !isRecord(stored.content)) return;
|
||||
const content = stored.content;
|
||||
if (typeof content.name !== "string" || typeof content.metadata !== "string" || !isRecord(content.files)) return;
|
||||
const next = documentFromSource(content.name, { files: content.files, _draftMetadata: content.metadata });
|
||||
if (JSON.stringify(next) !== JSON.stringify(initial)) setRecovery(next);
|
||||
} catch {
|
||||
/* Browser recovery is optional. */
|
||||
}
|
||||
}, [definitionId, initial, key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (recovery) return;
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
if (!dirty) {
|
||||
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
|
||||
if (isRecord(stored) && stored.definitionId === definitionId) localStorage.removeItem(key);
|
||||
return;
|
||||
}
|
||||
const payload = JSON.stringify({ definitionId, content: recoveryDocument(document) });
|
||||
if (payload.length <= maximumRecoveryBytes) localStorage.setItem(key, payload);
|
||||
} catch {
|
||||
/* Storage may be unavailable or full. */
|
||||
}
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [definitionId, dirty, document, key, recovery]);
|
||||
|
||||
useUnsavedChangesGuard(dirty);
|
||||
|
||||
const discardRecovery = () => {
|
||||
setRecovery(null);
|
||||
try {
|
||||
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
|
||||
if (isRecord(stored) && stored.definitionId === definitionId) localStorage.removeItem(key);
|
||||
} catch {
|
||||
/* Optional storage. */
|
||||
}
|
||||
};
|
||||
const markSaved = (value: PackageDocument) => {
|
||||
setSaved(value);
|
||||
history.current.field = "";
|
||||
if (JSON.stringify(current.current) === JSON.stringify(value)) discardRecovery();
|
||||
};
|
||||
return {
|
||||
document,
|
||||
dirty,
|
||||
edit,
|
||||
undo: () => move(-1),
|
||||
redo: () => move(1),
|
||||
historyState,
|
||||
reset: () => edit(saved),
|
||||
markSaved,
|
||||
recovery,
|
||||
discardRecovery,
|
||||
restoreRecovery: () => {
|
||||
if (recovery) edit(recovery);
|
||||
discardRecovery();
|
||||
},
|
||||
};
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
"use client";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||
import { customWidgetPackageSchema, widgetPackagePathSchema } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import clock from "@homarr/widget-sdk/examples/clock.json";
|
||||
import { documentFromSource, documentFromTemplate, documentSource } from "./_package-document";
|
||||
import { usePackageDocument } from "./_use-package-document";
|
||||
export type Installation = RouterOutputs["customWidget"]["package"]["get"];
|
||||
type Preview = RouterOutputs["customWidget"]["package"]["preview"] & { liveActions: boolean };
|
||||
export function usePackageWorkspace(
|
||||
installation: Installation | undefined,
|
||||
userId: string,
|
||||
initialSource?: unknown,
|
||||
initialName?: string,
|
||||
initialBindings?: Record<string, string>,
|
||||
initialBoardId?: string,
|
||||
) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const [initial] = useState(() => {
|
||||
if (installation) return documentFromSource(installation.name, installation.source);
|
||||
return documentFromTemplate(initialName ?? t("newName"), initialSource ?? clock);
|
||||
});
|
||||
const editor = usePackageDocument(initial, userId, installation?.id);
|
||||
const { document, edit } = editor;
|
||||
const [selected, setSelected] = useState(Object.keys(initial.files)[0] ?? "/widget.json");
|
||||
const [path, setPath] = useState("");
|
||||
useEffect(() => {
|
||||
if (selected !== "/widget.json" && !Object.hasOwn(document.files, selected)) setSelected("/widget.json");
|
||||
}, [document.files, selected]);
|
||||
const [pane, setPane] = useState("edit");
|
||||
const [trusted, setTrusted] = useState(false);
|
||||
const [scenario, setScenario] = useState<string | null>(null);
|
||||
const [liveActions, setLiveActions] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [message, setMessage] = useState("");
|
||||
const [bindings, setBindings] = useState(installation?.bindings ?? initialBindings ?? {});
|
||||
const savedInstallationId = useRef(installation?.id);
|
||||
const [options, setOptions] = useState<Record<string, unknown>>({});
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [previewExecutionKey, setPreviewExecutionKey] = useState("");
|
||||
const [stale, setStale] = useState(false);
|
||||
const [surface, setSurface] = useState<"tile" | "advanced" | "configuration">("tile");
|
||||
const [width, setWidth] = useState(320);
|
||||
const [height, setHeight] = useState(260);
|
||||
const [scale, setScale] = useState(1);
|
||||
const [previewTheme, setPreviewTheme] = useState<"system" | "light" | "dark">("system");
|
||||
const previewId = useRef<string | null>(null);
|
||||
const retiredPreviewIds = useRef(new Set<string>());
|
||||
const generation = useRef(0);
|
||||
const source = useMemo(() => documentSource(document), [document]);
|
||||
const parsed = useMemo(() => customWidgetPackageSchema.safeParse(source), [source]);
|
||||
const defaults = useMemo(() => (parsed.success ? getCustomWidgetDefaultOptions(parsed.data.options) : {}), [parsed]);
|
||||
const effectiveOptions = useMemo(() => ({ ...defaults, ...options }), [defaults, options]);
|
||||
const save = clientApi.customWidget.package.saveDraft.useMutation();
|
||||
const previewMutation = clientApi.customWidget.package.preview.useMutation();
|
||||
const discard = clientApi.customWidget.package.discardPreview.useMutation();
|
||||
const saveBindings = clientApi.customWidget.package.setBindings.useMutation();
|
||||
const discardPreview = discard.mutate;
|
||||
const busy = save.isPending || saveBindings.isPending || previewMutation.isPending;
|
||||
const resetExecution = useCallback(() => {
|
||||
generation.current += 1;
|
||||
if (previewId.current) setStale(true);
|
||||
}, []);
|
||||
const executionKey = JSON.stringify([source, bindings, effectiveOptions, liveActions, scenario]);
|
||||
useEffect(() => {
|
||||
resetExecution();
|
||||
}, [executionKey, resetExecution]);
|
||||
useEffect(() => {
|
||||
setTrusted(false);
|
||||
}, [source]);
|
||||
useEffect(() => {
|
||||
setLiveActions(false);
|
||||
}, [source, bindings, scenario]);
|
||||
useEffect(() => {
|
||||
if (scenario && parsed.success && !parsed.data.previewScenarios?.[scenario]) setScenario(null);
|
||||
}, [parsed, scenario]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
generation.current += 1;
|
||||
if (previewId.current) discardPreview({ previewId: previewId.current });
|
||||
for (const id of retiredPreviewIds.current) discardPreview({ previewId: id });
|
||||
retiredPreviewIds.current.clear();
|
||||
},
|
||||
[discardPreview],
|
||||
);
|
||||
|
||||
const saveDraft = async () => {
|
||||
setError("");
|
||||
setMessage("");
|
||||
const submitted = document;
|
||||
try {
|
||||
const result = await save.mutateAsync({ id: savedInstallationId.current, name: document.name, source });
|
||||
savedInstallationId.current = result.id;
|
||||
if (!installation && Object.keys(bindings).length > 0)
|
||||
await saveBindings.mutateAsync({ id: result.id, bindings });
|
||||
editor.markSaved(submitted);
|
||||
await Promise.all([
|
||||
utils.customWidget.package.get.invalidate(),
|
||||
utils.customWidget.package.list.invalidate(),
|
||||
utils.customWidget.package.draftChanges.invalidate(),
|
||||
utils.customWidget.package.inspectArtifact.invalidate(),
|
||||
]);
|
||||
setMessage(t("draftSaved"));
|
||||
if (!installation) {
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||
const destination = new URL(result.managementPath, window.location.origin);
|
||||
if (initialBoardId) destination.searchParams.set("boardId", initialBoardId);
|
||||
window.location.assign(destination.pathname + destination.search);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
const runPreview = async () => {
|
||||
if (!installation || !trusted || !parsed.success) return;
|
||||
resetExecution();
|
||||
setError("");
|
||||
const currentGeneration = generation.current;
|
||||
try {
|
||||
const next = await previewMutation.mutateAsync({
|
||||
id: installation.id,
|
||||
source,
|
||||
options: effectiveOptions,
|
||||
bindings,
|
||||
trusted: true,
|
||||
liveActions,
|
||||
scenario: scenario ?? undefined,
|
||||
});
|
||||
if (generation.current !== currentGeneration) {
|
||||
discardPreview({ previewId: next.previewId });
|
||||
return;
|
||||
}
|
||||
if (previewId.current) retiredPreviewIds.current.add(previewId.current);
|
||||
previewId.current = next.previewId;
|
||||
setPreview({ ...next, liveActions });
|
||||
setPreviewExecutionKey(executionKey);
|
||||
setStale(false);
|
||||
setPane("preview");
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
const addFile = () => {
|
||||
const checked = widgetPackagePathSchema.safeParse(path.trim());
|
||||
if (!checked.success) {
|
||||
setError(checked.error.issues[0]?.message ?? t("invalidPath"));
|
||||
return;
|
||||
}
|
||||
if (Object.hasOwn(document.files, checked.data)) {
|
||||
setError(t("duplicatePath"));
|
||||
return;
|
||||
}
|
||||
edit({ ...document, files: { ...document.files, [checked.data]: "" } });
|
||||
setSelected(checked.data);
|
||||
setPath("");
|
||||
};
|
||||
const removeFile = () => {
|
||||
if (selected === "/widget.json") return;
|
||||
const files = { ...document.files };
|
||||
delete files[selected];
|
||||
edit({ ...document, files });
|
||||
setSelected("/widget.json");
|
||||
};
|
||||
const renameFile = () => {
|
||||
if (selected === "/widget.json") return;
|
||||
const checked = widgetPackagePathSchema.safeParse(path.trim());
|
||||
if (!checked.success || Object.hasOwn(document.files, path.trim())) {
|
||||
setError(t("invalidPath"));
|
||||
return;
|
||||
}
|
||||
const files = { ...document.files, [checked.data]: document.files[selected] ?? "" };
|
||||
delete files[selected];
|
||||
edit({ ...document, files });
|
||||
setSelected(checked.data);
|
||||
setPath("");
|
||||
setMessage(t("renameImports"));
|
||||
};
|
||||
let editorValue = document.metadata;
|
||||
let language: "tsx" | "json" | "css" = "json";
|
||||
if (selected !== "/widget.json") {
|
||||
editorValue = document.files[selected] ?? "";
|
||||
language = "tsx";
|
||||
if (selected.endsWith(".css")) language = "css";
|
||||
if (selected.endsWith(".json")) language = "json";
|
||||
}
|
||||
const surfaceChoices = [{ value: "tile", label: t("tile") }];
|
||||
if (parsed.success && parsed.data.manifest.entrypoints.advanced)
|
||||
surfaceChoices.push({ value: "advanced", label: t("advanced") });
|
||||
if (parsed.success && parsed.data.manifest.entrypoints.configuration)
|
||||
surfaceChoices.push({ value: "configuration", label: t("configuration") });
|
||||
const saveLocalBindings = () => {
|
||||
if (!installation) return;
|
||||
saveBindings.mutate(
|
||||
{ id: installation.id, bindings },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setMessage(t("bindingsSaved"));
|
||||
void utils.customWidget.package.get.invalidate();
|
||||
void utils.customWidget.package.guestGrants.invalidate();
|
||||
void utils.customWidget.package.webhooks.invalidate();
|
||||
},
|
||||
onError: (cause) => setError(cause.message),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const previewReady = (id: string) => {
|
||||
if (previewId.current !== id) return;
|
||||
for (const retired of retiredPreviewIds.current) {
|
||||
if (retired !== id) discardPreview({ previewId: retired });
|
||||
}
|
||||
retiredPreviewIds.current.clear();
|
||||
};
|
||||
const previewLoadError = (id: string, cause: Error) => {
|
||||
if (previewId.current !== id) return;
|
||||
setStale(true);
|
||||
setError(cause.message);
|
||||
};
|
||||
|
||||
return {
|
||||
installationId: savedInstallationId.current,
|
||||
editor,
|
||||
document,
|
||||
edit,
|
||||
selected,
|
||||
setSelected,
|
||||
path,
|
||||
setPath,
|
||||
pane,
|
||||
setPane,
|
||||
trusted,
|
||||
setTrusted,
|
||||
liveActions,
|
||||
setLiveActions,
|
||||
scenario,
|
||||
setScenario,
|
||||
error,
|
||||
setError,
|
||||
message,
|
||||
setMessage,
|
||||
bindings,
|
||||
setBindings,
|
||||
options,
|
||||
setOptions,
|
||||
preview,
|
||||
stale: Boolean(preview) && (stale || previewExecutionKey !== executionKey),
|
||||
previewReady,
|
||||
previewLoadError,
|
||||
surface,
|
||||
setSurface,
|
||||
width,
|
||||
setWidth,
|
||||
height,
|
||||
setHeight,
|
||||
scale,
|
||||
setScale,
|
||||
previewTheme,
|
||||
setPreviewTheme,
|
||||
source,
|
||||
parsed,
|
||||
effectiveOptions,
|
||||
save,
|
||||
previewMutation,
|
||||
saveBindings,
|
||||
busy,
|
||||
saveDraft,
|
||||
runPreview,
|
||||
addFile,
|
||||
removeFile,
|
||||
renameFile,
|
||||
editorValue,
|
||||
language,
|
||||
surfaceChoices,
|
||||
saveLocalBindings,
|
||||
resetExecution,
|
||||
connectionChanged: () => {
|
||||
setLiveActions(false);
|
||||
resetExecution();
|
||||
},
|
||||
};
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Button } from "@mantine/core";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { CustomWidgetTabs } from "../../../_custom-widget-tabs";
|
||||
import { PackageCollectionSetup } from "../_collection-setup";
|
||||
|
||||
export default async function WidgetCollectionPage({ params }: { params: Promise<{ importId: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const { importId } = await params;
|
||||
const [collection, t] = await Promise.all([
|
||||
api.customWidget.package.collection({ importId }),
|
||||
getI18n("customWidget.package"),
|
||||
]);
|
||||
return (
|
||||
<ManagePageLayout
|
||||
title={collection.manifest.name}
|
||||
breadcrumb={<DynamicBreadcrumb dynamicMappings={new Map([[importId, collection.manifest.name]])} />}
|
||||
toolbar={<CustomWidgetTabs active="packages" />}
|
||||
primaryAction={
|
||||
<Button component={Link} href="/manage/custom-widgets/packages/collections" variant="default">
|
||||
{t("collections.title")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<PackageCollectionSetup initialData={collection} />
|
||||
</ManagePageLayout>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Accordion, Alert, Button, Group, MultiSelect, Stack, Text, TextInput } from "@mantine/core";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { fetchApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { downloadPackage } from "../_package-document";
|
||||
|
||||
export function PackageCollectionExport({
|
||||
installations,
|
||||
}: {
|
||||
installations: RouterOutputs["customWidget"]["package"]["list"];
|
||||
}) {
|
||||
const t = useI18n("customWidget.package.collections");
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [id, setId] = useState("");
|
||||
const [version, setVersion] = useState("1.0.0");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const exportCollection = async () => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const archive = await fetchApi.customWidget.package.exportCollection.query({
|
||||
manifest: { id, name, version },
|
||||
installationIds: selected,
|
||||
});
|
||||
downloadPackage(name, archive);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Accordion variant="contained">
|
||||
<Accordion.Item value="export">
|
||||
<Accordion.Control>{t("export")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("exportDescription")}
|
||||
</Text>
|
||||
<MultiSelect
|
||||
label={t("widgets")}
|
||||
searchable
|
||||
value={selected}
|
||||
onChange={setSelected}
|
||||
maxValues={32}
|
||||
data={installations
|
||||
.filter((entry) => entry.activeArtifactId)
|
||||
.map((entry) => ({ value: entry.id, label: entry.name }))}
|
||||
/>
|
||||
<Group grow>
|
||||
<TextInput label={t("name")} value={name} onChange={(event) => setName(event.currentTarget.value)} />
|
||||
<TextInput
|
||||
label={t("identity")}
|
||||
description={t("identityDescription")}
|
||||
placeholder={t("identityPlaceholder")}
|
||||
value={id}
|
||||
onChange={(event) => setId(event.currentTarget.value)}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("version")}
|
||||
value={version}
|
||||
onChange={(event) => setVersion(event.currentTarget.value)}
|
||||
/>
|
||||
</Group>
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
<Button
|
||||
loading={busy}
|
||||
disabled={!selected.length || !name.trim() || !id.trim()}
|
||||
onClick={() => void exportCollection()}
|
||||
>
|
||||
{t("export")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { Alert, Badge, Button, Stack, Text } from "@mantine/core";
|
||||
import { IconLayoutGrid } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { ManageCollectionItem, ManageCollectionList } from "~/components/manage/manage-collection";
|
||||
import { PackageCollectionExport } from "./_collection-export";
|
||||
|
||||
export function PackageCollectionList({
|
||||
initialData,
|
||||
installations,
|
||||
}: {
|
||||
initialData: RouterOutputs["customWidget"]["package"]["collections"];
|
||||
installations: RouterOutputs["customWidget"]["package"]["list"];
|
||||
}) {
|
||||
const t = useI18n("customWidget.package.collections");
|
||||
const collections = clientApi.customWidget.package.collections.useQuery(undefined, { initialData });
|
||||
return (
|
||||
<Stack>
|
||||
<Text c="dimmed">{t("description")}</Text>
|
||||
<PackageCollectionExport installations={installations} />
|
||||
{collections.data?.length === 0 && <Alert>{t("empty")}</Alert>}
|
||||
<ManageCollectionList ariaLabel={t("title")}>
|
||||
{collections.data?.map((collection) => (
|
||||
<ManageCollectionItem
|
||||
key={collection.importId}
|
||||
leading={<IconLayoutGrid size={26} stroke={1.4} />}
|
||||
title={<Text fw={600}>{collection.manifest.name}</Text>}
|
||||
badges={<Badge variant="light">{collection.manifest.version}</Badge>}
|
||||
description={
|
||||
<Stack gap={2}>
|
||||
<Text size="sm" c="dimmed">
|
||||
{collection.manifest.description}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("members", { count: collection.installationIds.length, enabled: collection.enabledCount })}
|
||||
</Text>
|
||||
</Stack>
|
||||
}
|
||||
actions={
|
||||
<Button
|
||||
component={Link}
|
||||
href={"/manage/custom-widgets/packages/collections/" + collection.importId}
|
||||
variant="default"
|
||||
>
|
||||
{t("configure")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ManageCollectionList>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Accordion, Alert, Badge, Button, Checkbox, Group, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { PackageOptionFields } from "@homarr/widgets/custom-api/package-option-fields";
|
||||
|
||||
import { PackageConnections } from "../_package-connections";
|
||||
import { useCollectionPlacement } from "./_use-collection-placement";
|
||||
import type { CollectionConfiguration, WidgetCollection } from "./_use-collection-placement";
|
||||
|
||||
export function PackageCollectionSetup({ initialData }: { initialData: WidgetCollection }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const query = clientApi.customWidget.package.collection.useQuery({ importId: initialData.importId }, { initialData });
|
||||
const collection = query.data;
|
||||
const boards = clientApi.board.getAllBoards.useQuery();
|
||||
const saveBindings = clientApi.customWidget.package.setCollectionBindings.useMutation();
|
||||
const [bindings, setBindings] = useState(initialData.bindings);
|
||||
const [configuration, setConfiguration] = useState<CollectionConfiguration>({});
|
||||
const [selected, setSelected] = useState(initialData.entries.map((entry) => entry.id));
|
||||
const [boardId, setBoardId] = useState<string | null>(null);
|
||||
const [reviewedKey, setReviewedKey] = useState<string | null>(null);
|
||||
const reviewKey = JSON.stringify([
|
||||
collection.entries.filter((entry) => selected.includes(entry.id)).map((entry) => [entry.id, entry.draftDigest]),
|
||||
bindings,
|
||||
]);
|
||||
const trusted = reviewedKey === reviewKey;
|
||||
const setTrusted = (value: boolean) => {
|
||||
setReviewedKey(value ? reviewKey : null);
|
||||
};
|
||||
const [error, setError] = useState("");
|
||||
const progress = useCollectionPlacement(collection);
|
||||
const busy = progress.busy || saveBindings.isPending;
|
||||
const board = boards.data?.find((candidate) => candidate.id === boardId);
|
||||
const requiredSlots = new Set(
|
||||
collection.entries
|
||||
.filter((entry) => selected.includes(entry.id))
|
||||
.flatMap((entry) =>
|
||||
Object.entries(entry.requirements)
|
||||
.filter(([, requirement]) => !requirement.optional)
|
||||
.map(([name]) => entry.mapping[name]),
|
||||
),
|
||||
);
|
||||
const missing = Object.entries(collection.connections).filter(([name]) => requiredSlots.has(name) && !bindings[name]);
|
||||
const save = () => {
|
||||
setError("");
|
||||
saveBindings.mutate(
|
||||
{ importId: collection.importId, bindings },
|
||||
{
|
||||
onSuccess: () => void query.refetch(),
|
||||
onError: (cause) => setError(cause.message),
|
||||
},
|
||||
);
|
||||
};
|
||||
return (
|
||||
<Stack>
|
||||
<Group>
|
||||
<Badge variant="light">{collection.manifest.version}</Badge>
|
||||
{collection.manifest.author && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{collection.manifest.author}
|
||||
</Text>
|
||||
)}
|
||||
{collection.manifest.license && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{collection.manifest.license}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Text c="dimmed">{collection.manifest.description ?? t("collections.description")}</Text>
|
||||
<Text size="sm">{t("collections.setupDescription")}</Text>
|
||||
{(error || progress.error) && <Alert color="red">{error || progress.error}</Alert>}
|
||||
{collection.bindingConflicts.length > 0 && (
|
||||
<Alert color="yellow">
|
||||
{t("collections.bindingConflicts", { names: collection.bindingConflicts.join(", ") })}
|
||||
</Alert>
|
||||
)}
|
||||
{Object.keys(collection.connections).length > 0 && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("connections")}</Text>
|
||||
<PackageConnections
|
||||
requirements={collection.connections}
|
||||
bindings={bindings}
|
||||
onChange={setBindings}
|
||||
onSave={save}
|
||||
saving={busy}
|
||||
onConnectionSaved={() => setTrusted(false)}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("collections.widgets")}</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("collections.optionsDescription")}
|
||||
</Text>
|
||||
{collection.entries.map((entry) => (
|
||||
<Stack key={entry.id} gap="xs">
|
||||
<Group justify="space-between">
|
||||
<Checkbox
|
||||
checked={selected.includes(entry.id)}
|
||||
disabled={busy || !entry.manifest}
|
||||
label={entry.name}
|
||||
onChange={(event) => {
|
||||
const checked = event.currentTarget.checked;
|
||||
setSelected((current) =>
|
||||
checked ? [...current, entry.id] : current.filter((id) => id !== entry.id),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
component={Link}
|
||||
href={entry.managementPath}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
variant="subtle"
|
||||
size="compact-xs"
|
||||
>
|
||||
{t("collections.review")}
|
||||
</Button>
|
||||
</Group>
|
||||
{!entry.manifest && <Alert color="red">{t("collections.needsRepair", { name: entry.name })}</Alert>}
|
||||
{progress.status[entry.id] && (
|
||||
<Text size="sm" c={progress.status[entry.id]?.failed ? "red" : "dimmed"}>
|
||||
{progress.status[entry.id]?.text}
|
||||
</Text>
|
||||
)}
|
||||
{Object.keys(entry.optionDefinitions).length > 0 && (
|
||||
<Accordion variant="default">
|
||||
<Accordion.Item value="options">
|
||||
<Accordion.Control>{t("options")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<div inert={busy}>
|
||||
<PackageOptionFields
|
||||
schema={entry.optionDefinitions}
|
||||
value={configuration[entry.id] ?? entry.configuration}
|
||||
onChange={(value) => setConfiguration((current) => ({ ...current, [entry.id]: value }))}
|
||||
/>
|
||||
</div>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)}
|
||||
</Stack>
|
||||
))}
|
||||
</Stack>
|
||||
</Paper>
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Select
|
||||
searchable
|
||||
label={t("board")}
|
||||
value={boardId}
|
||||
onChange={setBoardId}
|
||||
disabled={busy}
|
||||
data={(boards.data ?? []).map((candidate) => ({ value: candidate.id, label: candidate.name }))}
|
||||
/>
|
||||
{missing.length > 0 && (
|
||||
<Alert color="yellow">
|
||||
{t("bindFirst", { names: missing.map(([, requirement]) => requirement.label).join(", ") })}
|
||||
</Alert>
|
||||
)}
|
||||
<Checkbox
|
||||
checked={trusted}
|
||||
disabled={busy}
|
||||
onChange={(event) => setTrusted(event.currentTarget.checked)}
|
||||
label={t("collections.trust")}
|
||||
/>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("collections.activationDescription")}
|
||||
</Text>
|
||||
<Group>
|
||||
<Button
|
||||
loading={progress.busy}
|
||||
disabled={!board || !trusted || !selected.length || missing.length > 0 || saveBindings.isPending}
|
||||
onClick={() => {
|
||||
if (board) void progress.run(board, selected, bindings, configuration);
|
||||
}}
|
||||
>
|
||||
{t("collections.activateAndAdd")}
|
||||
</Button>
|
||||
{progress.busy && (
|
||||
<Button variant="default" disabled={progress.stopping} onClick={progress.stop}>
|
||||
{t("collections.stop")}
|
||||
</Button>
|
||||
)}
|
||||
{progress.completedBoard && (
|
||||
<Button component={Link} href={"/boards/" + encodeURIComponent(progress.completedBoard)} variant="light">
|
||||
{t("openBoard")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi, fetchApi } from "@homarr/api/client";
|
||||
import { validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export type WidgetCollection = RouterOutputs["customWidget"]["package"]["collection"];
|
||||
export type CollectionConfiguration = Record<string, Record<string, unknown>>;
|
||||
|
||||
export function useCollectionPlacement(collection: WidgetCollection) {
|
||||
const t = useI18n("customWidget.package.collections");
|
||||
const utils = clientApi.useUtils();
|
||||
const stopRequested = useRef(false);
|
||||
const running = useRef(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [status, setStatus] = useState<Record<string, { text: string; failed?: boolean }>>({});
|
||||
const [completedBoard, setCompletedBoard] = useState<string | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
stopRequested.current = true;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const run = async (
|
||||
board: { id: string; name: string },
|
||||
selected: string[],
|
||||
bindings: Record<string, string>,
|
||||
configuration: CollectionConfiguration,
|
||||
) => {
|
||||
if (running.current) return;
|
||||
setError("");
|
||||
setStatus({});
|
||||
setCompletedBoard(null);
|
||||
const entries = collection.entries.filter((entry) => selected.includes(entry.id));
|
||||
for (const entry of entries) {
|
||||
if (!entry.manifest) {
|
||||
setError(t("needsRepair", { name: entry.name }));
|
||||
return;
|
||||
}
|
||||
const issue = validateCustomWidgetOptions(
|
||||
entry.optionDefinitions,
|
||||
configuration[entry.id] ?? entry.configuration,
|
||||
)[0];
|
||||
if (issue) {
|
||||
setError(entry.name + ": " + issue.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
stopRequested.current = false;
|
||||
running.current = true;
|
||||
setStopping(false);
|
||||
setBusy(true);
|
||||
let added = false;
|
||||
try {
|
||||
await fetchApi.customWidget.package.setCollectionBindings.mutate({ importId: collection.importId, bindings });
|
||||
for (const entry of entries) {
|
||||
if (stopRequested.current) break;
|
||||
const report = (text: string, failed = false) =>
|
||||
setStatus((current) => ({ ...current, [entry.id]: { text, failed } }));
|
||||
try {
|
||||
report(t("activating"));
|
||||
await fetchApi.customWidget.package.activate.mutate({
|
||||
id: entry.id,
|
||||
trusted: true,
|
||||
expectedDraftDigest: entry.draftDigest,
|
||||
});
|
||||
const installation = await fetchApi.customWidget.package.get.query({ id: entry.id });
|
||||
// A response may have been lost after a successful previous add. Reading the installed
|
||||
// placements makes a user's retry reuse that tile instead of duplicating it.
|
||||
if (installation.placements.some((placement) => placement.boardId === board.id)) {
|
||||
report(t("alreadyPlaced"));
|
||||
added = true;
|
||||
continue;
|
||||
}
|
||||
report(t("adding"));
|
||||
await fetchApi.board.addItem.mutate({
|
||||
boardId: board.id,
|
||||
kind: "customApi",
|
||||
integrationIds: [],
|
||||
options: {
|
||||
definitionId: entry.id,
|
||||
configuration: configuration[entry.id] ?? entry.configuration,
|
||||
configurationVersion: entry.manifest?.configurationVersion ?? 1,
|
||||
connectionBindings: {},
|
||||
refreshInterval: 30,
|
||||
},
|
||||
});
|
||||
report(t("added"));
|
||||
added = true;
|
||||
} catch (cause) {
|
||||
report(cause instanceof Error ? cause.message : String(cause), true);
|
||||
}
|
||||
}
|
||||
if (added) setCompletedBoard(board.name);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
} finally {
|
||||
running.current = false;
|
||||
setBusy(false);
|
||||
setStopping(false);
|
||||
await Promise.allSettled([
|
||||
utils.customWidget.package.collection.invalidate({ importId: collection.importId }),
|
||||
utils.customWidget.package.collections.invalidate(),
|
||||
utils.customWidget.package.list.invalidate(),
|
||||
]);
|
||||
}
|
||||
};
|
||||
return {
|
||||
run,
|
||||
busy,
|
||||
stopping,
|
||||
error,
|
||||
status,
|
||||
completedBoard,
|
||||
stop() {
|
||||
stopRequested.current = true;
|
||||
setStopping(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Button, Group } from "@mantine/core";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { CustomWidgetTabs } from "../../_custom-widget-tabs";
|
||||
import { PackageImportButton } from "../_package-list";
|
||||
import { PackageCollectionList } from "./_collection-list";
|
||||
|
||||
export default async function WidgetCollectionsPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const [collections, installations, t] = await Promise.all([
|
||||
api.customWidget.package.collections(),
|
||||
api.customWidget.package.list(),
|
||||
getI18n("customWidget.package"),
|
||||
]);
|
||||
return (
|
||||
<ManagePageLayout
|
||||
title={t("collections.title")}
|
||||
toolbar={<CustomWidgetTabs active="packages" />}
|
||||
primaryAction={
|
||||
<Group gap="xs">
|
||||
<Button component={Link} href="/manage/custom-widgets/packages" variant="subtle">
|
||||
{t("library")}
|
||||
</Button>
|
||||
<PackageImportButton />
|
||||
</Group>
|
||||
}
|
||||
>
|
||||
<PackageCollectionList initialData={collections} installations={installations} />
|
||||
</ManagePageLayout>
|
||||
);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Container } from "@mantine/core";
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
|
||||
import { PackageConvert } from "../../_package-convert";
|
||||
|
||||
export default async function ConvertWidgetPage({ params }: { params: Promise<{ definitionId: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const { definitionId } = await params;
|
||||
const definition = await api.customWidget.get({ id: definitionId }).catch(catchTrpcNotFound);
|
||||
return (
|
||||
<Container size="sm">
|
||||
<PackageConvert definitionId={definitionId} name={definition.name} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Container, Stack, Title } from "@mantine/core";
|
||||
|
||||
import { widgetReferencePackages } from "@homarr/widget-sdk/examples";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
|
||||
import { NativePackageWorkspace } from "../_package-native-workspace";
|
||||
import { PackageWorkspace } from "../_package-workspace";
|
||||
|
||||
export default async function NewWidgetPackagePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ starter?: string; sourceItemId?: string }>;
|
||||
}) {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const t = await getI18n("customWidget.package");
|
||||
const query = await searchParams;
|
||||
const starter = Object.entries(widgetReferencePackages).find(([key]) => key === query.starter)?.[1];
|
||||
if (query.sourceItemId && query.starter && Object.hasOwn(widgetReferencePackages, query.starter))
|
||||
return (
|
||||
<Container fluid>
|
||||
<NativePackageWorkspace
|
||||
userId={session.user.id}
|
||||
sourceItemId={query.sourceItemId}
|
||||
starter={query.starter as keyof typeof widgetReferencePackages}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
return (
|
||||
<Container fluid>
|
||||
<Stack>
|
||||
<Title>{t("create")}</Title>
|
||||
<PackageWorkspace userId={session.user.id} initialSource={starter} />
|
||||
</Stack>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Button, Group } from "@mantine/core";
|
||||
import { IconLayoutGrid, IconPlus } from "@tabler/icons-react";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
|
||||
import { CustomWidgetTabs } from "../_custom-widget-tabs";
|
||||
import { PackageImportButton, PackageList } from "./_package-list";
|
||||
|
||||
export default async function WidgetPackagesPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const installations = await api.customWidget.package.list();
|
||||
const t = await getI18n("customWidget.package");
|
||||
return (
|
||||
<ManagePageLayout
|
||||
title={t("title")}
|
||||
toolbar={<CustomWidgetTabs active="packages" />}
|
||||
primaryAction={
|
||||
<Group gap="xs">
|
||||
<Button
|
||||
component={Link}
|
||||
href="/manage/custom-widgets/packages/collections"
|
||||
variant="default"
|
||||
leftSection={<IconLayoutGrid size={16} />}
|
||||
>
|
||||
{t("collections.title")}
|
||||
</Button>
|
||||
<PackageImportButton />
|
||||
<MobileAffixButton
|
||||
component={Link}
|
||||
href="/manage/custom-widgets/packages/new"
|
||||
leftSection={<IconPlus size={16} />}
|
||||
>
|
||||
{t("create")}
|
||||
</MobileAffixButton>
|
||||
</Group>
|
||||
}
|
||||
>
|
||||
<PackageList initialData={installations} />
|
||||
</ManagePageLayout>
|
||||
);
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { Container } from "@mantine/core";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { PackageSessionPreview } from "../../_package-session-preview";
|
||||
|
||||
export default async function PackagePreviewPage({ params }: { params: Promise<{ previewId: string }> }) {
|
||||
const session = await auth();
|
||||
if (!session?.user.permissions.includes("admin")) redirect("/manage/custom-widgets");
|
||||
const { previewId } = await params;
|
||||
return (
|
||||
<Container fluid>
|
||||
<PackageSessionPreview previewId={previewId} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Accordion, Alert, Button, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CodeEditor } from "~/components/custom-widgets/code-editor";
|
||||
import { PackageConnections } from "../../packages/_package-connections";
|
||||
import { PackageArtifactReview } from "../../packages/_package-artifact-review";
|
||||
|
||||
export function WorkshopPackageReview({ submissionId }: { submissionId: string }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const releases = clientApi.customWidget.package.workshopReleases.useQuery({ submissionId });
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const releaseId = selected ?? releases.data?.[0]?.id ?? "";
|
||||
const release = clientApi.customWidget.package.workshopRelease.useQuery(
|
||||
{ releaseId },
|
||||
{ enabled: Boolean(releaseId) },
|
||||
);
|
||||
const [bindings, setBindings] = useState<Record<string, string>>({});
|
||||
const install = clientApi.customWidget.package.installWorkshop.useMutation();
|
||||
return (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text fw={600}>{t("releaseReview")}</Text>
|
||||
<Text size="sm">{t("sourceOnly")}</Text>
|
||||
<Select
|
||||
label={t("release")}
|
||||
data={(releases.data ?? []).map((entry) => ({
|
||||
value: entry.id,
|
||||
label: `${entry.version} · ${entry.created}`,
|
||||
}))}
|
||||
value={releaseId || null}
|
||||
onChange={(value) => {
|
||||
setSelected(value);
|
||||
setBindings({});
|
||||
}}
|
||||
/>
|
||||
{releases.error && <Alert color="red">{releases.error.message}</Alert>}
|
||||
{release.error && <Alert color="red">{release.error.message}</Alert>}
|
||||
{release.data && (
|
||||
<>
|
||||
<Text size="sm" style={{ whiteSpace: "pre-wrap" }}>
|
||||
{release.data.release.changelog}
|
||||
</Text>
|
||||
<Text size="sm">
|
||||
{t("dependencies")}:{" "}
|
||||
{Object.entries(release.data.source.dependencies)
|
||||
.map(([name, version]) => `${name}@${version}`)
|
||||
.join(", ") || t("hostOnly")}
|
||||
</Text>
|
||||
<Text size="xs" ff="monospace">
|
||||
{release.data.origin.sourceDigest}
|
||||
</Text>
|
||||
<Accordion>
|
||||
{Object.entries(release.data.source.files).map(([path, content]) => (
|
||||
<Accordion.Item key={path} value={path}>
|
||||
<Accordion.Control>{path}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<CodeEditor
|
||||
id={`workshop-${path}`}
|
||||
label={path}
|
||||
language={path.endsWith(".css") ? "css" : "tsx"}
|
||||
value={content}
|
||||
readOnly
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
))}
|
||||
</Accordion>
|
||||
{release.data.artifact && <PackageArtifactReview artifact={release.data.artifact} />}
|
||||
<PackageConnections
|
||||
requirements={release.data.source.connections}
|
||||
bindings={bindings}
|
||||
onChange={setBindings}
|
||||
saving={false}
|
||||
/>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("installDisabled")}
|
||||
</Text>
|
||||
<Button
|
||||
loading={install.isPending}
|
||||
onClick={() =>
|
||||
install.mutate(
|
||||
{ releaseId, bindings },
|
||||
{ onSuccess: (result) => window.location.assign(result.managementPath) },
|
||||
)
|
||||
}
|
||||
>
|
||||
{t("installReview")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{install.error && <Alert color="red">{install.error.message}</Alert>}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
+24
-12
@@ -20,6 +20,8 @@ import {
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { IconAlertTriangle, IconArrowLeft, IconDownload, IconExternalLink, IconFlag } from "@tabler/icons-react";
|
||||
|
||||
import { CUSTOM_WIDGET_PACKAGE_SCHEMA } from "@homarr/custom-widgets/package";
|
||||
import { WorkshopPackageReview } from "./_package-review";
|
||||
import { CUSTOM_WIDGET_SCHEMA } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import { CustomWidgetSourceSetupPanel, ImportReviewContent } from "@homarr/custom-widgets/workbench";
|
||||
@@ -27,7 +29,7 @@ import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { useWorkshopReportSummariesQuery, useWorkshopSubmissionQuery } from "@homarr/workshop/backend";
|
||||
import type { WorkshopSubmissionDetail } from "@homarr/workshop/schema";
|
||||
import { validateWorkshopWidget, workshopExportFilename } from "@homarr/workshop/schema";
|
||||
import { validateWorkshopContent, workshopExportFilename } from "@homarr/workshop/schema";
|
||||
|
||||
import { useCustomWidgetImport } from "~/components/custom-widgets/use-custom-widget-import";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
@@ -53,11 +55,18 @@ export function WorkshopDetail({ id }: { id: string }) {
|
||||
const reportSummaries = useWorkshopReportSummariesQuery(session.client, detail.data?.reportCount ? id : "");
|
||||
|
||||
const content = detail.data?.content;
|
||||
const validation = useMemo(() => (content ? validateWorkshopWidget(content) : null), [content]);
|
||||
const validation = useMemo(() => (content ? validateWorkshopContent("customWidget", content) : null), [content]);
|
||||
const widget = useMemo<HomarrCustomWidgetV2 | null>(
|
||||
() => (validation?.success && typeof validation.data !== "string" ? validation.data : null),
|
||||
() =>
|
||||
validation?.success && typeof validation.data !== "string" && validation.data.$schema === CUSTOM_WIDGET_SCHEMA
|
||||
? validation.data
|
||||
: null,
|
||||
[validation],
|
||||
);
|
||||
const packageCompatible =
|
||||
validation?.success &&
|
||||
typeof validation.data !== "string" &&
|
||||
validation.data.$schema === CUSTOM_WIDGET_PACKAGE_SCHEMA;
|
||||
const compatible =
|
||||
detail.data?.type === "customWidget" && widget !== null && detail.data.widgetSchema === CUSTOM_WIDGET_SCHEMA;
|
||||
|
||||
@@ -164,7 +173,7 @@ export function WorkshopDetail({ id }: { id: string }) {
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
{!compatible && (
|
||||
{!compatible && !packageCompatible && (
|
||||
<Alert color="red" icon={<IconAlertTriangle size={18} />} title={t("installError")}>
|
||||
{t("installErrorDescription")}
|
||||
{validation && !validation.success ? ` ${validation.error}` : ""}
|
||||
@@ -180,6 +189,7 @@ export function WorkshopDetail({ id }: { id: string }) {
|
||||
screenshots={submission.screenshots}
|
||||
/>
|
||||
|
||||
{packageCompatible && <WorkshopPackageReview submissionId={submission.id} />}
|
||||
{compatible && importer.review && (
|
||||
<Paper withBorder radius="md" p="md">
|
||||
<Stack gap="md">
|
||||
@@ -258,14 +268,16 @@ export function WorkshopDetail({ id }: { id: string }) {
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Button
|
||||
size="md"
|
||||
loading={importer.pending || importer.succeeded}
|
||||
disabled={!compatible || !importer.ready || importer.succeeded}
|
||||
onClick={importer.importWidget}
|
||||
>
|
||||
{t("install")}
|
||||
</Button>
|
||||
{!packageCompatible && (
|
||||
<Button
|
||||
size="md"
|
||||
loading={importer.pending || importer.succeeded}
|
||||
disabled={!compatible || !importer.ready || importer.succeeded}
|
||||
onClick={importer.importWidget}
|
||||
>
|
||||
{t("install")}
|
||||
</Button>
|
||||
)}
|
||||
</ManageStickyFooter>
|
||||
</Stack>
|
||||
</ManagePageLayout>
|
||||
|
||||
@@ -76,6 +76,7 @@ import {
|
||||
needsCustomWidgetAuthoringContext,
|
||||
} from "./custom-widget-authoring-context";
|
||||
import { createAssistantMcpToolGroups } from "./assistant-tool-groups";
|
||||
import { isWidgetPackageWorkbench, widgetPackageAuthoringInstructions } from "./widget-package-authoring-context";
|
||||
import {
|
||||
customWidgetAssistantInstructions,
|
||||
getForcedAssistantToolName,
|
||||
@@ -497,7 +498,10 @@ export async function POST(request: Request) {
|
||||
return Response.json({ error: "The selected model does not support image input." }, { status: 400 });
|
||||
}
|
||||
const canAuthorCustomWidgets = session.user.permissions.includes("admin");
|
||||
const customWidgetAuthoringActive = canAuthorCustomWidgets && needsCustomWidgetAuthoringContext(incomingMessages);
|
||||
const widgetPackageAuthoringActive =
|
||||
canAuthorCustomWidgets && isWidgetPackageWorkbench(parsed.data.clientContext?.pathname);
|
||||
const customWidgetAuthoringActive =
|
||||
canAuthorCustomWidgets && !widgetPackageAuthoringActive && needsCustomWidgetAuthoringContext(incomingMessages);
|
||||
const customWidgetDiscoveryPhase = createCustomWidgetDiscoveryPhaseController();
|
||||
const customWidgetToolStepGate = createCustomWidgetToolStepGate();
|
||||
const loadedCustomWidgetContextRequests = new Set<string>();
|
||||
@@ -628,7 +632,7 @@ export async function POST(request: Request) {
|
||||
const activeCustomWidgetToolNames = getActiveCustomWidgetToolNames(
|
||||
Object.keys(homarrTools),
|
||||
incomingMessages,
|
||||
canAuthorCustomWidgets,
|
||||
canAuthorCustomWidgets && !widgetPackageAuthoringActive,
|
||||
);
|
||||
const getActiveToolNames = (steps: Parameters<typeof getCustomWidgetPhaseToolNames>[1] = []) => {
|
||||
const enabledToolNames = assistantToolGroups
|
||||
@@ -693,7 +697,10 @@ export async function POST(request: Request) {
|
||||
const initialModelMessages = await convertAssistantMessagesToModelMessages(
|
||||
prepareMessagesForModel(incomingMessages),
|
||||
);
|
||||
const baseInstructions = `${assistantInstructions}${customWidgetAuthoringActive ? customWidgetAssistantInstructions : ""}${openRouterServerToolsEnabled ? webSearchInstructions : ""}${requestContext}`;
|
||||
let authoringInstructions = "";
|
||||
if (widgetPackageAuthoringActive) authoringInstructions = widgetPackageAuthoringInstructions;
|
||||
else if (customWidgetAuthoringActive) authoringInstructions = customWidgetAssistantInstructions;
|
||||
const baseInstructions = `${assistantInstructions}${authoringInstructions}${openRouterServerToolsEnabled ? webSearchInstructions : ""}${requestContext}`;
|
||||
const getStepInstructions = (activeToolNames: readonly string[]) => {
|
||||
if (!customWidgetAuthoringActive) return undefined;
|
||||
return appendActiveCustomWidgetToolInstruction(baseInstructions, activeToolNames);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
export function isWidgetPackageWorkbench(pathname: string | undefined) {
|
||||
return /(?:^|\/)manage\/custom-widgets\/packages\/(?:new|[A-Za-z0-9_-]+)\/?$/u.test(pathname ?? "");
|
||||
}
|
||||
|
||||
export const widgetPackageAuthoringInstructions = `
|
||||
The user is editing a trusted Custom Widget v3 package in the open creator workspace.
|
||||
Use read_widget_package_draft to read the visible draft and its installed SDK reference before proposing code.
|
||||
Use propose_widget_package_changes for edits to that draft. The user reviews the proposed source changes, and applying them creates one Undo step.
|
||||
This is the full React/TypeScript/CSS package format, not the v2 JSX expression interpreter. Do not use v2 authoring bootstrap or v2 preview/create tools for this workspace.
|
||||
Preserve existing files, dependencies, connection requirements, options, and local changes unless the requested edit needs to change them. Reuse supported native integration adapters.
|
||||
Keep credentials in local connection settings. Never request or embed secrets in package source, examples, fixtures, prompts, or tool arguments.
|
||||
A proposed or applied draft is not saved, previewed, activated, installed on a board, or published. Report those states only from actual lifecycle tool results for the exact candidate.
|
||||
Preview execution requires explicit owner trust. SDK action simulation does not sandbox arbitrary trusted code. Offline services do not prevent draft saving.
|
||||
For lifecycle operations, use the customWidget package tools with the returned installation identity and retain normal operation approvals.
|
||||
`;
|
||||
@@ -1,5 +1,6 @@
|
||||
import crypto from "crypto";
|
||||
import fs from "fs";
|
||||
import { countEncryptedWidgetValues, reencryptWidgetValues } from "../widget-secrets";
|
||||
import path from "path";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
@@ -133,6 +134,7 @@ const reEncryptSecrets = (tempDb: InstanceType<typeof BetterSqlite3>, importedKe
|
||||
|
||||
const oldKey = Buffer.from(importedKeyHex, "hex");
|
||||
const newKey = Buffer.from(currentKeyHex, "hex");
|
||||
reencryptWidgetValues(tempDb, oldKey, newKey);
|
||||
|
||||
const rows = tempDb.prepare('SELECT "integration_id", "kind", "value" FROM "integrationSecret"').all() as {
|
||||
integration_id: string;
|
||||
@@ -305,7 +307,7 @@ export async function POST(req: Request) {
|
||||
const secretCount = (tempDb.prepare('SELECT COUNT(*) as count FROM "integrationSecret"').get() as { count: number })
|
||||
.count;
|
||||
|
||||
if (secretCount > 0 && !importedKey) {
|
||||
if (secretCount + countEncryptedWidgetValues(tempDb) > 0 && !importedKey) {
|
||||
throw new Error(
|
||||
"Backup contains integration secrets but no encryption key. " +
|
||||
"Cannot restore without the original SECRET_ENCRYPTION_KEY.",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
import type Database from "better-sqlite3";
|
||||
|
||||
const encryptedColumns = [
|
||||
{ table: "custom_widget_connection", column: "encrypted_secrets" },
|
||||
{ table: "custom_widget_v2_secret", column: "encrypted_value" },
|
||||
{ table: "custom_widget_secret", column: "value" },
|
||||
{ table: "widget_secret", column: "value" },
|
||||
] as const;
|
||||
|
||||
function existingTables(database: Database.Database) {
|
||||
return encryptedColumns.filter(({ table }) =>
|
||||
database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table),
|
||||
);
|
||||
}
|
||||
|
||||
export function countEncryptedWidgetValues(database: Database.Database) {
|
||||
return existingTables(database).reduce((count, { table }) => {
|
||||
const row = database.prepare(`SELECT COUNT(*) AS count FROM "${table}"`).get() as { count: number };
|
||||
return count + row.count;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
export function reencryptWidgetValues(database: Database.Database, oldKey: Buffer, newKey: Buffer) {
|
||||
database.transaction(() => {
|
||||
for (const { table, column } of existingTables(database)) {
|
||||
const values = database.prepare(`SELECT rowid, "${column}" AS value FROM "${table}"`).all() as Array<{
|
||||
rowid: number;
|
||||
value: string;
|
||||
}>;
|
||||
const update = database.prepare(`UPDATE "${table}" SET "${column}" = ? WHERE rowid = ?`);
|
||||
for (const row of values) {
|
||||
const parts = row.value.split(".");
|
||||
if (parts.length !== 2) throw new Error(`Malformed encrypted value in ${table}`);
|
||||
const [value, iv] = parts as [string, string];
|
||||
try {
|
||||
const decipher = createDecipheriv("aes-256-cbc", oldKey, Buffer.from(iv, "hex"));
|
||||
const plain = Buffer.concat([decipher.update(Buffer.from(value, "hex")), decipher.final()]);
|
||||
const nextIv = randomBytes(16);
|
||||
const cipher = createCipheriv("aes-256-cbc", newKey, nextIv);
|
||||
const encrypted = Buffer.concat([cipher.update(plain), cipher.final()]);
|
||||
update.run(`${encrypted.toString("hex")}.${nextIv.toString("hex")}`, row.rowid);
|
||||
} catch {
|
||||
throw new Error(`Cannot restore an encrypted widget value in ${table} with the supplied backup key`);
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { widgetArtifactResponse } from "@homarr/api/custom-widget/packages";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { db } from "@homarr/db";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = auth(async (request, context) => {
|
||||
const params = await context.params as { itemId: string; digest: string; surface: string };
|
||||
return widgetArtifactResponse({ db, session: request.auth }, { ...params, css: request.nextUrl.searchParams.get("asset") === "css" });
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { widgetArtifactResponse } from "@homarr/api/custom-widget/packages";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { db } from "@homarr/db";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = auth(async (request, context) => {
|
||||
const params = await context.params as { previewId: string; surface: string };
|
||||
return widgetArtifactResponse({ db, session: request.auth }, { ...params, css: request.nextUrl.searchParams.get("asset") === "css" });
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { widgetWebhookResponse } from "@homarr/api/custom-widget/webhooks";
|
||||
import { db } from "@homarr/db";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ itemId: string; id: string }> }) {
|
||||
return widgetWebhookResponse(db, request, await context.params);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import type { ToolCallMessagePartProps } from "@assistant-ui/react";
|
||||
import { Accordion, Alert, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { hasCompleteAssistantToolArguments } from "./assistant-human-tool-status";
|
||||
import type { PackageChangesResult, ProposePackageChangesArgs } from "./assistant-package-draft-contracts";
|
||||
import { packageDraftToolContracts } from "./assistant-package-draft-contracts";
|
||||
import {
|
||||
applyAssistantPackageChanges,
|
||||
getAssistantPackageDraftVersion,
|
||||
getServerPackageDraftVersion,
|
||||
reviewAssistantPackageChanges,
|
||||
subscribeAssistantPackageDraft,
|
||||
} from "./assistant-package-draft-registry";
|
||||
|
||||
const CodeEditor = dynamic(() => import("~/components/custom-widgets/code-editor").then((module) => module.CodeEditor));
|
||||
type Props = ToolCallMessagePartProps<ProposePackageChangesArgs, PackageChangesResult>;
|
||||
|
||||
export function AssistantPackageChangesTool({ args, status, result, addResult, toolCallId }: Props) {
|
||||
const t = useI18n("customWidget.package.assistant");
|
||||
useSyncExternalStore(subscribeAssistantPackageDraft, getAssistantPackageDraftVersion, getServerPackageDraftVersion);
|
||||
if (result) return <Text size="sm">{result.applied ? t("applied") : (result.error ?? t("rejected"))}</Text>;
|
||||
if (!hasCompleteAssistantToolArguments(status)) return <Text size="sm">{t("preparing")}</Text>;
|
||||
const checked = packageDraftToolContracts.propose_widget_package_changes.parameters.safeParse(args);
|
||||
if (!checked.success) return <Alert color="red">{t("invalidProposal")}</Alert>;
|
||||
const review = reviewAssistantPackageChanges(checked.data);
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
<Text fw={600}>{t("review")}</Text>
|
||||
<Text size="sm">{checked.data.summary}</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("reviewDescription")}
|
||||
</Text>
|
||||
{!review.available && <Alert color="yellow">{review.error}</Alert>}
|
||||
<Accordion multiple>
|
||||
{review.changes.map((change) => (
|
||||
<Accordion.Item key={change.path} value={change.path}>
|
||||
<Accordion.Control>{change.path}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<CodeEditor
|
||||
id={`${toolCallId}-${change.path}-before`}
|
||||
label={t("before")}
|
||||
value={change.before}
|
||||
language="tsx"
|
||||
readOnly
|
||||
height="200px"
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
<CodeEditor
|
||||
id={`${toolCallId}-${change.path}-after`}
|
||||
label={t("after")}
|
||||
value={change.after}
|
||||
language="tsx"
|
||||
readOnly
|
||||
height="240px"
|
||||
onChange={() => undefined}
|
||||
/>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
))}
|
||||
</Accordion>
|
||||
<Group>
|
||||
<Button
|
||||
size="xs"
|
||||
disabled={!review.available || review.changes.length === 0}
|
||||
onClick={() => addResult(applyAssistantPackageChanges(checked.data))}
|
||||
>
|
||||
{t("apply")}
|
||||
</Button>
|
||||
<Button size="xs" variant="subtle" onClick={() => addResult({ applied: false, cancelled: true })}>
|
||||
{t("reject")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const packagePath = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(240)
|
||||
.refine(
|
||||
(path) =>
|
||||
!path.startsWith("/") &&
|
||||
!path.includes("\\") &&
|
||||
!path.includes("\0") &&
|
||||
path.split("/").every((part) => part !== ".." && part !== "." && part.length > 0) &&
|
||||
!["__proto__", "prototype", "constructor"].includes(path),
|
||||
);
|
||||
|
||||
export const packageDraftToolContracts = {
|
||||
read_widget_package_draft: {
|
||||
description:
|
||||
"Read the currently open trusted widget package workspace draft, its revision, selected source files, validation diagnostics, public SDK guide and exact-candidate preview evidence. This is the unsaved browser draft, not the installed release. Connection bindings, credentials and runtime response data are excluded. Read before proposing edits. Request omitted files separately. An optional reference returns an inspectable source example; reading never executes code. Use these v3 tools instead of Custom JSX v2 authoring tools in the package workspace.",
|
||||
parameters: z.object({
|
||||
paths: z.array(packagePath).max(64).optional(),
|
||||
reference: z
|
||||
.enum([
|
||||
"clock",
|
||||
"timer",
|
||||
"beszel",
|
||||
"checklist",
|
||||
"downloads",
|
||||
"sonarr",
|
||||
"rack",
|
||||
"backup",
|
||||
"household",
|
||||
"overview",
|
||||
"media",
|
||||
])
|
||||
.optional(),
|
||||
}),
|
||||
},
|
||||
propose_widget_package_changes: {
|
||||
description:
|
||||
"Propose a patch against the revision returned by read_widget_package_draft. The owner reviews before/after source in the Assistant and explicitly applies or rejects it. Applied changes form one Undo step in the visible draft. Supply complete contents only for changed files; null deletes a file. metadata is the complete widget.json content excluding files. Preserve untouched content and dependencies. This does not save, trust, preview, activate, install or publish anything. Never claim a proposal has executed. Re-read the draft after it changes. Files containing redacted credentials cannot be replaced through this tool; move credentials to local connections manually first.",
|
||||
parameters: z.object({
|
||||
revision: z.string().min(1).max(128),
|
||||
summary: z.string().trim().min(1).max(800),
|
||||
name: z.string().trim().min(1).max(128).optional(),
|
||||
metadata: z.string().max(100_000).optional(),
|
||||
files: z
|
||||
.record(packagePath, z.string().max(180_000).nullable())
|
||||
.refine((files) => Object.keys(files).length <= 64),
|
||||
}),
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type ReadPackageDraftArgs = z.infer<typeof packageDraftToolContracts.read_widget_package_draft.parameters>;
|
||||
export type ProposePackageChangesArgs = z.infer<
|
||||
typeof packageDraftToolContracts.propose_widget_package_changes.parameters
|
||||
>;
|
||||
export type PackageChangesResult = { applied: boolean; revision?: string; error?: string; cancelled?: boolean };
|
||||
export interface PackageDraftReview {
|
||||
available: boolean;
|
||||
error?: string;
|
||||
changes: { path: string; before: string; after: string }[];
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type {
|
||||
PackageChangesResult,
|
||||
PackageDraftReview,
|
||||
ProposePackageChangesArgs,
|
||||
ReadPackageDraftArgs,
|
||||
} from "./assistant-package-draft-contracts";
|
||||
|
||||
interface PackageDraftAdapter {
|
||||
read(input: ReadPackageDraftArgs): unknown;
|
||||
review(input: ProposePackageChangesArgs): PackageDraftReview;
|
||||
apply(input: ProposePackageChangesArgs): PackageChangesResult;
|
||||
}
|
||||
|
||||
let adapter: PackageDraftAdapter | undefined;
|
||||
let version = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
const unavailable = "Open the widget package workspace before using draft tools.";
|
||||
|
||||
export function notifyPackageDraftChanged() {
|
||||
version += 1;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
export function registerAssistantPackageDraft(next: PackageDraftAdapter) {
|
||||
adapter = next;
|
||||
notifyPackageDraftChanged();
|
||||
return () => {
|
||||
if (adapter !== next) return;
|
||||
adapter = undefined;
|
||||
notifyPackageDraftChanged();
|
||||
};
|
||||
}
|
||||
|
||||
export function subscribeAssistantPackageDraft(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export const getAssistantPackageDraftVersion = () => version;
|
||||
export const getServerPackageDraftVersion = () => 0;
|
||||
export const readAssistantPackageDraft = (input: ReadPackageDraftArgs) =>
|
||||
adapter?.read(input) ?? { error: unavailable };
|
||||
export const reviewAssistantPackageChanges = (input: ProposePackageChangesArgs): PackageDraftReview =>
|
||||
adapter?.review(input) ?? { available: false, error: unavailable, changes: [] };
|
||||
export const applyAssistantPackageChanges = (input: ProposePackageChangesArgs): PackageChangesResult =>
|
||||
adapter?.apply(input) ?? { applied: false, error: unavailable };
|
||||
@@ -11,6 +11,7 @@ const humanToolKinds = {
|
||||
configure_app: "form",
|
||||
configure_board_settings: "form",
|
||||
configure_widget: "form",
|
||||
propose_widget_package_changes: "form",
|
||||
} as const;
|
||||
|
||||
const getStringArg = (args: unknown, key: string) => {
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import dynamic from "next/dynamic";
|
||||
import { readAssistantPackageDraft } from "./assistant-package-draft-registry";
|
||||
import type {
|
||||
AttachmentAdapter,
|
||||
MessageFormatAdapter,
|
||||
@@ -68,6 +70,9 @@ import { initialAssistantNotificationState, updateAssistantNotificationState } f
|
||||
import { AssistantViewRefreshProvider, useAssistantViewRefresh } from "./assistant-view-refresh";
|
||||
import { AssistantBoardWidget } from "./assistant-widget";
|
||||
|
||||
const AssistantPackageChangesTool = dynamic(() =>
|
||||
import("./assistant-package-changes-tool").then((module) => module.AssistantPackageChangesTool),
|
||||
);
|
||||
const ignoreUnsupportedArchiveAction = () => Promise.resolve();
|
||||
const assistantImageAttachmentTypes = ["image/gif", "image/jpeg", "image/png", "image/webp"];
|
||||
const assistantDocumentAttachmentTypes = [
|
||||
@@ -537,6 +542,7 @@ const AssistantThreadRuntime = () => {
|
||||
};
|
||||
|
||||
const AssistantRuntime = ({ children }: PropsWithChildren) => {
|
||||
const packageT = useI18n("customWidget.package.assistant");
|
||||
const router = useRouter();
|
||||
const { refreshCurrentView } = useAssistantViewRefresh();
|
||||
const runtime = useRemoteThreadListRuntime({
|
||||
@@ -558,6 +564,18 @@ const AssistantRuntime = ({ children }: PropsWithChildren) => {
|
||||
const toolkit = useMemo(
|
||||
() =>
|
||||
defineToolkit({
|
||||
read_widget_package_draft: {
|
||||
type: "frontend",
|
||||
...browserToolContracts.read_widget_package_draft,
|
||||
execute: readAssistantPackageDraft,
|
||||
renderText: { running: packageT("reading"), complete: packageT("read") },
|
||||
},
|
||||
propose_widget_package_changes: {
|
||||
type: "human",
|
||||
display: "standalone",
|
||||
...browserToolContracts.propose_widget_package_changes,
|
||||
render: AssistantPackageChangesTool,
|
||||
},
|
||||
ask_user: {
|
||||
type: "human",
|
||||
display: "standalone",
|
||||
@@ -610,7 +628,7 @@ const AssistantRuntime = ({ children }: PropsWithChildren) => {
|
||||
renderText: { running: "Refreshing current view…", complete: "Current view refreshed" },
|
||||
},
|
||||
}) as Toolkit,
|
||||
[browserToolExecutors],
|
||||
[browserToolExecutors, packageT],
|
||||
);
|
||||
return (
|
||||
<AssistantRuntimeProviderWithTools runtime={runtime} toolkit={toolkit}>
|
||||
|
||||
@@ -4,6 +4,8 @@ import { z } from "zod/v4";
|
||||
import { browserToolContracts, normalizeAssistantAppIconUrl } from "./assistant-tool-contracts";
|
||||
|
||||
const supportedToolArguments = {
|
||||
read_widget_package_draft: {},
|
||||
propose_widget_package_changes: { revision: "draft-1", summary: "Improve the widget spacing.", files: {} },
|
||||
ask_user: {
|
||||
question: "How should the app be added?",
|
||||
options: [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod/v4";
|
||||
import { packageDraftToolContracts } from "./assistant-package-draft-contracts";
|
||||
|
||||
import {
|
||||
backgroundImageAttachments,
|
||||
@@ -52,6 +53,7 @@ export const assistantBoardSettingsChangesSchema = z
|
||||
.describe("Only the board fields the user asked to change.");
|
||||
|
||||
export const browserToolContracts = {
|
||||
...packageDraftToolContracts,
|
||||
ask_user: {
|
||||
description:
|
||||
"Pause and ask the user one concise structured question. Use this only for missing information or a meaningful choice, never to confirm details that are already sufficient for a native review form or mutating tool. In particular, do not use ask_user before configure_app, configure_board_settings, or configure_widget when their inputs are known. Provide 2-4 distinct options and classify every option: agreement, approval, or proceeding is affirmative; refusal or stopping is negative; unrelated selections are alternative. A confirmation question must have exactly one affirmative option. The UI adds a freeform Other choice when allowOther is not false.",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/** Board authorization and the mounted placement still determine which links can open a surface. */
|
||||
export function useWidgetAdvancedDeepLink(itemId: string, enabled: boolean, open: () => void) {
|
||||
const callback = useRef(open);
|
||||
callback.current = open;
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let frame: number | undefined;
|
||||
const inspect = () => {
|
||||
const target = new URLSearchParams(window.location.hash.slice(1)).get("widget");
|
||||
if (target !== itemId) return;
|
||||
if (frame !== undefined) cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => callback.current());
|
||||
};
|
||||
inspect();
|
||||
window.addEventListener("hashchange", inspect);
|
||||
return () => {
|
||||
if (frame !== undefined) cancelAnimationFrame(frame);
|
||||
window.removeEventListener("hashchange", inspect);
|
||||
};
|
||||
}, [enabled, itemId]);
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import { getLogicalTrackSize } from "~/components/board/layout";
|
||||
import { useBoardCanvasScale } from "~/components/board/layout/scaled-board-canvas";
|
||||
import advancedFocusClasses from "../advanced-focus/advanced-focus.module.css";
|
||||
import { useAdvancedFocus } from "../advanced-focus/context";
|
||||
import { useWidgetAdvancedDeepLink } from "../advanced-focus/deep-link";
|
||||
import { startAdvancedFocusEntrance } from "../advanced-focus/entrance";
|
||||
import { getAdvancedFocusClosePosition, getAdvancedFocusRect } from "../advanced-focus/geometry";
|
||||
import { AdvancedFocusManualSurface } from "../advanced-focus/manual-surface";
|
||||
@@ -187,14 +188,16 @@ const LoadedBoardItemContent = ({
|
||||
|
||||
useEffect(() => () => dismiss(item.id), [dismiss, item.id]);
|
||||
|
||||
const openAdvancedView = () => {
|
||||
const openAdvancedView = useCallback(() => {
|
||||
if (sourceRef.current)
|
||||
open(item.id, sourceRef.current, {
|
||||
activation: "manual",
|
||||
autofocusClose: true,
|
||||
restoreFocusTarget: advancedFocusTriggerRef.current ?? sourceRef.current,
|
||||
});
|
||||
};
|
||||
}, [item.id, open]);
|
||||
|
||||
useWidgetAdvancedDeepLink(item.id, supportsAdvancedFocus && !isEditMode, openAdvancedView);
|
||||
|
||||
useEffect(() => {
|
||||
const surface = isManual ? manualSurface : cardRef.current;
|
||||
@@ -318,6 +321,8 @@ const LoadedBoardItemContent = ({
|
||||
widgetStateRef={widgetStateRef}
|
||||
widgetRuntimeRef={widgetRuntimeRef}
|
||||
displayMode={isAdvanced ? "advanced" : "compact"}
|
||||
openAdvancedFocus={openAdvancedView}
|
||||
closeAdvancedFocus={close}
|
||||
definition={definition}
|
||||
Component={Component}
|
||||
/>
|
||||
@@ -417,6 +422,8 @@ interface InnerContentProps {
|
||||
widgetStateRef: MutableRefObject<Record<string, unknown> | null>;
|
||||
widgetRuntimeRef: WidgetRuntimeRef;
|
||||
displayMode: "compact" | "advanced";
|
||||
openAdvancedFocus: () => void;
|
||||
closeAdvancedFocus: () => void;
|
||||
definition: WidgetDefinition;
|
||||
Component: ComponentType<WidgetComponentProps<SectionItem["kind"]>>;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,14 @@
|
||||
import type { MutableRefObject, ReactNode, RefObject } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Drawer, Group, Loader, Menu, Text, Tooltip } from "@mantine/core";
|
||||
import { IconAlertTriangle, IconCircleCheck, IconMaximize, IconRefresh, IconSettings } from "@tabler/icons-react";
|
||||
import {
|
||||
IconAlertTriangle,
|
||||
IconCircleCheck,
|
||||
IconCode,
|
||||
IconMaximize,
|
||||
IconRefresh,
|
||||
IconSettings,
|
||||
} from "@tabler/icons-react";
|
||||
import type { QueryClient, QueryKey } from "@tanstack/react-query";
|
||||
import { useIsFetching, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
@@ -21,9 +28,11 @@ import { translateIfNecessary } from "@homarr/translation";
|
||||
import type { TranslationFunction } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { useIsMobile } from "@homarr/ui/hooks";
|
||||
import { Link } from "@homarr/ui";
|
||||
import type { WidgetDefinition, WidgetRuntimeRef } from "@homarr/widgets/definition";
|
||||
import { getWidgetQueryKeys, getWidgetRuntimeQueries, supportsAdvancedFocus } from "@homarr/widgets/definition";
|
||||
import { reduceWidgetOptionsWithDefinition } from "@homarr/widgets/manifest";
|
||||
import { getNativeWidgetReferenceStarter } from "@homarr/widgets/native-reference-starters";
|
||||
import { getWidgetOptionTranslationNamespace } from "@homarr/widgets/option-translation";
|
||||
import type { WidgetPreviewDimensions } from "@homarr/widgets/modals";
|
||||
|
||||
@@ -75,6 +84,13 @@ export const WidgetContextMenu = ({
|
||||
const canConfigureWidget =
|
||||
hasChangeAccess && (item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false));
|
||||
const canOpenAdvancedFocus = supportsAdvancedFocus(definition);
|
||||
const referenceStarter = getNativeWidgetReferenceStarter(
|
||||
item.kind,
|
||||
integrationData
|
||||
.filter((integration) => item.integrationIds.includes(integration.id))
|
||||
.map((integration) => integration.kind),
|
||||
);
|
||||
const canCustomizeWidget = Boolean(referenceStarter) && (session?.user.permissions.includes("admin") ?? false);
|
||||
const queryClient = useQueryClient();
|
||||
const { open: openAdvancedFocus } = useAdvancedFocus();
|
||||
const integrationsWithInteractAccess = useIntegrationsWithInteractAccess();
|
||||
@@ -101,6 +117,7 @@ export const WidgetContextMenu = ({
|
||||
const widgetQueryKeys = useMemo(() => getWidgetQueryKeys(definition, item.kind), [definition, item.kind]);
|
||||
const matchesWidgetQuery = useCallback(
|
||||
(queryKey: QueryKey) =>
|
||||
(item.kind === "customApi" && queryKey[0] === "custom-widget-sdk" && queryKey[2] === item.id) ||
|
||||
matchesWidgetItemQuery(
|
||||
queryKey,
|
||||
widgetQueryKeys,
|
||||
@@ -113,7 +130,16 @@ export const WidgetContextMenu = ({
|
||||
},
|
||||
definition.queryMatcher,
|
||||
),
|
||||
[board.id, definition.queryMatcher, item.id, item.integrationIds, options, widgetQueryKeys, widgetRuntimeRef],
|
||||
[
|
||||
board.id,
|
||||
definition.queryMatcher,
|
||||
item.id,
|
||||
item.kind,
|
||||
item.integrationIds,
|
||||
options,
|
||||
widgetQueryKeys,
|
||||
widgetRuntimeRef,
|
||||
],
|
||||
);
|
||||
const isWidgetFetching =
|
||||
useIsFetching({
|
||||
@@ -330,6 +356,16 @@ export const WidgetContextMenu = ({
|
||||
>
|
||||
{tMenu("settings")}
|
||||
</Menu.Item>
|
||||
{canCustomizeWidget && (
|
||||
<Menu.Item
|
||||
component={Link}
|
||||
closeMenuOnClick
|
||||
leftSection={<IconCode size={16} />}
|
||||
href={`/manage/custom-widgets/packages/new?starter=${referenceStarter}&sourceItemId=${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{tMenu("customize")}
|
||||
</Menu.Item>
|
||||
)}
|
||||
</WidgetContextMenuDropdown>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@@ -32,4 +32,6 @@ export async function registerNodeInstrumentation() {
|
||||
};
|
||||
|
||||
await Promise.all([startTasksAsync(), startWebsocketAsync()]);
|
||||
const { startWidgetCollections } = await import("@homarr/api/custom-widget/collections");
|
||||
startWidgetCollections();
|
||||
}
|
||||
Reference in new issue
Block a user