fix: simplify custom widget package workbench
This commit is contained in:
1 parent
9a52a035aa
commit
48042a08ff
37 files changed
+1155
-608
No files matched your search
+1
-1
@@ -14,7 +14,7 @@ export const packageAssistantSdkContext = {
|
||||
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.",
|
||||
"Optional server.ts imports @homarr/widget-sdk/server and default-exports defineWidgetServer({handler:async(input,context)=>value}). Declare every handler in manifest.handlers with kind:'query'|'action'|'subscription'|'migration', permission:'view'|'modify'|'full', inputSchema? (JSON Schema), guestAccess?; actions default to modify. fetchWidgetConnection<T>(context,{connection:'slot',path,method?,query?,body?,responseType?}) returns {data,ok,status,contentType,durationMs,updatedAt}. getWidgetConnection<TSettings>(context,{connection,serviceType?}) returns {configuration:{kind,serviceType?,settings?:TSettings,...},secrets:Record<string,string>} only to trusted server code for Node SQL, MQTT, SSH, files or other service clients; never return secrets to browser queries. getWidgetServerContext(context) returns options,installationId,bindingNames,bindingLabels,isPreview. Declare connections with multiple:true for a repeatable group, and integrationKind (for example sonarr) to filter compatible native integrations. getWidgetConnectionGroup(context,slot) returns all {connection,label} members for queries and actions; do not hard-code first/second server slots. callWidgetIntegration(context,{connection,capability,input?}) invokes native adapters; subscribeWidgetIntegration yields native stream events. callWidgetRunner and subscribeWidgetRunner address owner-managed remote runners. Server modules have trusted Node capabilities. Secrets stay in owner-bound connections. Do not invent integration capabilities: use reference packages or declared capability docs.",
|
||||
lifecycle:
|
||||
"Proposals only change the visible draft after explicit review; they never save, trust, run or activate code. The owner saves the draft, reviews dependencies and trust, runs exact-candidate Preview, then explicitly activates the saved release for all placements. SDK actions are simulated in default previews, but arbitrary trusted browser/Node code still executes. A preview session proves compilation/session creation only, not successful UI rendering, live action success or all application behavior. Any source/options/binding edit invalidates preview evidence.",
|
||||
};
|
||||
+60
-33
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { Button, Divider, Group, Popover, Stack, Text, Textarea } from "@mantine/core";
|
||||
import { Alert, 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 { Link } from "@homarr/ui";
|
||||
import { useOptionalHomarrAssistant } from "~/components/assistant/assistant-context";
|
||||
|
||||
export function PackageAssistant() {
|
||||
@@ -11,8 +12,10 @@ export function PackageAssistant() {
|
||||
const assistant = useOptionalHomarrAssistant();
|
||||
const [request, setRequest] = useState("");
|
||||
const [opened, setOpened] = useState(false);
|
||||
if (!assistant?.enabled) return null;
|
||||
const [sendFailed, setSendFailed] = useState(false);
|
||||
const send = (intent: string) => {
|
||||
if (!assistant?.enabled || assistant.isRunning) return;
|
||||
setSendFailed(false);
|
||||
assistant.open();
|
||||
if (
|
||||
assistant.sendPrompt(
|
||||
@@ -21,45 +24,69 @@ export function PackageAssistant() {
|
||||
) {
|
||||
setOpened(false);
|
||||
setRequest("");
|
||||
}
|
||||
} else setSendFailed(true);
|
||||
};
|
||||
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}>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="light"
|
||||
leftSection={<IconSparkles size={14} />}
|
||||
onClick={() => setOpened((value) => !value)}
|
||||
aria-expanded={opened}
|
||||
>
|
||||
{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>
|
||||
{!assistant?.enabled && (
|
||||
<Stack gap="sm">
|
||||
<Text size="sm">{assistant?.unavailableDescription || t("unavailable")}</Text>
|
||||
<Button component={Link} href="/manage/assistant" variant="light" size="xs">
|
||||
{t("setup")}
|
||||
</Button>
|
||||
<Text size="xs" c="dimmed">{t("manual")}</Text>
|
||||
</Stack>
|
||||
)}
|
||||
{assistant?.enabled && (
|
||||
<>
|
||||
{assistant.isRunning && <Alert mb="xs">{t("busy")}</Alert>}
|
||||
{sendFailed && <Alert color="yellow" mb="xs">{t("sendFailed")}</Alert>}
|
||||
<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() || assistant.isRunning} onClick={() => send(request)}>
|
||||
{t("send")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Divider my="xs" />
|
||||
<Stack gap={4}>
|
||||
<Button variant="subtle" size="xs" justify="start" disabled={assistant.isRunning} onClick={() => send(t("createPrompt"))}>
|
||||
{t("create")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" justify="start" disabled={assistant.isRunning} onClick={() => send(t("improvePrompt"))}>
|
||||
{t("improve")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" justify="start" disabled={assistant.isRunning} onClick={() => send(t("advancedPrompt"))}>
|
||||
{t("advanced")}
|
||||
</Button>
|
||||
<Button variant="subtle" size="xs" justify="start" disabled={assistant.isRunning} onClick={() => send(t("fixPrompt"))}>
|
||||
{t("fix")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</>
|
||||
)}
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { Alert, MultiSelect, Select, Stack } from "@mantine/core";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getWidgetConnectionBindingNames, isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export function PackageBindingPicker({ name, requirement, connections, integrations, bindings, onChange }: {
|
||||
name: string;
|
||||
requirement: CustomWidgetPackage["connections"][string];
|
||||
connections: RouterOutputs["customWidget"]["package"]["connections"];
|
||||
integrations: RouterOutputs["integration"]["all"];
|
||||
bindings: Record<string, string>;
|
||||
onChange(bindings: Record<string, string>): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const saveConnection = clientApi.customWidget.package.saveConnection.useMutation();
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const currentBindings = useRef(bindings);
|
||||
currentBindings.current = bindings;
|
||||
const ids = getWidgetConnectionBindingNames(name, requirement, bindings).map((key) => bindings[key]!);
|
||||
const compatible = connections.filter((connection) => isWidgetConnectionCompatible(requirement, connection.configuration));
|
||||
const choices = compatible.map((connection) => ({ value: connection.id, label: connection.name }));
|
||||
if (requirement.kind === "integration") {
|
||||
for (const integration of integrations) {
|
||||
if (requirement.integrationKind && integration.kind !== requirement.integrationKind) continue;
|
||||
if (compatible.some((connection) => connection.integrationId === integration.id)) continue;
|
||||
choices.push({ value: `integration:${integration.id}`, label: integration.name });
|
||||
}
|
||||
}
|
||||
// Keep unavailable bindings visible so a removed integration can be diagnosed or replaced.
|
||||
for (const id of ids) {
|
||||
if (!choices.some((choice) => choice.value === id))
|
||||
choices.push({ value: id, label: connections.find((connection) => connection.id === id)?.name ?? t("unavailableConnection") });
|
||||
}
|
||||
const change = async (values: string[]) => {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
const nextIds: string[] = [];
|
||||
for (const value of values) {
|
||||
if (!value.startsWith("integration:")) {
|
||||
nextIds.push(value);
|
||||
continue;
|
||||
}
|
||||
const integration = integrations.find((entry) => `integration:${entry.id}` === value);
|
||||
if (!integration) throw new Error(t("unavailableConnection"));
|
||||
const result = await saveConnection.mutateAsync({
|
||||
name: integration.name,
|
||||
integrationId: integration.id,
|
||||
configuration: { kind: "integration" },
|
||||
});
|
||||
nextIds.push(result.id);
|
||||
}
|
||||
await utils.customWidget.package.connections.invalidate();
|
||||
const next = { ...currentBindings.current };
|
||||
for (const key of getWidgetConnectionBindingNames(name, requirement, next)) delete next[key];
|
||||
for (const [index, id] of nextIds.entries()) {
|
||||
let key = name;
|
||||
if (index > 0) key = `${name}:${id}`;
|
||||
next[key] = id;
|
||||
}
|
||||
onChange(next);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
const common = {
|
||||
label: requirement.label,
|
||||
description: requirement.description,
|
||||
placeholder: t("chooseConnection"),
|
||||
required: !requirement.optional,
|
||||
searchable: true,
|
||||
clearable: true,
|
||||
disabled: pending,
|
||||
data: choices,
|
||||
nothingFoundMessage: t("noCompatibleConnections"),
|
||||
};
|
||||
return (
|
||||
<Stack gap="xs" flex={1}>
|
||||
{requirement.multiple ? (
|
||||
<MultiSelect {...common} value={ids} onChange={(values) => void change(values)} />
|
||||
) : (
|
||||
<Select {...common} value={ids[0] ?? null} onChange={(value) => void change(value ? [value] : [])} />
|
||||
)}
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+59
-56
@@ -2,15 +2,16 @@
|
||||
|
||||
import { ConnectionEditor } from "./_package-connection-editor";
|
||||
import { PackageConnectionDiagnostic } from "./_package-connection-diagnostic";
|
||||
import { PackageBindingPicker } from "./_package-binding-picker";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, Group, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
import { Alert, Button, Group, Paper, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { isWidgetConnectionCompatible } from "@homarr/custom-widgets/package";
|
||||
import { getWidgetConnectionBindingNames } from "@homarr/custom-widgets/package";
|
||||
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
export function PackageConnections({
|
||||
requirements,
|
||||
@@ -30,6 +31,7 @@ export function PackageConnections({
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const connections = clientApi.customWidget.package.connections.useQuery();
|
||||
const integrations = clientApi.integration.all.useQuery();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [diagnostic, setDiagnostic] = useState<RouterOutputs["customWidget"]["package"]["diagnoseConnection"] | null>(
|
||||
@@ -45,65 +47,66 @@ export function PackageConnections({
|
||||
{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);
|
||||
}}
|
||||
<Stack gap="xs">
|
||||
<PackageBindingPicker
|
||||
name={name}
|
||||
requirement={requirement}
|
||||
connections={connections.data ?? []}
|
||||
integrations={integrations.data ?? []}
|
||||
bindings={bindings}
|
||||
onChange={onChange}
|
||||
/>
|
||||
<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>
|
||||
{getWidgetConnectionBindingNames(name, requirement, bindings).map((bindingName) => (
|
||||
<Group key={bindingName} gap="xs">
|
||||
<Text size="sm" flex={1}>{connections.data?.find((entry) => entry.id === bindings[bindingName])?.name ?? bindingName}</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
size="xs"
|
||||
loading={diagnose.isPending}
|
||||
onClick={() => {
|
||||
const id = bindings[bindingName];
|
||||
if (!id) return;
|
||||
setDiagnostic(null);
|
||||
setDiagnosticError("");
|
||||
diagnose.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: setDiagnostic,
|
||||
onError: (error) => setDiagnosticError(error.message),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t("diagnose")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
onClick={() => {
|
||||
setCreating(false);
|
||||
setEditingId(bindings[bindingName] ?? null);
|
||||
}}
|
||||
>
|
||||
{t("editConnection")}
|
||||
</Button>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</Paper>
|
||||
))}
|
||||
{diagnostic && <PackageConnectionDiagnostic result={diagnostic} />}
|
||||
{diagnosticError && <Alert color="red">{diagnosticError}</Alert>}
|
||||
{connections.error && <Alert color="red">{connections.error.message}</Alert>}
|
||||
{integrations.error && <Alert color="red">{integrations.error.message}</Alert>}
|
||||
<Group>
|
||||
{Object.values(requirements).some((requirement) => requirement.kind === "integration") && (
|
||||
<Button component={Link} href="/manage/integrations/new" target="_blank" rel="noopener noreferrer" variant="light">
|
||||
{t("createIntegration")}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="subtle" onClick={() => { void connections.refetch(); void integrations.refetch(); }}>
|
||||
{t("refresh")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { Group, Text, Tree, useTree } from "@mantine/core";
|
||||
import type { TreeNodeData } from "@mantine/core";
|
||||
import { IconChevronRight, IconCode, IconFolder, IconFolderOpen } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
export function PackageFileTree({ files, selected, onSelect }: {
|
||||
files: Record<string, string>;
|
||||
selected: string;
|
||||
onSelect(path: string): void;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const data = useMemo(() => {
|
||||
const roots: TreeNodeData[] = [{ value: "/widget.json", label: t("manifestFile") }];
|
||||
for (const path of Object.keys(files).toSorted()) {
|
||||
const parts = path.split("/");
|
||||
let siblings = roots;
|
||||
let prefix = "";
|
||||
for (const [index, label] of parts.entries()) {
|
||||
prefix += label;
|
||||
if (index === parts.length - 1) {
|
||||
siblings.push({ value: path, label });
|
||||
break;
|
||||
}
|
||||
prefix += "/";
|
||||
let folder = siblings.find((node) => node.value === prefix);
|
||||
if (!folder) {
|
||||
folder = { value: prefix, label, children: [] };
|
||||
siblings.push(folder);
|
||||
}
|
||||
siblings = folder.children ?? [];
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}, [files, t]);
|
||||
const tree = useTree({
|
||||
selectedState: [selected],
|
||||
onSelectedStateChange: (values) => {
|
||||
const value = values[0];
|
||||
if (value && !value.endsWith("/")) onSelect(value);
|
||||
},
|
||||
});
|
||||
return (
|
||||
<Tree
|
||||
aria-label={t("files")}
|
||||
data={data}
|
||||
tree={tree}
|
||||
levelOffset={16}
|
||||
selectOnClick
|
||||
renderNode={({ node, expanded, hasChildren, elementProps }) => {
|
||||
let Icon = IconCode;
|
||||
if (hasChildren) Icon = IconFolder;
|
||||
if (hasChildren && expanded) Icon = IconFolderOpen;
|
||||
return (
|
||||
<Group {...elementProps} gap={6} wrap="nowrap" py={5} title={node.value}>
|
||||
{hasChildren && <IconChevronRight size={12} style={{ transform: `rotate(${expanded ? 90 : 0}deg)` }} />}
|
||||
<Icon size={16} style={{ flexShrink: 0 }} />
|
||||
<Text size="xs" truncate>
|
||||
{node.label}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
"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 { Alert, Avatar, Badge, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconPackage, IconPencil, IconUpload } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
@@ -12,21 +12,20 @@ import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { ManageCollectionItem, ManageCollectionList } from "~/components/manage/manage-collection";
|
||||
import { NoResults } from "~/components/no-results";
|
||||
import { PackageRowActions } from "./_package-row-actions";
|
||||
|
||||
export function PackageList({ initialData }: { initialData: RouterOutputs["customWidget"]["package"]["list"] }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const tCommon = useI18n("common");
|
||||
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()),
|
||||
);
|
||||
const entries = installations.data ?? [];
|
||||
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>}
|
||||
{entries.length === 0 && <NoResults icon={IconPackage} title={t("empty")} action={{ href: "/manage/custom-widgets/packages/new", label: t("create") }} />}
|
||||
<ManageCollectionList ariaLabel={t("title")}>
|
||||
{filtered.map((entry) => {
|
||||
{entries.map((entry) => {
|
||||
let status = t("draftOnly");
|
||||
let color = "gray";
|
||||
if (entry.activeArtifactId) {
|
||||
@@ -39,7 +38,7 @@ export function PackageList({ initialData }: { initialData: RouterOutputs["custo
|
||||
return (
|
||||
<ManageCollectionItem
|
||||
key={entry.id}
|
||||
leading={<IconPackage size={26} stroke={1.4} />}
|
||||
leading={<Avatar size={40} radius="sm" color="pink"><IconPackage size={20} stroke={1.5} /></Avatar>}
|
||||
title={<Text fw={600}>{entry.name}</Text>}
|
||||
badges={
|
||||
<Badge color={color} variant="light">
|
||||
@@ -52,10 +51,14 @@ export function PackageList({ initialData }: { initialData: RouterOutputs["custo
|
||||
</Text>
|
||||
}
|
||||
actions={
|
||||
<Button component={Link} href={`/manage/custom-widgets/packages/${entry.id}`} variant="default">
|
||||
{t("openWorkspace")}
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button component={Link} href={`/manage/custom-widgets/packages/${entry.id}`} variant="default" size="sm" leftSection={<IconPencil size={16} stroke={1.5} />}>
|
||||
{tCommon("action.edit")}
|
||||
</Button>
|
||||
<PackageRowActions entry={entry} />
|
||||
</Group>
|
||||
}
|
||||
actionsAlignment="center"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
+87
-73
@@ -8,12 +8,9 @@ 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";
|
||||
@@ -25,9 +22,12 @@ export function PackageOperations({
|
||||
initialBoardId,
|
||||
source,
|
||||
options,
|
||||
setOptions,
|
||||
dirty,
|
||||
trusted,
|
||||
connectionsDirty,
|
||||
onTrustChange,
|
||||
onSave,
|
||||
saving,
|
||||
onError,
|
||||
onMessage,
|
||||
}: {
|
||||
@@ -35,9 +35,12 @@ export function PackageOperations({
|
||||
initialBoardId?: string;
|
||||
source?: CustomWidgetPackage;
|
||||
options: Record<string, unknown>;
|
||||
setOptions(options: Record<string, unknown>): void;
|
||||
dirty: boolean;
|
||||
trusted: boolean;
|
||||
connectionsDirty: boolean;
|
||||
onTrustChange(trusted: boolean): void;
|
||||
onSave(): void;
|
||||
saving: boolean;
|
||||
onError(error: string): void;
|
||||
onMessage(message: string): void;
|
||||
}) {
|
||||
@@ -88,32 +91,34 @@ export function PackageOperations({
|
||||
};
|
||||
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>}
|
||||
<Text size="sm" c="dimmed">{t("useDescription")}</Text>
|
||||
{!current && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack>
|
||||
<Text>{t("saveFirst")}</Text>
|
||||
<Button onClick={onSave} loading={saving}>{t("saveDraft")}</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
{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 && (
|
||||
<Alert color="yellow">
|
||||
<Stack gap="xs">
|
||||
<Text size="sm">{t("saveBeforeActivate")}</Text>
|
||||
<Button size="xs" onClick={onSave} loading={saving}>{t("saveDraft")}</Button>
|
||||
</Stack>
|
||||
</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>}
|
||||
<Checkbox checked={trusted} onChange={(event) => onTrustChange(event.currentTarget.checked)} label={t("trustAcknowledgement")} />
|
||||
<Group>
|
||||
<Button
|
||||
disabled={dirty || !trusted || !source || !matchesReviewedSource}
|
||||
disabled={dirty || connectionsDirty || !trusted || !source || !matchesReviewedSource}
|
||||
loading={activate.isPending}
|
||||
onClick={() =>
|
||||
void run(
|
||||
@@ -129,50 +134,66 @@ export function PackageOperations({
|
||||
>
|
||||
{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>
|
||||
</>
|
||||
)}
|
||||
<Accordion>
|
||||
<Accordion.Item value="release">
|
||||
<Accordion.Control>{t("releaseTools")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack>
|
||||
<Text size="xs" ff="monospace" style={{ overflowWrap: "anywhere" }}>
|
||||
{t("activeArtifact")}: {current.activeArtifactId ?? t("none")}
|
||||
</Text>
|
||||
{inspected.data?.artifact && <PackageArtifactReview artifact={inspected.data.artifact} />}
|
||||
{inspected.error && <Alert color="red">{inspected.error.message}</Alert>}
|
||||
<Group>
|
||||
{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>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
</Paper>
|
||||
<PackageConvertedPlacements
|
||||
@@ -186,20 +207,13 @@ export function PackageOperations({
|
||||
installation={current}
|
||||
initialBoardId={initialBoardId}
|
||||
source={activeSource.data}
|
||||
initialOptions={options}
|
||||
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} />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -16,6 +16,7 @@ export function AddPackagePlacement({
|
||||
installation,
|
||||
initialBoardId,
|
||||
source,
|
||||
initialOptions,
|
||||
onAdded,
|
||||
onError,
|
||||
onMessage,
|
||||
@@ -23,6 +24,7 @@ export function AddPackagePlacement({
|
||||
installation: Installation;
|
||||
initialBoardId?: string;
|
||||
source: CustomWidgetPackage;
|
||||
initialOptions?: Record<string, unknown>;
|
||||
onAdded(): void;
|
||||
onError(error: string): void;
|
||||
onMessage(message: string): void;
|
||||
@@ -31,7 +33,7 @@ export function AddPackagePlacement({
|
||||
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 [configuration, setConfiguration] = useState<Record<string, unknown>>(initialOptions ?? {});
|
||||
const values = { ...getCustomWidgetDefaultOptions(source.options), ...configuration };
|
||||
const missingConnections = Object.entries(source.connections).filter(
|
||||
([name, requirement]) => !requirement.optional && !installation.bindings[name],
|
||||
|
||||
+45
-67
@@ -1,49 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { Group, NumberInput, Select, Stack } from "@mantine/core";
|
||||
import { Accordion, Group, NumberInput, Select, Stack, Text } 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")}
|
||||
@@ -58,40 +26,50 @@ export function PackagePreviewControls({ state }: { state: ReturnType<typeof use
|
||||
}}
|
||||
/>
|
||||
</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>
|
||||
<Accordion>
|
||||
<Accordion.Item value="dimensions">
|
||||
<Accordion.Control>{t("customViewport")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<Text size="xs" c="dimmed">{t("customViewportDescription")}</Text>
|
||||
<Group gap="xs" grow>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("width")}
|
||||
min={100}
|
||||
max={2400}
|
||||
value={width}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setWidth(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("height")}
|
||||
min={100}
|
||||
max={1600}
|
||||
value={height}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setHeight(value);
|
||||
}}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("previewScale")}
|
||||
min={25}
|
||||
max={90}
|
||||
suffix="%"
|
||||
step={10}
|
||||
value={Math.round(scale * 100)}
|
||||
onChange={(value) => {
|
||||
if (typeof value === "number") setScale(Math.min(0.9, Math.max(0.25, value / 100)));
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { Accordion, Alert, Button, Checkbox, Group, Paper, Select, Stack, Text } from "@mantine/core";
|
||||
import { useState } from "react";
|
||||
import { Accordion, Alert, Badge, Button, Checkbox, Group, Select, Stack, Text } from "@mantine/core";
|
||||
import { IconCode, IconPlayerPlay } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { WidgetPreviewFrame } from "@homarr/widgets/preview";
|
||||
|
||||
import { PackagePreviewViewport } from "./_package-preview-viewport";
|
||||
import { PackagePreviewControls } from "./_package-preview-controls";
|
||||
import { PackageRuntimeStatus } from "./_package-runtime-status";
|
||||
import { downloadPackage } from "./_package-document";
|
||||
import 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;
|
||||
}) {
|
||||
export function PackagePreview({ state }: { state: ReturnType<typeof usePackageWorkspace> }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const [detailsOpen, setDetailsOpen] = useState<string | null>(null);
|
||||
const {
|
||||
parsed,
|
||||
trusted,
|
||||
@@ -49,6 +47,10 @@ export function PackagePreview({
|
||||
previewLoadError,
|
||||
setOptions,
|
||||
} = state;
|
||||
let buildStatus = t("previewNotBuilt");
|
||||
if (previewMutation.isPending) buildStatus = t("previewBuilding");
|
||||
if (previewMutation.isError) buildStatus = t("previewBuildFailed");
|
||||
if (previewMutation.isSuccess) buildStatus = t("previewBuildReady");
|
||||
return (
|
||||
<Stack className={classes.preview} gap="sm">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
@@ -63,8 +65,8 @@ export function PackagePreview({
|
||||
/>
|
||||
<Button
|
||||
leftSection={<IconPlayerPlay size={16} />}
|
||||
loading={previewMutation.isPending}
|
||||
disabled={!existing || !parsed.success || !trusted || save.isPending}
|
||||
loading={previewMutation.isPending || save.isPending}
|
||||
disabled={!parsed.success || !trusted || busy}
|
||||
onClick={() => void runPreview()}
|
||||
>
|
||||
{t("preview")}
|
||||
@@ -99,9 +101,9 @@ export function PackagePreview({
|
||||
onChange={(event) => setLiveActions(event.currentTarget.checked)}
|
||||
label={t("previewLiveActions")}
|
||||
/>
|
||||
{!existing && (
|
||||
{!state.installationId && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("saveFirst")}
|
||||
{t("previewSavesFirst")}
|
||||
</Text>
|
||||
)}
|
||||
{stale && (
|
||||
@@ -109,32 +111,39 @@ export function PackagePreview({
|
||||
{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>
|
||||
<WidgetPreviewFrame
|
||||
dimensions={{ width, height, scale }}
|
||||
resize={{ size: state.gridSize, maximumSize: { width: 12, height: 12 }, onChange: state.setGridSize }}
|
||||
>
|
||||
{({ scale: fittedScale }) => (
|
||||
<>
|
||||
{preview && (
|
||||
<PackagePreviewViewport width={width} height={height} scale={fittedScale} colorScheme={previewTheme}>
|
||||
<TrustedWidgetPreview
|
||||
data={preview.displayData}
|
||||
width={width}
|
||||
height={height}
|
||||
displayScale={fittedScale}
|
||||
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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!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>
|
||||
</WidgetPreviewFrame>
|
||||
<Group gap="xs" align="center">
|
||||
{preview && (
|
||||
<Text size="xs" c="dimmed">
|
||||
@@ -148,12 +157,18 @@ export function PackagePreview({
|
||||
)}
|
||||
</Group>
|
||||
<PackagePreviewControls state={state} />
|
||||
<Accordion variant="default">
|
||||
<Accordion variant="default" value={detailsOpen} onChange={setDetailsOpen}>
|
||||
<Accordion.Item value="trust">
|
||||
<Accordion.Control>{t("executionDetails")}</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
<Badge variant="light">{buildStatus}</Badge>
|
||||
{previewMutation.error && <Alert color="red">{previewMutation.error.message}</Alert>}
|
||||
<Text size="sm">{t("browserExecution")}</Text>
|
||||
<Text size="sm">{parsed.success && parsed.data.manifest.entrypoints.server ? t("serverExecution") : t("browserOnlyExecution")}</Text>
|
||||
<Text size="sm">{t("trustedCode")}</Text>
|
||||
<Text size="sm">{t("runtimeLogs")}</Text>
|
||||
{detailsOpen && state.installationId && <PackageRuntimeStatus id={state.installationId} />}
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("previewDescription")}
|
||||
</Text>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import { ActionIcon, Menu } from "@mantine/core";
|
||||
import { IconBuildingStore, IconCopy, IconDots, IconDownload, IconLayoutDashboard, IconPlayerPause, IconPlayerPlay, IconPlugConnected } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { downloadPackage } from "./_package-document";
|
||||
|
||||
export function PackageRowActions({ entry }: { entry: RouterOutputs["customWidget"]["package"]["list"][number] }) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const utils = clientApi.useUtils();
|
||||
const fork = clientApi.customWidget.package.fork.useMutation();
|
||||
const enable = clientApi.customWidget.package.setEnabled.useMutation();
|
||||
const busy = fork.isPending || enable.isPending;
|
||||
const path = `/manage/custom-widgets/packages/${entry.id}`;
|
||||
const run = async (action: () => Promise<unknown>) => {
|
||||
try {
|
||||
await action();
|
||||
await utils.customWidget.package.list.invalidate();
|
||||
} catch (error) {
|
||||
showErrorNotification({ title: t("title"), message: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Menu position="bottom-end" withinPortal>
|
||||
<Menu.Target>
|
||||
<ActionIcon variant="subtle" color="gray" aria-label={t("actionsMenu")} loading={busy}>
|
||||
<IconDots size={20} />
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item component={Link} href={`${path}?tab=installation`} leftSection={<IconLayoutDashboard size={16} />}>
|
||||
{t("addToBoard")}
|
||||
</Menu.Item>
|
||||
<Menu.Item component={Link} href={`${path}?tab=connections`} leftSection={<IconPlugConnected size={16} />}>
|
||||
{t("connections")}
|
||||
</Menu.Item>
|
||||
<Menu.Item component={Link} href={`${path}?tab=workshop`} leftSection={<IconBuildingStore size={16} />}>
|
||||
{t("workshopTab")}
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item disabled={busy} leftSection={<IconCopy size={16} />} onClick={() => void run(async () => {
|
||||
await fork.mutateAsync({ id: entry.id, name: t("forkDefaultName", { name: entry.name }).slice(0, 128) });
|
||||
})}>
|
||||
{t("fork")}
|
||||
</Menu.Item>
|
||||
<Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
|
||||
const draft = await utils.customWidget.package.get.fetch({ id: entry.id });
|
||||
downloadPackage(entry.name, draft.source);
|
||||
})}>
|
||||
{t("exportDraft")}
|
||||
</Menu.Item>
|
||||
{entry.activeArtifactId && <Menu.Item leftSection={<IconDownload size={16} />} onClick={() => void run(async () => {
|
||||
downloadPackage(entry.name, await utils.customWidget.package.export.fetch({ id: entry.id }));
|
||||
})}>{t("exportActive")}</Menu.Item>}
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
disabled={busy || !entry.activeArtifactId}
|
||||
leftSection={entry.enabled ? <IconPlayerPause size={16} /> : <IconPlayerPlay size={16} />}
|
||||
onClick={() => void run(() => enable.mutateAsync({ id: entry.id, enabled: !entry.enabled }))}
|
||||
>
|
||||
{entry.enabled ? t("disable") : t("enable")}
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { Alert, Badge, Button, Group, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
export function PackageRuntimeStatus({ id }: { id: string }) {
|
||||
const t = useI18n("customWidget.package.runtime");
|
||||
const status = clientApi.customWidget.package.runtimeStatus.useQuery({ id });
|
||||
const data = status.data;
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Text size="sm" fw={600}>{t("title")}</Text>
|
||||
<Text size="xs" c="dimmed">{t("description")}</Text>
|
||||
<Group>
|
||||
{data && <Badge variant="light">{t(data.state)}</Badge>}
|
||||
<Button variant="subtle" size="xs" loading={status.isFetching} onClick={() => void status.refetch()}>{t("refresh")}</Button>
|
||||
</Group>
|
||||
{data && "pid" in data && (
|
||||
<Text size="xs">{t("process", { pid: data.pid ?? "—", active: data.activeRequests, queued: data.queuedRequests })}</Text>
|
||||
)}
|
||||
{data && "error" in data && <Alert color="red">{data.error}</Alert>}
|
||||
{status.error && <Alert color="red">{status.error.message}</Alert>}
|
||||
<Button component={Link} href="/manage/tools/logs" target="_blank" rel="noopener noreferrer" variant="default" size="xs">{t("logs")}</Button>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+51
-57
@@ -1,13 +1,14 @@
|
||||
"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 { Button, Group, Select, Stack, Tabs, Text, TextInput, Alert, Collapse } from "@mantine/core";
|
||||
import { 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";
|
||||
import { PackageFileTree } from "./_package-file-tree";
|
||||
const PackageLanguageEditor = dynamic(() => import("./_package-language-editor"), { ssr: false });
|
||||
export function PackageSourceEditor({
|
||||
state,
|
||||
@@ -17,7 +18,8 @@ export function PackageSourceEditor({
|
||||
existing: boolean;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const [filesOpen, setFilesOpen] = useState(false);
|
||||
const [filesOpen, setFilesOpen] = useState(true);
|
||||
const [manageFiles, setManageFiles] = useState(false);
|
||||
const { document, edit, selected, setSelected, path, setPath, busy, addFile, renameFile, removeFile, parsed } = state;
|
||||
return (
|
||||
<Tabs.Panel value="source" pt="md">
|
||||
@@ -25,6 +27,7 @@ export function PackageSourceEditor({
|
||||
{!existing && (
|
||||
<Select
|
||||
label={t("starter")}
|
||||
description={t("starterDescription")}
|
||||
placeholder={t("chooseStarter")}
|
||||
data={Object.entries(widgetReferencePackages).map(([key, template]) => ({
|
||||
value: key,
|
||||
@@ -36,7 +39,7 @@ export function PackageSourceEditor({
|
||||
const template = Object.entries(widgetReferencePackages).find(([key]) => key === starter)?.[1];
|
||||
if (!template) return;
|
||||
edit(documentFromTemplate(document.name, template));
|
||||
setSelected("/widget.json");
|
||||
setSelected(template.manifest.entrypoints.tile);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -63,59 +66,50 @@ export function PackageSourceEditor({
|
||||
<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>
|
||||
<PackageFileTree files={document.files} selected={selected} onSelect={setSelected} />
|
||||
<Button size="compact-xs" variant="subtle" onClick={() => setManageFiles((value) => !value)} aria-expanded={manageFiles}>
|
||||
{t("manageFiles")}
|
||||
</Button>
|
||||
<Collapse in={manageFiles}>
|
||||
<Stack gap="xs">
|
||||
<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>
|
||||
</Collapse>
|
||||
</Stack>
|
||||
)}
|
||||
<PackageLanguageEditor state={state} />
|
||||
|
||||
+3
-1
@@ -29,11 +29,13 @@
|
||||
min-width: 0;
|
||||
}
|
||||
.editor[data-files-open="true"] {
|
||||
grid-template-columns: 140px minmax(0, 1fr);
|
||||
grid-template-columns: 190px minmax(0, 1fr);
|
||||
}
|
||||
.files {
|
||||
overflow: auto;
|
||||
max-height: 65vh;
|
||||
border-right: 1px solid var(--mantine-color-default-border);
|
||||
padding-right: var(--mantine-spacing-xs);
|
||||
}
|
||||
.preview {
|
||||
position: sticky;
|
||||
|
||||
+70
-12
@@ -1,4 +1,6 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
@@ -11,10 +13,12 @@ import {
|
||||
TextInput,
|
||||
Tooltip,
|
||||
ActionIcon,
|
||||
Paper,
|
||||
} from "@mantine/core";
|
||||
import { IconArrowBackUp, IconArrowForwardUp, IconInfoCircle } from "@tabler/icons-react";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { PackageOptionFields } from "@homarr/widgets/custom-api/package-option-fields";
|
||||
import { PackagePreview } from "./_package-preview";
|
||||
import { PackageSplit } from "./_package-split";
|
||||
import { PackageAssistant } from "./_package-assistant";
|
||||
@@ -22,6 +26,8 @@ import { usePackageAssistant } from "./_use-package-assistant";
|
||||
import { PackageSourceEditor } from "./_package-source-editor";
|
||||
import { PackageConnections } from "./_package-connections";
|
||||
import { PackageOperations } from "./_package-operations";
|
||||
import { PackageWorkshop } from "./_package-workshop";
|
||||
import { PackageTransfer } from "./_package-transfer";
|
||||
import { usePackageWorkspace } from "./_use-package-workspace";
|
||||
import type { Installation } from "./_use-package-workspace";
|
||||
import classes from "./_package-workspace.module.css";
|
||||
@@ -41,6 +47,8 @@ export function PackageWorkspace({
|
||||
initialBoardId?: string;
|
||||
}) {
|
||||
const t = useI18n("customWidget.package");
|
||||
const searchParams = useSearchParams();
|
||||
const [tab, setTab] = useState(searchParams.get("tab") ?? "source");
|
||||
const workspace = usePackageWorkspace(
|
||||
installation,
|
||||
userId,
|
||||
@@ -73,6 +81,13 @@ export function PackageWorkspace({
|
||||
saveLocalBindings,
|
||||
} = workspace;
|
||||
usePackageAssistant(workspace);
|
||||
const current = workspace.installation;
|
||||
let status = t("draftOnly");
|
||||
if (current?.activeArtifactId) status = t("disabled");
|
||||
if (current?.activeArtifactId && current.enabled) status = t("active");
|
||||
let draftStatus = t("saved");
|
||||
if (editor.dirty) draftStatus = t("unsaved");
|
||||
if (!workspace.installationId) draftStatus = t("notSaved");
|
||||
|
||||
return (
|
||||
<Stack
|
||||
@@ -100,16 +115,30 @@ export function PackageWorkspace({
|
||||
<Button variant="subtle" component={Link} href="/manage/custom-widgets/packages">
|
||||
{t("library")}
|
||||
</Button>
|
||||
<Badge variant="light">{editor.dirty ? t("unsaved") : t("saved")}</Badge>
|
||||
<Badge variant="light">{status}</Badge>
|
||||
<Text size="xs" c="dimmed">{draftStatus}</Text>
|
||||
<Button
|
||||
variant="default"
|
||||
loading={save.isPending}
|
||||
disabled={!document.name.trim() || previewMutation.isPending}
|
||||
disabled={!document.name.trim() || previewMutation.isPending || saveBindings.isPending}
|
||||
onClick={() => void saveDraft()}
|
||||
>
|
||||
{t("saveDraft")}
|
||||
</Button>
|
||||
<Button onClick={() => { setTab("installation"); setPane("edit"); }}>
|
||||
{t("installation")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
{!workspace.installationId && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="xs">
|
||||
<Text fw={600}>{t("gettingStarted")}</Text>
|
||||
<Text size="sm" c="dimmed">{t("gettingStartedDescription")}</Text>
|
||||
<Text size="sm">{t("manualSteps")}</Text>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
{error && (
|
||||
<Alert color="red" withCloseButton onClose={() => setError("")}>
|
||||
{error}
|
||||
@@ -120,6 +149,16 @@ export function PackageWorkspace({
|
||||
{message}
|
||||
</Alert>
|
||||
)}
|
||||
{workspace.bindingsDirty && (
|
||||
<Alert color="yellow">
|
||||
<Group justify="space-between">
|
||||
<Text size="sm">{t("connectionsUnsaved")}</Text>
|
||||
<Button size="xs" loading={saveBindings.isPending || save.isPending} onClick={saveLocalBindings}>
|
||||
{t("saveBindings")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Alert>
|
||||
)}
|
||||
{editor.recovery && (
|
||||
<Alert color="yellow">
|
||||
<Stack gap="xs">
|
||||
@@ -176,16 +215,18 @@ export function PackageWorkspace({
|
||||
<PackageSplit
|
||||
userId={userId}
|
||||
pane={pane}
|
||||
preview={<PackagePreview state={workspace} existing={Boolean(installation)} />}
|
||||
preview={<PackagePreview state={workspace} />}
|
||||
>
|
||||
<Stack className={classes.authoring}>
|
||||
<Tabs defaultValue="source">
|
||||
<Tabs value={tab} onChange={(value) => { if (value) setTab(value); }} keepMounted={false}>
|
||||
<Tabs.List>
|
||||
<Tabs.Tab value="source">{t("code")}</Tabs.Tab>
|
||||
<Tabs.Tab value="connections">{t("connections")}</Tabs.Tab>
|
||||
<Tabs.Tab value="options">{t("options")}</Tabs.Tab>
|
||||
<Tabs.Tab value="installation">{t("installation")}</Tabs.Tab>
|
||||
<Tabs.Tab value="workshop">{t("workshopTab")}</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
<PackageSourceEditor state={workspace} existing={Boolean(installation)} />
|
||||
<PackageSourceEditor state={workspace} existing={Boolean(workspace.installationId)} />
|
||||
<Tabs.Panel value="connections" pt="md">
|
||||
<PackageConnections
|
||||
requirements={parsed.success ? parsed.data.connections : {}}
|
||||
@@ -195,25 +236,42 @@ export function PackageWorkspace({
|
||||
saving={saveBindings.isPending}
|
||||
onConnectionSaved={workspace.connectionChanged}
|
||||
/>
|
||||
{!installation && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("saveFirst")}
|
||||
</Text>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="options" pt="md">
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">{t("optionsDescription")}</Text>
|
||||
{parsed.success && <PackageOptionFields schema={parsed.data.options} value={effectiveOptions} onChange={setOptions} />}
|
||||
{parsed.success && Object.keys(parsed.data.options).length === 0 && <Alert>{t("noOptions")}</Alert>}
|
||||
<Button variant="subtle" onClick={() => setOptions({})}>{t("resetOptions")}</Button>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="installation" pt="md">
|
||||
<PackageOperations
|
||||
installation={installation}
|
||||
installation={current}
|
||||
initialBoardId={initialBoardId}
|
||||
source={parsed.success ? parsed.data : undefined}
|
||||
options={effectiveOptions}
|
||||
setOptions={setOptions}
|
||||
dirty={editor.dirty}
|
||||
trusted={trusted}
|
||||
connectionsDirty={workspace.bindingsDirty}
|
||||
onTrustChange={workspace.setTrusted}
|
||||
onSave={() => void saveDraft()}
|
||||
saving={save.isPending}
|
||||
onError={setError}
|
||||
onMessage={setMessage}
|
||||
/>
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="workshop" pt="md">
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">{t("workshopDescription")}</Text>
|
||||
{current ? (
|
||||
<>
|
||||
<PackageWorkshop id={current.id} dirty={editor.dirty || workspace.bindingsDirty} />
|
||||
<PackageTransfer id={current.id} name={current.name} active={Boolean(current.activeArtifactId)} dirty={editor.dirty || workspace.bindingsDirty} onError={setError} />
|
||||
</>
|
||||
) : <Button onClick={() => void saveDraft()} loading={save.isPending}>{t("saveDraft")}</Button>}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
</Stack>
|
||||
</PackageSplit>
|
||||
|
||||
+7
-2
@@ -11,7 +11,12 @@ 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) {
|
||||
export function usePackageDocument(
|
||||
initial: PackageDocument,
|
||||
userId: string,
|
||||
installationId?: string,
|
||||
connectionsDirty = false,
|
||||
) {
|
||||
const [document, setDocument] = useState(initial);
|
||||
const [saved, setSaved] = useState(initial);
|
||||
const [recovery, setRecovery] = useState<PackageDocument | null>(null);
|
||||
@@ -101,7 +106,7 @@ export function usePackageDocument(initial: PackageDocument, userId: string, ins
|
||||
return () => clearTimeout(timer);
|
||||
}, [definitionId, dirty, document, key, recovery]);
|
||||
|
||||
useUnsavedChangesGuard(dirty);
|
||||
useUnsavedChangesGuard(dirty || connectionsDirty, { navigationKey: installationId });
|
||||
|
||||
const discardRecovery = () => {
|
||||
setRecovery(null);
|
||||
|
||||
+49
-21
@@ -6,6 +6,7 @@ import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||
import { customWidgetPackageSchema, widgetPackagePathSchema } from "@homarr/custom-widgets/package";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import clock from "@homarr/widget-sdk/examples/clock.json";
|
||||
import { getLogicalTrackSize } from "~/components/board/layout/geometry";
|
||||
import { documentFromSource, documentFromTemplate, documentSource } from "./_package-document";
|
||||
import { usePackageDocument } from "./_use-package-document";
|
||||
export type Installation = RouterOutputs["customWidget"]["package"]["get"];
|
||||
@@ -24,7 +25,12 @@ export function usePackageWorkspace(
|
||||
if (installation) return documentFromSource(installation.name, installation.source);
|
||||
return documentFromTemplate(initialName ?? t("newName"), initialSource ?? clock);
|
||||
});
|
||||
const editor = usePackageDocument(initial, userId, installation?.id);
|
||||
const [installationId, setInstallationId] = useState(installation?.id);
|
||||
const [bindings, setBindings] = useState(installation?.bindings ?? initialBindings ?? {});
|
||||
const [savedBindings, setSavedBindings] = useState(bindings);
|
||||
const bindingsDirty =
|
||||
JSON.stringify(Object.entries(bindings).toSorted()) !== JSON.stringify(Object.entries(savedBindings).toSorted());
|
||||
const editor = usePackageDocument(initial, userId, installationId, bindingsDirty);
|
||||
const { document, edit } = editor;
|
||||
const [selected, setSelected] = useState(Object.keys(initial.files)[0] ?? "/widget.json");
|
||||
const [path, setPath] = useState("");
|
||||
@@ -37,16 +43,19 @@ export function usePackageWorkspace(
|
||||
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 currentInstallation = clientApi.customWidget.package.get.useQuery(
|
||||
{ id: installationId ?? "" },
|
||||
{ enabled: Boolean(installationId), initialData: installation },
|
||||
);
|
||||
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 [gridSize, setGridSize] = useState({ width: 2, height: 2 });
|
||||
const [width, setWidth] = useState(getLogicalTrackSize(2));
|
||||
const [height, setHeight] = useState(getLogicalTrackSize(2));
|
||||
const [scale, setScale] = useState(0.9);
|
||||
const [previewTheme, setPreviewTheme] = useState<"system" | "light" | "dark">("system");
|
||||
const previewId = useRef<string | null>(null);
|
||||
const retiredPreviewIds = useRef(new Set<string>());
|
||||
@@ -93,11 +102,21 @@ export function usePackageWorkspace(
|
||||
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 });
|
||||
const result = await save.mutateAsync({ id: installationId, name: document.name, source });
|
||||
setInstallationId(result.id);
|
||||
editor.markSaved(submitted);
|
||||
// Stay in the editor: a full navigation can trigger the unsaved-changes guard
|
||||
// and discards selection, trust and the current preview after a successful save.
|
||||
if (!installationId) {
|
||||
const destination = new URL(window.location.href);
|
||||
destination.pathname = destination.pathname.replace(/\/packages\/.*$/u, `/packages/${result.id}`);
|
||||
if (initialBoardId) destination.searchParams.set("boardId", initialBoardId);
|
||||
window.history.replaceState(null, "", destination.pathname + destination.search);
|
||||
}
|
||||
if (!installationId && Object.keys(bindings).length > 0) {
|
||||
await saveBindings.mutateAsync({ id: result.id, bindings });
|
||||
setSavedBindings(bindings);
|
||||
}
|
||||
await Promise.all([
|
||||
utils.customWidget.package.get.invalidate(),
|
||||
utils.customWidget.package.list.invalidate(),
|
||||
@@ -105,24 +124,21 @@ export function usePackageWorkspace(
|
||||
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);
|
||||
}
|
||||
return result.id;
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
};
|
||||
const runPreview = async () => {
|
||||
if (!installation || !trusted || !parsed.success) return;
|
||||
if (!trusted || !parsed.success || busy) return;
|
||||
const id = installationId ?? (await saveDraft());
|
||||
if (!id) return;
|
||||
resetExecution();
|
||||
setError("");
|
||||
const currentGeneration = generation.current;
|
||||
try {
|
||||
const next = await previewMutation.mutateAsync({
|
||||
id: installation.id,
|
||||
id,
|
||||
source,
|
||||
options: effectiveOptions,
|
||||
bindings,
|
||||
@@ -193,11 +209,15 @@ export function usePackageWorkspace(
|
||||
if (parsed.success && parsed.data.manifest.entrypoints.configuration)
|
||||
surfaceChoices.push({ value: "configuration", label: t("configuration") });
|
||||
const saveLocalBindings = () => {
|
||||
if (!installation) return;
|
||||
if (!installationId) {
|
||||
void saveDraft();
|
||||
return;
|
||||
}
|
||||
saveBindings.mutate(
|
||||
{ id: installation.id, bindings },
|
||||
{ id: installationId, bindings },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setSavedBindings(bindings);
|
||||
setMessage(t("bindingsSaved"));
|
||||
void utils.customWidget.package.get.invalidate();
|
||||
void utils.customWidget.package.guestGrants.invalidate();
|
||||
@@ -222,7 +242,8 @@ export function usePackageWorkspace(
|
||||
};
|
||||
|
||||
return {
|
||||
installationId: savedInstallationId.current,
|
||||
installationId,
|
||||
installation: currentInstallation.data,
|
||||
editor,
|
||||
document,
|
||||
edit,
|
||||
@@ -243,6 +264,7 @@ export function usePackageWorkspace(
|
||||
message,
|
||||
setMessage,
|
||||
bindings,
|
||||
bindingsDirty,
|
||||
setBindings,
|
||||
options,
|
||||
setOptions,
|
||||
@@ -256,6 +278,12 @@ export function usePackageWorkspace(
|
||||
setWidth,
|
||||
height,
|
||||
setHeight,
|
||||
gridSize,
|
||||
setGridSize: (size: { width: number; height: number }) => {
|
||||
setGridSize(size);
|
||||
setWidth(getLogicalTrackSize(size.width));
|
||||
setHeight(getLogicalTrackSize(size.height));
|
||||
},
|
||||
scale,
|
||||
setScale,
|
||||
previewTheme,
|
||||
|
||||
@@ -9,6 +9,8 @@ import { registerUnsavedChangesGuard } from "./unsaved-changes-guard";
|
||||
|
||||
interface UnsavedChangesGuardOptions {
|
||||
guardBeforeUnload?: boolean;
|
||||
/** Reset the remembered URL when an unsaved resource gets its first saved identity. */
|
||||
navigationKey?: string;
|
||||
}
|
||||
|
||||
export function useUnsavedChangesGuard(isDirty: boolean, options: UnsavedChangesGuardOptions = {}) {
|
||||
@@ -45,6 +47,6 @@ export function useUnsavedChangesGuard(isDirty: boolean, options: UnsavedChanges
|
||||
confirmNavigation: (href) => confirmNavigationRef.current(href),
|
||||
guardBeforeUnload: options.guardBeforeUnload,
|
||||
}),
|
||||
[options.guardBeforeUnload],
|
||||
[options.guardBeforeUnload, options.navigationKey],
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user